mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-16 20:11:08 +00:00
Refactors terminal logic into modular hooks and runtimes
Improves maintainability and code clarity by extracting authentication, search, and context menu behaviors into dedicated hooks. Moves terminal session logic into runtime/session-starter modules, reducing component complexity. Removes inline implementations in favor of reusable abstractions, streamlining prop and state management throughout the terminal UI. Enables easier future enhancements and testing by promoting separation of concerns and reducing code duplication.
This commit is contained in:
7 files changed
+1530
-1327
No files matched your search
+199
-1327
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,154 @@
|
||||
import type { Terminal as XTerm } from "@xterm/xterm";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { MutableRefObject } from "react";
|
||||
import type { Host, TerminalSession } from "../../../types";
|
||||
import type { PendingAuth } from "../runtime/createTerminalSessionStarters";
|
||||
import type { TerminalAuthMethod } from "../TerminalAuthDialog";
|
||||
import { logger } from "../../../lib/logger";
|
||||
|
||||
export const useTerminalAuthState = ({
|
||||
host,
|
||||
pendingAuthRef,
|
||||
termRef,
|
||||
onUpdateHost,
|
||||
onStartSsh,
|
||||
setStatus,
|
||||
setProgressLogs,
|
||||
}: {
|
||||
host: Host;
|
||||
pendingAuthRef: MutableRefObject<PendingAuth>;
|
||||
termRef: MutableRefObject<XTerm | null>;
|
||||
onUpdateHost?: (host: Host) => void;
|
||||
onStartSsh: (term: XTerm) => void;
|
||||
setStatus: (status: TerminalSession["status"]) => void;
|
||||
setProgressLogs: (next: string[] | ((prev: string[]) => string[])) => void;
|
||||
}) => {
|
||||
const [needsAuth, setNeedsAuth] = useState(false);
|
||||
const [authRetryMessage, setAuthRetryMessage] = useState<string | null>(null);
|
||||
const [authUsername, setAuthUsername] = useState(host.username || "root");
|
||||
const [authMethod, setAuthMethod] = useState<TerminalAuthMethod>("password");
|
||||
const [authPassword, setAuthPassword] = useState("");
|
||||
const [authKeyId, setAuthKeyId] = useState<string | null>(null);
|
||||
const [authPassphrase, setAuthPassphrase] = useState("");
|
||||
const [showAuthPassword, setShowAuthPassword] = useState(false);
|
||||
const [showAuthPassphrase, setShowAuthPassphrase] = useState(false);
|
||||
const [saveCredentials, setSaveCredentials] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
setNeedsAuth(false);
|
||||
setAuthRetryMessage(null);
|
||||
setAuthUsername(host.username || "root");
|
||||
setAuthPassword("");
|
||||
setAuthKeyId(null);
|
||||
setAuthPassphrase("");
|
||||
setShowAuthPassword(false);
|
||||
setShowAuthPassphrase(false);
|
||||
setSaveCredentials(true);
|
||||
}, [host.id, host.username]);
|
||||
|
||||
const isValid = useMemo(() => {
|
||||
if (!authUsername.trim()) return false;
|
||||
if (authMethod === "password") return authPassword.trim().length > 0;
|
||||
if (authMethod === "key" || authMethod === "certificate") return !!authKeyId;
|
||||
return false;
|
||||
}, [authKeyId, authMethod, authPassword, authUsername]);
|
||||
|
||||
const resetForRetry = useCallback(() => {
|
||||
setNeedsAuth(false);
|
||||
setAuthRetryMessage(null);
|
||||
pendingAuthRef.current = null;
|
||||
}, [pendingAuthRef]);
|
||||
|
||||
const submit = useCallback(
|
||||
(opts?: { saveToHost?: boolean }) => {
|
||||
if (!isValid) return;
|
||||
|
||||
pendingAuthRef.current = {
|
||||
authMethod,
|
||||
username: authUsername,
|
||||
password: authMethod === "password" ? authPassword : undefined,
|
||||
keyId:
|
||||
authMethod === "key" || authMethod === "certificate"
|
||||
? (authKeyId ?? undefined)
|
||||
: undefined,
|
||||
passphrase:
|
||||
authMethod === "key" || authMethod === "certificate"
|
||||
? authPassphrase || undefined
|
||||
: undefined,
|
||||
};
|
||||
|
||||
const shouldSave = opts?.saveToHost ?? saveCredentials;
|
||||
if (shouldSave && onUpdateHost) {
|
||||
const updatedHost: Host = {
|
||||
...host,
|
||||
username: authUsername,
|
||||
authMethod: authMethod,
|
||||
password: authMethod === "password" ? authPassword : undefined,
|
||||
identityFileId:
|
||||
authMethod === "key" || authMethod === "certificate"
|
||||
? (authKeyId ?? undefined)
|
||||
: undefined,
|
||||
};
|
||||
onUpdateHost(updatedHost);
|
||||
}
|
||||
|
||||
setNeedsAuth(false);
|
||||
setAuthRetryMessage(null);
|
||||
setStatus("connecting");
|
||||
setProgressLogs(["Authenticating with provided credentials..."]);
|
||||
|
||||
const term = termRef.current;
|
||||
if (!term) return;
|
||||
|
||||
try {
|
||||
term.clear?.();
|
||||
} catch (err) {
|
||||
logger.warn("Failed to clear terminal", err);
|
||||
}
|
||||
|
||||
onStartSsh(term);
|
||||
},
|
||||
[
|
||||
authKeyId,
|
||||
authMethod,
|
||||
authPassphrase,
|
||||
authPassword,
|
||||
authUsername,
|
||||
host,
|
||||
isValid,
|
||||
onStartSsh,
|
||||
onUpdateHost,
|
||||
pendingAuthRef,
|
||||
saveCredentials,
|
||||
setProgressLogs,
|
||||
setStatus,
|
||||
termRef,
|
||||
],
|
||||
);
|
||||
|
||||
return {
|
||||
needsAuth,
|
||||
setNeedsAuth,
|
||||
authRetryMessage,
|
||||
setAuthRetryMessage,
|
||||
authUsername,
|
||||
setAuthUsername,
|
||||
authMethod,
|
||||
setAuthMethod,
|
||||
authPassword,
|
||||
setAuthPassword,
|
||||
authKeyId,
|
||||
setAuthKeyId,
|
||||
authPassphrase,
|
||||
setAuthPassphrase,
|
||||
showAuthPassword,
|
||||
setShowAuthPassword,
|
||||
showAuthPassphrase,
|
||||
setShowAuthPassphrase,
|
||||
saveCredentials,
|
||||
setSaveCredentials,
|
||||
isValid,
|
||||
resetForRetry,
|
||||
submit,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { Terminal as XTerm } from "@xterm/xterm";
|
||||
import { useCallback } from "react";
|
||||
import type { MutableRefObject } from "react";
|
||||
import { logger } from "../../../lib/logger";
|
||||
|
||||
type TerminalBackendWriteApi = {
|
||||
writeToSession: (sessionId: string, data: string) => void;
|
||||
};
|
||||
|
||||
export const useTerminalContextActions = ({
|
||||
termRef,
|
||||
sessionRef,
|
||||
terminalBackend,
|
||||
onHasSelectionChange,
|
||||
}: {
|
||||
termRef: MutableRefObject<XTerm | null>;
|
||||
sessionRef: MutableRefObject<string | null>;
|
||||
terminalBackend: TerminalBackendWriteApi;
|
||||
onHasSelectionChange?: (hasSelection: boolean) => void;
|
||||
}) => {
|
||||
const onCopy = useCallback(() => {
|
||||
const term = termRef.current;
|
||||
if (!term) return;
|
||||
const selection = term.getSelection();
|
||||
if (selection) {
|
||||
navigator.clipboard.writeText(selection);
|
||||
}
|
||||
}, [termRef]);
|
||||
|
||||
const onPaste = useCallback(async () => {
|
||||
const term = termRef.current;
|
||||
if (!term) return;
|
||||
try {
|
||||
const text = await navigator.clipboard.readText();
|
||||
if (text && sessionRef.current) terminalBackend.writeToSession(sessionRef.current, text);
|
||||
} catch (err) {
|
||||
logger.warn("Failed to paste from clipboard", err);
|
||||
}
|
||||
}, [sessionRef, termRef, terminalBackend]);
|
||||
|
||||
const onSelectAll = useCallback(() => {
|
||||
const term = termRef.current;
|
||||
if (!term) return;
|
||||
term.selectAll();
|
||||
onHasSelectionChange?.(true);
|
||||
}, [onHasSelectionChange, termRef]);
|
||||
|
||||
const onClear = useCallback(() => {
|
||||
const term = termRef.current;
|
||||
if (!term) return;
|
||||
term.clear();
|
||||
}, [termRef]);
|
||||
|
||||
const onSelectWord = useCallback(() => {
|
||||
const term = termRef.current;
|
||||
if (!term) return;
|
||||
term.selectAll();
|
||||
onHasSelectionChange?.(true);
|
||||
}, [onHasSelectionChange, termRef]);
|
||||
|
||||
return { onCopy, onPaste, onSelectAll, onClear, onSelectWord };
|
||||
};
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { SearchAddon } from "@xterm/addon-search";
|
||||
import type { Terminal as XTerm } from "@xterm/xterm";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import type { MutableRefObject } from "react";
|
||||
|
||||
type SearchMatchCount = { current: number; total: number } | null;
|
||||
|
||||
export const useTerminalSearch = ({
|
||||
searchAddonRef,
|
||||
termRef,
|
||||
}: {
|
||||
searchAddonRef: MutableRefObject<SearchAddon | null>;
|
||||
termRef: MutableRefObject<XTerm | null>;
|
||||
}) => {
|
||||
const [isSearchOpen, setIsSearchOpen] = useState(false);
|
||||
const [searchMatchCount, setSearchMatchCount] = useState<SearchMatchCount>(null);
|
||||
const searchTermRef = useRef<string>("");
|
||||
|
||||
const clearSearchDecorations = useCallback(() => {
|
||||
searchAddonRef.current?.clearDecorations();
|
||||
}, [searchAddonRef]);
|
||||
|
||||
const handleToggleSearch = useCallback(() => {
|
||||
setIsSearchOpen((prev) => !prev);
|
||||
if (isSearchOpen) {
|
||||
setSearchMatchCount(null);
|
||||
clearSearchDecorations();
|
||||
}
|
||||
}, [clearSearchDecorations, isSearchOpen]);
|
||||
|
||||
const handleSearch = useCallback(
|
||||
(term: string): boolean => {
|
||||
const searchAddon = searchAddonRef.current;
|
||||
if (!searchAddon || !term) {
|
||||
setSearchMatchCount(null);
|
||||
return false;
|
||||
}
|
||||
|
||||
searchTermRef.current = term;
|
||||
searchAddon.clearDecorations();
|
||||
|
||||
const found = searchAddon.findNext(term, {
|
||||
regex: false,
|
||||
caseSensitive: false,
|
||||
wholeWord: false,
|
||||
decorations: {
|
||||
matchBackground: "#FFFF0044",
|
||||
matchBorder: "#FFFF00",
|
||||
matchOverviewRuler: "#FFFF00",
|
||||
activeMatchBackground: "#FF880088",
|
||||
activeMatchBorder: "#FF8800",
|
||||
activeMatchColorOverviewRuler: "#FF8800",
|
||||
},
|
||||
});
|
||||
|
||||
if (found) {
|
||||
setSearchMatchCount({ current: 1, total: 1 });
|
||||
} else {
|
||||
setSearchMatchCount({ current: 0, total: 0 });
|
||||
}
|
||||
|
||||
return found;
|
||||
},
|
||||
[searchAddonRef],
|
||||
);
|
||||
|
||||
const handleFindNext = useCallback((): boolean => {
|
||||
const searchAddon = searchAddonRef.current;
|
||||
const term = searchTermRef.current;
|
||||
if (!searchAddon || !term) return false;
|
||||
return searchAddon.findNext(term, {
|
||||
regex: false,
|
||||
caseSensitive: false,
|
||||
wholeWord: false,
|
||||
decorations: {
|
||||
matchBackground: "#FFFF0044",
|
||||
matchBorder: "#FFFF00",
|
||||
matchOverviewRuler: "#FFFF00",
|
||||
activeMatchBackground: "#FF880088",
|
||||
activeMatchBorder: "#FF8800",
|
||||
activeMatchColorOverviewRuler: "#FF8800",
|
||||
},
|
||||
});
|
||||
}, [searchAddonRef]);
|
||||
|
||||
const handleFindPrevious = useCallback((): boolean => {
|
||||
const searchAddon = searchAddonRef.current;
|
||||
const term = searchTermRef.current;
|
||||
if (!searchAddon || !term) return false;
|
||||
return searchAddon.findPrevious(term, {
|
||||
regex: false,
|
||||
caseSensitive: false,
|
||||
wholeWord: false,
|
||||
decorations: {
|
||||
matchBackground: "#FFFF0044",
|
||||
matchBorder: "#FFFF00",
|
||||
matchOverviewRuler: "#FFFF00",
|
||||
activeMatchBackground: "#FF880088",
|
||||
activeMatchBorder: "#FF8800",
|
||||
activeMatchColorOverviewRuler: "#FF8800",
|
||||
},
|
||||
});
|
||||
}, [searchAddonRef]);
|
||||
|
||||
const handleCloseSearch = useCallback(() => {
|
||||
setIsSearchOpen(false);
|
||||
setSearchMatchCount(null);
|
||||
clearSearchDecorations();
|
||||
termRef.current?.focus();
|
||||
}, [clearSearchDecorations, termRef]);
|
||||
|
||||
return {
|
||||
isSearchOpen,
|
||||
setIsSearchOpen,
|
||||
searchMatchCount,
|
||||
handleToggleSearch,
|
||||
handleSearch,
|
||||
handleFindNext,
|
||||
handleFindPrevious,
|
||||
handleCloseSearch,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -22,3 +22,7 @@ export { TerminalSearchBar } from './TerminalSearchBar';
|
||||
export type { TerminalSearchBarProps } from './TerminalSearchBar';
|
||||
|
||||
export { createHighlightProcessor, highlightKeywords, compileHighlightRules } from './keywordHighlight';
|
||||
|
||||
export { useTerminalSearch } from './hooks/useTerminalSearch';
|
||||
export { useTerminalContextActions } from './hooks/useTerminalContextActions';
|
||||
export { useTerminalAuthState } from './hooks/useTerminalAuthState';
|
||||
@@ -0,0 +1,530 @@
|
||||
import type { FitAddon } from "@xterm/addon-fit";
|
||||
import type { SerializeAddon } from "@xterm/addon-serialize";
|
||||
import type { Terminal as XTerm } from "@xterm/xterm";
|
||||
import type { Dispatch, MutableRefObject, SetStateAction } from "react";
|
||||
import { logger } from "../../../lib/logger";
|
||||
import type { Host, SSHKey, TerminalSession, TerminalSettings } from "../../../types";
|
||||
|
||||
type TerminalBackendApi = {
|
||||
backendAvailable: () => boolean;
|
||||
telnetAvailable: () => boolean;
|
||||
moshAvailable: () => boolean;
|
||||
localAvailable: () => boolean;
|
||||
execAvailable: () => boolean;
|
||||
startSSHSession: (options: NetcattySSHOptions) => Promise<string>;
|
||||
startTelnetSession: (
|
||||
options: Parameters<NonNullable<NetcattyBridge["startTelnetSession"]>>[0],
|
||||
) => Promise<string>;
|
||||
startMoshSession: (
|
||||
options: Parameters<NonNullable<NetcattyBridge["startMoshSession"]>>[0],
|
||||
) => Promise<string>;
|
||||
startLocalSession: (
|
||||
options: Parameters<NonNullable<NetcattyBridge["startLocalSession"]>>[0],
|
||||
) => Promise<string>;
|
||||
execCommand: (options: Parameters<NetcattyBridge["execCommand"]>[0]) => Promise<{
|
||||
stdout?: string;
|
||||
stderr?: string;
|
||||
}>;
|
||||
onSessionData: (sessionId: string, cb: (data: string) => void) => () => void;
|
||||
onSessionExit: (
|
||||
sessionId: string,
|
||||
cb: (evt: { exitCode?: number; signal?: number }) => void,
|
||||
) => () => void;
|
||||
onChainProgress: (
|
||||
cb: (hop: number, total: number, label: string, status: string) => void,
|
||||
) => (() => void) | undefined;
|
||||
writeToSession: (sessionId: string, data: string) => void;
|
||||
resizeSession: (sessionId: string, cols: number, rows: number) => void;
|
||||
};
|
||||
|
||||
export type PendingAuth = {
|
||||
authMethod: "password" | "key" | "certificate";
|
||||
username: string;
|
||||
password?: string;
|
||||
keyId?: string;
|
||||
passphrase?: string;
|
||||
} | null;
|
||||
|
||||
type ChainProgressState = {
|
||||
currentHop: number;
|
||||
totalHops: number;
|
||||
currentHostLabel: string;
|
||||
} | null;
|
||||
|
||||
export type TerminalSessionStartersContext = {
|
||||
host: Host;
|
||||
keys: SSHKey[];
|
||||
resolvedChainHosts: Host[];
|
||||
sessionId: string;
|
||||
startupCommand?: string;
|
||||
terminalSettings?: TerminalSettings;
|
||||
terminalBackend: TerminalBackendApi;
|
||||
|
||||
sessionRef: MutableRefObject<string | null>;
|
||||
hasConnectedRef: MutableRefObject<boolean>;
|
||||
hasRunStartupCommandRef: MutableRefObject<boolean>;
|
||||
disposeDataRef: MutableRefObject<(() => void) | null>;
|
||||
disposeExitRef: MutableRefObject<(() => void) | null>;
|
||||
fitAddonRef: MutableRefObject<FitAddon | null>;
|
||||
serializeAddonRef: MutableRefObject<SerializeAddon | null>;
|
||||
highlightProcessorRef: MutableRefObject<(text: string) => string>;
|
||||
pendingAuthRef: MutableRefObject<PendingAuth>;
|
||||
|
||||
updateStatus: (next: TerminalSession["status"]) => void;
|
||||
setStatus: Dispatch<SetStateAction<TerminalSession["status"]>>;
|
||||
setError: Dispatch<SetStateAction<string | null>>;
|
||||
setNeedsAuth: Dispatch<SetStateAction<boolean>>;
|
||||
setAuthRetryMessage: Dispatch<SetStateAction<string | null>>;
|
||||
setAuthPassword: Dispatch<SetStateAction<string>>;
|
||||
setProgressLogs: Dispatch<SetStateAction<string[]>>;
|
||||
setProgressValue: Dispatch<SetStateAction<number>>;
|
||||
setChainProgress: Dispatch<SetStateAction<ChainProgressState>>;
|
||||
|
||||
onSessionExit?: (sessionId: string) => void;
|
||||
onTerminalDataCapture?: (sessionId: string, data: string) => void;
|
||||
onOsDetected?: (hostId: string, distro: string) => void;
|
||||
onCommandExecuted?: (
|
||||
command: string,
|
||||
hostId: string,
|
||||
hostLabel: string,
|
||||
sessionId: string,
|
||||
) => void;
|
||||
};
|
||||
|
||||
const buildTermEnv = (host: Host, terminalSettings?: TerminalSettings) => {
|
||||
const env: Record<string, string> = {
|
||||
TERM: terminalSettings?.terminalEmulationType ?? "xterm-256color",
|
||||
};
|
||||
|
||||
if (host.environmentVariables) {
|
||||
for (const { name, value } of host.environmentVariables) {
|
||||
if (name) env[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return env;
|
||||
};
|
||||
|
||||
const attachSessionToTerminal = (
|
||||
ctx: TerminalSessionStartersContext,
|
||||
term: XTerm,
|
||||
id: string,
|
||||
opts?: {
|
||||
onExitMessage?: (evt: { exitCode?: number; signal?: number }) => string;
|
||||
onConnected?: () => void;
|
||||
},
|
||||
) => {
|
||||
ctx.sessionRef.current = id;
|
||||
|
||||
ctx.disposeDataRef.current = ctx.terminalBackend.onSessionData(id, (chunk) => {
|
||||
term.write(ctx.highlightProcessorRef.current(chunk));
|
||||
if (!ctx.hasConnectedRef.current) {
|
||||
ctx.updateStatus("connected");
|
||||
opts?.onConnected?.();
|
||||
setTimeout(() => {
|
||||
if (!ctx.fitAddonRef.current) return;
|
||||
try {
|
||||
ctx.fitAddonRef.current.fit();
|
||||
if (ctx.sessionRef.current) {
|
||||
ctx.terminalBackend.resizeSession(ctx.sessionRef.current, term.cols, term.rows);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn("Post-connect fit failed", err);
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
});
|
||||
|
||||
ctx.disposeExitRef.current = ctx.terminalBackend.onSessionExit(id, (evt) => {
|
||||
ctx.updateStatus("disconnected");
|
||||
term.writeln(opts?.onExitMessage?.(evt) ?? "\r\n[session closed]");
|
||||
|
||||
if (ctx.onTerminalDataCapture && ctx.serializeAddonRef.current) {
|
||||
try {
|
||||
const terminalData = ctx.serializeAddonRef.current.serialize();
|
||||
ctx.onTerminalDataCapture(ctx.sessionId, terminalData);
|
||||
} catch (err) {
|
||||
logger.warn("Failed to serialize terminal data:", err);
|
||||
}
|
||||
}
|
||||
|
||||
ctx.onSessionExit?.(ctx.sessionId);
|
||||
});
|
||||
};
|
||||
|
||||
const runDistroDetection = async (ctx: TerminalSessionStartersContext, key?: SSHKey) => {
|
||||
if (!ctx.terminalBackend.execAvailable()) return;
|
||||
try {
|
||||
const res = await ctx.terminalBackend.execCommand({
|
||||
hostname: ctx.host.hostname,
|
||||
username: ctx.host.username || "root",
|
||||
port: ctx.host.port || 22,
|
||||
password: ctx.host.password,
|
||||
privateKey: key?.privateKey,
|
||||
command: "cat /etc/os-release 2>/dev/null || uname -a",
|
||||
timeout: 8000,
|
||||
});
|
||||
const data = `${res.stdout || ""}\n${res.stderr || ""}`;
|
||||
const idMatch = data.match(/ID=([\\w\\-]+)/i);
|
||||
const distro = idMatch
|
||||
? idMatch[1].replace(/"/g, "")
|
||||
: (data.split(/\s+/)[0] || "").toLowerCase();
|
||||
if (distro) ctx.onOsDetected?.(ctx.host.id, distro);
|
||||
} catch (err) {
|
||||
logger.warn("OS probe failed", err);
|
||||
}
|
||||
};
|
||||
|
||||
export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContext) => {
|
||||
const startSSH = async (term: XTerm) => {
|
||||
try {
|
||||
term.clear?.();
|
||||
} catch (err) {
|
||||
logger.warn("Failed to clear terminal before connect", err);
|
||||
}
|
||||
|
||||
if (!ctx.terminalBackend.backendAvailable()) {
|
||||
ctx.setError("Native SSH bridge unavailable. Launch via Electron app.");
|
||||
term.writeln(
|
||||
"\r\n[netcatty SSH bridge unavailable. Please run the desktop build to connect.]",
|
||||
);
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
|
||||
const pendingAuth = ctx.pendingAuthRef.current;
|
||||
const effectiveUsername = pendingAuth?.username || ctx.host.username || "root";
|
||||
const effectivePassword = pendingAuth?.password || ctx.host.password;
|
||||
const effectiveKeyId = pendingAuth?.keyId || ctx.host.identityFileId;
|
||||
const effectivePassphrase = pendingAuth?.passphrase;
|
||||
|
||||
const key = effectiveKeyId
|
||||
? ctx.keys.find((k) => k.id === effectiveKeyId)
|
||||
: undefined;
|
||||
|
||||
const proxyConfig = ctx.host.proxyConfig
|
||||
? {
|
||||
type: ctx.host.proxyConfig.type,
|
||||
host: ctx.host.proxyConfig.host,
|
||||
port: ctx.host.proxyConfig.port,
|
||||
username: ctx.host.proxyConfig.username,
|
||||
password: ctx.host.proxyConfig.password,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const jumpHosts = ctx.resolvedChainHosts.map<NetcattyJumpHost>((jumpHost) => {
|
||||
const jumpKey = jumpHost.identityFileId
|
||||
? ctx.keys.find((k) => k.id === jumpHost.identityFileId)
|
||||
: undefined;
|
||||
return {
|
||||
hostname: jumpHost.hostname,
|
||||
port: jumpHost.port || 22,
|
||||
username: jumpHost.username || "root",
|
||||
password: jumpHost.password,
|
||||
privateKey: jumpKey?.privateKey,
|
||||
certificate: jumpKey?.certificate,
|
||||
passphrase: jumpKey?.passphrase,
|
||||
publicKey: jumpKey?.publicKey,
|
||||
credentialId: jumpKey?.credentialId,
|
||||
rpId: jumpKey?.rpId,
|
||||
keyId: jumpKey?.id,
|
||||
keySource: jumpKey?.source,
|
||||
userVerification: jumpKey?.source === "biometric" ? "required" : "preferred",
|
||||
label: jumpHost.label,
|
||||
};
|
||||
});
|
||||
|
||||
const totalHops = jumpHosts.length + 1;
|
||||
let unsubscribeChainProgress: (() => void) | undefined;
|
||||
|
||||
if (jumpHosts.length > 0) {
|
||||
ctx.setChainProgress({
|
||||
currentHop: 1,
|
||||
totalHops,
|
||||
currentHostLabel:
|
||||
jumpHosts[0]?.label || jumpHosts[0]?.hostname || ctx.host.hostname,
|
||||
});
|
||||
ctx.setProgressLogs((prev) => [
|
||||
...prev,
|
||||
`Starting chain connection (${totalHops} hops)...`,
|
||||
]);
|
||||
|
||||
const unsub = ctx.terminalBackend.onChainProgress((hop, total, label, status) => {
|
||||
ctx.setChainProgress({
|
||||
currentHop: hop,
|
||||
totalHops: total,
|
||||
currentHostLabel: label,
|
||||
});
|
||||
ctx.setProgressLogs((prev) => [
|
||||
...prev,
|
||||
`Chain ${hop} of ${total}: ${label} - ${status}`,
|
||||
]);
|
||||
const hopProgress = (hop / total) * 80 + 10;
|
||||
ctx.setProgressValue(Math.min(95, hopProgress));
|
||||
});
|
||||
if (unsub) unsubscribeChainProgress = unsub;
|
||||
}
|
||||
|
||||
try {
|
||||
const termEnv = buildTermEnv(ctx.host, ctx.terminalSettings);
|
||||
|
||||
// DEBUG: Log key info for troubleshooting
|
||||
console.log("[Terminal] Starting SSH session with key info:", {
|
||||
keyId: key?.id,
|
||||
keyLabel: key?.label,
|
||||
keySource: key?.source,
|
||||
hasCredentialId: !!key?.credentialId,
|
||||
hasRpId: !!key?.rpId,
|
||||
hasPublicKey: !!key?.publicKey,
|
||||
hasPrivateKey: !!key?.privateKey,
|
||||
});
|
||||
|
||||
const id = await ctx.terminalBackend.startSSHSession({
|
||||
sessionId: ctx.sessionId,
|
||||
hostname: ctx.host.hostname,
|
||||
username: effectiveUsername,
|
||||
port: ctx.host.port || 22,
|
||||
password: effectivePassword,
|
||||
privateKey: key?.privateKey,
|
||||
certificate: key?.certificate,
|
||||
publicKey: key?.publicKey,
|
||||
credentialId: key?.credentialId,
|
||||
rpId: key?.rpId,
|
||||
keyId: key?.id,
|
||||
keySource: key?.source,
|
||||
userVerification: key?.source === "biometric" ? "required" : "preferred",
|
||||
passphrase: effectivePassphrase || key?.passphrase,
|
||||
agentForwarding: ctx.host.agentForwarding,
|
||||
cols: term.cols,
|
||||
rows: term.rows,
|
||||
charset: ctx.host.charset,
|
||||
env: termEnv,
|
||||
proxy: proxyConfig,
|
||||
jumpHosts: jumpHosts.length > 0 ? jumpHosts : undefined,
|
||||
});
|
||||
|
||||
if (unsubscribeChainProgress) unsubscribeChainProgress();
|
||||
|
||||
attachSessionToTerminal(ctx, term, id, {
|
||||
onConnected: () => ctx.setChainProgress(null),
|
||||
onExitMessage: (evt) =>
|
||||
`\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`,
|
||||
});
|
||||
|
||||
const commandToRun = ctx.startupCommand || ctx.host.startupCommand;
|
||||
if (commandToRun && !ctx.hasRunStartupCommandRef.current) {
|
||||
ctx.hasRunStartupCommandRef.current = true;
|
||||
setTimeout(() => {
|
||||
if (!ctx.sessionRef.current) return;
|
||||
ctx.terminalBackend.writeToSession(ctx.sessionRef.current, `${commandToRun}\r`);
|
||||
if (ctx.onCommandExecuted) {
|
||||
ctx.onCommandExecuted(commandToRun, ctx.host.id, ctx.host.label, ctx.sessionId);
|
||||
}
|
||||
}, 600);
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
const isAuthError =
|
||||
message.toLowerCase().includes("authentication") ||
|
||||
message.toLowerCase().includes("auth") ||
|
||||
message.toLowerCase().includes("password") ||
|
||||
message.toLowerCase().includes("permission denied");
|
||||
|
||||
if (isAuthError) {
|
||||
ctx.setError(null);
|
||||
ctx.setNeedsAuth(true);
|
||||
ctx.setAuthRetryMessage(
|
||||
"Authentication failed. Please check your credentials and try again.",
|
||||
);
|
||||
ctx.setAuthPassword("");
|
||||
ctx.setProgressLogs((prev) => [
|
||||
...prev,
|
||||
"Authentication failed. Please try again.",
|
||||
]);
|
||||
ctx.setStatus("connecting");
|
||||
} else {
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[Failed to start SSH: ${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
}
|
||||
|
||||
ctx.setChainProgress(null);
|
||||
if (unsubscribeChainProgress) unsubscribeChainProgress();
|
||||
}
|
||||
|
||||
setTimeout(() => void runDistroDetection(ctx, key), 600);
|
||||
};
|
||||
|
||||
const startTelnet = async (term: XTerm) => {
|
||||
try {
|
||||
term.clear?.();
|
||||
} catch (err) {
|
||||
logger.warn("Failed to clear terminal before connect", err);
|
||||
}
|
||||
|
||||
if (!ctx.terminalBackend.telnetAvailable()) {
|
||||
ctx.setError("Telnet bridge unavailable. Please run the desktop build.");
|
||||
term.writeln("\r\n[Telnet bridge unavailable. Please run the desktop build.]");
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const telnetEnv = buildTermEnv(ctx.host, ctx.terminalSettings);
|
||||
const id = await ctx.terminalBackend.startTelnetSession({
|
||||
sessionId: ctx.sessionId,
|
||||
hostname: ctx.host.hostname,
|
||||
port: ctx.host.telnetPort || ctx.host.port || 23,
|
||||
cols: term.cols,
|
||||
rows: term.rows,
|
||||
charset: ctx.host.charset,
|
||||
env: telnetEnv,
|
||||
});
|
||||
|
||||
attachSessionToTerminal(ctx, term, id, {
|
||||
onExitMessage: (evt) =>
|
||||
`\r\n[Telnet session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`,
|
||||
});
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[Failed to start Telnet: ${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
}
|
||||
};
|
||||
|
||||
const startMosh = async (term: XTerm) => {
|
||||
try {
|
||||
term.clear?.();
|
||||
} catch (err) {
|
||||
logger.warn("Failed to clear terminal before connect", err);
|
||||
}
|
||||
|
||||
if (!ctx.terminalBackend.moshAvailable()) {
|
||||
ctx.setError("Mosh bridge unavailable. Please run the desktop build.");
|
||||
term.writeln("\r\n[Mosh bridge unavailable. Please run the desktop build.]");
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const moshEnv = buildTermEnv(ctx.host, ctx.terminalSettings);
|
||||
const id = await ctx.terminalBackend.startMoshSession({
|
||||
sessionId: ctx.sessionId,
|
||||
hostname: ctx.host.hostname,
|
||||
username: ctx.host.username || "root",
|
||||
port: ctx.host.port || 22,
|
||||
moshServerPath: ctx.host.moshServerPath,
|
||||
agentForwarding: ctx.host.agentForwarding,
|
||||
cols: term.cols,
|
||||
rows: term.rows,
|
||||
charset: ctx.host.charset,
|
||||
env: moshEnv,
|
||||
});
|
||||
|
||||
attachSessionToTerminal(ctx, term, id, {
|
||||
onExitMessage: (evt) =>
|
||||
`\r\n[Mosh session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`,
|
||||
});
|
||||
|
||||
const commandToRun = ctx.startupCommand || ctx.host.startupCommand;
|
||||
if (commandToRun && !ctx.hasRunStartupCommandRef.current) {
|
||||
ctx.hasRunStartupCommandRef.current = true;
|
||||
setTimeout(() => {
|
||||
if (!ctx.sessionRef.current) return;
|
||||
ctx.terminalBackend.writeToSession(ctx.sessionRef.current, `${commandToRun}\r`);
|
||||
if (ctx.onCommandExecuted) {
|
||||
ctx.onCommandExecuted(commandToRun, ctx.host.id, ctx.host.label, ctx.sessionId);
|
||||
}
|
||||
}, 600);
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[Failed to start Mosh: ${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
}
|
||||
};
|
||||
|
||||
const startLocal = async (term: XTerm) => {
|
||||
try {
|
||||
term.clear?.();
|
||||
} catch (err) {
|
||||
logger.warn("Failed to clear terminal before connect", err);
|
||||
}
|
||||
|
||||
if (!ctx.terminalBackend.localAvailable()) {
|
||||
ctx.setError("Local shell bridge unavailable. Please run the desktop build.");
|
||||
term.writeln(
|
||||
"\r\n[Local shell bridge unavailable. Please run the desktop build to spawn a local terminal.]",
|
||||
);
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const id = await ctx.terminalBackend.startLocalSession({
|
||||
sessionId: ctx.sessionId,
|
||||
cols: term.cols,
|
||||
rows: term.rows,
|
||||
env: {
|
||||
TERM: ctx.terminalSettings?.terminalEmulationType ?? "xterm-256color",
|
||||
},
|
||||
});
|
||||
|
||||
ctx.sessionRef.current = id;
|
||||
ctx.disposeDataRef.current = ctx.terminalBackend.onSessionData(id, (chunk) => {
|
||||
term.write(ctx.highlightProcessorRef.current(chunk));
|
||||
if (!ctx.hasConnectedRef.current) {
|
||||
ctx.updateStatus("connected");
|
||||
setTimeout(() => {
|
||||
if (!ctx.fitAddonRef.current) return;
|
||||
try {
|
||||
ctx.fitAddonRef.current.fit();
|
||||
if (ctx.sessionRef.current) {
|
||||
ctx.terminalBackend.resizeSession(ctx.sessionRef.current, term.cols, term.rows);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn("Post-connect fit failed", err);
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
});
|
||||
|
||||
ctx.disposeExitRef.current = ctx.terminalBackend.onSessionExit(id, (evt) => {
|
||||
ctx.updateStatus("disconnected");
|
||||
term.writeln(
|
||||
`\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`,
|
||||
);
|
||||
|
||||
logger.info("[Terminal] Session exit, capturing data", {
|
||||
sessionId: ctx.sessionId,
|
||||
hasCallback: !!ctx.onTerminalDataCapture,
|
||||
hasSerializeAddon: !!ctx.serializeAddonRef.current,
|
||||
});
|
||||
|
||||
if (ctx.onTerminalDataCapture && ctx.serializeAddonRef.current) {
|
||||
try {
|
||||
const terminalData = ctx.serializeAddonRef.current.serialize();
|
||||
logger.info("[Terminal] Serialized terminal data", {
|
||||
sessionId: ctx.sessionId,
|
||||
dataLength: terminalData.length,
|
||||
});
|
||||
ctx.onTerminalDataCapture(ctx.sessionId, terminalData);
|
||||
} catch (err) {
|
||||
logger.warn("Failed to serialize terminal data:", err);
|
||||
}
|
||||
}
|
||||
|
||||
ctx.onSessionExit?.(ctx.sessionId);
|
||||
});
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[Failed to start local shell: ${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
}
|
||||
};
|
||||
|
||||
return { startSSH, startTelnet, startMosh, startLocal };
|
||||
};
|
||||
@@ -0,0 +1,457 @@
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { SearchAddon } from "@xterm/addon-search";
|
||||
import { SerializeAddon } from "@xterm/addon-serialize";
|
||||
import { WebLinksAddon } from "@xterm/addon-web-links";
|
||||
import { WebglAddon } from "@xterm/addon-webgl";
|
||||
import { Terminal as XTerm } from "@xterm/xterm";
|
||||
import type { Dispatch, MutableRefObject, SetStateAction } from "react";
|
||||
import {
|
||||
checkAppShortcut,
|
||||
getAppLevelActions,
|
||||
getTerminalPassthroughActions,
|
||||
} from "../../../application/state/useGlobalHotkeys";
|
||||
import { TERMINAL_FONTS } from "../../../infrastructure/config/fonts";
|
||||
import {
|
||||
XTERM_PERFORMANCE_CONFIG,
|
||||
type XTermPlatform,
|
||||
resolveXTermPerformanceConfig,
|
||||
} from "../../../infrastructure/config/xtermPerformance";
|
||||
import { logger } from "../../../lib/logger";
|
||||
import type {
|
||||
Host,
|
||||
KeyBinding,
|
||||
TerminalSession,
|
||||
TerminalSettings,
|
||||
TerminalTheme,
|
||||
} from "../../../types";
|
||||
|
||||
type TerminalBackendApi = {
|
||||
openExternalAvailable: () => boolean;
|
||||
openExternal: (url: string) => Promise<void>;
|
||||
writeToSession: (sessionId: string, data: string) => void;
|
||||
resizeSession: (sessionId: string, cols: number, rows: number) => void;
|
||||
};
|
||||
|
||||
export type XTermRuntime = {
|
||||
term: XTerm;
|
||||
fitAddon: FitAddon;
|
||||
serializeAddon: SerializeAddon;
|
||||
searchAddon: SearchAddon;
|
||||
dispose: () => void;
|
||||
};
|
||||
|
||||
export type CreateXTermRuntimeContext = {
|
||||
container: HTMLDivElement;
|
||||
host: Host;
|
||||
fontSize: number;
|
||||
terminalTheme: TerminalTheme;
|
||||
terminalSettingsRef: MutableRefObject<TerminalSettings | undefined>;
|
||||
terminalBackend: TerminalBackendApi;
|
||||
sessionRef: MutableRefObject<string | null>;
|
||||
|
||||
hotkeySchemeRef: MutableRefObject<"disabled" | "mac" | "pc">;
|
||||
keyBindingsRef: MutableRefObject<KeyBinding[]>;
|
||||
onHotkeyActionRef: MutableRefObject<
|
||||
((action: string, event: KeyboardEvent) => void) | undefined
|
||||
>;
|
||||
|
||||
isBroadcastEnabledRef: MutableRefObject<boolean | undefined>;
|
||||
onBroadcastInputRef: MutableRefObject<
|
||||
((data: string, sourceSessionId: string) => void) | undefined
|
||||
>;
|
||||
|
||||
sessionId: string;
|
||||
status: TerminalSession["status"];
|
||||
onCommandExecuted?: (
|
||||
command: string,
|
||||
hostId: string,
|
||||
hostLabel: string,
|
||||
sessionId: string,
|
||||
) => void;
|
||||
commandBufferRef: MutableRefObject<string>;
|
||||
setIsSearchOpen: Dispatch<SetStateAction<boolean>>;
|
||||
};
|
||||
|
||||
const detectPlatform = (): XTermPlatform => {
|
||||
if (
|
||||
typeof process !== "undefined" &&
|
||||
(process.platform === "darwin" ||
|
||||
process.platform === "win32" ||
|
||||
process.platform === "linux")
|
||||
) {
|
||||
return process.platform;
|
||||
}
|
||||
|
||||
if (typeof navigator !== "undefined") {
|
||||
const ua = navigator.userAgent.toLowerCase();
|
||||
if (ua.includes("win")) return "win32";
|
||||
if (ua.includes("linux")) return "linux";
|
||||
}
|
||||
|
||||
return "darwin";
|
||||
};
|
||||
|
||||
export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime => {
|
||||
const platform = detectPlatform();
|
||||
const deviceMemoryGb =
|
||||
typeof navigator !== "undefined" &&
|
||||
typeof (navigator as { deviceMemory?: number }).deviceMemory === "number"
|
||||
? (navigator as { deviceMemory?: number }).deviceMemory
|
||||
: undefined;
|
||||
|
||||
const performanceConfig = resolveXTermPerformanceConfig({
|
||||
platform,
|
||||
deviceMemoryGb,
|
||||
});
|
||||
|
||||
const hostFontId = ctx.host.fontFamily || "menlo";
|
||||
const fontObj = TERMINAL_FONTS.find((f) => f.id === hostFontId) || TERMINAL_FONTS[0];
|
||||
const fontFamily = fontObj.family;
|
||||
|
||||
const effectiveFontSize = ctx.host.fontSize || ctx.fontSize;
|
||||
|
||||
const settings = ctx.terminalSettingsRef.current;
|
||||
const cursorStyle = settings?.cursorShape ?? "block";
|
||||
const cursorBlink = settings?.cursorBlink ?? true;
|
||||
const scrollback = settings?.scrollback ?? 10000;
|
||||
const fontLigatures = settings?.fontLigatures ?? true;
|
||||
const drawBoldTextInBrightColors = settings?.drawBoldInBrightColors ?? true;
|
||||
const fontWeight = settings?.fontWeight ?? 400;
|
||||
const fontWeightBold = settings?.fontWeightBold ?? 700;
|
||||
const lineHeight = 1 + (settings?.linePadding ?? 0) / 10;
|
||||
const minimumContrastRatio = settings?.minimumContrastRatio ?? 1;
|
||||
const scrollOnUserInput = settings?.scrollOnInput ?? true;
|
||||
const altIsMeta = settings?.altAsMeta ?? false;
|
||||
const wordSeparator = settings?.wordSeparators ?? " ()[]{}'\"";
|
||||
|
||||
const term = new XTerm({
|
||||
...performanceConfig.options,
|
||||
fontSize: effectiveFontSize,
|
||||
fontFamily,
|
||||
fontWeight: fontWeight as
|
||||
| 100
|
||||
| 200
|
||||
| 300
|
||||
| 400
|
||||
| 500
|
||||
| 600
|
||||
| 700
|
||||
| 800
|
||||
| 900
|
||||
| "normal"
|
||||
| "bold",
|
||||
fontWeightBold: fontWeightBold as
|
||||
| 100
|
||||
| 200
|
||||
| 300
|
||||
| 400
|
||||
| 500
|
||||
| 600
|
||||
| 700
|
||||
| 800
|
||||
| 900
|
||||
| "normal"
|
||||
| "bold",
|
||||
lineHeight,
|
||||
cursorStyle,
|
||||
cursorBlink,
|
||||
scrollback,
|
||||
allowProposedApi: fontLigatures,
|
||||
drawBoldTextInBrightColors,
|
||||
minimumContrastRatio,
|
||||
scrollOnUserInput,
|
||||
altClickMovesCursor: !altIsMeta,
|
||||
wordSeparator,
|
||||
theme: {
|
||||
...ctx.terminalTheme.colors,
|
||||
selectionBackground: ctx.terminalTheme.colors.selection,
|
||||
},
|
||||
});
|
||||
|
||||
type MaybeRenderer = {
|
||||
constructor?: { name?: string };
|
||||
type?: string;
|
||||
};
|
||||
|
||||
type IntrospectableTerminal = XTerm & {
|
||||
_core?: {
|
||||
_renderService?: {
|
||||
_renderer?: MaybeRenderer;
|
||||
};
|
||||
};
|
||||
options?: {
|
||||
rendererType?: string;
|
||||
};
|
||||
};
|
||||
|
||||
const logRenderer = (attempt = 0) => {
|
||||
const introspected = term as IntrospectableTerminal;
|
||||
const renderer = introspected._core?._renderService?._renderer;
|
||||
const candidates = [
|
||||
renderer?.type,
|
||||
renderer?.constructor?.name,
|
||||
introspected.options?.rendererType,
|
||||
];
|
||||
const rendererName =
|
||||
candidates.find((value) => typeof value === "string" && value.length > 0) ||
|
||||
undefined;
|
||||
const normalized = rendererName
|
||||
? rendererName.toLowerCase().includes("webgl")
|
||||
? "webgl"
|
||||
: rendererName.toLowerCase().includes("canvas")
|
||||
? "canvas"
|
||||
: rendererName
|
||||
: "unknown";
|
||||
logger.info(`[XTerm] renderer=${normalized}`);
|
||||
const scopedWindow = window as Window & { __xtermRenderer?: string };
|
||||
scopedWindow.__xtermRenderer = normalized;
|
||||
if (normalized === "unknown" && attempt < 3) {
|
||||
setTimeout(() => logRenderer(attempt + 1), 150);
|
||||
}
|
||||
};
|
||||
|
||||
const fitAddon = new FitAddon();
|
||||
term.loadAddon(fitAddon);
|
||||
|
||||
const serializeAddon = new SerializeAddon();
|
||||
term.loadAddon(serializeAddon);
|
||||
|
||||
const searchAddon = new SearchAddon();
|
||||
term.loadAddon(searchAddon);
|
||||
|
||||
term.open(ctx.container);
|
||||
|
||||
let webglAddon: WebglAddon | null = null;
|
||||
let webglLoaded = false;
|
||||
const scopedWindow = window as Window & {
|
||||
__xtermWebGLLoaded?: boolean;
|
||||
__xtermRendererPreference?: string;
|
||||
};
|
||||
|
||||
if (performanceConfig.useWebGLAddon) {
|
||||
try {
|
||||
webglAddon = (() => {
|
||||
const webglOptions: Record<string, unknown> = { useCustomGlyphHandler: true };
|
||||
try {
|
||||
const WebglCtor = WebglAddon as unknown as new (options?: unknown) => WebglAddon;
|
||||
return new WebglCtor(webglOptions);
|
||||
} catch {
|
||||
return new WebglAddon();
|
||||
}
|
||||
})();
|
||||
webglAddon.onContextLoss(() => {
|
||||
logger.warn("[XTerm] WebGL context loss detected, disposing addon");
|
||||
webglAddon?.dispose();
|
||||
});
|
||||
term.loadAddon(webglAddon);
|
||||
webglLoaded = true;
|
||||
} catch (webglErr) {
|
||||
logger.warn(
|
||||
"[XTerm] WebGL addon failed, using canvas renderer. Error:",
|
||||
webglErr instanceof Error ? webglErr.message : webglErr,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
logger.info(
|
||||
"[XTerm] Skipping WebGL addon (canvas preferred for macOS profile or low-memory devices)",
|
||||
);
|
||||
}
|
||||
|
||||
scopedWindow.__xtermWebGLLoaded = webglLoaded;
|
||||
scopedWindow.__xtermRendererPreference = performanceConfig.preferCanvasRenderer
|
||||
? "canvas"
|
||||
: "webgl";
|
||||
|
||||
const webLinksAddon = new WebLinksAddon((event, uri) => {
|
||||
const currentLinkModifier = ctx.terminalSettingsRef.current?.linkModifier ?? "none";
|
||||
let shouldOpen = false;
|
||||
switch (currentLinkModifier) {
|
||||
case "none":
|
||||
shouldOpen = true;
|
||||
break;
|
||||
case "ctrl":
|
||||
shouldOpen = event.ctrlKey;
|
||||
break;
|
||||
case "alt":
|
||||
shouldOpen = event.altKey;
|
||||
break;
|
||||
case "meta":
|
||||
shouldOpen = event.metaKey;
|
||||
break;
|
||||
}
|
||||
if (!shouldOpen) return;
|
||||
|
||||
if (ctx.terminalBackend.openExternalAvailable()) {
|
||||
void ctx.terminalBackend.openExternal(uri);
|
||||
} else {
|
||||
window.open(uri, "_blank");
|
||||
}
|
||||
});
|
||||
term.loadAddon(webLinksAddon);
|
||||
|
||||
logRenderer();
|
||||
|
||||
const appLevelActions = getAppLevelActions();
|
||||
const terminalActions = getTerminalPassthroughActions();
|
||||
|
||||
term.attachCustomKeyEventHandler((e: KeyboardEvent) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === "f" && e.type === "keydown") {
|
||||
e.preventDefault();
|
||||
ctx.setIsSearchOpen(true);
|
||||
return false;
|
||||
}
|
||||
|
||||
const currentScheme = ctx.hotkeySchemeRef.current;
|
||||
const currentBindings = ctx.keyBindingsRef.current;
|
||||
const hotkeyCallback = ctx.onHotkeyActionRef.current;
|
||||
|
||||
if (currentScheme === "disabled" || currentBindings.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const isMac = currentScheme === "mac";
|
||||
const matched = checkAppShortcut(e, currentBindings, isMac);
|
||||
if (!matched) return true;
|
||||
|
||||
const { action } = matched;
|
||||
|
||||
if (appLevelActions.has(action)) {
|
||||
e.preventDefault();
|
||||
hotkeyCallback?.(action, e);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (terminalActions.has(action)) {
|
||||
e.preventDefault();
|
||||
switch (action) {
|
||||
case "copy": {
|
||||
const selection = term.getSelection();
|
||||
if (selection) navigator.clipboard.writeText(selection);
|
||||
break;
|
||||
}
|
||||
case "paste": {
|
||||
navigator.clipboard.readText().then((text) => {
|
||||
const id = ctx.sessionRef.current;
|
||||
if (id) ctx.terminalBackend.writeToSession(id, text);
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "selectAll": {
|
||||
term.selectAll();
|
||||
break;
|
||||
}
|
||||
case "clearBuffer": {
|
||||
term.clear();
|
||||
break;
|
||||
}
|
||||
case "searchTerminal": {
|
||||
ctx.setIsSearchOpen(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
let cleanupMiddleClick: (() => void) | null = null;
|
||||
const middleClickPaste = settings?.middleClickPaste ?? true;
|
||||
if (middleClickPaste) {
|
||||
const handleMiddleClick = async (e: MouseEvent) => {
|
||||
if (e.button !== 1) return;
|
||||
e.preventDefault();
|
||||
try {
|
||||
const text = await navigator.clipboard.readText();
|
||||
if (text && ctx.sessionRef.current) {
|
||||
ctx.terminalBackend.writeToSession(ctx.sessionRef.current, text);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn("[Terminal] Failed to paste from clipboard:", err);
|
||||
}
|
||||
};
|
||||
|
||||
ctx.container.addEventListener("auxclick", handleMiddleClick);
|
||||
cleanupMiddleClick = () =>
|
||||
ctx.container.removeEventListener("auxclick", handleMiddleClick);
|
||||
}
|
||||
|
||||
fitAddon.fit();
|
||||
term.focus();
|
||||
|
||||
term.onData((data) => {
|
||||
const id = ctx.sessionRef.current;
|
||||
if (id) {
|
||||
ctx.terminalBackend.writeToSession(id, data);
|
||||
|
||||
if (ctx.isBroadcastEnabledRef.current && ctx.onBroadcastInputRef.current) {
|
||||
ctx.onBroadcastInputRef.current(data, ctx.sessionId);
|
||||
}
|
||||
|
||||
if (ctx.status === "connected" && ctx.onCommandExecuted) {
|
||||
if (data === "\r" || data === "\n") {
|
||||
const cmd = ctx.commandBufferRef.current.trim();
|
||||
if (cmd) ctx.onCommandExecuted(cmd, ctx.host.id, ctx.host.label, ctx.sessionId);
|
||||
ctx.commandBufferRef.current = "";
|
||||
} else if (data === "\x7f" || data === "\b") {
|
||||
ctx.commandBufferRef.current = ctx.commandBufferRef.current.slice(0, -1);
|
||||
} else if (data === "\x03") {
|
||||
ctx.commandBufferRef.current = "";
|
||||
} else if (data === "\x15") {
|
||||
ctx.commandBufferRef.current = "";
|
||||
} else if (data.length === 1 && data.charCodeAt(0) >= 32) {
|
||||
ctx.commandBufferRef.current += data;
|
||||
} else if (data.length > 1 && !data.startsWith("\x1b")) {
|
||||
ctx.commandBufferRef.current += data;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let resizeTimeout: NodeJS.Timeout | null = null;
|
||||
const resizeDebounceMs = XTERM_PERFORMANCE_CONFIG.resize.debounceMs;
|
||||
term.onResize(({ cols, rows }) => {
|
||||
const id = ctx.sessionRef.current;
|
||||
if (!id) return;
|
||||
if (resizeTimeout) clearTimeout(resizeTimeout);
|
||||
resizeTimeout = setTimeout(() => {
|
||||
ctx.terminalBackend.resizeSession(id, cols, rows);
|
||||
resizeTimeout = null;
|
||||
}, resizeDebounceMs);
|
||||
});
|
||||
|
||||
return {
|
||||
term,
|
||||
fitAddon,
|
||||
serializeAddon,
|
||||
searchAddon,
|
||||
dispose: () => {
|
||||
cleanupMiddleClick?.();
|
||||
try {
|
||||
term.dispose();
|
||||
} catch (err) {
|
||||
logger.warn("[XTerm] dispose failed", err);
|
||||
}
|
||||
try {
|
||||
fitAddon.dispose();
|
||||
} catch (err) {
|
||||
logger.warn("[XTerm] fitAddon dispose failed", err);
|
||||
}
|
||||
try {
|
||||
serializeAddon.dispose();
|
||||
} catch (err) {
|
||||
logger.warn("[XTerm] serializeAddon dispose failed", err);
|
||||
}
|
||||
try {
|
||||
searchAddon.dispose();
|
||||
} catch (err) {
|
||||
logger.warn("[XTerm] searchAddon dispose failed", err);
|
||||
}
|
||||
try {
|
||||
webglAddon?.dispose();
|
||||
} catch (err) {
|
||||
logger.warn("[XTerm] webglAddon dispose failed", err);
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
Reference in new issue
Block a user