mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-12-05 17:51:19 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f06188b705 | ||
|
|
129b306e01 | ||
|
|
4852c92c8a | ||
|
|
7cee6c6de7 | ||
|
|
730c6e7125 |
No files matched your search
@@ -880,7 +880,7 @@ export const enVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent': 'Use System SSH Agent to Sign In',
|
||||
'hostDetails.systemSshAgent.desc': 'Use keys already unlocked by macOS, Linux, Windows, 1Password, or another compatible SSH agent',
|
||||
'hostDetails.systemSshAgent.socket': 'Agent Socket',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Leave empty to use SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Leave empty to auto-detect SSH_AUTH_SOCK when present; on macOS, also checks the Bitwarden agent socket',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Only Use Configured Keys',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Match agent keys to public keys configured for this host. To use agent keys without a local public key, choose Automatic authentication and leave this off.',
|
||||
'hostDetails.systemSshAgent.notRunning': 'System SSH agent is unavailable',
|
||||
|
||||
@@ -876,7 +876,7 @@ export const esVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent': 'Usar el agente SSH del sistema para iniciar sesión',
|
||||
'hostDetails.systemSshAgent.desc': 'Usa claves ya desbloqueadas por macOS, Linux, Windows, 1Password u otro agente SSH compatible',
|
||||
'hostDetails.systemSshAgent.socket': 'Socket del agente',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Déjalo vacío para usar SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Déjalo vacío para detectar automáticamente SSH_AUTH_SOCK si está presente; en macOS también busca el socket del agente de Bitwarden',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Usar solo las claves configuradas',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Usa las claves del agente que coincidan con las claves públicas configuradas para este host. Para usar el agente sin una clave pública local, elige la autenticación automática y desactiva esta opción.',
|
||||
'hostDetails.systemSshAgent.notRunning': 'El agente SSH del sistema no está disponible',
|
||||
|
||||
@@ -922,7 +922,7 @@ export const ruVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent': 'Использовать системный SSH-агент для входа',
|
||||
'hostDetails.systemSshAgent.desc': 'Использовать ключи, разблокированные macOS, Linux, Windows, 1Password или другим совместимым агентом',
|
||||
'hostDetails.systemSshAgent.socket': 'Сокет агента',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Оставьте пустым, чтобы использовать SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Оставьте пустым для автоопределения SSH_AUTH_SOCK, если задан; в macOS также проверяет сокет агента Bitwarden',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Только настроенные ключи',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Использовать ключи агента, соответствующие открытым ключам этого хоста. Чтобы использовать агент без локального открытого ключа, выберите автоматическую аутентификацию и отключите эту настройку.',
|
||||
'hostDetails.systemSshAgent.notRunning': 'Системный SSH-агент недоступен',
|
||||
|
||||
@@ -307,7 +307,7 @@ export const zhCNVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent': '使用系统 SSH 密钥登录',
|
||||
'hostDetails.systemSshAgent.desc': '使用已由 macOS、Linux、Windows、1Password 或其他兼容服务解锁的密钥',
|
||||
'hostDetails.systemSshAgent.socket': '代理地址',
|
||||
'hostDetails.systemSshAgent.socket.desc': '留空时使用 SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.socket.desc': '留空时自动检测 SSH_AUTH_SOCK(若已设置),在 macOS 上也会查找 Bitwarden 代理地址',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': '仅使用已配置的密钥',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '只尝试与此主机已配置公钥匹配的代理密钥。如需使用代理中的密钥且本地没有公钥,请将认证方式设为“自动选择”,并关闭此选项。',
|
||||
'hostDetails.systemSshAgent.notRunning': '系统 SSH 密钥服务不可用',
|
||||
|
||||
@@ -307,7 +307,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent': '使用系統 SSH 金鑰登入',
|
||||
'hostDetails.systemSshAgent.desc': '使用已由 macOS、Linux、Windows、1Password 或其他相容服務解鎖的金鑰',
|
||||
'hostDetails.systemSshAgent.socket': '代理位址',
|
||||
'hostDetails.systemSshAgent.socket.desc': '留空時使用 SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.socket.desc': '留空時自動偵測 SSH_AUTH_SOCK(若已設定),在 macOS 上也會尋找 Bitwarden 代理位址',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': '僅使用已設定的金鑰',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '僅嘗試與此主機已設定公鑰相符的代理程式金鑰。若要使用代理程式中的金鑰且本機沒有公鑰,請將驗證方式設為「自動選擇」並關閉此選項。',
|
||||
'hostDetails.systemSshAgent.notRunning': '系統 SSH 金鑰服務無法使用',
|
||||
|
||||
@@ -4492,6 +4492,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
resolvedLoginUsername: dragDropSftpHost === host ? resolvedLoginUsername : dragDropSftpHost.username,
|
||||
resolvedSudoPassword: dragDropSudoPassword,
|
||||
isLocalConnection,
|
||||
shellType,
|
||||
isNetworkDevice,
|
||||
onOpenSftp,
|
||||
resolveSftpInitialPath,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { extractRootPathsFromDropEntries } from './terminalHelpers.ts';
|
||||
import { getLocalTerminalDropPaths } from './terminalHelpers.ts';
|
||||
|
||||
// Inline copy of extractRootPathsFromClipboardFiles for standalone test
|
||||
function extractRootPathsFromClipboardFiles(
|
||||
@@ -98,29 +98,26 @@ describe('extractRootPathsFromClipboardFiles', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractRootPathsFromDropEntries', () => {
|
||||
it('uses a reconstructed DropEntry local path when File.path is unavailable', () => {
|
||||
const fileWithoutPath = { name: 'child.txt' } as File;
|
||||
assert.deepEqual(
|
||||
extractRootPathsFromDropEntries([{
|
||||
file: fileWithoutPath,
|
||||
localPath: '/home/user/folder/child.txt',
|
||||
relativePath: 'folder/child.txt',
|
||||
isDirectory: false,
|
||||
}]),
|
||||
['/home/user/folder'],
|
||||
);
|
||||
describe('getLocalTerminalDropPaths', () => {
|
||||
const filesAt = (...paths: string[]) => paths.map(path => ({ path })) as unknown as FileList;
|
||||
|
||||
it('inserts only the selected native roots, preserving order and quoting each path', () => {
|
||||
const folder = "/Users/alice/Project $1";
|
||||
const file = "/Users/alice/notes.txt";
|
||||
assert.deepEqual(getLocalTerminalDropPaths(filesAt(folder, file, folder), 'posix'), [
|
||||
"'/Users/alice/Project $1'", file,
|
||||
]);
|
||||
});
|
||||
|
||||
it('uses native path-only entries from a folder scan', () => {
|
||||
assert.deepEqual(
|
||||
extractRootPathsFromDropEntries([{
|
||||
file: null,
|
||||
localPath: '/home/user/folder/src/main.ts',
|
||||
relativePath: 'folder/src/main.ts',
|
||||
isDirectory: false,
|
||||
}]),
|
||||
['/home/user/folder'],
|
||||
);
|
||||
it('quotes a Windows folder for the local shell', () => {
|
||||
const folder = String.raw`C:\Users\alice\My Folder`;
|
||||
assert.deepEqual(getLocalTerminalDropPaths(filesAt(folder), 'powershell'), ["'" + folder + "'"]);
|
||||
assert.deepEqual(getLocalTerminalDropPaths(filesAt(folder), 'cmd'), ['"' + folder + '"']);
|
||||
assert.deepEqual(getLocalTerminalDropPaths(filesAt(folder), 'unknown'), ['"' + folder + '"']);
|
||||
assert.throws(() => getLocalTerminalDropPaths(filesAt(folder + '$HOME'), 'unknown'));
|
||||
});
|
||||
|
||||
it('rejects paths containing terminal control characters', () => {
|
||||
assert.throws(() => getLocalTerminalDropPaths(filesAt('/tmp/a\rb'), 'posix'));
|
||||
});
|
||||
});
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
} from "../../../domain/sftpDropElevation";
|
||||
import { toast } from "../../ui/toast";
|
||||
import {
|
||||
extractRootPathsFromDropEntries,
|
||||
getLocalTerminalDropPaths,
|
||||
type TerminalProps,
|
||||
} from "../terminalHelpers";
|
||||
|
||||
@@ -32,6 +32,7 @@ interface UseTerminalDragDropOptions {
|
||||
/** Login username already resolved through host auth (host or Keychain identity). */
|
||||
resolvedLoginUsername?: string;
|
||||
isLocalConnection: boolean;
|
||||
shellType?: TerminalSession["shellType"];
|
||||
isNetworkDevice?: boolean;
|
||||
onOpenSftp?: TerminalProps["onOpenSftp"];
|
||||
resolveSftpInitialPath: (options?: {
|
||||
@@ -190,38 +191,28 @@ function createRzMissingWatcher({
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleTerminalDropEntries({
|
||||
export async function handleRemoteTerminalDropEntries({
|
||||
dropEntries,
|
||||
host,
|
||||
isLocalConnection,
|
||||
isNetworkDevice = false,
|
||||
onOpenSftp,
|
||||
resolveSftpInitialPath,
|
||||
resolvedLoginUsername,
|
||||
resolvedSudoPassword,
|
||||
scrollToBottomAfterProgrammaticInput,
|
||||
sessionId,
|
||||
sessionRef,
|
||||
terminalBackend,
|
||||
isSensitiveInput,
|
||||
rzMissingFallbackTimeoutMs,
|
||||
termRef,
|
||||
}: Pick<
|
||||
UseTerminalDragDropOptions,
|
||||
| "host"
|
||||
| "resolvedLoginUsername"
|
||||
| "resolvedSudoPassword"
|
||||
| "isLocalConnection"
|
||||
| "isNetworkDevice"
|
||||
| "onOpenSftp"
|
||||
| "resolveSftpInitialPath"
|
||||
| "scrollToBottomAfterProgrammaticInput"
|
||||
| "sessionId"
|
||||
| "sessionRef"
|
||||
| "terminalBackend"
|
||||
| "isSensitiveInput"
|
||||
| "rzMissingFallbackTimeoutMs"
|
||||
| "termRef"
|
||||
> & {
|
||||
dropEntries: DropEntry[];
|
||||
}): Promise<void> {
|
||||
@@ -229,20 +220,6 @@ export async function handleTerminalDropEntries({
|
||||
return;
|
||||
}
|
||||
|
||||
if (isLocalConnection) {
|
||||
const paths = extractRootPathsFromDropEntries(dropEntries);
|
||||
|
||||
if (paths.length > 0 && termRef.current && sessionRef.current) {
|
||||
const pathsText = paths.join(" ");
|
||||
terminalBackend.writeToSession(sessionRef.current, pathsText, {
|
||||
sensitive: isSensitiveInput?.() === true,
|
||||
});
|
||||
scrollToBottomAfterProgrammaticInput(pathsText);
|
||||
termRef.current.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const requiresSftpForDirectoryDrop = dropEntries.some((entry) => (
|
||||
entry.isDirectory || /[\\/]/.test(entry.relativePath)
|
||||
));
|
||||
@@ -332,24 +309,28 @@ export async function handleTerminalDropEntries({
|
||||
}
|
||||
}
|
||||
|
||||
export function useTerminalDragDrop({
|
||||
host,
|
||||
resolvedLoginUsername,
|
||||
resolvedSudoPassword,
|
||||
isLocalConnection,
|
||||
isNetworkDevice = false,
|
||||
onOpenSftp,
|
||||
resolveSftpInitialPath,
|
||||
scrollToBottomAfterProgrammaticInput,
|
||||
sessionId,
|
||||
sessionRef,
|
||||
status,
|
||||
t,
|
||||
terminalBackend,
|
||||
isSensitiveInput,
|
||||
rzMissingFallbackTimeoutMs,
|
||||
termRef,
|
||||
}: UseTerminalDragDropOptions) {
|
||||
export async function handleTerminalFileDrop(
|
||||
dataTransfer: DataTransfer,
|
||||
options: Omit<UseTerminalDragDropOptions, "status" | "t">,
|
||||
): Promise<void> {
|
||||
if (options.isLocalConnection) {
|
||||
const { shellType, termRef, sessionRef, terminalBackend, isSensitiveInput, scrollToBottomAfterProgrammaticInput } = options;
|
||||
const paths = getLocalTerminalDropPaths(dataTransfer.files, shellType);
|
||||
if (paths.length && termRef.current && sessionRef.current) {
|
||||
const text = paths.join(" ");
|
||||
terminalBackend.writeToSession(sessionRef.current, text, { sensitive: isSensitiveInput?.() === true });
|
||||
scrollToBottomAfterProgrammaticInput(text);
|
||||
termRef.current.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const dropEntries = await extractDropEntries(dataTransfer);
|
||||
await handleRemoteTerminalDropEntries({ ...options, dropEntries });
|
||||
}
|
||||
|
||||
export function useTerminalDragDrop(options: UseTerminalDragDropOptions) {
|
||||
const { status, t } = options;
|
||||
const [isDraggingOver, setIsDraggingOver] = useState(false);
|
||||
const dragCounterRef = useRef(0);
|
||||
|
||||
@@ -395,24 +376,7 @@ export function useTerminalDragDrop({
|
||||
}
|
||||
|
||||
try {
|
||||
const dropEntries = await extractDropEntries(e.dataTransfer);
|
||||
await handleTerminalDropEntries({
|
||||
dropEntries,
|
||||
host,
|
||||
resolvedLoginUsername,
|
||||
resolvedSudoPassword,
|
||||
isLocalConnection,
|
||||
isNetworkDevice,
|
||||
onOpenSftp,
|
||||
resolveSftpInitialPath,
|
||||
scrollToBottomAfterProgrammaticInput,
|
||||
sessionId,
|
||||
sessionRef,
|
||||
terminalBackend,
|
||||
isSensitiveInput,
|
||||
rzMissingFallbackTimeoutMs,
|
||||
termRef,
|
||||
});
|
||||
await handleTerminalFileDrop(e.dataTransfer, options);
|
||||
} catch (error) {
|
||||
logger.error("Failed to handle file drop", error);
|
||||
const message = resolveTerminalDropErrorMessage(error, t);
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
terminalDataToHtmlContent,
|
||||
terminalDataToPlainText,
|
||||
} from "@/domain/terminalLogSanitizer.shared.cjs";
|
||||
import {
|
||||
createReplaySafeTerminalLog,
|
||||
createReplaySafeTerminalLogSanitizer,
|
||||
@@ -18,7 +22,7 @@ test("plain text output is preserved in large chunks", () => {
|
||||
test("common shell clear sequence is safe to replay", () => {
|
||||
const log = createReplaySafeTerminalLog("login banner\n$ clear\n\x1b[H\x1b[2J\x1b[3Jafter clear\n");
|
||||
|
||||
assert.equal(log, "login banner\n$ clear\n\r\nafter clear\n");
|
||||
assert.equal(log, "login banner\n$ clear\n\r\nafter clear\r\n");
|
||||
assert.equal(log.includes("\x1b[2J"), false);
|
||||
assert.equal(log.includes("\x1b[3J"), false);
|
||||
});
|
||||
@@ -26,21 +30,21 @@ test("common shell clear sequence is safe to replay", () => {
|
||||
test("display clear followed by cursor home keeps prior replay history", () => {
|
||||
assert.equal(
|
||||
createReplaySafeTerminalLog("old1\nold2\n\x1b[2J\x1b[Hnew\n"),
|
||||
"old1\nold2\n\r\nnew\n",
|
||||
"old1\nold2\n\r\nnew\r\n",
|
||||
);
|
||||
});
|
||||
|
||||
test("home erase-to-end clear keeps prior replay history", () => {
|
||||
assert.equal(
|
||||
createReplaySafeTerminalLog("before zellij\n$ zellij\n\x1b[H\x1b[Jzellij pane\n"),
|
||||
"before zellij\n$ zellij\n\r\nzellij pane\n",
|
||||
"before zellij\n$ zellij\n\r\nzellij pane\r\n",
|
||||
);
|
||||
});
|
||||
|
||||
test("repeated home erase-to-end clears create fresh replay sections", () => {
|
||||
const log = createReplaySafeTerminalLog("history\n\x1b[2Jframe1\x1b[H\x1b[Jframe2\n");
|
||||
|
||||
assert.equal(log, "history\n\r\nframe1\r\n\r\nframe2\n");
|
||||
assert.equal(log, "history\n\r\nframe1\r\n\r\nframe2\r\n");
|
||||
assert.equal(log.includes("\x1b[H"), false);
|
||||
assert.equal(log.includes("\x1b[J"), false);
|
||||
});
|
||||
@@ -48,22 +52,26 @@ test("repeated home erase-to-end clears create fresh replay sections", () => {
|
||||
test("repeated cursor home before clear does not overwrite replay history", () => {
|
||||
const log = createReplaySafeTerminalLog("old1\nold2\n\x1b[H\x1b[H\x1b[2Jafter\n");
|
||||
|
||||
assert.equal(log, "old1\nold2\n\r\nafter\n");
|
||||
assert.equal(log, "old1\nold2\n\r\nafter\r\n");
|
||||
assert.equal(log.includes("\x1b[H"), false);
|
||||
});
|
||||
|
||||
test("mode controls after clear do not allow later home to overwrite history", () => {
|
||||
const log = createReplaySafeTerminalLog("history\n\x1b[H\x1b[2J\x1b[?25l\x1b[Hnew\n");
|
||||
|
||||
assert.equal(log, "history\n\r\n\x1b[?25lnew\n");
|
||||
assert.equal(log, "history\n\r\nnew\r\n");
|
||||
assert.equal(log.includes("\x1b[H"), false);
|
||||
});
|
||||
|
||||
test("cursor positioning after clear does not overwrite replay history", () => {
|
||||
test("cursor positioning after clear is applied visually without overwriting replay history", () => {
|
||||
const log = createReplaySafeTerminalLog(
|
||||
"old1\nold2\n\x1b[2J\x1b[10;5Hpanel\x1b[999Aup\x1b[5Fprev\x1b[12drow\x1b[20Gcol\n",
|
||||
);
|
||||
|
||||
assert.equal(log, "old1\nold2\n\r\npanelupprevrowcol\n");
|
||||
assert.equal(
|
||||
log,
|
||||
"old1\nold2\n\r\nprev up\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n panel\r\n\r\n row col\r\n",
|
||||
);
|
||||
assert.equal(log.includes("\x1b[10;5H"), false);
|
||||
assert.equal(log.includes("\x1b[999A"), false);
|
||||
assert.equal(log.includes("\x1b[5F"), false);
|
||||
@@ -71,17 +79,17 @@ test("cursor positioning after clear does not overwrite replay history", () => {
|
||||
assert.equal(log.includes("\x1b[20G"), false);
|
||||
});
|
||||
|
||||
test("cursor home after protected clear is dropped when no erase follows", () => {
|
||||
test("cursor home after protected clear stays within new screen when no erase follows", () => {
|
||||
const log = createReplaySafeTerminalLog("old\n\x1b[2Jframe\x1b[H\x1b[?25ltext\n");
|
||||
|
||||
assert.equal(log, "old\n\r\nframe\x1b[?25ltext\n");
|
||||
assert.equal(log, "old\n\r\ntexte\r\n");
|
||||
assert.equal(log.includes("\x1b[H"), false);
|
||||
});
|
||||
|
||||
test("single-character cursor controls after clear do not overwrite replay history", () => {
|
||||
const log = createReplaySafeTerminalLog("old\n\x1b[2J\x1bMri\x8dc1ri\x1bDind\x84c1ind\x1bEnel\x85c1nel\n");
|
||||
|
||||
assert.equal(log, "old\n\r\nric1riindc1indnelc1nel\n");
|
||||
assert.equal(log, "old\n\r\nric1ri\r\n ind\r\n c1ind\r\nnel\r\nc1nel\r\n");
|
||||
assert.equal(log.includes("\x1bM"), false);
|
||||
assert.equal(log.includes("\x8d"), false);
|
||||
assert.equal(log.includes("\x1bD"), false);
|
||||
@@ -93,7 +101,7 @@ test("single-character cursor controls after clear do not overwrite replay histo
|
||||
test("queued cursor and erase controls before clear are not preserved", () => {
|
||||
const log = createReplaySafeTerminalLog("old\n\x1b[H\x1b[2;1H\x1b[K\x1b[s\x1b[u\x1b[?25l\x1b[2Jnew\n");
|
||||
|
||||
assert.equal(log, "old\n\r\n\x1b[?25lnew\n");
|
||||
assert.equal(log, "old\n\r\nnew\r\n");
|
||||
assert.equal(log.includes("\x1b[2;1H"), false);
|
||||
assert.equal(log.includes("\x1b[K"), false);
|
||||
assert.equal(log.includes("\x1b[s"), false);
|
||||
@@ -112,23 +120,25 @@ test("pending cursor-home controls are preserved when no clear follows", () => {
|
||||
assert.equal(log, "abc\x1b[H\x1b[s\x1b[2;1HXYZ");
|
||||
});
|
||||
|
||||
test("mode controls between home and erase are kept without preserving clear controls", () => {
|
||||
test("mode controls between home and erase do not preserve clear controls", () => {
|
||||
const log = createReplaySafeTerminalLog("history\n\x1b[H\x1b[?25l\x1b[Jnew\n");
|
||||
|
||||
assert.equal(log, "history\n\r\n\x1b[?25lnew\n");
|
||||
assert.equal(log, "history\n\r\nnew\r\n");
|
||||
assert.equal(log.includes("\x1b[H"), false);
|
||||
assert.equal(log.includes("\x1b[J"), false);
|
||||
});
|
||||
|
||||
test("erase-display backward controls are dropped from replay data", () => {
|
||||
test("erase-display backward controls are applied within the new screen without wiping history", () => {
|
||||
const log = createReplaySafeTerminalLog("old\n\x1b[2Jnew\x1b[1Jafter\n");
|
||||
|
||||
assert.equal(log, "old\n\r\nnew\r\n\r\nafter\n");
|
||||
assert.equal(log, "old\n\r\n after\r\n");
|
||||
assert.equal(log.includes("\x1b[1J"), false);
|
||||
});
|
||||
|
||||
test("scrollback-only clears protect replay history", () => {
|
||||
const log = createReplaySafeTerminalLog("history\n\x1b[3J\x1b[Hoverwrite\n");
|
||||
|
||||
assert.equal(log, "history\n\r\noverwrite\n");
|
||||
assert.equal(log, "history\n\r\noverwrite\r\n");
|
||||
assert.equal(log.includes("\x1b[3J"), false);
|
||||
assert.equal(log.includes("\x1b[H"), false);
|
||||
});
|
||||
@@ -181,7 +191,7 @@ test("pending cursor-home lookahead controls are bounded before clear", () => {
|
||||
const controls = "\x1b[31m".repeat(900);
|
||||
const log = createReplaySafeTerminalLog(`old\n\x1b[H${controls}\x1b[2Jnew\n`);
|
||||
|
||||
assert.equal(log, "old\n\r\nnew\n");
|
||||
assert.equal(log, "old\n\r\nnew\r\n");
|
||||
assert.equal(log.includes("\x1b[31m"), false);
|
||||
});
|
||||
|
||||
@@ -258,7 +268,7 @@ test("dec cursor save mode is not treated as alternate screen", () => {
|
||||
test("cursor save and restore controls are stripped around protected clears", () => {
|
||||
const log = createReplaySafeTerminalLog("old\n\x1b[s\x1b7\x1b[2J\x1b[uafter\x1b8done\n");
|
||||
|
||||
assert.equal(log, "old\n\x1b[s\x1b7\r\n\r\nafterdone\n");
|
||||
assert.equal(log, "old\n\x1b[s\x1b7\r\n\r\nafterdone\r\n");
|
||||
assert.equal(log.includes("\x1b[s"), true);
|
||||
assert.equal(log.includes("\x1b[u"), false);
|
||||
assert.equal(log.includes("\x1b7"), true);
|
||||
@@ -268,14 +278,14 @@ test("cursor save and restore controls are stripped around protected clears", ()
|
||||
test("terminal reset controls are dropped from replay data", () => {
|
||||
const log = createReplaySafeTerminalLog("before\x1bcafter\n");
|
||||
|
||||
assert.equal(log, "before\r\n\r\nafter\n");
|
||||
assert.equal(log, "before\r\n\r\nafter\r\n");
|
||||
assert.equal(log.includes("\x1bc"), false);
|
||||
});
|
||||
|
||||
test("RIS during alternate screen restores logging of later shell output", () => {
|
||||
const log = createReplaySafeTerminalLog("before\n\x1b[?1049hTUI\x1bcshell-after\n");
|
||||
|
||||
assert.equal(log, "before\n\r\nshell-after\n");
|
||||
assert.equal(log, "before\n\r\nshell-after\r\n");
|
||||
assert.equal(log.includes("TUI"), false);
|
||||
assert.equal(log.includes("\x1bc"), false);
|
||||
});
|
||||
@@ -287,7 +297,7 @@ test("split RIS during alternate screen restores logging of later shell output",
|
||||
+ sanitizer.append("cshell-after\n")
|
||||
+ sanitizer.finish();
|
||||
|
||||
assert.equal(log, "before\n\r\nshell-after\n");
|
||||
assert.equal(log, "before\n\r\nshell-after\r\n");
|
||||
assert.equal(log.includes("TUI"), false);
|
||||
assert.equal(log.includes("\x1bc"), false);
|
||||
});
|
||||
@@ -299,7 +309,7 @@ test("split terminal reset controls are dropped from replay data", () => {
|
||||
+ sanitizer.append("cafter\n")
|
||||
+ sanitizer.finish();
|
||||
|
||||
assert.equal(log, "before\r\n\r\nafter\n");
|
||||
assert.equal(log, "before\r\n\r\nafter\r\n");
|
||||
assert.equal(log.includes("\x1bc"), false);
|
||||
});
|
||||
|
||||
@@ -308,3 +318,201 @@ test("non-clear cursor and color controls are preserved", () => {
|
||||
|
||||
assert.equal(createReplaySafeTerminalLog(input), input);
|
||||
});
|
||||
|
||||
test("Windows ConPTY ED + CUP redraws preserve visual layout and clear history", () => {
|
||||
const prompt = "administrator@WIN-HOST C:\\Users\\Administrator>";
|
||||
const conptyStream = [
|
||||
// Initial ConPTY clear + viewport blank padding + CUP home banner paint
|
||||
"\x1b[?25l\x1b[2J\x1b[m\x1b[H",
|
||||
"\r\n".repeat(40),
|
||||
"\x1b[1;1HMicrosoft Windows [Version 10.0.26100.32230]\r\n",
|
||||
"(c) Microsoft Corporation. All rights reserved.",
|
||||
`\x1b[4;1H${prompt}`,
|
||||
// Redraw from CUP home + viewport padding + CUP back to prompt to type ipconfig
|
||||
"\x1b[1;1HMicrosoft Windows [Version 10.0.26100.32230]\r\n",
|
||||
"(c) Microsoft Corporation. All rights reserved.\r\n\r\n",
|
||||
prompt,
|
||||
"\r\n".repeat(35),
|
||||
`\x1b[4;${prompt.length + 1}Hipconfig\r\n`,
|
||||
"\x1b[6;1HWindows IP Configuration\r\n",
|
||||
"\x1b[8;1H Default Gateway . . . . . . . . . : 192.168.242.2",
|
||||
// ConPTY positions next prompt via CUP instead of CRLF
|
||||
`\x1b[10;1H${prompt}dir\r\n`,
|
||||
"\x1b[12;1H Volume in drive C has no label.\r\n",
|
||||
// Later `cls` clears viewport; earlier history must remain preserved
|
||||
"\x1b[2J\x1b[H",
|
||||
`\x1b[1;1H${prompt}whoami\r\n`,
|
||||
"win-host\\administrator\r\n",
|
||||
].join("");
|
||||
|
||||
const log = createReplaySafeTerminalLog(conptyStream);
|
||||
const plain = terminalDataToPlainText(log);
|
||||
const lines = plain.split("\n");
|
||||
|
||||
// No leading blank lines from dropped CUP after ED
|
||||
assert.equal(lines[0], "Microsoft Windows [Version 10.0.26100.32230]");
|
||||
// Banner is not duplicated by the CUP-home redraw
|
||||
assert.equal(
|
||||
lines.filter((line) => line.includes("Microsoft Windows [Version 10.0.26100.32230]")).length,
|
||||
1,
|
||||
);
|
||||
// First command sits on the prompt line, not separated by 35 blank lines
|
||||
assert.equal(lines.includes(`${prompt}ipconfig`), true);
|
||||
// Next prompt is on its own line, never glued to the previous output
|
||||
assert.equal(lines.includes(" Default Gateway . . . . . . . . . : 192.168.242.2"), true);
|
||||
assert.equal(lines.includes(`${prompt}dir`), true);
|
||||
assert.equal(plain.includes(`192.168.242.2${prompt}`), false);
|
||||
// Earlier history survives later cls/ED2
|
||||
assert.equal(lines.includes(" Volume in drive C has no label."), true);
|
||||
assert.equal(lines.includes(`${prompt}whoami`), true);
|
||||
assert.equal(lines.includes("win-host\\administrator"), true);
|
||||
// No raw cursor positioning or display erase sequences remain for LogView
|
||||
assert.equal(log.includes("\x1b[2J"), false);
|
||||
assert.equal(log.includes("\x1b[1;1H"), false);
|
||||
assert.equal(log.includes("\x1b[10;1H"), false);
|
||||
});
|
||||
|
||||
test("post-clear virtual screen preserves SGR colors for LogView and bounds buffered lines", () => {
|
||||
const colored = createReplaySafeTerminalLog(
|
||||
"\x1b[2J\x1b[H\x1b[32mPS>\x1b[0m \x1b[93mdir\x1b[0m\r\n\x1b[38;2;10;20;30mrgb\x1b[0m\r\n",
|
||||
);
|
||||
assert.equal(colored, "\x1b[32mPS>\x1b[0m \x1b[93mdir\x1b[0m\r\n\x1b[38;2;10;20;30mrgb\x1b[0m\r\n");
|
||||
|
||||
const sanitizer = createReplaySafeTerminalLogSanitizer();
|
||||
let streamed = sanitizer.append("before\r\n\x1b[2J\x1b[H");
|
||||
let drainedDuringAppend = false;
|
||||
for (let i = 0; i < 1200; i += 1) {
|
||||
const chunk = sanitizer.append(`line-${i}\r\n`);
|
||||
if (chunk) drainedDuringAppend = true;
|
||||
streamed += chunk;
|
||||
}
|
||||
streamed += sanitizer.finish();
|
||||
|
||||
assert.equal(drainedDuringAppend, true);
|
||||
const plain = terminalDataToPlainText(streamed);
|
||||
assert.equal(plain.startsWith("before\n\nline-0\n"), true);
|
||||
assert.equal(plain.endsWith("line-1198\nline-1199"), true);
|
||||
assert.equal(plain.includes("line-999\nline-1000\nline-1001"), true);
|
||||
});
|
||||
|
||||
test("successive ED2 + CUP clears preserve every cleared screen in order", () => {
|
||||
const input = "old\r\n\x1b[2Jone\r\n\x1b[2J\x1b[Htwo\r\n\x1b[2J\x1b[Hthree\r\n\x1b[2J\x1b[Hfour\r\n";
|
||||
const log = createReplaySafeTerminalLog(input);
|
||||
|
||||
assert.equal(log, "old\r\n\r\none\r\n\r\ntwo\r\n\r\nthree\r\n\r\nfour\r\n");
|
||||
assert.equal(terminalDataToPlainText(log), "old\n\none\n\ntwo\n\nthree\n\nfour");
|
||||
});
|
||||
|
||||
test("pre-clear SGR state is synchronized across virtual-screen handoff", () => {
|
||||
const resetAfterClear = createReplaySafeTerminalLog("\x1b[31mold\r\n\x1b[2J\x1b[0mnew\r\n");
|
||||
assert.equal(resetAfterClear, "\x1b[31mold\r\n\x1b[0m\r\nnew\r\n");
|
||||
assert.equal(
|
||||
terminalDataToHtmlContent(resetAfterClear),
|
||||
'<span style="color: var(--ansi-1, #cd3131)">old</span>\n\nnew',
|
||||
);
|
||||
|
||||
const carriedAcrossClear = createReplaySafeTerminalLog(
|
||||
"\x1b[31mold\r\n\x1b[2Jstill-red\r\n\x1b[0mplain\r\n",
|
||||
);
|
||||
assert.equal(
|
||||
terminalDataToHtmlContent(carriedAcrossClear),
|
||||
'<span style="color: var(--ansi-1, #cd3131)">old</span>\n\n<span style="color: var(--ansi-1, #cd3131)">still-red</span>\nplain',
|
||||
);
|
||||
|
||||
const resetByRis = createReplaySafeTerminalLog("\x1b[31mold\r\n\x1bcnew\r\n");
|
||||
assert.equal(
|
||||
terminalDataToHtmlContent(resetByRis),
|
||||
'<span style="color: var(--ansi-1, #cd3131)">old</span>\n\nnew',
|
||||
);
|
||||
|
||||
const queuedSgrBeforeClear = createReplaySafeTerminalLog(
|
||||
"\x1b[H\x1b[31mstay\r\n\x1b[2J\x1b[0mnew\r\n",
|
||||
);
|
||||
assert.equal(
|
||||
terminalDataToHtmlContent(queuedSgrBeforeClear),
|
||||
'<span style="color: var(--ansi-1, #cd3131)">stay</span>\n\nnew',
|
||||
);
|
||||
});
|
||||
|
||||
test("successive home + ED0 clears preserve every screen in replay-safe logs", () => {
|
||||
const input = "\x1b[2Jone\n\x1b[H\x1b[Jtwo\n\x1b[H\x1b[Jthree\n";
|
||||
const log = createReplaySafeTerminalLog(input);
|
||||
|
||||
assert.equal(log, "one\r\n\r\ntwo\r\n\r\nthree\r\n");
|
||||
assert.equal(terminalDataToPlainText(log), "one\n\ntwo\n\nthree");
|
||||
// Default plain-text renderer still deduplicates TUI-style home + ED0.
|
||||
assert.equal(terminalDataToPlainText(input), "one\n\nthree");
|
||||
});
|
||||
|
||||
test("post-clear newline-free flood is bounded by live virtual screen cell cap", () => {
|
||||
const sanitizer = createReplaySafeTerminalLogSanitizer();
|
||||
const drained = sanitizer.append(`\x1b[2J${"a".repeat(250_000)}TAIL`);
|
||||
const tail = sanitizer.finish();
|
||||
|
||||
assert.equal(drained, "");
|
||||
assert.equal(tail.length <= 100_000, true);
|
||||
assert.equal(tail.endsWith("TAIL"), true);
|
||||
|
||||
const customSanitizer = createReplaySafeTerminalLogSanitizer({ maxBufferedCells: 200 });
|
||||
const customOut = customSanitizer.append(`\x1b[2J${"x".repeat(5_000)}END\b!\r\nline2\r\n`)
|
||||
+ customSanitizer.finish();
|
||||
const customPlain = terminalDataToPlainText(customOut);
|
||||
assert.equal(customPlain.length <= 210, true);
|
||||
assert.equal(customPlain.endsWith("EN!\nline2"), true);
|
||||
});
|
||||
|
||||
test("post-clear and post-RIS pathological CUP/CUD row targets are clamped without blowing up", () => {
|
||||
const cases = [
|
||||
"before\r\n\x1b[2J\x1b[100000000;1Hshort\r\n",
|
||||
"before\r\n\x1bc\x1b[100000000;1Hshort\r\n",
|
||||
"before\r\n\x1b[2J\x1b[100000000Bshort\r\n",
|
||||
"before\r\n\x1b[2J\x1b[100000000dshort\r\n",
|
||||
];
|
||||
|
||||
for (const input of cases) {
|
||||
const start = Date.now();
|
||||
const sanitizer = createReplaySafeTerminalLogSanitizer();
|
||||
const log = sanitizer.append(input) + sanitizer.finish();
|
||||
const elapsedMs = Date.now() - start;
|
||||
|
||||
assert.equal(elapsedMs < 2000, true);
|
||||
const plain = terminalDataToPlainText(log);
|
||||
const lines = plain.split("\n");
|
||||
assert.equal(lines[0], "before");
|
||||
assert.equal(lines[lines.length - 1], "short");
|
||||
assert.equal(lines.length <= 1005, true);
|
||||
}
|
||||
});
|
||||
|
||||
test("post-clear 900 x ~150-char transcript drains overflow instead of dropping early lines", () => {
|
||||
const lineCount = 900;
|
||||
const padding = "x".repeat(140);
|
||||
const makeLine = (i: number) => `line-${String(i).padStart(4, "0")}-${padding}`;
|
||||
|
||||
// One line per append (matches Codex repro where cell cap previously dropped lines 0..336).
|
||||
const sanitizer = createReplaySafeTerminalLogSanitizer();
|
||||
let streamed = sanitizer.append("\x1b[2J");
|
||||
let drainedDuringAppend = false;
|
||||
for (let i = 0; i < lineCount; i += 1) {
|
||||
const chunk = sanitizer.append(`${makeLine(i)}\r\n`);
|
||||
if (chunk) drainedDuringAppend = true;
|
||||
streamed += chunk;
|
||||
}
|
||||
streamed += sanitizer.finish();
|
||||
|
||||
assert.equal(drainedDuringAppend, true);
|
||||
const lines = terminalDataToPlainText(streamed).split("\n");
|
||||
assert.equal(lines.length, lineCount);
|
||||
assert.equal(lines[0], makeLine(0));
|
||||
assert.equal(lines[336], makeLine(336));
|
||||
assert.equal(lines[337], makeLine(337));
|
||||
assert.equal(lines[lineCount - 1], makeLine(lineCount - 1));
|
||||
|
||||
// Single-append bulk transcript also preserves every line from line 0 in order.
|
||||
const bulkInput = `\x1b[2J${Array.from({ length: lineCount }, (_, i) => `${makeLine(i)}\r\n`).join("")}`;
|
||||
const bulkLog = createReplaySafeTerminalLog(bulkInput);
|
||||
const bulkLines = terminalDataToPlainText(bulkLog).split("\n");
|
||||
assert.equal(bulkLines.length, lineCount);
|
||||
assert.equal(bulkLines[0], makeLine(0));
|
||||
assert.equal(bulkLines[lineCount - 1], makeLine(lineCount - 1));
|
||||
});
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
createReplaySgrTracker,
|
||||
createTerminalTextRenderer,
|
||||
} from "@/domain/terminalLogSanitizer.shared.cjs";
|
||||
|
||||
type CsiSequence = {
|
||||
raw: string;
|
||||
end: number;
|
||||
@@ -10,12 +15,16 @@ const BEL = "\x07";
|
||||
const ST = "\x9c";
|
||||
const CSI = "\x9b";
|
||||
const MAX_PENDING_ESCAPE_CHARS = 4096;
|
||||
const MAX_BUFFERED_SCREEN_LINES = 1000;
|
||||
const MAX_BUFFERED_SCREEN_CELLS = 100_000;
|
||||
|
||||
type ControlStringMode = "osc" | "string";
|
||||
|
||||
export type ReplaySafeTerminalLogSanitizerOptions = {
|
||||
/** Seed when attaching mid-TUI so live redraws stay omitted until leave. */
|
||||
alternateScreenActive?: boolean;
|
||||
/** Upper bound on cells buffered by the post-clear virtual screen. */
|
||||
maxBufferedCells?: number;
|
||||
};
|
||||
|
||||
export interface ReplaySafeTerminalLogSanitizer {
|
||||
@@ -25,6 +34,11 @@ export interface ReplaySafeTerminalLogSanitizer {
|
||||
|
||||
const isCsiFinal = (ch: string): boolean => ch >= "@" && ch <= "~";
|
||||
|
||||
const isEscIntermediateByte = (ch: string): boolean => {
|
||||
const code = ch.charCodeAt(0);
|
||||
return code >= 0x20 && code <= 0x2f;
|
||||
};
|
||||
|
||||
const readCsiSequence = (input: string, index: number): CsiSequence | null => {
|
||||
const isEscCsi = input[index] === ESC && input[index + 1] === "[";
|
||||
const isC1Csi = input[index] === CSI;
|
||||
@@ -133,6 +147,9 @@ const getEraseDisplayMode = (sequence: CsiSequence): number | null => {
|
||||
const isEraseSequence = (sequence: CsiSequence): boolean =>
|
||||
sequence.final === "J" || sequence.final === "K" || sequence.final === "X";
|
||||
|
||||
const isSgrSequence = (sequence: CsiSequence): boolean =>
|
||||
sequence.final === "m" && !/[?><= -/]/.test(sequence.params);
|
||||
|
||||
const isSafePendingAfterCursorHomeSequence = (sequence: CsiSequence): boolean =>
|
||||
!isUnsafeCursorReplaySequence(sequence) && !isEraseSequence(sequence);
|
||||
|
||||
@@ -149,9 +166,6 @@ const getAlternateScreenMode = (sequence: CsiSequence): "enter" | "exit" | null
|
||||
const isC1SingleCharCursorControl = (ch: string): boolean =>
|
||||
ch === "\x84" || ch === "\x85" || ch === "\x8d";
|
||||
|
||||
const isEscSingleCharCursorControl = (ch: string): boolean =>
|
||||
ch === "D" || ch === "E" || ch === "M";
|
||||
|
||||
// ESC or any C1 control (0x80-0x9f): every branch of the sanitizer's parser
|
||||
// that can rewrite output starts at one of these characters.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
@@ -178,14 +192,25 @@ class ReplaySafeTerminalLogSanitizerImpl implements ReplaySafeTerminalLogSanitiz
|
||||
private controlStringMode: ControlStringMode | null = null;
|
||||
private controlStringEscPending = false;
|
||||
private discardingCsi = false;
|
||||
private inClearCluster = false;
|
||||
private protectingClearedHistory = false;
|
||||
private alternateScreenActive: boolean;
|
||||
private hasOutput = false;
|
||||
private hasVisibleOutput = false;
|
||||
private lastOutputChar = "";
|
||||
// Once a clear/RIS protects earlier history, render subsequent output on the
|
||||
// shared virtual screen so cursor moves (e.g. Windows ConPTY CUP redraws)
|
||||
// become visual lines instead of overwriting history or gluing text together.
|
||||
private screen: ReturnType<typeof createTerminalTextRenderer> | null = null;
|
||||
private pendingScreenSeparator = false;
|
||||
private preScreenSgr = createReplaySgrTracker();
|
||||
private readonly maxBufferedCells: number;
|
||||
|
||||
constructor(options: ReplaySafeTerminalLogSanitizerOptions = {}) {
|
||||
this.alternateScreenActive = options.alternateScreenActive === true;
|
||||
this.maxBufferedCells =
|
||||
typeof options.maxBufferedCells === "number"
|
||||
&& Number.isFinite(options.maxBufferedCells)
|
||||
&& options.maxBufferedCells > 0
|
||||
? Math.floor(options.maxBufferedCells)
|
||||
: MAX_BUFFERED_SCREEN_CELLS;
|
||||
}
|
||||
|
||||
append(input: string): string {
|
||||
@@ -193,13 +218,36 @@ class ReplaySafeTerminalLogSanitizerImpl implements ReplaySafeTerminalLogSanitiz
|
||||
const data = this.pendingInput + input;
|
||||
this.pendingInput = "";
|
||||
|
||||
const appendOutput = (next: string) => {
|
||||
const appendOutput = (next: string, visible: boolean) => {
|
||||
if (!next) return;
|
||||
output += next;
|
||||
this.hasOutput = true;
|
||||
if (visible) this.hasVisibleOutput = true;
|
||||
this.lastOutputChar = next[next.length - 1];
|
||||
};
|
||||
|
||||
const emitScreenText = (text: string, screenBoundary: boolean) => {
|
||||
if (!text) {
|
||||
if (screenBoundary && this.hasVisibleOutput) {
|
||||
this.pendingScreenSeparator = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const prefix = this.pendingScreenSeparator ? "\r\n" : "";
|
||||
this.pendingScreenSeparator = screenBoundary;
|
||||
appendOutput(prefix + text, true);
|
||||
};
|
||||
|
||||
const drainScreen = () => {
|
||||
if (!this.screen) return;
|
||||
const segments = this.screen.drainReplayAnsi({
|
||||
maxBufferedLines: MAX_BUFFERED_SCREEN_LINES,
|
||||
maxBufferedCells: this.maxBufferedCells,
|
||||
});
|
||||
for (const segment of segments) {
|
||||
emitScreenText(segment.text, segment.screenBoundary);
|
||||
}
|
||||
};
|
||||
|
||||
if (
|
||||
!this.alternateScreenActive
|
||||
&& !this.pendingCursorHome
|
||||
@@ -207,20 +255,34 @@ class ReplaySafeTerminalLogSanitizerImpl implements ReplaySafeTerminalLogSanitiz
|
||||
&& !this.controlStringMode
|
||||
&& !hasReplayControlCandidate(data)
|
||||
) {
|
||||
appendOutput(data);
|
||||
if (data) {
|
||||
this.inClearCluster = false;
|
||||
if (this.screen) {
|
||||
if (data) {
|
||||
this.screen.feed(data);
|
||||
drainScreen();
|
||||
}
|
||||
return output;
|
||||
}
|
||||
appendOutput(data, true);
|
||||
return output;
|
||||
}
|
||||
|
||||
const trackEmittedCsiSgr = (csiText: string) => {
|
||||
for (let idx = 0; idx < csiText.length;) {
|
||||
const seq = readCsiSequence(csiText, idx);
|
||||
if (!seq) break;
|
||||
if (isSgrSequence(seq)) {
|
||||
this.preScreenSgr.apply(seq.params);
|
||||
}
|
||||
idx = seq.end;
|
||||
}
|
||||
};
|
||||
|
||||
const flushPendingCursorHome = () => {
|
||||
if (!this.pendingCursorHome) return;
|
||||
if (this.protectingClearedHistory) {
|
||||
appendOutput(this.replaySafePendingAfterCursorHome);
|
||||
} else {
|
||||
appendOutput(this.pendingCursorHome);
|
||||
appendOutput(this.pendingAfterCursorHome);
|
||||
appendOutput(this.pendingCursorHome, false);
|
||||
if (this.pendingAfterCursorHome) {
|
||||
trackEmittedCsiSgr(this.pendingAfterCursorHome);
|
||||
appendOutput(this.pendingAfterCursorHome, false);
|
||||
}
|
||||
this.pendingCursorHome = "";
|
||||
this.pendingAfterCursorHome = "";
|
||||
@@ -228,18 +290,36 @@ class ReplaySafeTerminalLogSanitizerImpl implements ReplaySafeTerminalLogSanitiz
|
||||
this.pendingAfterCursorHomeOverflowed = false;
|
||||
};
|
||||
|
||||
const emitClearSeparator = (preservePendingControls: boolean) => {
|
||||
const enterProtectedScreen = (preservePendingControls: boolean, resetSgr = false) => {
|
||||
const preservedControls = preservePendingControls ? this.replaySafePendingAfterCursorHome : "";
|
||||
const initialSgr = resetSgr ? "" : this.preScreenSgr.toAnsiSgr();
|
||||
const needsReplaySgrReset = this.preScreenSgr.hasActiveStyle();
|
||||
this.preScreenSgr.reset();
|
||||
this.pendingCursorHome = "";
|
||||
this.pendingAfterCursorHome = "";
|
||||
this.replaySafePendingAfterCursorHome = "";
|
||||
this.pendingAfterCursorHomeOverflowed = false;
|
||||
if (!this.inClearCluster && this.hasOutput) {
|
||||
appendOutput(/[\r\n]$/.test(this.lastOutputChar) ? "\r\n" : "\r\n\r\n");
|
||||
const needsLineBreak = this.hasVisibleOutput && !/[\r\n]$/.test(this.lastOutputChar);
|
||||
if (needsReplaySgrReset) {
|
||||
appendOutput("\x1b[0m", false);
|
||||
}
|
||||
if (this.hasVisibleOutput) {
|
||||
if (needsLineBreak) {
|
||||
appendOutput("\r\n", false);
|
||||
}
|
||||
this.pendingScreenSeparator = true;
|
||||
}
|
||||
this.screen = createTerminalTextRenderer({
|
||||
preserveClearedScreens: true,
|
||||
maxBufferedLines: MAX_BUFFERED_SCREEN_LINES,
|
||||
maxBufferedCells: this.maxBufferedCells,
|
||||
});
|
||||
if (initialSgr) {
|
||||
this.screen.feed(initialSgr);
|
||||
}
|
||||
if (preservedControls) {
|
||||
this.screen.feed(preservedControls);
|
||||
}
|
||||
appendOutput(preservedControls);
|
||||
this.inClearCluster = true;
|
||||
this.protectingClearedHistory = true;
|
||||
};
|
||||
|
||||
for (let i = 0; i < data.length;) {
|
||||
@@ -287,34 +367,31 @@ class ReplaySafeTerminalLogSanitizerImpl implements ReplaySafeTerminalLogSanitiz
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isCursorHomeSequence(sequence)) {
|
||||
if (!this.inClearCluster) {
|
||||
if (!this.pendingCursorHome) {
|
||||
flushPendingCursorHome();
|
||||
}
|
||||
this.pendingCursorHome = sequence.raw;
|
||||
}
|
||||
if (this.screen) {
|
||||
this.screen.feed(sequence.raw);
|
||||
drainScreen();
|
||||
i = sequence.end;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.protectingClearedHistory && isUnsafeCursorReplaySequence(sequence)) {
|
||||
if (isCursorHomeSequence(sequence)) {
|
||||
if (!this.pendingCursorHome) {
|
||||
flushPendingCursorHome();
|
||||
}
|
||||
this.pendingCursorHome = sequence.raw;
|
||||
i = sequence.end;
|
||||
continue;
|
||||
}
|
||||
|
||||
const eraseMode = getEraseDisplayMode(sequence);
|
||||
if (eraseMode !== null) {
|
||||
if (eraseMode === 3) {
|
||||
emitClearSeparator(false);
|
||||
} else if (eraseMode === 1) {
|
||||
emitClearSeparator(false);
|
||||
if (eraseMode === 3 || eraseMode === 1) {
|
||||
enterProtectedScreen(false);
|
||||
} else if (eraseMode === 2 || (eraseMode === 0 && this.pendingCursorHome)) {
|
||||
emitClearSeparator(true);
|
||||
enterProtectedScreen(true);
|
||||
} else {
|
||||
flushPendingCursorHome();
|
||||
appendOutput(sequence.raw);
|
||||
this.inClearCluster = false;
|
||||
appendOutput(sequence.raw, false);
|
||||
}
|
||||
i = sequence.end;
|
||||
continue;
|
||||
@@ -326,19 +403,15 @@ class ReplaySafeTerminalLogSanitizerImpl implements ReplaySafeTerminalLogSanitiz
|
||||
continue;
|
||||
}
|
||||
|
||||
const preserveClearCluster = this.inClearCluster;
|
||||
flushPendingCursorHome();
|
||||
appendOutput(sequence.raw);
|
||||
this.inClearCluster = preserveClearCluster;
|
||||
if (isSgrSequence(sequence)) {
|
||||
this.preScreenSgr.apply(sequence.params);
|
||||
}
|
||||
appendOutput(sequence.raw, false);
|
||||
i = sequence.end;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.protectingClearedHistory && isC1SingleCharCursorControl(data[i])) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.alternateScreenActive) {
|
||||
if (data[i] === ESC && i + 1 >= data.length) {
|
||||
this.setPendingEscapeInput(data.slice(i));
|
||||
@@ -349,7 +422,12 @@ class ReplaySafeTerminalLogSanitizerImpl implements ReplaySafeTerminalLogSanitiz
|
||||
// shell output is not dropped from the connection log.
|
||||
if (data[i] === ESC && data[i + 1] === "c") {
|
||||
this.alternateScreenActive = false;
|
||||
emitClearSeparator(false);
|
||||
if (this.screen) {
|
||||
this.screen.feed("\x1bc");
|
||||
drainScreen();
|
||||
} else {
|
||||
enterProtectedScreen(false, true);
|
||||
}
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
@@ -358,6 +436,49 @@ class ReplaySafeTerminalLogSanitizerImpl implements ReplaySafeTerminalLogSanitiz
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.screen) {
|
||||
if (isC1SingleCharCursorControl(data[i])) {
|
||||
this.screen.feed(data[i]);
|
||||
drainScreen();
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (data[i] === ESC) {
|
||||
if (i + 1 >= data.length) {
|
||||
this.setPendingEscapeInput(data.slice(i));
|
||||
break;
|
||||
}
|
||||
if (isEscIntermediateByte(data[i + 1])) {
|
||||
let j = i + 1;
|
||||
while (j < data.length && isEscIntermediateByte(data[j])) {
|
||||
j += 1;
|
||||
}
|
||||
if (j >= data.length) {
|
||||
if (j - i > MAX_PENDING_ESCAPE_CHARS) {
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
this.setPendingEscapeInput(data.slice(i));
|
||||
break;
|
||||
}
|
||||
i = j + 1;
|
||||
continue;
|
||||
}
|
||||
this.screen.feed(data.slice(i, i + 2));
|
||||
drainScreen();
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
const nextControl = nextReplayControlCandidate(data, i + 1);
|
||||
const end = nextControl === -1 ? data.length : nextControl;
|
||||
this.screen.feed(data.slice(i, end));
|
||||
drainScreen();
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (data[i] === ESC) {
|
||||
if (i + 1 >= data.length) {
|
||||
this.setPendingEscapeInput(data.slice(i));
|
||||
@@ -366,17 +487,7 @@ class ReplaySafeTerminalLogSanitizerImpl implements ReplaySafeTerminalLogSanitiz
|
||||
|
||||
if (data[i + 1] === "c") {
|
||||
this.alternateScreenActive = false;
|
||||
emitClearSeparator(false);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.protectingClearedHistory && (data[i + 1] === "7" || data[i + 1] === "8")) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.protectingClearedHistory && isEscSingleCharCursorControl(data[i + 1])) {
|
||||
enterProtectedScreen(false, true);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
@@ -387,8 +498,7 @@ class ReplaySafeTerminalLogSanitizerImpl implements ReplaySafeTerminalLogSanitiz
|
||||
flushPendingCursorHome();
|
||||
const nextControl = nextReplayControlCandidate(data, i + 1);
|
||||
const end = nextControl === -1 ? data.length : nextControl;
|
||||
appendOutput(data.slice(i, end));
|
||||
this.inClearCluster = false;
|
||||
appendOutput(data.slice(i, end), true);
|
||||
i = end;
|
||||
}
|
||||
|
||||
@@ -402,9 +512,20 @@ class ReplaySafeTerminalLogSanitizerImpl implements ReplaySafeTerminalLogSanitiz
|
||||
this.discardingCsi = false;
|
||||
|
||||
let output = "";
|
||||
if (this.screen) {
|
||||
const text = this.screen.finishReplayAnsi();
|
||||
if (text) {
|
||||
const prefix = this.pendingScreenSeparator ? "\r\n" : "";
|
||||
this.pendingScreenSeparator = false;
|
||||
output = prefix + text;
|
||||
this.hasVisibleOutput = true;
|
||||
this.lastOutputChar = output[output.length - 1];
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
if (this.pendingCursorHome) {
|
||||
output = this.pendingCursorHome + this.pendingAfterCursorHome;
|
||||
this.hasOutput = true;
|
||||
this.lastOutputChar = output[output.length - 1];
|
||||
this.pendingCursorHome = "";
|
||||
this.pendingAfterCursorHome = "";
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import type { Terminal } from "@xterm/xterm";
|
||||
import type { DropEntry } from "../../lib/sftpFileUtils";
|
||||
import type { Host } from "../../types";
|
||||
import { TerminalDropNeedsSudoError } from "../../domain/sftpDropElevation";
|
||||
import {
|
||||
ActiveTerminalCwdUnavailableError,
|
||||
DEFAULT_RZ_MISSING_FALLBACK_TIMEOUT_MS,
|
||||
handleTerminalDropEntries,
|
||||
handleRemoteTerminalDropEntries,
|
||||
handleTerminalFileDrop,
|
||||
resolveTerminalDropErrorMessage,
|
||||
} from "./hooks/useTerminalDragDrop";
|
||||
import { resolvePasswordAuthSftpHost } from "../../domain/authIdentityPicker";
|
||||
@@ -61,11 +63,33 @@ test("terminal drag-drop asks to enable sudo when /root is not writable as the l
|
||||
assert.deepEqual(requestedKeys, ["terminal.dragDrop.needsSudoElevation"]);
|
||||
});
|
||||
|
||||
test("local folder drop writes only the selected path without accessing the directory tree", async () => {
|
||||
const path = "/Users/alice/projects/large-folder";
|
||||
const transfer = {
|
||||
files: [{ path }],
|
||||
get items() { throw new Error("local path insertion must not enumerate upload entries"); },
|
||||
} as unknown as DataTransfer;
|
||||
const writes: string[] = [];
|
||||
await handleTerminalFileDrop(transfer, {
|
||||
host: { ...host, protocol: "local" },
|
||||
isLocalConnection: true,
|
||||
shellType: "posix",
|
||||
resolveSftpInitialPath: async () => { throw new Error("unexpected SFTP lookup"); },
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "local",
|
||||
sessionRef: { current: "local" },
|
||||
terminalBackend: { writeToSession: (_id, data) => { writes.push(data); } },
|
||||
termRef: { current: { focus() {} } as Terminal },
|
||||
});
|
||||
|
||||
assert.deepEqual(writes, [path]);
|
||||
});
|
||||
|
||||
test("remote SSH terminal drop triggers ZMODEM drag-drop upload", async () => {
|
||||
let uploadedFiles: unknown;
|
||||
let uploadedSessionId: string | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [
|
||||
{
|
||||
file: {
|
||||
@@ -77,11 +101,8 @@ test("remote SSH terminal drop triggers ZMODEM drag-drop upload", async () => {
|
||||
},
|
||||
],
|
||||
host,
|
||||
isLocalConnection: false,
|
||||
resolveSftpInitialPath: async () => "/srv/app/current",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: {
|
||||
writeToSession: () => {},
|
||||
startZmodemDragDropUpload: async (sessionId, files) => {
|
||||
@@ -90,7 +111,6 @@ test("remote SSH terminal drop triggers ZMODEM drag-drop upload", async () => {
|
||||
return { success: true };
|
||||
},
|
||||
},
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.equal(uploadedSessionId, "session-1");
|
||||
@@ -106,7 +126,7 @@ test("remote SSH terminal drop stays on ZMODEM when rz starts", async () => {
|
||||
let openedSftp = false;
|
||||
let zmodemCallback: ((event: { type: string; transferType?: string }) => void) | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [
|
||||
{
|
||||
file: {
|
||||
@@ -118,14 +138,11 @@ test("remote SSH terminal drop stays on ZMODEM when rz starts", async () => {
|
||||
},
|
||||
],
|
||||
host,
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: () => {
|
||||
openedSftp = true;
|
||||
},
|
||||
resolveSftpInitialPath: async () => "/srv/app/current",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: {
|
||||
writeToSession: () => {},
|
||||
cancelZmodem: () => {},
|
||||
@@ -142,7 +159,6 @@ test("remote SSH terminal drop stays on ZMODEM when rz starts", async () => {
|
||||
return { success: true };
|
||||
},
|
||||
},
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.equal(openedSftp, false);
|
||||
@@ -152,7 +168,7 @@ test("remote SSH terminal drop still waits for rz after the old 2.5 second deadl
|
||||
let openedSftp = false;
|
||||
let zmodemCallback: ((event: { type: string; transferType?: string }) => void) | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [{
|
||||
file: {
|
||||
name: "report.txt",
|
||||
@@ -162,12 +178,9 @@ test("remote SSH terminal drop still waits for rz after the old 2.5 second deadl
|
||||
isDirectory: false,
|
||||
}],
|
||||
host,
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: () => { openedSftp = true; },
|
||||
resolveSftpInitialPath: async () => "/srv/app/current",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: {
|
||||
writeToSession: () => {},
|
||||
cancelZmodem: () => {},
|
||||
@@ -183,7 +196,6 @@ test("remote SSH terminal drop still waits for rz after the old 2.5 second deadl
|
||||
return { success: true };
|
||||
},
|
||||
},
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.equal(openedSftp, false);
|
||||
@@ -192,7 +204,7 @@ test("remote SSH terminal drop still waits for rz after the old 2.5 second deadl
|
||||
test("serial terminal drop does not wrap rz with an SSH shell fallback", async () => {
|
||||
let uploadCommandSeen: string | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [
|
||||
{
|
||||
file: {
|
||||
@@ -204,12 +216,9 @@ test("serial terminal drop does not wrap rz with an SSH shell fallback", async (
|
||||
},
|
||||
],
|
||||
host: { ...host, protocol: "serial" } as Host,
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: () => {},
|
||||
resolveSftpInitialPath: async () => "/srv/app/current",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: {
|
||||
writeToSession: () => {},
|
||||
cancelZmodem: () => {},
|
||||
@@ -219,7 +228,6 @@ test("serial terminal drop does not wrap rz with an SSH shell fallback", async (
|
||||
return { success: true };
|
||||
},
|
||||
},
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.equal(uploadCommandSeen, undefined);
|
||||
@@ -228,7 +236,7 @@ test("serial terminal drop does not wrap rz with an SSH shell fallback", async (
|
||||
test("telnet terminal drop does not wrap rz with an SSH shell fallback", async () => {
|
||||
let uploadCommandSeen: string | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [
|
||||
{
|
||||
file: {
|
||||
@@ -240,12 +248,9 @@ test("telnet terminal drop does not wrap rz with an SSH shell fallback", async (
|
||||
},
|
||||
],
|
||||
host: { ...host, protocol: "telnet" } as Host,
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: () => {},
|
||||
resolveSftpInitialPath: async () => "/srv/app/current",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: {
|
||||
writeToSession: () => {},
|
||||
cancelZmodem: () => {},
|
||||
@@ -255,7 +260,6 @@ test("telnet terminal drop does not wrap rz with an SSH shell fallback", async (
|
||||
return { success: true };
|
||||
},
|
||||
},
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.equal(uploadCommandSeen, undefined);
|
||||
@@ -267,10 +271,9 @@ test("network device drop falls back to SFTP upload with a freshly resolved cwd"
|
||||
let openedEntries: DropEntry[] | undefined;
|
||||
let openedSessionId: string | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries,
|
||||
host,
|
||||
isLocalConnection: false,
|
||||
isNetworkDevice: true,
|
||||
onOpenSftp: (_host, initialPath, pendingUploadEntries, sourceSessionId) => {
|
||||
openedPath = initialPath;
|
||||
@@ -281,13 +284,10 @@ test("network device drop falls back to SFTP upload with a freshly resolved cwd"
|
||||
receivedOptions = options;
|
||||
return "/srv/app/current";
|
||||
},
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: {
|
||||
writeToSession: () => {},
|
||||
},
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.deepEqual(receivedOptions, {
|
||||
@@ -307,7 +307,7 @@ test("remote SSH terminal drop falls back to SFTP when rz is unavailable", async
|
||||
let dataCallback: ((chunk: string) => void) | undefined;
|
||||
let cancelled: { sessionId: string; interrupt?: boolean } | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [
|
||||
{
|
||||
file: {
|
||||
@@ -319,7 +319,6 @@ test("remote SSH terminal drop falls back to SFTP when rz is unavailable", async
|
||||
},
|
||||
],
|
||||
host,
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: (_host, initialPath, pendingUploadEntries, sourceSessionId) => {
|
||||
openedPath = initialPath;
|
||||
openedEntries = pendingUploadEntries;
|
||||
@@ -329,9 +328,7 @@ test("remote SSH terminal drop falls back to SFTP when rz is unavailable", async
|
||||
receivedOptions = options;
|
||||
return "/srv/app/current";
|
||||
},
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: {
|
||||
writeToSession: () => {},
|
||||
onSessionData: (_sessionId: string, cb: (chunk: string) => void) => {
|
||||
@@ -352,7 +349,6 @@ test("remote SSH terminal drop falls back to SFTP when rz is unavailable", async
|
||||
return { success: true };
|
||||
},
|
||||
},
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.deepEqual(receivedOptions, {
|
||||
@@ -372,7 +368,7 @@ test("remote SSH terminal drop falls back to SFTP when rz never starts", async (
|
||||
let openedEntries: DropEntry[] | undefined;
|
||||
let cancelled: { sessionId: string; interrupt?: boolean } | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [
|
||||
{
|
||||
file: {
|
||||
@@ -384,7 +380,6 @@ test("remote SSH terminal drop falls back to SFTP when rz never starts", async (
|
||||
},
|
||||
],
|
||||
host,
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: (_host, initialPath, pendingUploadEntries) => {
|
||||
openedPath = initialPath;
|
||||
openedEntries = pendingUploadEntries;
|
||||
@@ -393,9 +388,7 @@ test("remote SSH terminal drop falls back to SFTP when rz never starts", async (
|
||||
receivedOptions = options;
|
||||
return "/srv/app/current";
|
||||
},
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: {
|
||||
writeToSession: () => {},
|
||||
onSessionData: () => () => {},
|
||||
@@ -405,7 +398,6 @@ test("remote SSH terminal drop falls back to SFTP when rz never starts", async (
|
||||
startZmodemDragDropUpload: async () => ({ success: true }),
|
||||
},
|
||||
rzMissingFallbackTimeoutMs: 1,
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.deepEqual(receivedOptions, {
|
||||
@@ -439,19 +431,16 @@ test("remote SSH folder drop uses SFTP to preserve directory structure", async (
|
||||
},
|
||||
];
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: folderEntries,
|
||||
host,
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: (_host, _initialPath, pendingUploadEntries, origin, source) => {
|
||||
openedEntries = pendingUploadEntries;
|
||||
originSessionId = origin;
|
||||
sourceSessionId = source;
|
||||
},
|
||||
resolveSftpInitialPath: async () => "/srv/app/current",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: {
|
||||
writeToSession: () => {},
|
||||
startZmodemDragDropUpload: async () => {
|
||||
@@ -459,7 +448,6 @@ test("remote SSH folder drop uses SFTP to preserve directory structure", async (
|
||||
return { success: true };
|
||||
},
|
||||
},
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.equal(zmodemStarted, false);
|
||||
@@ -472,20 +460,16 @@ test("Mosh folder drop keeps its origin but opens a fresh SFTP route", async ()
|
||||
let originSessionId: string | undefined;
|
||||
let sourceSessionId: string | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [{ file: null, relativePath: "docs", isDirectory: true }],
|
||||
host: { ...host, moshEnabled: true },
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: (_host, _path, _entries, origin, source) => {
|
||||
originSessionId = origin;
|
||||
sourceSessionId = source;
|
||||
},
|
||||
resolveSftpInitialPath: async () => "/srv/app/current",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "mosh-session",
|
||||
sessionRef: { current: "mosh-session" },
|
||||
terminalBackend: { writeToSession: () => {} },
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.equal(originSessionId, "mosh-session");
|
||||
@@ -497,7 +481,7 @@ test("ET rz fallback keeps its origin but opens a fresh SFTP route", async () =>
|
||||
let sourceSessionId: string | undefined;
|
||||
let dataCallback: ((chunk: string) => void) | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [{
|
||||
file: {
|
||||
name: "report.txt",
|
||||
@@ -507,15 +491,12 @@ test("ET rz fallback keeps its origin but opens a fresh SFTP route", async () =>
|
||||
isDirectory: false,
|
||||
}],
|
||||
host: { ...host, etEnabled: true },
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: (_host, _path, _entries, origin, source) => {
|
||||
originSessionId = origin;
|
||||
sourceSessionId = source;
|
||||
},
|
||||
resolveSftpInitialPath: async () => "/srv/app/current",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "et-session",
|
||||
sessionRef: { current: "et-session" },
|
||||
terminalBackend: {
|
||||
writeToSession: () => {},
|
||||
onSessionData: (_sessionId, callback) => {
|
||||
@@ -530,7 +511,6 @@ test("ET rz fallback keeps its origin but opens a fresh SFTP route", async () =>
|
||||
return { success: true };
|
||||
},
|
||||
},
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.equal(originSessionId, "et-session");
|
||||
@@ -541,20 +521,16 @@ test("remote SSH folder drop to /root reuses the saved host password for sudo SF
|
||||
let openedHost: Host | undefined;
|
||||
let openedPath: string | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [{ file: null, relativePath: "docs", isDirectory: true }],
|
||||
host: { ...host, password: "secret" },
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: (nextHost, initialPath) => {
|
||||
openedHost = nextHost;
|
||||
openedPath = initialPath;
|
||||
},
|
||||
resolveSftpInitialPath: async () => "/root",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: { writeToSession: () => {} },
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.equal(openedPath, "/root");
|
||||
@@ -566,21 +542,17 @@ test("remote SSH folder drop to /root reuses the saved host password for sudo SF
|
||||
test("remote SSH folder drop to /root uses a resolved identity username over a stale host username", async () => {
|
||||
let openedHost: Host | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [{ file: null, relativePath: "docs", isDirectory: true }],
|
||||
host: { ...host, username: "root", password: "secret" },
|
||||
resolvedLoginUsername: "alice",
|
||||
resolvedSudoPassword: "secret",
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: (nextHost) => {
|
||||
openedHost = nextHost;
|
||||
},
|
||||
resolveSftpInitialPath: async () => "/root",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: { writeToSession: () => {} },
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.equal(openedHost?.sftpSudo, true);
|
||||
@@ -589,20 +561,16 @@ test("remote SSH folder drop to /root uses a resolved identity username over a s
|
||||
test("remote SSH folder drop to /root uses a resolved identity password", async () => {
|
||||
let openedHost: Host | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [{ file: null, relativePath: "docs", isDirectory: true }],
|
||||
host: { ...host, identityId: "id-1" },
|
||||
resolvedSudoPassword: "identity-secret",
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: (nextHost) => {
|
||||
openedHost = nextHost;
|
||||
},
|
||||
resolveSftpInitialPath: async () => "/root",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: { writeToSession: () => {} },
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.equal(openedHost?.sftpSudo, true);
|
||||
@@ -620,19 +588,15 @@ test("folder drop after choosing deploy identity keeps its saved sudo password",
|
||||
authMethod: "password", username: "deploy", password: "deploy-secret", savedToHost: false,
|
||||
});
|
||||
let openedHost: Host | undefined;
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [{ file: null, relativePath: "docs", isDirectory: true }],
|
||||
host: sftpHost,
|
||||
resolvedLoginUsername: sftpHost.username,
|
||||
resolvedSudoPassword: identity.password,
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: (nextHost) => { openedHost = nextHost; },
|
||||
resolveSftpInitialPath: async () => "/root",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: { writeToSession: () => {} },
|
||||
termRef: { current: null },
|
||||
});
|
||||
assert.equal(openedHost?.username, "deploy");
|
||||
assert.equal(openedHost?.identityId, "deploy-id");
|
||||
@@ -644,19 +608,15 @@ test("remote SSH folder drop to /root fails closed without a saved sudo password
|
||||
let openedSftp = false;
|
||||
|
||||
await assert.rejects(
|
||||
handleTerminalDropEntries({
|
||||
handleRemoteTerminalDropEntries({
|
||||
dropEntries: [{ file: null, relativePath: "docs", isDirectory: true }],
|
||||
host,
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: () => {
|
||||
openedSftp = true;
|
||||
},
|
||||
resolveSftpInitialPath: async () => "/root",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: { writeToSession: () => {} },
|
||||
termRef: { current: null },
|
||||
}),
|
||||
TerminalDropNeedsSudoError,
|
||||
);
|
||||
@@ -667,19 +627,15 @@ test("remote SSH folder drop to /root fails closed without a saved sudo password
|
||||
test("remote SSH folder drop to the login home does not enable sudo", async () => {
|
||||
let openedHost: Host | undefined;
|
||||
|
||||
await handleTerminalDropEntries({
|
||||
await handleRemoteTerminalDropEntries({
|
||||
dropEntries: [{ file: null, relativePath: "docs", isDirectory: true }],
|
||||
host: { ...host, password: "secret" },
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: (nextHost) => {
|
||||
openedHost = nextHost;
|
||||
},
|
||||
resolveSftpInitialPath: async () => "/home/alice",
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: { writeToSession: () => {} },
|
||||
termRef: { current: null },
|
||||
});
|
||||
|
||||
assert.equal(openedHost?.sftpSudo, undefined);
|
||||
@@ -690,7 +646,7 @@ test("remote SSH folder drop refuses to guess a destination when the active shel
|
||||
let receivedOptions: unknown;
|
||||
|
||||
await assert.rejects(
|
||||
handleTerminalDropEntries({
|
||||
handleRemoteTerminalDropEntries({
|
||||
dropEntries: [
|
||||
{
|
||||
file: null,
|
||||
@@ -699,7 +655,6 @@ test("remote SSH folder drop refuses to guess a destination when the active shel
|
||||
},
|
||||
],
|
||||
host,
|
||||
isLocalConnection: false,
|
||||
onOpenSftp: () => {
|
||||
openedSftp = true;
|
||||
},
|
||||
@@ -707,13 +662,10 @@ test("remote SSH folder drop refuses to guess a destination when the active shel
|
||||
receivedOptions = options;
|
||||
return undefined;
|
||||
},
|
||||
scrollToBottomAfterProgrammaticInput: () => {},
|
||||
sessionId: "session-1",
|
||||
sessionRef: { current: "session-1" },
|
||||
terminalBackend: {
|
||||
writeToSession: () => {},
|
||||
},
|
||||
termRef: { current: null },
|
||||
}),
|
||||
/Could not determine the active terminal directory/,
|
||||
);
|
||||
|
||||
@@ -6,7 +6,8 @@ import type { TerminalContextReader } from "../../domain/terminalContextRead";
|
||||
import type { TerminalSessionExitEvent } from "../../application/state/resolveTerminalSessionExitIntent";
|
||||
import { resolveSessionTabTitle } from "../../domain/sessionTabTitle";
|
||||
import { logger } from "../../lib/logger";
|
||||
import { getDropEntryLocalPath, type DropEntry } from "../../lib/sftpFileUtils";
|
||||
import { quoteSftpPathForShell, resolveSftpTerminalShellKind } from "../../domain/sftpTerminalPath";
|
||||
import { getPathForFile, type DropEntry } from "../../lib/sftpFileUtils";
|
||||
import { normalizeLineEndings } from "../../lib/utils";
|
||||
import { resolveSnippetMultiLineRunMode } from "../../domain/snippetRunMode";
|
||||
import type {
|
||||
@@ -64,47 +65,22 @@ export interface TerminalBroadcastInputOptions {
|
||||
|
||||
export { resolveSessionTabTitle };
|
||||
|
||||
/**
|
||||
* Extract unique root paths from drop entries for local terminal path insertion.
|
||||
* For nested files, extracts the root folder path; for single files, uses the full path.
|
||||
* Paths with spaces are quoted.
|
||||
*/
|
||||
export function extractRootPathsFromDropEntries(dropEntries: DropEntry[]): string[] {
|
||||
const paths: string[] = [];
|
||||
const seenPaths = new Set<string>();
|
||||
/** The native drop contains one File per selected root, including directories. */
|
||||
export function getLocalTerminalDropPaths(files: FileList, shellType?: TerminalSession["shellType"]): string[] {
|
||||
const paths = new Set<string>();
|
||||
for (const file of Array.from(files)) {
|
||||
const path = getPathForFile(file);
|
||||
if (!path) continue;
|
||||
|
||||
for (const entry of dropEntries) {
|
||||
const fullPath = getDropEntryLocalPath(entry);
|
||||
if (!fullPath) continue;
|
||||
|
||||
const pathParts = entry.relativePath.split("/");
|
||||
|
||||
if (pathParts.length > 1) {
|
||||
const rootFolderName = pathParts[0];
|
||||
const separator = fullPath.includes("\\") ? "\\" : "/";
|
||||
|
||||
const rootFolderIndex = fullPath.lastIndexOf(separator + rootFolderName + separator);
|
||||
const altRootFolderIndex = fullPath.lastIndexOf(separator + rootFolderName);
|
||||
const folderStartIndex = rootFolderIndex !== -1
|
||||
? rootFolderIndex + 1
|
||||
: (altRootFolderIndex !== -1 ? altRootFolderIndex + 1 : -1);
|
||||
|
||||
if (folderStartIndex !== -1) {
|
||||
const folderEndIndex = folderStartIndex + rootFolderName.length;
|
||||
const folderPath = fullPath.substring(0, folderEndIndex);
|
||||
|
||||
if (!seenPaths.has(folderPath)) {
|
||||
paths.push(folderPath.includes(" ") ? `"${folderPath}"` : folderPath);
|
||||
seenPaths.add(folderPath);
|
||||
}
|
||||
}
|
||||
} else if (!seenPaths.has(fullPath)) {
|
||||
paths.push(fullPath.includes(" ") ? `"${fullPath}"` : fullPath);
|
||||
seenPaths.add(fullPath);
|
||||
const shellKind = resolveSftpTerminalShellKind(shellType, { path });
|
||||
const quoted = quoteSftpPathForShell(path, shellKind ?? "cmd");
|
||||
// With an unidentified Windows shell, use only quoting that also stays literal in PowerShell.
|
||||
if (!quoted || (!shellKind && /[$`“”„‟]/u.test(path))) {
|
||||
throw new Error("Cannot insert the dropped path into the terminal");
|
||||
}
|
||||
paths.add(quoted);
|
||||
}
|
||||
|
||||
return paths;
|
||||
return [...paths];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+56
@@ -0,0 +1,56 @@
|
||||
interface ReplayAnsiSegment {
|
||||
text: string;
|
||||
screenBoundary: boolean;
|
||||
}
|
||||
|
||||
interface SharedTerminalTextRendererOptions {
|
||||
alternateScreenActive?: boolean;
|
||||
preserveClearedScreens?: boolean;
|
||||
maxBufferedLines?: number;
|
||||
maxBufferedCells?: number;
|
||||
}
|
||||
|
||||
interface ReplaySgrTracker {
|
||||
apply(params: string): void;
|
||||
hasActiveStyle(): boolean;
|
||||
toAnsiSgr(): string;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
interface SharedTerminalTextRenderer {
|
||||
feed(input: string, timestamp?: number): void;
|
||||
finish(): string;
|
||||
getBufferedCellCount(): number;
|
||||
getBufferedLineCount(): number;
|
||||
drainReplayAnsi(options?: {
|
||||
maxBufferedLines?: number;
|
||||
maxBufferedCells?: number;
|
||||
}): ReplayAnsiSegment[];
|
||||
finishReplayAnsi(): string;
|
||||
toString(options?: {
|
||||
includePendingClearedScreen?: boolean;
|
||||
formatLine?: (line: string, timestamp?: number) => string;
|
||||
}): string;
|
||||
toHtmlContent(options?: {
|
||||
includePendingClearedScreen?: boolean;
|
||||
formatLine?: (line: string, timestamp?: number) => string;
|
||||
}): string;
|
||||
}
|
||||
|
||||
declare module "./terminalLogSanitizer.shared.cjs" {
|
||||
export function createTerminalTextRenderer(
|
||||
options?: SharedTerminalTextRendererOptions,
|
||||
): SharedTerminalTextRenderer;
|
||||
export function createReplaySgrTracker(): ReplaySgrTracker;
|
||||
export function terminalDataToPlainText(terminalData: string): string;
|
||||
export function terminalDataToHtmlContent(terminalData: string): string;
|
||||
}
|
||||
|
||||
declare module "@/domain/terminalLogSanitizer.shared.cjs" {
|
||||
export function createTerminalTextRenderer(
|
||||
options?: SharedTerminalTextRendererOptions,
|
||||
): SharedTerminalTextRenderer;
|
||||
export function createReplaySgrTracker(): ReplaySgrTracker;
|
||||
export function terminalDataToPlainText(terminalData: string): string;
|
||||
export function terminalDataToHtmlContent(terminalData: string): string;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Generated by node scripts/generate-terminal-width-data.cjs
|
||||
// Unicode 17.0.0 W/F data from get-east-asian-width 1.5.0:
|
||||
// https://github.com/sindresorhus/get-east-asian-width/tree/v1.5.0
|
||||
/*
|
||||
MIT License
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
const fullwidthRanges = [
|
||||
12288, 12288, 65281, 65376, 65504, 65510,
|
||||
];
|
||||
|
||||
const wideRanges = [
|
||||
4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203,
|
||||
9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871,
|
||||
9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934,
|
||||
9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981,
|
||||
9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069,
|
||||
10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088,
|
||||
11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350,
|
||||
12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830,
|
||||
12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255,
|
||||
65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198,
|
||||
94208, 101589, 101631, 101662, 101760, 101874, 110576, 110579, 110581, 110587, 110589, 110590,
|
||||
110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355,
|
||||
119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386,
|
||||
127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776,
|
||||
127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984,
|
||||
127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334,
|
||||
128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709,
|
||||
128716, 128716, 128720, 128722, 128725, 128728, 128732, 128735, 128747, 128748, 128756, 128764,
|
||||
128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660,
|
||||
129664, 129674, 129678, 129734, 129736, 129736, 129741, 129756, 129759, 129770, 129775, 129784,
|
||||
131072, 196605, 196608, 262141,
|
||||
];
|
||||
|
||||
module.exports = { fullwidthRanges, wideRanges };
|
||||
@@ -107,6 +107,8 @@ module.exports = {
|
||||
'domain/terminalInterruptParsing.shared.cjs',
|
||||
'domain/terminalGitChanges.cjs',
|
||||
'domain/programmaticCommandLog.shared.cjs',
|
||||
'domain/terminalLogSanitizer.shared.cjs',
|
||||
'domain/terminalWidthData.shared.cjs',
|
||||
'domain/sdkSessionIdentity.shared.cjs',
|
||||
'domain/pluginRuntimePolicy.cjs',
|
||||
'domain/pluginGitHubRepository.cjs',
|
||||
|
||||
@@ -192,7 +192,7 @@ test('real Bash vi replacement and multiline Ctrl-L remain unready through every
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
const scenarios = JSON.parse(result.stdout);
|
||||
assert.equal(scenarios.length, 2);
|
||||
assert.equal(scenarios[0].readline_line, ' ', 'bind -x confirms vi replacement leaves real input');
|
||||
assert.equal(scenarios[0].readline_line, ' ', 'commented readline buffer confirms vi replacement leaves real input');
|
||||
assert.equal(scenarios[0].states.slice(1).map(({ raw }) => raw).join(''), 'x\b \b');
|
||||
assert.equal(scenarios[1].readline_line, 'echo pending');
|
||||
const redraw = scenarios[1].states.at(-1).raw;
|
||||
|
||||
@@ -813,43 +813,19 @@ function getSshAgentSocket(identityAgent, context = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ssh-agent socket path with async validation (checks Windows service status)
|
||||
* @returns {Promise<string|null>}
|
||||
*/
|
||||
async function getAvailableAgentSocket(identityAgent, injected = {}) {
|
||||
const configuredSocket = resolveIdentityAgentPath(identityAgent, injected);
|
||||
if (identityAgent && !configuredSocket) return null;
|
||||
const platform = injected.platform || process.platform;
|
||||
if (platform === "win32") {
|
||||
const socketPath = configuredSocket || WIN_SSH_AGENT_PIPE;
|
||||
const running = isWindowsNamedPipe(socketPath)
|
||||
? await (injected.windowsPipeConnectable || windowsPipeConnectable)(socketPath)
|
||||
: socketPath === "pageant"
|
||||
? await (injected.ssh2AgentConnectable || ssh2AgentConnectable)(socketPath)
|
||||
: await (injected.cygwinAgentConnectable || cygwinAgentConnectable)(socketPath);
|
||||
return running ? socketPath : null;
|
||||
}
|
||||
async function getAvailableUnixAgentSocket(configuredSocket, injected = {}) {
|
||||
const socketPath = getSshAgentSocket(configuredSocket, injected);
|
||||
if (!socketPath) return null;
|
||||
const running = await (injected.socketAgentConnectable || socketAgentConnectable)(socketPath);
|
||||
return running ? socketPath : null;
|
||||
}
|
||||
|
||||
async function getAvailableForwardingAgentSocket(identityAgent, injected = {}) {
|
||||
const resolveAvailable = injected.getAvailableAgentSocketImpl || getAvailableAgentSocket;
|
||||
const platform = injected.platform || process.platform;
|
||||
const forwardingIdentityAgent = typeof identityAgent === "string"
|
||||
&& identityAgent.trim().replace(/^["']|["']$/g, "").trim().toLowerCase() === "none"
|
||||
? undefined
|
||||
: identityAgent;
|
||||
if (forwardingIdentityAgent || platform !== "darwin") {
|
||||
return resolveAvailable(forwardingIdentityAgent, injected);
|
||||
}
|
||||
|
||||
async function discoverDarwinAgentSocket(resolveAvailable, injected = {}) {
|
||||
const env = injected.localEnv || process.env;
|
||||
const home = injected.homedir || os.homedir();
|
||||
const inheritedCandidates = [env.SSH_AUTH_SOCK, env.SSH_AUTH_SOCKET].filter(Boolean);
|
||||
const inheritedCandidates = [env.SSH_AUTH_SOCK, env.SSH_AUTH_SOCKET]
|
||||
.map((candidate) => (typeof candidate === "string" ? candidate.trim() : ""))
|
||||
.filter(Boolean);
|
||||
const candidates = [...new Set([
|
||||
...inheritedCandidates,
|
||||
path.join(home, ".bitwarden-ssh-agent.sock"),
|
||||
@@ -874,6 +850,45 @@ async function getAvailableForwardingAgentSocket(identityAgent, injected = {}) {
|
||||
return fallbackSocket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ssh-agent socket path with async validation (checks Windows service status)
|
||||
* @returns {Promise<string|null>}
|
||||
*/
|
||||
async function getAvailableAgentSocket(identityAgent, injected = {}) {
|
||||
const hasIdentityAgent = typeof identityAgent === "string" && identityAgent.trim() !== "";
|
||||
const configuredSocket = resolveIdentityAgentPath(identityAgent, injected);
|
||||
if (hasIdentityAgent && !configuredSocket) return null;
|
||||
const platform = injected.platform || process.platform;
|
||||
if (platform === "win32") {
|
||||
const socketPath = configuredSocket || WIN_SSH_AGENT_PIPE;
|
||||
const running = isWindowsNamedPipe(socketPath)
|
||||
? await (injected.windowsPipeConnectable || windowsPipeConnectable)(socketPath)
|
||||
: socketPath === "pageant"
|
||||
? await (injected.ssh2AgentConnectable || ssh2AgentConnectable)(socketPath)
|
||||
: await (injected.cygwinAgentConnectable || cygwinAgentConnectable)(socketPath);
|
||||
return running ? socketPath : null;
|
||||
}
|
||||
if (!hasIdentityAgent && platform === "darwin") {
|
||||
const resolveAvailable = injected.getAvailableAgentSocketImpl || getAvailableUnixAgentSocket;
|
||||
return discoverDarwinAgentSocket(resolveAvailable, injected);
|
||||
}
|
||||
return getAvailableUnixAgentSocket(configuredSocket, injected);
|
||||
}
|
||||
|
||||
async function getAvailableForwardingAgentSocket(identityAgent, injected = {}) {
|
||||
const resolveAvailable = injected.getAvailableAgentSocketImpl || getAvailableAgentSocket;
|
||||
const platform = injected.platform || process.platform;
|
||||
const trimmedIdentityAgent = typeof identityAgent === "string" ? identityAgent.trim() : "";
|
||||
const forwardingIdentityAgent = trimmedIdentityAgent.replace(/^["']|["']$/g, "").trim().toLowerCase() === "none"
|
||||
? undefined
|
||||
: (trimmedIdentityAgent || undefined);
|
||||
if (forwardingIdentityAgent || platform !== "darwin") {
|
||||
return resolveAvailable(forwardingIdentityAgent, injected);
|
||||
}
|
||||
|
||||
return discoverDarwinAgentSocket(resolveAvailable, injected);
|
||||
}
|
||||
|
||||
async function getNativeOpenSshAgentSocket(identityAgent, injected = {}) {
|
||||
const socketPath = await getAvailableAgentSocket(identityAgent, injected);
|
||||
const platform = injected.platform || process.platform;
|
||||
|
||||
@@ -132,6 +132,156 @@ test("non-macOS forwarding keeps the existing agent resolution path", async () =
|
||||
assert.deepEqual(calls, [undefined]);
|
||||
});
|
||||
|
||||
async function listenFakeAgentSocket(t, socketPath, identityCount) {
|
||||
const server = net.createServer((socket) => {
|
||||
socket.once("data", () => {
|
||||
const response = Buffer.from([0, 0, 0, 5, 12, 0, 0, 0, 0]);
|
||||
response.writeUInt32BE(identityCount, 5);
|
||||
socket.write(response);
|
||||
});
|
||||
});
|
||||
await new Promise((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(socketPath, resolve);
|
||||
});
|
||||
t.after(() => server.close());
|
||||
}
|
||||
|
||||
test("macOS login discovers a connectable Bitwarden home socket with identities when no inherited env is set", async (t) => {
|
||||
const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-bw-home-"));
|
||||
t.after(() => fs.rmSync(homeDir, { recursive: true, force: true }));
|
||||
const bitwardenSocket = path.join(homeDir, ".bitwarden-ssh-agent.sock");
|
||||
await listenFakeAgentSocket(t, bitwardenSocket, 1);
|
||||
|
||||
assert.equal(await getAvailableAgentSocket(undefined, {
|
||||
platform: "darwin",
|
||||
localEnv: {},
|
||||
homedir: homeDir,
|
||||
}), bitwardenSocket);
|
||||
assert.equal(await getAvailableAgentSocket("", {
|
||||
platform: "darwin",
|
||||
localEnv: {},
|
||||
homedir: homeDir,
|
||||
}), bitwardenSocket);
|
||||
});
|
||||
|
||||
test("macOS login prefers a Bitwarden home socket with identities over an empty inherited agent", async () => {
|
||||
const inheritedSocket = "/private/tmp/com.apple.launchd.test/Listeners";
|
||||
const bitwardenSocket = "/Users/alice/.bitwarden-ssh-agent.sock";
|
||||
const checked = [];
|
||||
|
||||
const result = await getAvailableAgentSocket(undefined, {
|
||||
platform: "darwin",
|
||||
localEnv: { SSH_AUTH_SOCK: inheritedSocket },
|
||||
homedir: "/Users/alice",
|
||||
getAvailableAgentSocketImpl: async (candidate) => {
|
||||
checked.push(candidate);
|
||||
return candidate;
|
||||
},
|
||||
socketAgentIdentityCount: async (candidate) => (
|
||||
candidate === bitwardenSocket ? 1 : 0
|
||||
),
|
||||
});
|
||||
|
||||
assert.equal(result, bitwardenSocket);
|
||||
assert.deepEqual(checked, [inheritedSocket, bitwardenSocket]);
|
||||
});
|
||||
|
||||
test("macOS login keeps the inherited agent when only the inherited socket is available", async () => {
|
||||
const inheritedSocket = "/private/tmp/com.apple.launchd.test/Listeners";
|
||||
|
||||
const result = await getAvailableAgentSocket(undefined, {
|
||||
platform: "darwin",
|
||||
localEnv: { SSH_AUTH_SOCK: inheritedSocket },
|
||||
homedir: "/Users/alice",
|
||||
getAvailableAgentSocketImpl: async (candidate) => (
|
||||
candidate === inheritedSocket ? candidate : null
|
||||
),
|
||||
socketAgentIdentityCount: async () => 0,
|
||||
});
|
||||
|
||||
assert.equal(result, inheritedSocket);
|
||||
});
|
||||
|
||||
test("macOS login keeps an explicitly configured IdentityAgent path authoritative", async (t) => {
|
||||
const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-explicit-agent-"));
|
||||
t.after(() => fs.rmSync(homeDir, { recursive: true, force: true }));
|
||||
const bitwardenSocket = path.join(homeDir, ".bitwarden-ssh-agent.sock");
|
||||
const explicitSocket = path.join(homeDir, "custom.sock");
|
||||
await listenFakeAgentSocket(t, bitwardenSocket, 1);
|
||||
await listenFakeAgentSocket(t, explicitSocket, 0);
|
||||
|
||||
let identityChecks = 0;
|
||||
assert.equal(await getAvailableAgentSocket(explicitSocket, {
|
||||
platform: "darwin",
|
||||
localEnv: {},
|
||||
homedir: homeDir,
|
||||
socketAgentIdentityCount: async () => {
|
||||
identityChecks += 1;
|
||||
return 0;
|
||||
},
|
||||
}), explicitSocket);
|
||||
assert.equal(identityChecks, 0);
|
||||
|
||||
assert.equal(await getAvailableAgentSocket(path.join(homeDir, "missing.sock"), {
|
||||
platform: "darwin",
|
||||
localEnv: {},
|
||||
homedir: homeDir,
|
||||
}), null);
|
||||
});
|
||||
|
||||
test("macOS login disables agent discovery for IdentityAgent none and unresolvable values", async () => {
|
||||
const inheritedSocket = "/private/tmp/com.apple.launchd.test/Listeners";
|
||||
const injected = {
|
||||
platform: "darwin",
|
||||
localEnv: { SSH_AUTH_SOCK: inheritedSocket },
|
||||
homedir: "/Users/alice",
|
||||
getAvailableAgentSocketImpl: async () => {
|
||||
throw new Error("must not probe sockets when IdentityAgent disables login");
|
||||
},
|
||||
socketAgentIdentityCount: async () => {
|
||||
throw new Error("must not count identities when IdentityAgent disables login");
|
||||
},
|
||||
};
|
||||
|
||||
assert.equal(await getAvailableAgentSocket("none", injected), null);
|
||||
assert.equal(await getAvailableAgentSocket("\"none\"", injected), null);
|
||||
assert.equal(await getAvailableAgentSocket("$NETCATTY_UNSET_TEST_IDENTITY_AGENT", injected), null);
|
||||
});
|
||||
|
||||
test("non-macOS login with empty IdentityAgent keeps the existing resolution path", async (t) => {
|
||||
const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-linux-agent-"));
|
||||
t.after(() => fs.rmSync(homeDir, { recursive: true, force: true }));
|
||||
const bitwardenSocket = path.join(homeDir, ".bitwarden-ssh-agent.sock");
|
||||
const envSocket = path.join(homeDir, "env-agent.sock");
|
||||
await listenFakeAgentSocket(t, bitwardenSocket, 1);
|
||||
await listenFakeAgentSocket(t, envSocket, 0);
|
||||
|
||||
const previousSock = process.env.SSH_AUTH_SOCK;
|
||||
t.after(() => {
|
||||
if (previousSock === undefined) delete process.env.SSH_AUTH_SOCK;
|
||||
else process.env.SSH_AUTH_SOCK = previousSock;
|
||||
});
|
||||
|
||||
delete process.env.SSH_AUTH_SOCK;
|
||||
assert.equal(await getAvailableAgentSocket(undefined, {
|
||||
platform: "linux",
|
||||
homedir: homeDir,
|
||||
socketAgentIdentityCount: async () => {
|
||||
throw new Error("must not inspect identities outside macOS discovery");
|
||||
},
|
||||
}), null);
|
||||
|
||||
process.env.SSH_AUTH_SOCK = envSocket;
|
||||
assert.equal(await getAvailableAgentSocket(undefined, {
|
||||
platform: "linux",
|
||||
homedir: homeDir,
|
||||
socketAgentIdentityCount: async () => {
|
||||
throw new Error("must not inspect identities outside macOS discovery");
|
||||
},
|
||||
}), envSocket);
|
||||
});
|
||||
|
||||
test("explicit agent opt-out suppresses automatic socket fallback", () => {
|
||||
const auth = buildAuthHandler({
|
||||
username: "deploy",
|
||||
|
||||
@@ -144,7 +144,7 @@ test("normal SSH startup preserves fallback after an unavailable system agent",
|
||||
assert.equal(result.error, undefined);
|
||||
assert.deepEqual(result.methods, ["none", "password"]);
|
||||
assert.equal(result.shells, 1);
|
||||
assert.equal(result.agentChecks, options.stale === false ? 1 : 0);
|
||||
assert.equal(result.agentChecks, options.stale === false ? 2 : 0);
|
||||
assert.equal(result.sent.some(({ channel }) => channel === "netcatty:auth:failed"), false);
|
||||
assert.equal(result.sent.some(({ channel }) => channel === "netcatty:exit"), false);
|
||||
});
|
||||
|
||||
@@ -165,7 +165,7 @@ async function getAvailableAgentSocket() {
|
||||
return agentStatus.running ? WIN_SSH_AGENT_PIPE : null;
|
||||
}
|
||||
|
||||
return getSshAgentSocket();
|
||||
return getAvailableSystemAgentSocket();
|
||||
}
|
||||
|
||||
const SSH_DEBUG_REDACTED_KEYS = new Set([
|
||||
|
||||
@@ -1,882 +1,3 @@
|
||||
/**
|
||||
* Terminal log sanitizer.
|
||||
*
|
||||
* This is intentionally stateful: terminal output is a stream of cursor and
|
||||
* erase operations, not plain text with decoration. The renderer below keeps a
|
||||
* small virtual text buffer so plain-text and HTML logs reflect what common
|
||||
* line-editing output actually leaves on screen.
|
||||
*
|
||||
* Full-screen TUIs (vim/less/htop) use the alternate screen buffer
|
||||
* (DECSET 47/1047/1049). While that mode is active, paint is omitted so session
|
||||
* logs keep shell history instead of tilde rows and status lines.
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const { fullwidthRanges, wideRanges } = require("./terminalWidthData.cjs");
|
||||
const ZERO_WIDTH_MARK_RE = /[\p{Mn}\p{Me}]/u;
|
||||
const ZERO_WIDTH_FORMAT_RE = /(?=\p{Cf})\p{Default_Ignorable_Code_Point}/u;
|
||||
const CSI_FINAL_RE = /[@-~]/;
|
||||
|
||||
function inWidthRanges(codePoint, ranges) {
|
||||
if (codePoint < ranges[0] || codePoint > ranges.at(-1)) return false;
|
||||
let low = 0, high = ranges.length / 2 - 1;
|
||||
while (low <= high) {
|
||||
const middle = Math.floor((low + high) / 2), index = middle * 2;
|
||||
if (codePoint < ranges[index]) high = middle - 1;
|
||||
else if (codePoint > ranges[index + 1]) low = middle + 1;
|
||||
else return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// ANSI palette colors are emitted as CSS variables (with hex fallbacks) so the
|
||||
// wrapping HTML page can provide light and dark palettes. Indexes 0-7 are the
|
||||
// basic colors, 8-15 the bright colors.
|
||||
const DEFAULT_FOREGROUND = "#d4d4d4";
|
||||
const DEFAULT_BACKGROUND = "#1e1e1e";
|
||||
const BASIC_COLORS = [
|
||||
"#000000",
|
||||
"#cd3131",
|
||||
"#0dbc79",
|
||||
"#e5e510",
|
||||
"#2472c8",
|
||||
"#bc3fbc",
|
||||
"#11a8cd",
|
||||
"#e5e5e5",
|
||||
];
|
||||
const BRIGHT_COLORS = [
|
||||
"#666666",
|
||||
"#f14c4c",
|
||||
"#23d18b",
|
||||
"#f5f543",
|
||||
"#3b8eea",
|
||||
"#d670d6",
|
||||
"#29b8db",
|
||||
"#ffffff",
|
||||
];
|
||||
|
||||
function ansiColorVar(index) {
|
||||
const fallback = index < 8 ? BASIC_COLORS[index] : BRIGHT_COLORS[index - 8];
|
||||
return `var(--ansi-${index}, ${fallback})`;
|
||||
}
|
||||
|
||||
class TerminalTextRenderer {
|
||||
constructor(options = {}) {
|
||||
this.lines = [[]];
|
||||
this.row = 0;
|
||||
this.col = 0;
|
||||
this.screenBaseRow = 0;
|
||||
this.state = "normal";
|
||||
this.escapeBuffer = "";
|
||||
this.style = createDefaultStyle();
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
this.justStartedLogScreen = false;
|
||||
this.hasPreservedScreenHistory = false;
|
||||
this.pendingClearedScreen = null;
|
||||
// Seed when a session log starts while vim/less is already on the alternate buffer.
|
||||
this.alternateScreenActive = options.alternateScreenActive === true;
|
||||
}
|
||||
|
||||
feed(input, timestamp) {
|
||||
if (!input) return;
|
||||
this.timestamp = timestamp;
|
||||
|
||||
for (const ch of input) this.#consume(ch);
|
||||
}
|
||||
|
||||
finish() {
|
||||
this.state = "normal";
|
||||
this.escapeBuffer = "";
|
||||
this.#commitPendingClearedScreen();
|
||||
return this.toString();
|
||||
}
|
||||
|
||||
getCursorLine() {
|
||||
return (this.lines[this.row] || []).map(cellText).join("");
|
||||
}
|
||||
|
||||
toString({ includePendingClearedScreen = false, formatLine = (line) => line } = {}) {
|
||||
const lines = includePendingClearedScreen ? this.#linesWithPendingClearedScreen() : this.lines;
|
||||
return lines
|
||||
.map((line) => formatLine(line.map(cellText).join("").replace(/[ \t]+$/g, ""), line.timestamp))
|
||||
.join("\n")
|
||||
.replace(/\n+$/g, "");
|
||||
}
|
||||
|
||||
toHtmlContent({ includePendingClearedScreen = false, formatLine = (line) => line } = {}) {
|
||||
const lines = includePendingClearedScreen ? this.#linesWithPendingClearedScreen() : this.lines;
|
||||
return lines
|
||||
.map((line) => formatLine(renderLineHtml(line), line.timestamp))
|
||||
.join("\n")
|
||||
.replace(/\n+$/g, "");
|
||||
}
|
||||
|
||||
#consume(ch) {
|
||||
if (this.state === "esc") {
|
||||
this.#consumeEsc(ch);
|
||||
return;
|
||||
}
|
||||
if (this.state === "csi") {
|
||||
this.escapeBuffer += ch;
|
||||
if (CSI_FINAL_RE.test(ch)) {
|
||||
this.#applyCsi(this.escapeBuffer);
|
||||
this.state = "normal";
|
||||
this.escapeBuffer = "";
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.state === "osc") {
|
||||
if (ch === "\x07") {
|
||||
this.state = "normal";
|
||||
this.escapeBuffer = "";
|
||||
return;
|
||||
}
|
||||
if (ch === "\x1b") {
|
||||
this.state = "oscEsc";
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.state === "oscEsc") {
|
||||
this.state = ch === "\\" ? "normal" : "osc";
|
||||
return;
|
||||
}
|
||||
|
||||
switch (ch) {
|
||||
case "\x1b":
|
||||
this.state = "esc";
|
||||
this.escapeBuffer = "";
|
||||
break;
|
||||
case "\x9b":
|
||||
// 8-bit C1 CSI (single-byte form of ESC [). Same private modes as the
|
||||
// 7-bit sequence, including alternate-screen enter/leave.
|
||||
this.state = "csi";
|
||||
this.escapeBuffer = "";
|
||||
break;
|
||||
case "\b":
|
||||
if (this.alternateScreenActive) break;
|
||||
this.col = Math.max(0, this.col - 1);
|
||||
break;
|
||||
case "\r":
|
||||
if (this.alternateScreenActive) break;
|
||||
this.col = 0;
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
break;
|
||||
case "\n":
|
||||
if (this.alternateScreenActive) break;
|
||||
this.row += 1;
|
||||
this.col = 0;
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
this.#ensureLine();
|
||||
break;
|
||||
case "\t":
|
||||
if (this.alternateScreenActive) break;
|
||||
this.#writeText(" ".repeat(8 - (this.col % 8)));
|
||||
break;
|
||||
default:
|
||||
if (this.alternateScreenActive) break;
|
||||
if (this.#isPrintable(ch)) this.#writeText(ch);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#consumeEsc(ch) {
|
||||
if (ch === "[") {
|
||||
this.state = "csi";
|
||||
this.escapeBuffer = "";
|
||||
return;
|
||||
}
|
||||
if (ch === "]") {
|
||||
this.state = "osc";
|
||||
this.escapeBuffer = "";
|
||||
return;
|
||||
}
|
||||
// RIS (ESC c) fully resets the terminal: leave the alternate buffer, clear
|
||||
// SGR, and rebase the log screen so post-reset cursor homes cannot overwrite
|
||||
// preserved history. Prior lines stay in the log (not a live ED2 wipe).
|
||||
if (ch === "c") {
|
||||
this.#applyRisReset();
|
||||
}
|
||||
// Single-character ESC sequences are terminal controls. Ignore them for
|
||||
// logs, but consume them so they never leak into txt/html output.
|
||||
this.state = "normal";
|
||||
this.escapeBuffer = "";
|
||||
}
|
||||
|
||||
#applyRisReset() {
|
||||
this.alternateScreenActive = false;
|
||||
this.style = createDefaultStyle();
|
||||
this.pendingClearedScreen = null;
|
||||
|
||||
// Drop trailing blank rows so "before\\n" + RIS does not leave an empty
|
||||
// separator before the new screen, then base cursor-home on a fresh row.
|
||||
while (this.lines.length > 0 && getTrimmedLineLength(this.lines[this.lines.length - 1]) === 0) {
|
||||
this.lines.pop();
|
||||
}
|
||||
|
||||
if (this.lines.length === 0) {
|
||||
this.lines = [[]];
|
||||
this.row = 0;
|
||||
this.col = 0;
|
||||
this.screenBaseRow = 0;
|
||||
this.hasPreservedScreenHistory = false;
|
||||
} else {
|
||||
this.lines.push([]);
|
||||
this.screenBaseRow = this.lines.length - 1;
|
||||
this.row = this.screenBaseRow;
|
||||
this.col = 0;
|
||||
this.hasPreservedScreenHistory = true;
|
||||
}
|
||||
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
this.justStartedLogScreen = true;
|
||||
}
|
||||
|
||||
#applyCsi(sequence) {
|
||||
const final = sequence.at(-1);
|
||||
const params = sequence.slice(0, -1);
|
||||
const isPrivateMode = params.includes("?");
|
||||
const values = params
|
||||
.replace(/[?><=]/g, "")
|
||||
.split(";")
|
||||
.map((part) => {
|
||||
if (part === "") return undefined;
|
||||
const n = Number.parseInt(part, 10);
|
||||
return Number.isFinite(n) ? n : undefined;
|
||||
});
|
||||
const n = values[0] || 1;
|
||||
|
||||
if ((final === "h" || final === "l") && isPrivateMode) {
|
||||
const alternateModes = values.filter((value) => value === 47 || value === 1047 || value === 1049);
|
||||
if (alternateModes.length > 0) {
|
||||
this.alternateScreenActive = final === "h";
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.alternateScreenActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (final) {
|
||||
case "A":
|
||||
this.row = Math.max(this.screenBaseRow, this.row - n);
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
this.#ensureLine();
|
||||
break;
|
||||
case "B":
|
||||
case "E":
|
||||
this.row += n;
|
||||
if (final === "E") this.col = 0;
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
this.#ensureLine();
|
||||
break;
|
||||
case "C":
|
||||
this.col += n;
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
break;
|
||||
case "D":
|
||||
this.col = Math.max(0, this.col - n);
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
break;
|
||||
case "F":
|
||||
this.row = Math.max(this.screenBaseRow, this.row - n);
|
||||
this.col = 0;
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
this.#ensureLine();
|
||||
break;
|
||||
case "G":
|
||||
this.col = Math.max(0, n - 1);
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
break;
|
||||
case "H":
|
||||
case "f":
|
||||
this.row = this.screenBaseRow + Math.max(0, (values[0] || 1) - 1);
|
||||
this.col = Math.max(0, (values[1] || 1) - 1);
|
||||
this.cursorMovedHomeByCsi = this.row === this.screenBaseRow && this.col === 0;
|
||||
this.#ensureLine();
|
||||
break;
|
||||
case "J":
|
||||
this.#eraseDisplay(values[0] || 0);
|
||||
break;
|
||||
case "K":
|
||||
this.#eraseLine(values[0] || 0);
|
||||
break;
|
||||
case "m":
|
||||
this.#applySgr(values);
|
||||
break;
|
||||
default:
|
||||
// Unsupported CSI controls are intentionally ignored.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#applySgr(values) {
|
||||
// Cells share style snapshots. Copy before SGR mutations so earlier output
|
||||
// (including preserved cleared screens) keeps its original appearance.
|
||||
this.style = { ...this.style };
|
||||
const codes = values.length > 0 ? values : [0];
|
||||
|
||||
for (let i = 0; i < codes.length; i += 1) {
|
||||
const code = codes[i] ?? 0;
|
||||
|
||||
if (code === 0) {
|
||||
this.style = createDefaultStyle();
|
||||
} else if (code === 1) {
|
||||
this.style.bold = true;
|
||||
} else if (code === 3) {
|
||||
this.style.italic = true;
|
||||
} else if (code === 4) {
|
||||
this.style.underline = true;
|
||||
} else if (code === 7) {
|
||||
this.style.inverse = true;
|
||||
} else if (code === 22) {
|
||||
this.style.bold = false;
|
||||
} else if (code === 23) {
|
||||
this.style.italic = false;
|
||||
} else if (code === 24) {
|
||||
this.style.underline = false;
|
||||
} else if (code === 27) {
|
||||
this.style.inverse = false;
|
||||
} else if (code >= 30 && code <= 37) {
|
||||
this.style.fg = ansiColorVar(code - 30);
|
||||
} else if (code === 39) {
|
||||
this.style.fg = null;
|
||||
} else if (code >= 40 && code <= 47) {
|
||||
this.style.bg = ansiColorVar(code - 40);
|
||||
} else if (code === 49) {
|
||||
this.style.bg = null;
|
||||
} else if (code >= 90 && code <= 97) {
|
||||
this.style.fg = ansiColorVar(8 + code - 90);
|
||||
} else if (code >= 100 && code <= 107) {
|
||||
this.style.bg = ansiColorVar(8 + code - 100);
|
||||
} else if ((code === 38 || code === 48) && codes[i + 1] === 5) {
|
||||
const color = colorFromAnsi256(codes[i + 2]);
|
||||
if (color) {
|
||||
if (code === 38) this.style.fg = color;
|
||||
else this.style.bg = color;
|
||||
}
|
||||
i += 2;
|
||||
} else if ((code === 38 || code === 48) && codes[i + 1] === 2) {
|
||||
const color = colorFromRgb(codes[i + 2], codes[i + 3], codes[i + 4]);
|
||||
if (color) {
|
||||
if (code === 38) this.style.fg = color;
|
||||
else this.style.bg = color;
|
||||
}
|
||||
i += 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#writeText(text) {
|
||||
this.#ensureLine();
|
||||
const line = this.lines[this.row];
|
||||
if (this.timestamp !== undefined) line.timestamp = this.timestamp;
|
||||
while (line.length < this.col) line.push(createCell(" ", createDefaultStyle()));
|
||||
for (const ch of text) {
|
||||
const codePoint = ch.codePointAt(0);
|
||||
// Readline counts code points, including spacing marks and emoji
|
||||
// modifiers, rather than collapsing an entire grapheme into one cell.
|
||||
const zeroWidth = ZERO_WIDTH_MARK_RE.test(ch)
|
||||
|| (codePoint !== 0x00ad && ZERO_WIDTH_FORMAT_RE.test(ch))
|
||||
|| (codePoint >= 0x1160 && codePoint <= 0x11ff)
|
||||
|| (codePoint >= 0xd7b0 && codePoint <= 0xd7ff);
|
||||
const width = zeroWidth ? 0
|
||||
: inWidthRanges(codePoint, fullwidthRanges) || inWidthRanges(codePoint, wideRanges) ? 2 : 1;
|
||||
if (width === 0) {
|
||||
let previous = this.col - 1;
|
||||
if (line[previous]?.continuation) previous -= 1;
|
||||
if (previous >= 0 && line[previous]) {
|
||||
line[previous] = { ...line[previous], ch: line[previous].ch + ch };
|
||||
} else {
|
||||
line[this.col] = createCell((line[this.col]?.width === 0 ? line[this.col].ch : "") + ch,
|
||||
this.style, { width: 0 });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const prefix = line[this.col]?.width === 0 ? line[this.col].ch : "";
|
||||
for (let offset = 0; offset < width; offset += 1) this.#clearWideCellAt(line, this.col + offset);
|
||||
line[this.col] = createCell(prefix + ch, this.style, { width });
|
||||
if (width === 2) line[this.col + 1] = createCell("", this.style, { continuation: true });
|
||||
this.col += width;
|
||||
}
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
this.justStartedLogScreen = false;
|
||||
}
|
||||
|
||||
#clearWideCellAt(line, column) {
|
||||
const start = line[column]?.continuation ? column - 1 : column;
|
||||
if (line[start]?.width !== 2) return;
|
||||
// Overwriting either half removes the glyph. Preserve evidence that both
|
||||
// blank cells came from text, so a following readline erase can certify it.
|
||||
for (let i = start; i <= start + 1; i += 1) {
|
||||
line[i] = createCell(" ", createDefaultStyle());
|
||||
}
|
||||
}
|
||||
|
||||
#eraseLine(mode) {
|
||||
this.#ensureLine();
|
||||
const line = this.lines[this.row];
|
||||
const changesContent = mode === 1
|
||||
? line.slice(0, Math.min(this.col + 1, getTrimmedLineLength(line))).some((cell) =>
|
||||
cell && (cell.ch !== " " || !stylesEqual(cell.style, createDefaultStyle()))
|
||||
)
|
||||
: mode === 2 ? getTrimmedLineLength(line) > 0 : this.col < getTrimmedLineLength(line);
|
||||
if (changesContent && this.timestamp !== undefined) line.timestamp = this.timestamp;
|
||||
if (mode === 1) {
|
||||
for (let i = 0; i <= this.col && i < line.length; i += 1) {
|
||||
this.#clearWideCellAt(line, i);
|
||||
line[i] = createCell(" ", createDefaultStyle());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (mode === 2) {
|
||||
this.lines[this.row] = [];
|
||||
return;
|
||||
}
|
||||
if (line[this.col]?.continuation) this.#clearWideCellAt(line, this.col);
|
||||
line.length = Math.min(line.length, this.col);
|
||||
}
|
||||
|
||||
#eraseDisplay(mode) {
|
||||
this.#ensureLine();
|
||||
if (mode === 3 && this.pendingClearedScreen) {
|
||||
this.#commitPendingClearedScreen();
|
||||
return;
|
||||
}
|
||||
if (mode === 3) {
|
||||
this.pendingClearedScreen = null;
|
||||
return;
|
||||
}
|
||||
if (mode === 2) {
|
||||
if (this.hasPreservedScreenHistory) {
|
||||
this.#clearCurrentLogScreen({ keepPending: true });
|
||||
return;
|
||||
}
|
||||
this.#startNewLogScreen();
|
||||
return;
|
||||
}
|
||||
if (mode === 1) {
|
||||
for (let i = this.screenBaseRow; i < this.row; i += 1) {
|
||||
this.lines[i] = [];
|
||||
}
|
||||
this.#eraseLine(1);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
this.row === this.screenBaseRow &&
|
||||
this.col === 0 &&
|
||||
this.cursorMovedHomeByCsi &&
|
||||
!this.hasPreservedScreenHistory
|
||||
) {
|
||||
this.#startNewLogScreen();
|
||||
return;
|
||||
}
|
||||
this.#eraseLine(0);
|
||||
this.lines.length = this.row + 1;
|
||||
}
|
||||
|
||||
#clearCurrentLogScreen({ keepPending = false } = {}) {
|
||||
const targetRow = this.row;
|
||||
if (keepPending && this.#currentLogScreenHasContent()) {
|
||||
this.pendingClearedScreen = {
|
||||
lines: cloneLines(this.lines.slice(this.screenBaseRow)),
|
||||
baseRow: this.screenBaseRow,
|
||||
};
|
||||
} else if (!keepPending) {
|
||||
this.pendingClearedScreen = null;
|
||||
}
|
||||
for (let i = this.screenBaseRow; i < this.lines.length; i += 1) {
|
||||
this.lines[i] = [];
|
||||
}
|
||||
this.row = Math.max(this.screenBaseRow, targetRow);
|
||||
this.#ensureLine();
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
this.justStartedLogScreen = true;
|
||||
}
|
||||
|
||||
#commitPendingClearedScreen() {
|
||||
const pending = this.pendingClearedScreen;
|
||||
if (!pending) return;
|
||||
const relativeRow = Math.max(0, this.row - pending.baseRow);
|
||||
const col = this.col;
|
||||
const { lines, screenBaseRow } = this.#buildLinesWithPendingClearedScreen(pending);
|
||||
this.lines = lines;
|
||||
this.screenBaseRow = screenBaseRow;
|
||||
this.row = this.screenBaseRow + relativeRow;
|
||||
this.col = col;
|
||||
this.#ensureLine();
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
this.justStartedLogScreen = true;
|
||||
this.hasPreservedScreenHistory = true;
|
||||
this.pendingClearedScreen = null;
|
||||
}
|
||||
|
||||
#linesWithPendingClearedScreen() {
|
||||
const pending = this.pendingClearedScreen;
|
||||
if (!pending) return this.lines;
|
||||
return this.#buildLinesWithPendingClearedScreen(pending).lines;
|
||||
}
|
||||
|
||||
#buildLinesWithPendingClearedScreen(pending) {
|
||||
const prefix = this.lines.slice(0, pending.baseRow);
|
||||
const activeLines = this.lines.slice(pending.baseRow);
|
||||
const pendingLines = trimTrailingBlankLines(pending.lines);
|
||||
return {
|
||||
lines: prefix.concat(pendingLines, [[]], activeLines.length > 0 ? activeLines : [[]]),
|
||||
screenBaseRow: prefix.length + pendingLines.length + 1,
|
||||
};
|
||||
}
|
||||
|
||||
#startNewLogScreen() {
|
||||
if (this.justStartedLogScreen) return;
|
||||
const hasContent = this.lines.some((line) => getTrimmedLineLength(line) > 0);
|
||||
if (hasContent) {
|
||||
this.lines.push([]);
|
||||
this.row = this.lines.length - 1;
|
||||
} else {
|
||||
this.lines = [[]];
|
||||
this.row = 0;
|
||||
}
|
||||
this.screenBaseRow = this.row;
|
||||
this.col = 0;
|
||||
this.cursorMovedHomeByCsi = false;
|
||||
this.justStartedLogScreen = true;
|
||||
this.hasPreservedScreenHistory = hasContent;
|
||||
this.pendingClearedScreen = null;
|
||||
}
|
||||
|
||||
#currentLogScreenHasContent() {
|
||||
for (let i = this.screenBaseRow; i < this.lines.length; i += 1) {
|
||||
if (getTrimmedLineLength(this.lines[i]) > 0) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#ensureLine() {
|
||||
while (this.lines.length <= this.row) this.lines.push([]);
|
||||
}
|
||||
|
||||
#isPrintable(ch) {
|
||||
const code = ch.codePointAt(0);
|
||||
if (code === undefined) return false;
|
||||
return code >= 0x20 && code !== 0x7f;
|
||||
}
|
||||
}
|
||||
|
||||
function terminalDataToPlainText(terminalData) {
|
||||
const renderer = new TerminalTextRenderer();
|
||||
renderer.feed(terminalData || "");
|
||||
return renderer.finish();
|
||||
}
|
||||
|
||||
function terminalCursorLine(terminalData, options) {
|
||||
return terminalCursorState(terminalData, options).line;
|
||||
}
|
||||
|
||||
function terminalCursorState(terminalData, options) {
|
||||
// Prompt tracking keeps a rolling tail, so the alternate-screen entry may
|
||||
// already have scrolled off. Seed the mode that was active at the first
|
||||
// byte still in that tail; a fresh renderer would otherwise treat TUI paint
|
||||
// as the main screen.
|
||||
const renderer = new TerminalTextRenderer({
|
||||
alternateScreenActive: options?.alternateScreenActive === true,
|
||||
});
|
||||
renderer.feed(terminalData || "");
|
||||
renderer.finish();
|
||||
// A full-screen program owns the display. The main buffer may still hold
|
||||
// the shell prompt from before the alternate screen was entered.
|
||||
if (renderer.alternateScreenActive) return { line: "", column: 0 };
|
||||
return {
|
||||
line: renderer.getCursorLine(),
|
||||
column: renderer.col,
|
||||
};
|
||||
}
|
||||
|
||||
function renderCursorBoundScreenText(terminalData, options) {
|
||||
const renderer = new TerminalTextRenderer({
|
||||
alternateScreenActive: options?.alternateScreenActive === true,
|
||||
});
|
||||
renderer.feed(terminalData || "");
|
||||
renderer.finish();
|
||||
if (renderer.alternateScreenActive) return null;
|
||||
const cursorRow = renderer.row;
|
||||
const cursorCol = renderer.col;
|
||||
for (let r = cursorRow + 1; r < renderer.lines.length; r += 1) {
|
||||
if (getTrimmedLineLength(renderer.lines[r]) > 0) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const cursorLineCells = renderer.lines[cursorRow] || [];
|
||||
if (cursorLineCells[cursorCol]?.continuation) {
|
||||
return null;
|
||||
}
|
||||
for (let c = cursorCol; c < cursorLineCells.length; c += 1) {
|
||||
const cell = cursorLineCells[c];
|
||||
if (!cell || cell.continuation) continue;
|
||||
const ch = cell.ch || " ";
|
||||
if (ch !== " " && ch !== "\t") {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const cursorPrefix = cursorLineCells.slice(0, cursorCol).map(cellText).join("");
|
||||
const cursorLineText = cursorCol > cursorLineCells.length
|
||||
? `${cursorPrefix}${" ".repeat(cursorCol - cursorLineCells.length)}`
|
||||
: cursorPrefix;
|
||||
const rawLines = [];
|
||||
const trimmedAboveLines = [];
|
||||
const startRow = Math.max(0, renderer.screenBaseRow || 0);
|
||||
for (let r = startRow; r < cursorRow; r += 1) {
|
||||
const lineText = (renderer.lines[r] || []).map(cellText).join("");
|
||||
rawLines.push(lineText);
|
||||
trimmedAboveLines.push(lineText.replace(/[ \t]+$/g, ""));
|
||||
}
|
||||
rawLines.push(cursorLineText);
|
||||
trimmedAboveLines.push(cursorLineText);
|
||||
return {
|
||||
rawText: rawLines.join("\n"),
|
||||
trimmedAboveText: trimmedAboveLines.join("\n"),
|
||||
};
|
||||
}
|
||||
|
||||
// Alternate-screen transitions from TerminalTextRenderer, without a text
|
||||
// buffer. Callers replay the bytes a rolling tail dropped so truncation
|
||||
// cannot clear the guard.
|
||||
function alternateScreenActiveAfter(text, alternateScreenActive) {
|
||||
let active = alternateScreenActive === true;
|
||||
if (!text) return active;
|
||||
let state = "normal";
|
||||
let escapeBuffer = "";
|
||||
|
||||
for (const ch of text) {
|
||||
if (state === "esc") {
|
||||
if (ch === "[") {
|
||||
state = "csi";
|
||||
escapeBuffer = "";
|
||||
continue;
|
||||
}
|
||||
if (ch === "]") {
|
||||
state = "osc";
|
||||
continue;
|
||||
}
|
||||
if (ch === "c") active = false;
|
||||
state = "normal";
|
||||
continue;
|
||||
}
|
||||
if (state === "csi") {
|
||||
escapeBuffer += ch;
|
||||
if (CSI_FINAL_RE.test(ch)) {
|
||||
active = alternateScreenActiveFromCsi(escapeBuffer, active);
|
||||
state = "normal";
|
||||
escapeBuffer = "";
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (state === "osc") {
|
||||
if (ch === "\x07") state = "normal";
|
||||
else if (ch === "\x1b") state = "oscEsc";
|
||||
continue;
|
||||
}
|
||||
if (state === "oscEsc") {
|
||||
state = ch === "\\" ? "normal" : "osc";
|
||||
continue;
|
||||
}
|
||||
if (ch === "\x1b") {
|
||||
state = "esc";
|
||||
continue;
|
||||
}
|
||||
if (ch === "\x9b") {
|
||||
state = "csi";
|
||||
escapeBuffer = "";
|
||||
}
|
||||
}
|
||||
return active;
|
||||
}
|
||||
|
||||
function alternateScreenActiveFromCsi(sequence, active) {
|
||||
const final = sequence.at(-1);
|
||||
if (final !== "h" && final !== "l") return active;
|
||||
const params = sequence.slice(0, -1);
|
||||
if (!params.includes("?")) return active;
|
||||
for (const part of params.replace(/[?><=]/g, "").split(";")) {
|
||||
if (part === "") continue;
|
||||
const mode = Number.parseInt(part, 10);
|
||||
if (mode === 47 || mode === 1047 || mode === 1049) return final === "h";
|
||||
}
|
||||
return active;
|
||||
}
|
||||
|
||||
function terminalDataToHtmlContent(terminalData) {
|
||||
const renderer = new TerminalTextRenderer();
|
||||
renderer.feed(terminalData || "");
|
||||
renderer.finish();
|
||||
return renderer.toHtmlContent();
|
||||
}
|
||||
|
||||
function createTerminalTextRenderer(options = {}) {
|
||||
return new TerminalTextRenderer(options);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TerminalTextRenderer,
|
||||
createTerminalTextRenderer,
|
||||
terminalDataToHtmlContent,
|
||||
terminalDataToPlainText,
|
||||
terminalCursorLine,
|
||||
terminalCursorState,
|
||||
renderCursorBoundScreenText,
|
||||
alternateScreenActiveAfter,
|
||||
};
|
||||
|
||||
function createDefaultStyle() {
|
||||
return {
|
||||
fg: null,
|
||||
bg: null,
|
||||
bold: false,
|
||||
italic: false,
|
||||
underline: false,
|
||||
inverse: false,
|
||||
};
|
||||
}
|
||||
|
||||
function createCell(ch, style, options = {}) {
|
||||
return {
|
||||
ch,
|
||||
style,
|
||||
...options,
|
||||
};
|
||||
}
|
||||
|
||||
function cellText(cell) {
|
||||
return cell?.continuation ? "" : cell?.ch || " ";
|
||||
}
|
||||
|
||||
function cloneLines(lines) {
|
||||
return lines.map((line) => {
|
||||
const clone = line.map((cell) => (cell ? { ...cell } : cell));
|
||||
if (line.timestamp !== undefined) clone.timestamp = line.timestamp;
|
||||
return clone;
|
||||
});
|
||||
}
|
||||
|
||||
function trimTrailingBlankLines(lines) {
|
||||
let length = lines.length;
|
||||
while (length > 0 && getTrimmedLineLength(lines[length - 1]) === 0) {
|
||||
length -= 1;
|
||||
}
|
||||
return lines.slice(0, length);
|
||||
}
|
||||
|
||||
function renderLineHtml(line) {
|
||||
let html = "";
|
||||
let runText = "";
|
||||
let runStyle = null;
|
||||
|
||||
const flush = () => {
|
||||
if (!runText) return;
|
||||
const escaped = escapeHtml(runText);
|
||||
const style = styleToCss(runStyle);
|
||||
html += style ? `<span style="${style}">${escaped}</span>` : escaped;
|
||||
runText = "";
|
||||
};
|
||||
|
||||
const trimmedLength = getTrimmedLineLength(line);
|
||||
for (let i = 0; i < trimmedLength; i += 1) {
|
||||
const cell = line[i] || createCell(" ", createDefaultStyle());
|
||||
if (cell.continuation) continue;
|
||||
if (!runStyle || !stylesEqual(runStyle, cell.style)) {
|
||||
flush();
|
||||
runStyle = cell.style;
|
||||
}
|
||||
runText += cell.ch;
|
||||
}
|
||||
flush();
|
||||
return html;
|
||||
}
|
||||
|
||||
function getTrimmedLineLength(line) {
|
||||
let length = line.length;
|
||||
while (length > 0) {
|
||||
const cell = line[length - 1];
|
||||
if (cell?.continuation) break;
|
||||
const ch = cell?.ch || " ";
|
||||
if (ch !== " " && ch !== "\t") break;
|
||||
if (styleToCss(cell?.style)) break;
|
||||
length -= 1;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
function styleToCss(style) {
|
||||
if (!style) return "";
|
||||
const declarations = [];
|
||||
let fg = style.inverse
|
||||
? (style.bg || `var(--term-default-bg, ${DEFAULT_BACKGROUND})`)
|
||||
: style.fg;
|
||||
let bg = style.inverse
|
||||
? (style.fg || `var(--term-default-fg, ${DEFAULT_FOREGROUND})`)
|
||||
: style.bg;
|
||||
// Theme the normal page foreground, but preserve the original color pair
|
||||
// when output supplies a background (including a foreground inverted into
|
||||
// one). Darkening foregrounds independently can make these runs unreadable.
|
||||
if (style.bg || (style.inverse && style.fg)) {
|
||||
const originalColor = (color) => color?.replace(/var\(--[\w-]+, (#[a-f0-9]{6})\)/g, "$1");
|
||||
fg = originalColor(fg) || DEFAULT_FOREGROUND;
|
||||
bg = originalColor(bg);
|
||||
} else if (fg?.startsWith("#")) {
|
||||
// The wrapper supplies a readable light variant for extended/true colors.
|
||||
fg = `var(--term-custom-${fg.slice(1)}, ${fg})`;
|
||||
}
|
||||
if (fg) declarations.push(`color: ${fg}`);
|
||||
if (bg) declarations.push(`background-color: ${bg}`);
|
||||
if (style.bold) declarations.push("font-weight: 700");
|
||||
if (style.italic) declarations.push("font-style: italic");
|
||||
if (style.underline) declarations.push("text-decoration: underline");
|
||||
return declarations.join("; ");
|
||||
}
|
||||
|
||||
function stylesEqual(a, b) {
|
||||
return (
|
||||
a.fg === b.fg &&
|
||||
a.bg === b.bg &&
|
||||
a.bold === b.bold &&
|
||||
a.italic === b.italic &&
|
||||
a.underline === b.underline &&
|
||||
a.inverse === b.inverse
|
||||
);
|
||||
}
|
||||
|
||||
function colorFromAnsi256(value) {
|
||||
if (!Number.isInteger(value) || value < 0 || value > 255) return null;
|
||||
if (value < 16) return ansiColorVar(value);
|
||||
if (value < 232) {
|
||||
const n = value - 16;
|
||||
const r = Math.floor(n / 36);
|
||||
const g = Math.floor((n % 36) / 6);
|
||||
const b = n % 6;
|
||||
return colorFromRgb(colorCubeValue(r), colorCubeValue(g), colorCubeValue(b));
|
||||
}
|
||||
const level = 8 + (value - 232) * 10;
|
||||
return colorFromRgb(level, level, level);
|
||||
}
|
||||
|
||||
function colorCubeValue(n) {
|
||||
return n === 0 ? 0 : 55 + n * 40;
|
||||
}
|
||||
|
||||
function colorFromRgb(r, g, b) {
|
||||
if (![r, g, b].every((part) => Number.isInteger(part) && part >= 0 && part <= 255)) {
|
||||
return null;
|
||||
}
|
||||
return `#${hex2(r)}${hex2(g)}${hex2(b)}`;
|
||||
}
|
||||
|
||||
function hex2(value) {
|
||||
return value.toString(16).padStart(2, "0");
|
||||
}
|
||||
|
||||
function escapeHtml(str) {
|
||||
return str
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
module.exports = require("../../domain/terminalLogSanitizer.shared.cjs");
|
||||
@@ -437,3 +437,179 @@ test("pending cleared-screen clones share immutable styles but retain independen
|
||||
assert.equal(renderer.toString({ includePendingClearedScreen: true }), "first\nold\n\nnew");
|
||||
assert.equal(renderer.toHtmlContent({ includePendingClearedScreen: true }), 'first\n<span style="color: var(--ansi-1, #cd3131)">old</span>\n\n<span style="color: var(--ansi-2, #0dbc79)">new</span>');
|
||||
});
|
||||
|
||||
test("preserveClearedScreens commits pending ED2 history before subsequent display clears", () => {
|
||||
const input = "old\r\n\x1b[2Jone\r\n\x1b[2J\x1b[Htwo\r\n\x1b[2J\x1b[Hthree\r\n\x1b[2J\x1b[Hfour\r\n";
|
||||
|
||||
const fullRenderer = createTerminalTextRenderer({ preserveClearedScreens: true });
|
||||
fullRenderer.feed(input);
|
||||
assert.equal(fullRenderer.finish(), "old\n\none\n\ntwo\n\nthree\n\nfour");
|
||||
|
||||
const replayRenderer = createTerminalTextRenderer({ preserveClearedScreens: true });
|
||||
replayRenderer.feed(input);
|
||||
const drained = replayRenderer.drainReplayAnsi().map((segment) => segment.text);
|
||||
const tail = replayRenderer.finishReplayAnsi();
|
||||
const combined = `${drained.join("\r\n")}\r\n${tail}`;
|
||||
assert.equal(terminalDataToPlainText(combined), "old\n\none\n\ntwo\n\nthree\n\nfour");
|
||||
});
|
||||
|
||||
test("successive home + ED0 honors preserveClearedScreens without changing default TUI dedup", () => {
|
||||
const input = "\x1b[2Jone\n\x1b[H\x1b[Jtwo\n\x1b[H\x1b[Jthree\n";
|
||||
|
||||
// Default renderer keeps TUI-style home+ED0 deduplication.
|
||||
assert.equal(terminalDataToPlainText(input), "one\n\nthree");
|
||||
const defaultRenderer = createTerminalTextRenderer();
|
||||
defaultRenderer.feed(input);
|
||||
assert.equal(defaultRenderer.finish(), "one\n\nthree");
|
||||
|
||||
// preserveClearedScreens commits intermediate home+ED0 screens like ED2.
|
||||
const preservingRenderer = createTerminalTextRenderer({ preserveClearedScreens: true });
|
||||
preservingRenderer.feed(input);
|
||||
assert.equal(preservingRenderer.finish(), "one\n\ntwo\n\nthree");
|
||||
|
||||
const replayRenderer = createTerminalTextRenderer({ preserveClearedScreens: true });
|
||||
replayRenderer.feed(input);
|
||||
const drained = replayRenderer.drainReplayAnsi().map((segment) => segment.text);
|
||||
const tail = replayRenderer.finishReplayAnsi();
|
||||
const combined = `${drained.join("\r\n")}\r\n${tail}`;
|
||||
assert.equal(terminalDataToPlainText(combined), "one\n\ntwo\n\nthree");
|
||||
});
|
||||
|
||||
test("maxBufferedCells bounds newline-free live virtual screen during feed and keeps cursor consistent", () => {
|
||||
const cap = 1000;
|
||||
const renderer = createTerminalTextRenderer({
|
||||
preserveClearedScreens: true,
|
||||
maxBufferedCells: cap,
|
||||
});
|
||||
|
||||
renderer.feed(`\x1b[2J${"a".repeat(cap * 25)}END\b!`);
|
||||
const rawCellCount = renderer.lines.reduce((sum, line) => sum + line.length, 0);
|
||||
assert.equal(renderer.getBufferedCellCount(), rawCellCount);
|
||||
assert.equal(rawCellCount <= cap, true);
|
||||
assert.equal(renderer.col <= cap, true);
|
||||
|
||||
// Subsequent writes, drain, and finish remain consistent and never throw.
|
||||
renderer.feed("\r\nnext");
|
||||
assert.equal(renderer.getBufferedCellCount() <= cap, true);
|
||||
assert.doesNotThrow(() => renderer.drainReplayAnsi({ maxBufferedCells: cap }));
|
||||
assert.equal(renderer.getBufferedCellCount() <= cap, true);
|
||||
const finished = renderer.finishReplayAnsi();
|
||||
assert.equal(finished.includes("EN!\r\nnext"), true);
|
||||
assert.equal(renderer.getBufferedCellCount(), 0);
|
||||
});
|
||||
|
||||
test("maxBufferedCells handles wide-char boundaries, huge column jumps, and drainReplayAnsi caps", () => {
|
||||
const cap = 32;
|
||||
const wideRenderer = createTerminalTextRenderer({ maxBufferedCells: cap });
|
||||
wideRenderer.feed(`\x1b[2J${"\u754c".repeat(100)}Z`);
|
||||
assert.equal(wideRenderer.getBufferedCellCount() <= cap, true);
|
||||
assert.equal(wideRenderer.lines[wideRenderer.row][0]?.continuation, undefined);
|
||||
assert.equal(wideRenderer.finish().endsWith("\u754cZ"), true);
|
||||
|
||||
const jumpRenderer = createTerminalTextRenderer({ maxBufferedCells: cap });
|
||||
jumpRenderer.feed("\x1b[2J\x1b[2000000Gx");
|
||||
assert.equal(jumpRenderer.getBufferedCellCount() <= cap, true);
|
||||
assert.equal(jumpRenderer.finish().endsWith("x"), true);
|
||||
|
||||
const drainBounded = createTerminalTextRenderer({ preserveClearedScreens: true });
|
||||
drainBounded.feed(`\x1b[2J${"b".repeat(500)}TAIL`);
|
||||
assert.equal(drainBounded.getBufferedCellCount(), 504);
|
||||
drainBounded.drainReplayAnsi({ maxBufferedCells: 64 });
|
||||
assert.equal(drainBounded.getBufferedCellCount() <= 64, true);
|
||||
assert.equal(drainBounded.finishReplayAnsi().endsWith("TAIL"), true);
|
||||
});
|
||||
|
||||
test("clamps pathological CUP/CUD/VPA row jumps and empty-row floods before allocation when bounded", () => {
|
||||
const capCells = 100_000;
|
||||
const capLines = 1000;
|
||||
const payloads = [
|
||||
"\x1b[2J\x1b[100000000;1Hhi",
|
||||
"\x1bc\x1b[100000000;1Hhi",
|
||||
"\x1b[2J\x1b[100000000Bhi",
|
||||
"\x1b[2J\x1b[100000000Ehi",
|
||||
"\x1b[2J\x1b[100000000dhi",
|
||||
"\x1b[2J\x1b[100000000ehi",
|
||||
`\x1b[2J${"\n".repeat(5_000)}hi`,
|
||||
];
|
||||
|
||||
for (const payload of payloads) {
|
||||
const start = Date.now();
|
||||
const renderer = createTerminalTextRenderer({
|
||||
preserveClearedScreens: true,
|
||||
maxBufferedCells: capCells,
|
||||
});
|
||||
assert.doesNotThrow(() => renderer.feed(payload));
|
||||
const elapsedMs = Date.now() - start;
|
||||
assert.equal(elapsedMs < 2000, true);
|
||||
assert.equal(renderer.lines.length <= capLines, true);
|
||||
assert.equal(renderer.getBufferedLineCount() <= capLines, true);
|
||||
assert.equal(renderer.getBufferedCellCount() <= capCells, true);
|
||||
const out = renderer.drainReplayAnsi().map((s) => s.text).join("") + renderer.finishReplayAnsi();
|
||||
assert.equal(out.endsWith("hi"), true);
|
||||
}
|
||||
});
|
||||
|
||||
test("spills completed lines during feed instead of discarding them under maxBufferedCells", () => {
|
||||
const capCells = 100_000;
|
||||
const lineCount = 900;
|
||||
const padding = "x".repeat(140);
|
||||
const makeLine = (i) => `line-${String(i).padStart(4, "0")}-${padding}`;
|
||||
|
||||
// Incremental feed + drainReplayAnsi (one line per feed, matching Codex repro).
|
||||
const incremental = createTerminalTextRenderer({
|
||||
preserveClearedScreens: true,
|
||||
maxBufferedLines: 1000,
|
||||
maxBufferedCells: capCells,
|
||||
});
|
||||
incremental.feed("\x1b[2J");
|
||||
let incrementalAnsi = "";
|
||||
let drainedDuringFeed = false;
|
||||
for (let i = 0; i < lineCount; i += 1) {
|
||||
incremental.feed(`${makeLine(i)}\r\n`);
|
||||
assert.equal(incremental.getBufferedCellCount() <= capCells, true);
|
||||
const segments = incremental.drainReplayAnsi({
|
||||
maxBufferedLines: 1000,
|
||||
maxBufferedCells: capCells,
|
||||
});
|
||||
if (segments.length > 0) {
|
||||
drainedDuringFeed = true;
|
||||
incrementalAnsi += segments.map((s) => s.text).join("");
|
||||
}
|
||||
assert.equal(incremental.getBufferedCellCount() <= capCells, true);
|
||||
assert.equal(incremental.lines.length <= 1000, true);
|
||||
}
|
||||
incrementalAnsi += incremental.finishReplayAnsi();
|
||||
assert.equal(drainedDuringFeed, true);
|
||||
const incrementalLines = terminalDataToPlainText(incrementalAnsi).split("\n");
|
||||
assert.equal(incrementalLines.length, lineCount);
|
||||
assert.equal(incrementalLines[0], makeLine(0));
|
||||
assert.equal(incrementalLines[336], makeLine(336));
|
||||
assert.equal(incrementalLines[337], makeLine(337));
|
||||
assert.equal(incrementalLines[lineCount - 1], makeLine(lineCount - 1));
|
||||
|
||||
// Single large feed() must spill during ingest and preserve all lines on finish() / finishReplayAnsi().
|
||||
const bulkInput = `\x1b[2J${Array.from({ length: lineCount }, (_, i) => `${makeLine(i)}\r\n`).join("")}`;
|
||||
|
||||
const finishPlainRenderer = createTerminalTextRenderer({
|
||||
preserveClearedScreens: true,
|
||||
maxBufferedCells: capCells,
|
||||
});
|
||||
finishPlainRenderer.feed(bulkInput);
|
||||
assert.equal(finishPlainRenderer.getBufferedCellCount() <= capCells, true);
|
||||
assert.equal(finishPlainRenderer.lines.length <= 1000, true);
|
||||
const plainLines = finishPlainRenderer.finish().split("\n");
|
||||
assert.equal(plainLines.length, lineCount);
|
||||
assert.equal(plainLines[0], makeLine(0));
|
||||
assert.equal(plainLines[lineCount - 1], makeLine(lineCount - 1));
|
||||
|
||||
const finishAnsiRenderer = createTerminalTextRenderer({
|
||||
preserveClearedScreens: true,
|
||||
maxBufferedCells: capCells,
|
||||
});
|
||||
finishAnsiRenderer.feed(bulkInput);
|
||||
assert.equal(finishAnsiRenderer.getBufferedCellCount() <= capCells, true);
|
||||
const ansiLines = terminalDataToPlainText(finishAnsiRenderer.finishReplayAnsi()).split("\n");
|
||||
assert.equal(ansiLines.length, lineCount);
|
||||
assert.equal(ansiLines[0], makeLine(0));
|
||||
assert.equal(ansiLines[lineCount - 1], makeLine(lineCount - 1));
|
||||
});
|
||||
@@ -1,44 +1,3 @@
|
||||
// Generated by node scripts/generate-terminal-width-data.cjs
|
||||
// Unicode 17.0.0 W/F data from get-east-asian-width 1.5.0:
|
||||
// https://github.com/sindresorhus/get-east-asian-width/tree/v1.5.0
|
||||
/*
|
||||
MIT License
|
||||
"use strict";
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
const fullwidthRanges = [
|
||||
12288, 12288, 65281, 65376, 65504, 65510,
|
||||
];
|
||||
|
||||
const wideRanges = [
|
||||
4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203,
|
||||
9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871,
|
||||
9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934,
|
||||
9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981,
|
||||
9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069,
|
||||
10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088,
|
||||
11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350,
|
||||
12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830,
|
||||
12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255,
|
||||
65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198,
|
||||
94208, 101589, 101631, 101662, 101760, 101874, 110576, 110579, 110581, 110587, 110589, 110590,
|
||||
110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355,
|
||||
119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386,
|
||||
127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776,
|
||||
127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984,
|
||||
127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334,
|
||||
128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709,
|
||||
128716, 128716, 128720, 128722, 128725, 128728, 128732, 128735, 128747, 128748, 128756, 128764,
|
||||
128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660,
|
||||
129664, 129674, 129678, 129734, 129736, 129736, 129741, 129756, 129759, 129770, 129775, 129784,
|
||||
131072, 196605, 196608, 262141,
|
||||
];
|
||||
|
||||
module.exports = { fullwidthRanges, wideRanges };
|
||||
module.exports = require("../../domain/terminalWidthData.shared.cjs");
|
||||
+3
-3
@@ -1,14 +1,14 @@
|
||||
{
|
||||
version = "1.2.1";
|
||||
version = "1.2.2";
|
||||
|
||||
sources = {
|
||||
x86_64-linux = {
|
||||
appImageArch = "x86_64";
|
||||
hash = "sha256-r77kW311qvgzuhgnq9vye0Dz1tOT3PrqAJXnSXt5rns=";
|
||||
hash = "sha256-00crU+JKd/a2qgVw91/zKGB5mee2FvZr+mbscmj5rIA=";
|
||||
};
|
||||
aarch64-linux = {
|
||||
appImageArch = "arm64";
|
||||
hash = "sha256-vyeNJ+z4dHbuWx0wRfK4E+hLNbs0uq533lTt0IejowE=";
|
||||
hash = "sha256-O/xOBnQrr8QdJS0HjLc7ZrA5N2rh1woIAZO1W36DLZE=";
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -45,6 +45,8 @@ test("build.files includes shared interrupt parsing, command log, SDK session id
|
||||
"domain/terminalInterruptParsing.shared.cjs",
|
||||
"domain/terminalGitChanges.cjs",
|
||||
"domain/programmaticCommandLog.shared.cjs",
|
||||
"domain/terminalLogSanitizer.shared.cjs",
|
||||
"domain/terminalWidthData.shared.cjs",
|
||||
"domain/sdkSessionIdentity.shared.cjs",
|
||||
]) {
|
||||
assert.ok(
|
||||
|
||||
@@ -18,9 +18,12 @@ if utf8_locale is None:
|
||||
sys.exit(77)
|
||||
prompt_text = "review@\u754c\u4e3b\u673a:~$ " if "--wide-prompt" in sys.argv else "review@local:~$ "
|
||||
env.update(
|
||||
PS1=r"\[\e]133;A\a\]" + prompt_text + r"\[\e]133;B\a\]",
|
||||
PS2="> ", HISTFILE="/dev/null", TERM="dumb", LC_ALL=utf8_locale,
|
||||
INPUTRC="/dev/null", PROMPT_COMMAND="",
|
||||
# In dumb-terminal mode, Bash 3.2 backspaces over every byte marked with
|
||||
# \[...\] after displaying PS1. Keep the single-line probes well within
|
||||
# one row even when Readline counts the OSC bytes toward the prompt width.
|
||||
PS1=r"\e]133;A\a" + prompt_text + r"\e]133;B\a",
|
||||
PS2="> ", HISTFILE="/dev/null", TERM="dumb", COLUMNS="80", LC_ALL=utf8_locale,
|
||||
INPUTRC="/dev/null", PROMPT_COMMAND="", HISTCONTROL="", HISTIGNORE="", HISTSIZE="10",
|
||||
)
|
||||
def prepare_pty_child():
|
||||
os.setsid()
|
||||
@@ -137,11 +140,11 @@ rc_path = os.path.join(rc_directory.name, "bashrc")
|
||||
with open(rc_path, "w", encoding="ascii") as rc:
|
||||
rc.write(r'''PS1=$NETCATTY_TEST_PS1
|
||||
PS2="> "
|
||||
__capture_readline() { printf '\n__READLINE_BEGIN__%s__READLINE_END__\n' "$READLINE_LINE"; }
|
||||
bind -m vi-command -x '"\C-x\C-p":__capture_readline'
|
||||
__capture_readline() { printf '\n__READLINE_BEGIN__%s__READLINE_END__\n' "$(history -p '!!')"; }
|
||||
bind -m vi-command '"\C-x\C-p": insert-comment'
|
||||
bind -m vi-insert '"\C-g":abort'
|
||||
bind -m vi-insert -x '"\C-x\C-p":__capture_readline'
|
||||
bind -m emacs-standard -x '"\C-x\C-p":__capture_readline'
|
||||
bind -m vi-insert '"\C-x\C-p": insert-comment'
|
||||
bind -m emacs-standard '"\C-x\C-p": insert-comment'
|
||||
''')
|
||||
|
||||
scenarios = []
|
||||
@@ -194,17 +197,21 @@ for name, steps in cases:
|
||||
states.append(dict(step=step, raw=raw, ready=ready))
|
||||
scenario = dict(name=name, states=states)
|
||||
if risk_probes:
|
||||
os.write(master, b"\x18\x10")
|
||||
# Bash 3.2 does not expose READLINE_LINE to bind -x. Submit the
|
||||
# real buffer as a comment so history preserves even a lone blank.
|
||||
os.write(master, b"\x18\x10__capture_readline\r")
|
||||
proof = drain(b"__READLINE_END__")
|
||||
scenario["readline_line"] = proof.split("__READLINE_BEGIN__", 1)[1].split("__READLINE_END__", 1)[0]
|
||||
scenario["readline_line"] = proof.split("__READLINE_BEGIN__#", 1)[1].split("__READLINE_END__", 1)[0]
|
||||
scenarios.append(scenario)
|
||||
finally:
|
||||
if shell is not None:
|
||||
shell.kill()
|
||||
# Darwin can keep the child waiting on unread PTY output during exit.
|
||||
os.close(master)
|
||||
if shell is not None:
|
||||
shell.wait(timeout=3)
|
||||
if slave is not None:
|
||||
os.close(slave)
|
||||
os.close(master)
|
||||
|
||||
rc_directory.cleanup()
|
||||
print(json.dumps(scenarios))
|
||||
@@ -20,7 +20,7 @@ for (const name of ['fullwidthRanges', 'wideRanges']) {
|
||||
output += '];\n\n';
|
||||
}
|
||||
output += 'module.exports = { fullwidthRanges, wideRanges };\n';
|
||||
const target = path.join(__dirname, '../electron/bridges/terminalWidthData.cjs');
|
||||
const target = path.join(__dirname, '../domain/terminalWidthData.shared.cjs');
|
||||
if (process.argv.includes('--check')) {
|
||||
if (fs.readFileSync(target, 'utf8') !== output) throw new Error('Terminal width data is out of date');
|
||||
} else fs.writeFileSync(target, output);
|
||||
+3
-1
@@ -138,6 +138,8 @@ export const PREBUNDLED_LOCAL_CJS_ENTRIES = [
|
||||
'@/domain/terminalPromptSecurity.shared.cjs',
|
||||
'@/domain/terminalInterruptParsing.shared.cjs',
|
||||
'@/domain/programmaticCommandLog.shared.cjs',
|
||||
'@/domain/terminalLogSanitizer.shared.cjs',
|
||||
'@/domain/terminalWidthData.shared.cjs',
|
||||
'@/domain/sdkSessionIdentity.shared.cjs',
|
||||
'@/domain/totpPrompt.shared.cjs',
|
||||
'@/lib/localShell.cjs',
|
||||
@@ -200,7 +202,7 @@ export default defineConfig(() => {
|
||||
include: [
|
||||
/node_modules/,
|
||||
/lib\/localShell\.cjs$/,
|
||||
/domain\/(?:sshPublicKey|singleChannelSshBanner|terminalPromptSecurity|totpPrompt)\.shared\.cjs$/,
|
||||
/domain\/(?:sshPublicKey|singleChannelSshBanner|terminalPromptSecurity|totpPrompt|terminalLogSanitizer|terminalWidthData)\.shared\.cjs$/,
|
||||
/domain\/systemManager\/containerRuntime\.shared\.cjs$/,
|
||||
/domain\/plugin(?:RuntimePolicy|PermissionDescriptions|ThemePack|RemoteTreePolicy|ViewStylePolicy|GitHubRepository)\.cjs$/,
|
||||
],
|
||||
|
||||
Reference in new issue
Block a user