mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-26 10:53:56 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ae0e17501 | ||
|
|
645d7a4f5d | ||
|
|
9d99c675ab |
No files matched your search
+206
-20
@@ -9,6 +9,25 @@ import { getAvailablePaneMagnificationController } from '../../domain/paneMagnif
|
||||
import { sanitizeHostIconFields } from '../../domain/hostIcon';
|
||||
import { resolveEffectiveTerminalProtocol } from '../../domain/terminalProtocol';
|
||||
import { isPluginHostProtocol } from '../../domain/pluginConnection';
|
||||
import {
|
||||
applyHostDefaultConnectProtocol,
|
||||
buildHostForProtocolOverride,
|
||||
isRemoteDesktopProtocol,
|
||||
resolveRemoteDesktopConnectionSpec,
|
||||
shouldPromptHostProtocolOnConnect,
|
||||
type RemoteDesktopProtocol,
|
||||
} from '../../domain/remoteDesktop';
|
||||
import { resolveTerminalChainHosts } from '../../domain/terminalHostResolution';
|
||||
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
|
||||
import {
|
||||
buildSystemRemoteDesktopPayload,
|
||||
isRemoteDesktopGrabReleaseChord,
|
||||
isTargetInsideRemoteDesktopCapture,
|
||||
} from '../../components/remoteDesktop/remoteDesktopHelpers';
|
||||
import {
|
||||
getConnectionLogsActions,
|
||||
getConnectionLogsSnapshot,
|
||||
} from '../state/connectionLogsStore';
|
||||
import { getTerminalPassthroughActions } from '../state/useGlobalHotkeys';
|
||||
import { getSettingsChromeSnapshot } from '../state/settingsChromeStore';
|
||||
import { isHostTreeWorkTabSurface } from './workTabSurface';
|
||||
@@ -253,6 +272,13 @@ export function flushQueuedTrayPanelConnectHostsImpl(getCtx: AppContextGetter) {
|
||||
export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: KeyboardEvent) {
|
||||
const { HOTKEY_DEBUG, closeTabKeyStr, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding } = getCtx();
|
||||
{
|
||||
if (
|
||||
isTargetInsideRemoteDesktopCapture(e.target, e.composedPath?.bind(e))
|
||||
&& !isRemoteDesktopGrabReleaseChord(e)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isMac = hotkeyScheme === 'mac';
|
||||
const target = e.target as HTMLElement;
|
||||
const isCloseTabHotkey = closeTabKeyStr ? matchesKeyBinding(e, closeTabKeyStr, isMac) : false;
|
||||
@@ -856,6 +882,40 @@ export function collectBatchBusyProbeSessionIds(
|
||||
return sessionIdsToProbe;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stamp `endTime` on open RDP/VNC `ConnectionLog` entries when remote desktop
|
||||
* sessions close so they do not stay stuck at "Ongoing" in Connection Logs.
|
||||
*/
|
||||
export function stampRemoteDesktopSessionEndTimes(
|
||||
getCtx: AppContextGetter,
|
||||
closingSessionIds: readonly string[],
|
||||
): number {
|
||||
if (!closingSessionIds.length) return 0;
|
||||
const ctx = getCtx();
|
||||
const sessionsList: TerminalSession[] = Array.isArray(ctx.sessions) ? ctx.sessions : [];
|
||||
const logs = Array.isArray(ctx.connectionLogs)
|
||||
? ctx.connectionLogs
|
||||
: [...getConnectionLogsSnapshot().connectionLogs];
|
||||
const updateLog = ctx.updateConnectionLog ?? getConnectionLogsActions()?.updateConnectionLog;
|
||||
if (!updateLog || logs.length === 0) return 0;
|
||||
|
||||
let stamped = 0;
|
||||
const now = Date.now();
|
||||
for (const sessionId of new Set(closingSessionIds)) {
|
||||
const session = sessionsList.find((candidate) => candidate.id === sessionId);
|
||||
const matchingLog = selectConnectionLogForTerminalDataCapture(logs, {
|
||||
sessionId,
|
||||
hostname: session?.hostname,
|
||||
});
|
||||
if (!matchingLog || matchingLog.endTime) continue;
|
||||
const protocol = session?.protocol ?? matchingLog.protocol;
|
||||
if (!isRemoteDesktopProtocol(protocol)) continue;
|
||||
void Promise.resolve(updateLog(matchingLog.id, { endTime: now })).catch(() => {});
|
||||
stamped += 1;
|
||||
}
|
||||
return stamped;
|
||||
}
|
||||
|
||||
export async function closeTabsBatchImpl(getCtx: AppContextGetter, targetIds: string[]) {
|
||||
const {
|
||||
closeLogView, closeSessions, closeTabsInFlightRef, closeWorkspace,
|
||||
@@ -893,6 +953,12 @@ export async function closeTabsBatchImpl(getCtx: AppContextGetter, targetIds: st
|
||||
sessions.some((session) => session.workspaceId === id && keepTabIds.has(session.id))
|
||||
));
|
||||
const standaloneSessionIds = effectiveRegularIds.filter((id) => sessions.some((session) => session.id === id));
|
||||
const workspaceSessionIds = effectiveRegularIds.flatMap((id) => (
|
||||
workspaces.some((workspace) => workspace.id === id)
|
||||
? sessions.filter((session) => session.workspaceId === id).map((session) => session.id)
|
||||
: []
|
||||
));
|
||||
stampRemoteDesktopSessionEndTimes(getCtx, [...standaloneSessionIds, ...workspaceSessionIds]);
|
||||
if (standaloneSessionIds.length) closeSessions(standaloneSessionIds);
|
||||
for (const id of effectiveRegularIds) {
|
||||
if (workspaces.some((workspace) => workspace.id === id)) closeWorkspace(id);
|
||||
@@ -986,13 +1052,19 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
|
||||
switch (intent.kind) {
|
||||
case 'closeSingleTab': {
|
||||
const ok = await confirmIfBusyLocalTerminal([intent.sessionId]);
|
||||
if (ok) closeSession(intent.sessionId);
|
||||
if (ok) {
|
||||
stampRemoteDesktopSessionEndTimes(getCtx, [intent.sessionId]);
|
||||
closeSession(intent.sessionId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'closeWorkspace': {
|
||||
const ids = sessions.filter((s) => s.workspaceId === intent.workspaceId).map((s) => s.id);
|
||||
const ok = await confirmIfBusyLocalTerminal(ids);
|
||||
if (ok) closeWorkspace(intent.workspaceId);
|
||||
if (ok) {
|
||||
stampRemoteDesktopSessionEndTimes(getCtx, ids);
|
||||
closeWorkspace(intent.workspaceId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'noop':
|
||||
@@ -1028,6 +1100,7 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
|
||||
if (focusedId) {
|
||||
const ok = await confirmIfBusyLocalTerminal([focusedId]);
|
||||
if (ok) {
|
||||
stampRemoteDesktopSessionEndTimes(getCtx, [focusedId]);
|
||||
// The pane shortcut closes the tab when only one pane remains.
|
||||
if (aliveIds.length === 1) closeWorkspace(workspace.id);
|
||||
else closeSession(focusedId);
|
||||
@@ -1036,7 +1109,10 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
|
||||
} else if (session) {
|
||||
// Standalone session tab — close the session
|
||||
const ok = await confirmIfBusyLocalTerminal([session.id]);
|
||||
if (ok) closeSession(session.id);
|
||||
if (ok) {
|
||||
stampRemoteDesktopSessionEndTimes(getCtx, [session.id]);
|
||||
closeSession(session.id);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
closeTabInFlightRef.current = false;
|
||||
@@ -1340,7 +1416,11 @@ export function handleConnectToHostImpl(getCtx: AppContextGetter, host: Host, hi
|
||||
// Local-shell vault hosts carry no SSH credentials, so log the system
|
||||
// user like local terminals do (see handleCreateLocalTerminalImpl)
|
||||
// instead of 'root' or an inherited group SSH username.
|
||||
username: protocol === 'local' ? username : (resolvedAuth.username || 'root'),
|
||||
username: protocol === 'local'
|
||||
? username
|
||||
: isRemoteDesktopProtocol(protocol)
|
||||
? (effectiveHost.username || '')
|
||||
: (resolvedAuth.username || 'root'),
|
||||
protocol,
|
||||
...getLogHostVisualSnapshot(effectiveHost),
|
||||
startTime: Date.now(),
|
||||
@@ -1352,6 +1432,85 @@ export function handleConnectToHostImpl(getCtx: AppContextGetter, host: Host, hi
|
||||
}
|
||||
}
|
||||
|
||||
export function handleConnectRemoteDesktopImpl(
|
||||
getCtx: AppContextGetter,
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
options?: { splitFromSessionId?: string },
|
||||
) {
|
||||
const { addConnectionLog, connectToHostRemoteDesktop, identities, resolveEffectiveHost, systemInfoRef } = getCtx();
|
||||
const effectiveHost = resolveEffectiveHost(host);
|
||||
const spec = resolveRemoteDesktopConnectionSpec(effectiveHost, protocol, identities ?? []);
|
||||
const sessionId = connectToHostRemoteDesktop(effectiveHost, protocol, options);
|
||||
if (!sessionId) return null;
|
||||
const { username: localUsername, hostname: localHostname } = systemInfoRef.current;
|
||||
addConnectionLog({
|
||||
sessionId,
|
||||
hostId: host.id,
|
||||
hostLabel: spec.isCompanion ? `${spec.label} (${protocol.toUpperCase()})` : spec.label,
|
||||
hostname: spec.hostHostname,
|
||||
username: spec.username,
|
||||
protocol,
|
||||
...getLogHostVisualSnapshot(effectiveHost),
|
||||
startTime: Date.now(),
|
||||
localUsername,
|
||||
localHostname,
|
||||
saved: false,
|
||||
});
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
export async function handleOpenSystemRemoteDesktopImpl(
|
||||
getCtx: AppContextGetter,
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
rawRdpContent?: string,
|
||||
) {
|
||||
const {
|
||||
groupConfigs,
|
||||
hosts,
|
||||
identities,
|
||||
keys,
|
||||
knownHosts,
|
||||
netcattyBridge,
|
||||
proxyProfiles,
|
||||
resolveEffectiveHost,
|
||||
toast,
|
||||
} = getCtx();
|
||||
const rdBridge = netcattyBridge.get()?.remoteDesktop;
|
||||
if (!rdBridge?.openSystemClient) {
|
||||
toast?.error?.('System remote desktop launch is unavailable');
|
||||
return { ok: false };
|
||||
}
|
||||
const effectiveHost = resolveEffectiveHost(host);
|
||||
const chainHosts = resolveTerminalChainHosts({
|
||||
host: effectiveHost,
|
||||
hosts: hosts ?? [],
|
||||
groupConfigs: groupConfigs ?? [],
|
||||
proxyProfiles: proxyProfiles ?? [],
|
||||
});
|
||||
const payload = buildSystemRemoteDesktopPayload({
|
||||
host: effectiveHost,
|
||||
protocol,
|
||||
chainHosts,
|
||||
keys: keys ?? [],
|
||||
identities: identities ?? [],
|
||||
knownHosts: knownHosts ?? [],
|
||||
rawRdpContent,
|
||||
});
|
||||
try {
|
||||
const result = await rdBridge.openSystemClient(payload);
|
||||
if (!result?.ok) {
|
||||
toast?.error?.(result?.error || 'Failed to open system remote desktop client');
|
||||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to open system remote desktop client';
|
||||
toast?.error?.(message);
|
||||
return { ok: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
export function startRestoredSessionConnectionLogImpl(getCtx: AppContextGetter, session: TerminalSession) {
|
||||
const { addConnectionLog, systemInfoRef } = getCtx();
|
||||
const { username, hostname } = systemInfoRef.current;
|
||||
@@ -1388,10 +1547,16 @@ export async function handleTerminalDataCaptureImpl(getCtx: AppContextGetter, se
|
||||
// The IndexedDB replay write commits asynchronously. Waiting here keeps
|
||||
// a crash during session teardown from dropping the newest capture any
|
||||
// more often than the old synchronous localStorage write.
|
||||
await updateConnectionLog(matchingLog.id, {
|
||||
endTime: Date.now(),
|
||||
terminalData: data,
|
||||
});
|
||||
const isRemoteDesktopLog = isRemoteDesktopProtocol(session?.protocol ?? matchingLog.protocol);
|
||||
await updateConnectionLog(
|
||||
matchingLog.id,
|
||||
isRemoteDesktopLog && !data
|
||||
? { endTime: Date.now() }
|
||||
: {
|
||||
endTime: Date.now(),
|
||||
terminalData: data,
|
||||
},
|
||||
);
|
||||
if (IS_DEV) console.log('[handleTerminalDataCapture] Updated log with terminalData');
|
||||
|
||||
// Auto-save is now handled by real-time streaming in the main process
|
||||
@@ -1413,8 +1578,7 @@ export function hasMultipleProtocolsImpl(getCtx: AppContextGetter, host: Host) {
|
||||
// SSH/Telnet pickers driven by an inherited group Telnet flag. Hosts
|
||||
// without an explicit protocol are legacy SSH entries.
|
||||
const effective = resolveEffectiveHost(host);
|
||||
const effectiveProtocol = effective.protocol ?? 'ssh';
|
||||
return effectiveProtocol === 'ssh' && Boolean(effective.telnetEnabled);
|
||||
return shouldPromptHostProtocolOnConnect(effective);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1431,18 +1595,40 @@ export function handleHostConnectWithProtocolCheckImpl(getCtx: AppContextGetter,
|
||||
}
|
||||
}
|
||||
|
||||
export function handleProtocolSelectImpl(getCtx: AppContextGetter, protocol: HostProtocol, port: number) {
|
||||
const { handleConnectToHost, protocolSelectHost, setProtocolSelectHost } = getCtx();
|
||||
export function handleProtocolSelectImpl(
|
||||
getCtx: AppContextGetter,
|
||||
protocol: HostProtocol,
|
||||
port: number,
|
||||
rememberDefault?: boolean,
|
||||
) {
|
||||
const {
|
||||
handleConnectToHost,
|
||||
handleConnectRemoteDesktop,
|
||||
protocolSelectHost,
|
||||
setProtocolSelectHost,
|
||||
updateHosts,
|
||||
} = getCtx();
|
||||
{
|
||||
if (protocolSelectHost) {
|
||||
const hostWithProtocol: Host = {
|
||||
...protocolSelectHost,
|
||||
protocol: (protocol === 'mosh' || protocol === 'et') ? 'ssh' : protocol,
|
||||
port,
|
||||
moshEnabled: protocol === 'mosh',
|
||||
etEnabled: protocol === 'et',
|
||||
};
|
||||
handleConnectToHost(hostWithProtocol);
|
||||
if (
|
||||
rememberDefault &&
|
||||
typeof updateHosts === 'function' &&
|
||||
(protocol === 'ssh' || protocol === 'mosh' || protocol === 'et' || protocol === 'rdp' || protocol === 'vnc' || protocol === 'telnet')
|
||||
) {
|
||||
updateHosts((prev: Host[]) =>
|
||||
prev.map((h) =>
|
||||
h.id === protocolSelectHost.id
|
||||
? applyHostDefaultConnectProtocol(h, protocol)
|
||||
: h,
|
||||
),
|
||||
);
|
||||
}
|
||||
const dispatch = buildHostForProtocolOverride(protocolSelectHost, protocol, port);
|
||||
if (dispatch.mode === 'remoteDesktop' && typeof handleConnectRemoteDesktop === 'function') {
|
||||
handleConnectRemoteDesktop(dispatch.host, dispatch.protocol);
|
||||
} else {
|
||||
handleConnectToHost(dispatch.host);
|
||||
}
|
||||
setProtocolSelectHost(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,8 @@ interface AppHostTreeLayerProps {
|
||||
themeById: ReadonlyMap<string, TerminalTheme>;
|
||||
resolveSessionAppearance?: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance;
|
||||
onConnect: (host: Host) => void;
|
||||
onConnectRemoteDesktop?: (host: Host, protocol: 'vnc' | 'rdp') => void;
|
||||
onOpenSystemRemoteDesktop?: (host: Host, protocol: 'vnc' | 'rdp') => void;
|
||||
onNewHost?: (defaultGroup?: string) => void;
|
||||
onEditHost?: (host: Host) => void;
|
||||
onCreateLocalTerminal?: () => void;
|
||||
@@ -68,6 +70,8 @@ function appHostTreeLayerAreEqual(
|
||||
&& prev.themeById === next.themeById
|
||||
&& prev.resolveSessionAppearance === next.resolveSessionAppearance
|
||||
&& prev.onConnect === next.onConnect
|
||||
&& prev.onConnectRemoteDesktop === next.onConnectRemoteDesktop
|
||||
&& prev.onOpenSystemRemoteDesktop === next.onOpenSystemRemoteDesktop
|
||||
&& prev.onNewHost === next.onNewHost
|
||||
&& prev.onEditHost === next.onEditHost
|
||||
&& prev.onCreateLocalTerminal === next.onCreateLocalTerminal;
|
||||
@@ -89,6 +93,8 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
|
||||
themeById,
|
||||
resolveSessionAppearance,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onOpenSystemRemoteDesktop,
|
||||
onNewHost,
|
||||
onEditHost,
|
||||
onCreateLocalTerminal,
|
||||
@@ -185,6 +191,8 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
|
||||
resolvedPreviewTheme={sidebarPreviewTheme}
|
||||
activeHostId={activeHostId}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
|
||||
onNewHost={onNewHost}
|
||||
onEditHost={onEditHost}
|
||||
onCreateLocalTerminal={onCreateLocalTerminal}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import React, { useEffect, useMemo } from 'react';
|
||||
|
||||
import { PluginContributionHost } from '../../components/plugins/PluginContributionHost';
|
||||
import {
|
||||
isRemoteDesktopGrabReleaseChord,
|
||||
isTargetInsideRemoteDesktopCapture,
|
||||
} from '../../components/remoteDesktop/remoteDesktopHelpers';
|
||||
import type { TerminalSession, Workspace } from '../../types';
|
||||
import { useActiveTabId } from '../state/activeTabStore';
|
||||
import { resolveActivePluginKeybindingContext } from '../state/pluginContributionContexts';
|
||||
@@ -25,6 +29,21 @@ export function AppPluginKeybindingHost({
|
||||
workspaces: Workspace[];
|
||||
}) {
|
||||
const activeTabId = useActiveTabId();
|
||||
|
||||
// Short-circuit plugin keybindings when keyboard focus is inside an active
|
||||
// remote desktop capture surface (except for the grab-release chord).
|
||||
useEffect(() => {
|
||||
const onDocumentKeyDown = (event: KeyboardEvent) => {
|
||||
if (!isTargetInsideRemoteDesktopCapture(event.target, event.composedPath?.bind(event))) {
|
||||
return;
|
||||
}
|
||||
if (isRemoteDesktopGrabReleaseChord(event)) return;
|
||||
event.preventDefault();
|
||||
};
|
||||
document.addEventListener('keydown', onDocumentKeyDown);
|
||||
return () => document.removeEventListener('keydown', onDocumentKeyDown);
|
||||
}, []);
|
||||
|
||||
const keybindingContext = useMemo(() => {
|
||||
// AI chat recency drives the workspace anchor fallback (#4098 phase 2).
|
||||
// Read without subscribing: keybinding context is best-effort and refreshes
|
||||
|
||||
@@ -104,7 +104,8 @@ import { collectSnippetDeleteIds } from '../../domain/snippetSelection.ts';
|
||||
import { shouldOpenLocalTerminalOnStartup, resolveStartupLandingSetting } from '../../domain/startupLanding';
|
||||
import { createOpenTerminalQueue } from './openTerminalQueue';
|
||||
import { useAppStartupEffects } from './useAppStartupEffects';
|
||||
import { handleTrayJumpToSessionImpl, handleTrayTogglePortForwardImpl, handleTrayPanelConnectImpl, handleTrayPanelConnectRequestImpl, flushQueuedTrayPanelConnectHostsImpl, handleGlobalHotkeyKeyDownImpl, handleEscapeKeyDownImpl, handleKeyboardInteractiveSubmitImpl, handleKeyboardInteractiveCancelImpl, handlePassphraseSubmitImpl, handlePassphraseCancelImpl, handlePassphraseSkipImpl, handleFidoPromptSubmitImpl, handleFidoPromptCancelImpl, createLocalTerminalWithCurrentShellImpl, splitSessionWithCurrentShellImpl, copySessionWithCurrentShellImpl, duplicateSessionWithCurrentShellImpl, copyWorkspaceWithCurrentShellImpl, copySessionToNewWindowWithCurrentShellImpl, moveSessionToNewWindowImpl, confirmIfBusyLocalTerminalImpl, closeTabsBatchImpl, executeHotkeyActionImpl, handleCreateLocalTerminalImpl, handleConnectToHostImpl, handleTerminalDataCaptureImpl, startRestoredSessionConnectionLogImpl, hasMultipleProtocolsImpl, handleHostConnectWithProtocolCheckImpl, handleProtocolSelectImpl, handleRootContextMenuImpl, markForwardedNativeShortcutEvent } from './AppHandlers';
|
||||
import { handleTrayJumpToSessionImpl, handleTrayTogglePortForwardImpl, handleTrayPanelConnectImpl, handleTrayPanelConnectRequestImpl, flushQueuedTrayPanelConnectHostsImpl, handleGlobalHotkeyKeyDownImpl, handleEscapeKeyDownImpl, handleKeyboardInteractiveSubmitImpl, handleKeyboardInteractiveCancelImpl, handlePassphraseSubmitImpl, handlePassphraseCancelImpl, handlePassphraseSkipImpl, handleFidoPromptSubmitImpl, handleFidoPromptCancelImpl, createLocalTerminalWithCurrentShellImpl, splitSessionWithCurrentShellImpl, copySessionWithCurrentShellImpl, duplicateSessionWithCurrentShellImpl, copyWorkspaceWithCurrentShellImpl, copySessionToNewWindowWithCurrentShellImpl, moveSessionToNewWindowImpl, confirmIfBusyLocalTerminalImpl, closeTabsBatchImpl, executeHotkeyActionImpl, handleCreateLocalTerminalImpl, handleConnectToHostImpl, handleConnectRemoteDesktopImpl, handleOpenSystemRemoteDesktopImpl, handleTerminalDataCaptureImpl, startRestoredSessionConnectionLogImpl, hasMultipleProtocolsImpl, handleHostConnectWithProtocolCheckImpl, handleProtocolSelectImpl, handleRootContextMenuImpl, markForwardedNativeShortcutEvent } from './AppHandlers';
|
||||
import type { RemoteDesktopProtocol } from '../../domain/remoteDesktop';
|
||||
|
||||
type OpenSessionInNewWindowPayload = {
|
||||
title?: string;
|
||||
@@ -260,6 +261,7 @@ export function AppSideEffects() {
|
||||
createLocalTerminal,
|
||||
createSerialSession,
|
||||
connectToHost,
|
||||
connectToHostRemoteDesktop,
|
||||
appendHostToWorkspaceConfirmed,
|
||||
closeSession,
|
||||
closeSessions,
|
||||
@@ -1517,6 +1519,38 @@ export function AppSideEffects() {
|
||||
}), connectionHost, hidden);
|
||||
}, [addConnectionLog, appendHostToWorkspaceConfirmed, connectToHost, resolveEffectiveHost, identities, keys, discoveredShells]);
|
||||
|
||||
const handleConnectRemoteDesktop = useCallback((
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
options?: { splitFromSessionId?: string },
|
||||
) => {
|
||||
return handleConnectRemoteDesktopImpl(() => ({
|
||||
addConnectionLog,
|
||||
connectToHostRemoteDesktop,
|
||||
identities,
|
||||
resolveEffectiveHost,
|
||||
systemInfoRef,
|
||||
}), host, protocol, options);
|
||||
}, [addConnectionLog, connectToHostRemoteDesktop, identities, resolveEffectiveHost]);
|
||||
|
||||
const handleOpenSystemRemoteDesktop = useCallback((
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
rawRdpContent?: string,
|
||||
) => {
|
||||
void handleOpenSystemRemoteDesktopImpl(() => ({
|
||||
groupConfigs,
|
||||
hosts,
|
||||
identities,
|
||||
keys,
|
||||
knownHosts: knownHostsRef.current,
|
||||
netcattyBridge,
|
||||
proxyProfiles,
|
||||
resolveEffectiveHost,
|
||||
toast,
|
||||
}), host, protocol, rawRdpContent);
|
||||
}, [groupConfigs, hosts, identities, keys, proxyProfiles, resolveEffectiveHost]);
|
||||
|
||||
const handleConnectToHostWithTabName = useCallback((host: Host, tabName?: string) => {
|
||||
const sessionId = handleConnectToHost(host);
|
||||
if (sessionId && tabName) {
|
||||
@@ -1769,6 +1803,33 @@ export function AppSideEffects() {
|
||||
}
|
||||
return;
|
||||
}
|
||||
const targetProtocol = result.target.protocol.toLowerCase();
|
||||
const jumpServerRdpLaunchMode = settings.jumpServerRdpLaunchMode ?? 'builtin';
|
||||
if (
|
||||
targetProtocol === 'rdp'
|
||||
&& jumpServerRdpLaunchMode === 'system'
|
||||
&& result.target.rawRdpFileContent
|
||||
) {
|
||||
const rdBridge = netcattyBridge.get()?.remoteDesktop;
|
||||
if (rdBridge?.openSystemClient) {
|
||||
void rdBridge.openSystemClient({
|
||||
protocol: 'rdp',
|
||||
hostname: result.target.hostname,
|
||||
port: result.target.port,
|
||||
username: result.target.username || undefined,
|
||||
domain: result.target.domain || undefined,
|
||||
label: result.target.label,
|
||||
rdpContent: result.target.rawRdpFileContent,
|
||||
}).then((res) => {
|
||||
if (!res?.ok) {
|
||||
toast.error(res?.error || 'Failed to launch system RDP client');
|
||||
}
|
||||
}).catch((err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to launch system RDP client');
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
const ephemeralHost = buildJmsDeepLinkEphemeralHost(result.target, {
|
||||
id: crypto.randomUUID(),
|
||||
now: Date.now(),
|
||||
@@ -2009,7 +2070,26 @@ export function AppSideEffects() {
|
||||
const handleHostConnectWithProtocolCheck = useCallback((host: Host) => { return handleHostConnectWithProtocolCheckImpl(() => ({ handleConnectToHost, hasMultipleProtocols, host, resolveEffectiveHost, setIsQuickSwitcherOpen, setProtocolSelectHost }), host); }, [hasMultipleProtocols, handleConnectToHost, resolveEffectiveHost]);
|
||||
|
||||
// Handle protocol selection from dialog
|
||||
const handleProtocolSelect = useCallback((protocol: HostProtocol, port: number) => { return handleProtocolSelectImpl(() => ({ handleConnectToHost, port, protocol, protocolSelectHost, setProtocolSelectHost }), protocol, port); }, [protocolSelectHost, handleConnectToHost]);
|
||||
const handleProtocolSelect = useCallback(
|
||||
(protocol: HostProtocol, port: number, rememberDefault?: boolean) => {
|
||||
return handleProtocolSelectImpl(
|
||||
() => ({
|
||||
handleConnectToHost,
|
||||
handleConnectRemoteDesktop,
|
||||
port,
|
||||
protocol,
|
||||
protocolSelectHost,
|
||||
rememberDefault,
|
||||
setProtocolSelectHost,
|
||||
updateHosts,
|
||||
}),
|
||||
protocol,
|
||||
port,
|
||||
rememberDefault,
|
||||
);
|
||||
},
|
||||
[protocolSelectHost, handleConnectToHost, handleConnectRemoteDesktop, updateHosts],
|
||||
);
|
||||
|
||||
const handleOpenQuickSwitcher = useCallback(() => {
|
||||
setIsQuickSwitcherOpen(true);
|
||||
@@ -2102,6 +2182,8 @@ export function AppSideEffects() {
|
||||
createWorkspaceWithHosts: createWorkspaceWithEffectiveHosts,
|
||||
handleConnectSerial,
|
||||
handleConnectToHost,
|
||||
handleConnectRemoteDesktop,
|
||||
handleOpenSystemRemoteDesktop,
|
||||
handleCreateLocalTerminal,
|
||||
handleHotkeyAction,
|
||||
handleSessionStatusChange,
|
||||
@@ -2181,6 +2263,8 @@ export function AppSideEffects() {
|
||||
createWorkspaceWithEffectiveHosts,
|
||||
handleConnectSerial,
|
||||
handleConnectToHost,
|
||||
handleConnectRemoteDesktop,
|
||||
handleOpenSystemRemoteDesktop,
|
||||
handleCreateLocalTerminal,
|
||||
handleHotkeyAction,
|
||||
handleSessionStatusChange,
|
||||
|
||||
@@ -277,7 +277,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
convertKnownHostToHost, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
|
||||
customGroups, currentTerminalTheme, deepLinkHostDraft, draggingSessionId, effectiveKnownHosts, editorTabs, editorWordWrap, emptyVaultConflict,
|
||||
followAppTerminalTheme,
|
||||
groupConfigs, handleAddKnownHost, handleConnectSerial, handleConnectToHost, handleCreateLocalTerminal, handleDefaultTerminalThemeChange, handleDeleteHost,
|
||||
groupConfigs, handleAddKnownHost, handleConnectSerial, handleConnectToHost, handleConnectRemoteDesktop, handleOpenSystemRemoteDesktop, handleCreateLocalTerminal, handleDefaultTerminalThemeChange, handleDeleteHost,
|
||||
handleEndSessionDrag, handleFollowAppTerminalThemeChange, handleHostConnectWithProtocolCheck, handleHotkeyAction, handleKeyboardInteractiveCancel, handleKeyboardInteractiveSubmit,
|
||||
handleOpenHostFromVaultNote, handleOpenQuickSwitcher, handleOpenSettings, handleOpenVaultHostFromChat, handleOpenVaultNoteFromChat, handleOpenVaultSectionFromChat, handleOpenVaultSnippetFromChat, handleRootContextMenu, handlePassphraseCancel, handlePassphraseSkip, handlePassphraseSubmit, handleFidoPromptSubmit, handleFidoPromptCancel, handleProtocolSelect,
|
||||
handleRequestCloseEditorTabRef, handleSessionStatusChange, handleSyncNowManual, handleTerminalDataCapture, handleUpdateHostFromTerminal,
|
||||
@@ -621,6 +621,8 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
themeById={themeById}
|
||||
resolveSessionAppearance={resolveSessionAppearance}
|
||||
onConnect={handleConnectToHost}
|
||||
onConnectRemoteDesktop={handleConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={handleOpenSystemRemoteDesktop}
|
||||
onNewHost={workSurfaceHostEditor.openNew}
|
||||
onEditHost={workSurfaceHostEditor.openEdit}
|
||||
onCreateLocalTerminal={handleCreateLocalTerminal}
|
||||
@@ -672,6 +674,8 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
onConnectSerial={handleConnectSerial}
|
||||
onDeleteHost={handleDeleteHost}
|
||||
onConnect={handleConnectToHost}
|
||||
onConnectRemoteDesktop={handleConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={handleOpenSystemRemoteDesktop}
|
||||
onOpenHostFromNote={handleOpenHostFromVaultNote}
|
||||
groupConfigs={groupConfigs}
|
||||
onUpdateGroupConfigs={updateGroupConfigs}
|
||||
@@ -799,6 +803,8 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
onCopySessionToNewWindow={copySessionToNewWindowWithCurrentShell}
|
||||
onSplitSession={splitSessionWithCurrentShell}
|
||||
onConnectToHost={handleConnectToHost}
|
||||
onConnectRemoteDesktop={handleConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={handleOpenSystemRemoteDesktop}
|
||||
openNoteRequest={openNoteRequest}
|
||||
onOpenVaultNoteFromChat={handleOpenVaultNoteFromChat}
|
||||
onOpenVaultHostFromChat={handleOpenVaultHostFromChat}
|
||||
|
||||
@@ -195,6 +195,8 @@ export function TerminalHost() {
|
||||
resolveSessionAppearance: resolveFocusedAppearance,
|
||||
handleConnectSerial: handlers.handleConnectSerial,
|
||||
handleConnectToHost: handlers.handleConnectToHost,
|
||||
handleConnectRemoteDesktop: handlers.handleConnectRemoteDesktop,
|
||||
handleOpenSystemRemoteDesktop: handlers.handleOpenSystemRemoteDesktop,
|
||||
handleCreateLocalTerminal: handlers.handleCreateLocalTerminal,
|
||||
handleDefaultTerminalThemeChange,
|
||||
handleFollowAppTerminalThemeChange,
|
||||
|
||||
@@ -53,6 +53,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
createLocalTerminal,
|
||||
createSerialSession,
|
||||
connectToHost,
|
||||
connectToHostRemoteDesktop,
|
||||
updateSessionStatus,
|
||||
updateSessionFontSize,
|
||||
clearSessionFontSizeOverride,
|
||||
@@ -141,6 +142,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
createLocalTerminal,
|
||||
createSerialSession,
|
||||
connectToHost,
|
||||
connectToHostRemoteDesktop,
|
||||
updateSessionStatus,
|
||||
updateSessionFontSize,
|
||||
clearSessionFontSizeOverride,
|
||||
@@ -188,6 +190,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
closeSessions,
|
||||
closeWorkspace,
|
||||
connectToHost,
|
||||
connectToHostRemoteDesktop,
|
||||
copySession,
|
||||
copyWorkspace,
|
||||
createLocalTerminal,
|
||||
|
||||
@@ -868,4 +868,21 @@ export const enAiMessages: Messages = {
|
||||
"ai.toolSettings.conflict": "Settings changed in another window. Your draft is preserved. Cancel and reopen to load the saved settings.",
|
||||
"ai.toolSettings.retry": "Retry",
|
||||
"ai.toolSettings.applyingHttp": "Applying HTTP configuration...",
|
||||
"ai.vision.quickPrompt.explainError": "Explain current error",
|
||||
"ai.vision.quickPrompt.diagnoseUi": "Diagnose UI issue",
|
||||
"ai.vision.quickPrompt.summarizeScreen": "Summarize screen",
|
||||
"ai.vision.unsupportedModelWarning": "Current model ({model}) does not support image input. Switch to a vision-capable model to read remote screens.",
|
||||
"ai.vision.switchModel": "Switch model",
|
||||
"ai.vision.modelSupportsVision": "Supports image input",
|
||||
"ai.vision.snip.hint": "Drag to select a region · Esc to cancel",
|
||||
"ai.vision.snip.cancel": "Cancel region snip",
|
||||
"ai.vision.snip.ariaLabel": "Select a region of the remote desktop screen",
|
||||
"ai.vision.privacyBlocked": "AI screen reading is blocked for this session.",
|
||||
"ai.vision.viewingScreen": "AI is viewing screen",
|
||||
"ai.vision.askAi": "Ask AI",
|
||||
"ai.vision.captureFullAndAsk": "Capture screen & ask AI",
|
||||
"ai.vision.snipRegionAndAsk": "Snip region & ask AI",
|
||||
"ai.vision.openAiChat": "Open AI assistant",
|
||||
"ai.vision.privacyLockOn": "AI screen reading blocked",
|
||||
"ai.vision.privacyLockOff": "Allow AI to read screen",
|
||||
};
|
||||
@@ -106,4 +106,16 @@ export const enMonitorMessages = {
|
||||
"monitor.status.disconnected": "Disconnected",
|
||||
"monitor.status.stale": "Out of date",
|
||||
"monitor.status.missing": "Host deleted",
|
||||
"monitor.status.online": "Online",
|
||||
"monitor.status.offline": "Offline",
|
||||
"monitor.checkNow": "Check now",
|
||||
"monitor.openRemoteDesktop": "Open {protocol}",
|
||||
"monitor.latencyTrend": "Latency trend",
|
||||
"monitor.bannerVerified": "Protocol verified",
|
||||
"monitor.bannerUnverified": "Port open (banner unverified)",
|
||||
"monitor.companionDesktops": "Remote Desktop Services",
|
||||
"monitor.reachabilityOnly": "Reachability probe only",
|
||||
"monitor.viaSsh": "via SSH",
|
||||
"monitor.direct": "Direct",
|
||||
"monitor.rttStats": "Min / Avg / Max",
|
||||
};
|
||||
@@ -676,6 +676,7 @@ export const enVaultMessages: Messages = {
|
||||
|
||||
// Protocol select dialog
|
||||
'protocolSelect.chooseProtocol': 'Choose protocol',
|
||||
'protocolSelect.rememberDefault': 'Remember as default (skip this prompt next time)',
|
||||
'protocolSelect.port': 'port:',
|
||||
|
||||
// Host Details
|
||||
@@ -987,7 +988,22 @@ export const enVaultMessages: Messages = {
|
||||
'hostDetails.startupCommand.runMode.help': 'Choose how multi-line startup commands are sent after connection.',
|
||||
'hostDetails.startupCommand.runMode.lineDelay': 'Send line by line',
|
||||
'hostDetails.startupCommand.runMode.paste': 'Send all at once',
|
||||
'hostDetails.otherProtocols': 'Other Protocols',
|
||||
'hostDetails.otherProtocols': 'Additional Protocols',
|
||||
'hostDetails.otherProtocolsHint': 'Attach secondary access methods to this SSH host without changing its default connection',
|
||||
'hostDetails.protocol.defaultHint': 'Default on double-click ({protocol})',
|
||||
'hostDetails.protocol.secondaryHint': 'Enabled as secondary protocol',
|
||||
'hostDetails.protocol.setDefault': 'Set as default',
|
||||
'hostDetails.protocol.remove': 'Remove',
|
||||
'hostDetails.protocol.doubleClick': 'On double-click',
|
||||
'hostDetails.protocol.connectOptionDefault': 'Default: {protocol}',
|
||||
'hostDetails.protocol.connectOptionAsk': 'Ask every time',
|
||||
'hostDetails.protocol.alsoEnable': 'Also enable',
|
||||
'hostDetails.protocol.removeProtocol': 'Remove {protocol}',
|
||||
'hostDetails.protocol.addProtocol': 'Add {protocol}',
|
||||
'hostDetails.section.connectBehavior': 'Connection Behavior',
|
||||
'hostDetails.protocol.notEnabledDesc': '{protocol} is not enabled on this host yet.',
|
||||
'hostDetails.protocol.addSecondary': 'Add {protocol} (keep {defaultProtocol} default)',
|
||||
'hostDetails.protocol.switchOnly': 'Use {protocol} only',
|
||||
'hostDetails.telnetOn': 'Telnet on',
|
||||
'hostDetails.port': 'port',
|
||||
'hostDetails.telnet.credentials': 'Credentials',
|
||||
@@ -1087,4 +1103,224 @@ export const enVaultMessages: Messages = {
|
||||
'vault.import.plugins.moreItems': '{count} more items are included in this import.',
|
||||
'vault.import.plugins.moreDiagnostics': '{count} more diagnostics were omitted from this preview.',
|
||||
|
||||
// Remote Desktop (VNC / RDP / JumpServer RDP)
|
||||
'vault.hosts.newRdpHost': 'New RDP Host',
|
||||
'vault.hosts.newVncHost': 'New VNC Host',
|
||||
'vault.hosts.connectRdp': 'Connect RDP',
|
||||
'vault.hosts.connectSsh': 'Connect SSH',
|
||||
'vault.hosts.connectVnc': 'Connect VNC',
|
||||
'vault.hosts.openInSystemRdp': 'Open in System RDP',
|
||||
'vault.hosts.openInSystemVnc': 'Open in Screen Sharing',
|
||||
'settings.jmsDeepLink.rdpLaunchMode': 'Open JumpServer RDP in',
|
||||
'settings.jmsDeepLink.rdpLaunchModeDesc': 'Choose whether JumpServer jms:// RDP sessions open in Netcatty\'s built-in client or your system RDP app.',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.builtin': 'Built-in Client',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.system': 'System RDP Client',
|
||||
'vault.import.rdp.label': 'RDP (.rdp)',
|
||||
'vault.import.rdp.hint': 'Import one or more Microsoft / JumpServer .rdp files.',
|
||||
'vault.import.remoteDesktopTip': 'MobaXterm, CSV, and .rdp imports also support RDP and VNC hosts.',
|
||||
'keychain.identity.domain': 'Domain (RDP, optional)',
|
||||
'keychain.identity.domainPlaceholder': 'CORP or AD domain',
|
||||
'quickConnect.rdp.domain': 'Domain (optional)',
|
||||
'quickConnect.rdp.domainPlaceholder': 'CORP or leave empty for local account',
|
||||
'quickConnect.vnc.optionalUsername': 'Username (optional, for Apple ARD / VeNCrypt)',
|
||||
'quickConnect.vnc.optionalUsernameHint': 'Most VNC servers only require a password.',
|
||||
'quickConnect.vnc.passwordHint': 'Leave empty if the VNC server does not require authentication.',
|
||||
'quickConnect.vnc.displayHelper': 'Display {display}',
|
||||
'hostDetails.protocol.label': 'Protocol',
|
||||
'hostDetails.rdp.portLabel': 'RDP on',
|
||||
'hostDetails.vnc.portLabel': 'VNC on',
|
||||
'hostDetails.vnc.displayHint': 'Display {display}',
|
||||
'hostDetails.vnc.displayPlaceholder': '5900 or :0',
|
||||
'hostDetails.rdp.domain': 'Domain (optional)',
|
||||
'hostDetails.rdp.domainPlaceholder': 'CORP (optional)',
|
||||
'hostDetails.rdp.domainLabel': 'Domain',
|
||||
'hostDetails.rdp.usernamePlaceholder': 'Username, DOMAIN\\user, or JumpServer user|uuid',
|
||||
'hostDetails.vnc.optionalUsername': 'Username (Apple ARD / VeNCrypt)',
|
||||
'hostDetails.vnc.optionalUsernameHint': 'Optional. Standard VNC servers authenticate with password only.',
|
||||
'hostDetails.vnc.usernamePlaceholder': 'Username (optional)',
|
||||
'hostDetails.remoteDesktop.sectionTitle': 'Remote Desktop Display & Options',
|
||||
'hostDetails.rdp.resolutionMode': 'Resolution Mode',
|
||||
'hostDetails.rdp.resolutionMode.dynamic': 'Dynamic Resize',
|
||||
'hostDetails.rdp.resolutionMode.fit': 'Fit to Window',
|
||||
'hostDetails.rdp.resolutionMode.fixed': 'Fixed Size',
|
||||
'hostDetails.rdp.width': 'Width',
|
||||
'hostDetails.rdp.height': 'Height',
|
||||
'hostDetails.rdp.colorDepth': 'Color Depth',
|
||||
'hostDetails.rdp.audio': 'Audio Output',
|
||||
'hostDetails.rdp.audioDesc': 'Play remote desktop sound locally',
|
||||
'hostDetails.rdp.clipboard': 'Clipboard Sync',
|
||||
'hostDetails.rdp.clipboardDesc': 'Share text and images with the remote desktop',
|
||||
'hostDetails.rdp.clipboardFiles': 'Clipboard File Transfer',
|
||||
'hostDetails.rdp.clipboardFilesDesc': 'Allow copying and dropping files via clipboard',
|
||||
'hostDetails.rdp.securityMode': 'Security Mode',
|
||||
'hostDetails.rdp.securityMode.auto': 'Auto',
|
||||
'hostDetails.rdp.securityMode.nla': 'NLA (CredSSP)',
|
||||
'hostDetails.rdp.securityMode.tls': 'TLS',
|
||||
'hostDetails.rdp.securityMode.rdp': 'Standard RDP',
|
||||
'hostDetails.rdp.ignoreCertErrors': 'Ignore Certificate Errors',
|
||||
'hostDetails.rdp.ignoreCertErrorsDesc': 'Skip TLS certificate trust prompts (not recommended)',
|
||||
'hostDetails.rdp.advanced': 'Advanced RDP Options',
|
||||
'hostDetails.rdp.loadBalanceInfo': 'Load Balance Info',
|
||||
'hostDetails.rdp.loadBalanceInfoPlaceholder': 'tsv://MS Terminal Services Plugin.1.Collection',
|
||||
'hostDetails.rdp.alternateShell': 'Alternate Shell',
|
||||
'hostDetails.rdp.alternateShellPlaceholder': 'Optional startup program path',
|
||||
'hostDetails.rdp.shellWorkingDir': 'Working Directory',
|
||||
'hostDetails.rdp.shellWorkingDirPlaceholder': 'Optional startup directory',
|
||||
'hostDetails.vnc.scalingMode': 'Scaling Mode',
|
||||
'hostDetails.vnc.scalingMode.fit': 'Fit to Window',
|
||||
'hostDetails.vnc.scalingMode.actual': 'Actual (1:1)',
|
||||
'hostDetails.vnc.scalingMode.stretch': 'Stretch',
|
||||
'hostDetails.vnc.scalingMode.dynamic': 'Dynamic Resize',
|
||||
'hostDetails.vnc.quality': 'Image Quality',
|
||||
'hostDetails.vnc.compression': 'Compression Level',
|
||||
'hostDetails.vnc.viewOnly': 'View-Only Mode',
|
||||
'hostDetails.vnc.viewOnlyDesc': 'Disable sending mouse and keyboard input',
|
||||
'hostDetails.vnc.sharedSession': 'Shared Session',
|
||||
'hostDetails.vnc.sharedSessionDesc': 'Keep other VNC clients connected',
|
||||
'hostDetails.vnc.clipboard': 'Clipboard Sync',
|
||||
'hostDetails.vnc.clipboardDesc': 'Sync UTF-8 clipboard text with remote desktop',
|
||||
'hostDetails.vnc.showRemoteCursor': 'Show Remote Cursor',
|
||||
'hostDetails.vnc.showRemoteCursorDesc': 'Render server-provided cursor shape',
|
||||
'hostDetails.companion.addVnc': 'Add VNC',
|
||||
'hostDetails.companion.addRdp': 'Add RDP',
|
||||
'hostDetails.companion.tunnelViaSsh': 'Tunnel via this host\'s SSH',
|
||||
'hostDetails.companion.tunnelViaSshDesc': 'Forward through this host\'s SSH connection automatically',
|
||||
'hostDetails.companion.tunnelTargetHost': 'Remote target address',
|
||||
'hostDetails.companion.credentialsSource': 'Credentials',
|
||||
'hostDetails.companion.credentials.host': 'Reuse host SSH credentials',
|
||||
'hostDetails.companion.credentials.manual': 'Custom username / password',
|
||||
'hostDetails.companion.credentials.manualHint': 'Saved securely to Keychain when you save this host',
|
||||
'hostDetails.companion.credentials.identity': 'Keychain Identity',
|
||||
'hostDetails.companion.credentials.ask': 'Ask on connect',
|
||||
'hostDetails.companion.identityPlaceholder': 'Select a saved identity',
|
||||
'hostDetails.companion.saveAsIdentity': 'Save as Identity',
|
||||
'hostDetails.companion.saveIdentityAction': 'Create & Select Identity',
|
||||
'hostDetails.companion.identityLabelPlaceholder': 'Identity label (e.g. Desktop VNC)',
|
||||
'hostDetails.companion.identitySaved': 'Identity saved and selected.',
|
||||
'hostDetails.companion.setDefaultRdp': 'Connect with RDP by default',
|
||||
'hostDetails.companion.setDefaultVnc': 'Connect with VNC by default',
|
||||
|
||||
// Known Hosts — Remote Desktop TLS Certificates
|
||||
'knownHosts.tabs.ssh': 'SSH Host Keys',
|
||||
'knownHosts.tabs.remoteDesktopCerts': 'Remote Desktop Certificates',
|
||||
'knownHosts.certs.clearAll': 'Clear All',
|
||||
'knownHosts.certs.expired': 'Expired',
|
||||
'knownHosts.certs.expiredNotice': 'This certificate has passed its validity expiration date.',
|
||||
'knownHosts.certs.copied': 'SHA-256 fingerprint copied',
|
||||
'knownHosts.certs.action.inspect': 'Inspect Certificate',
|
||||
'knownHosts.certs.action.copyFingerprint': 'Copy SHA-256',
|
||||
'knownHosts.certs.action.revoke': 'Revoke Trust',
|
||||
'knownHosts.certs.empty.title': 'No Trusted Remote Desktop Certificates',
|
||||
'knownHosts.certs.empty.desc': 'TLS certificates you trust while connecting to RDP or VeNCrypt VNC hosts will appear here.',
|
||||
'knownHosts.certs.empty.searchTitle': 'No Matching Certificates',
|
||||
'knownHosts.certs.empty.searchDesc': 'Try a different hostname, port, protocol, or SHA-256 fingerprint.',
|
||||
'knownHosts.certs.detail.subtitle': 'Pinned TLS certificate trusted on this device (TOFU)',
|
||||
'knownHosts.certs.detail.fingerprint': 'SHA-256 Fingerprint',
|
||||
'knownHosts.certs.detail.subject': 'Subject',
|
||||
'knownHosts.certs.detail.issuer': 'Issuer',
|
||||
'knownHosts.certs.detail.validFrom': 'Valid From',
|
||||
'knownHosts.certs.detail.validTo': 'Valid To',
|
||||
'knownHosts.certs.detail.trustedAt': 'Trusted At',
|
||||
'knownHosts.certs.detail.lastSeen': 'Last Seen',
|
||||
'knownHosts.certs.revokeConfirm.title': 'Revoke certificate for {endpoint}?',
|
||||
'knownHosts.certs.revokeConfirm.desc': 'You will be asked to verify this server\'s TLS certificate again on the next connection.',
|
||||
'knownHosts.certs.clearAllConfirm.title': 'Clear all trusted remote desktop certificates?',
|
||||
'knownHosts.certs.clearAllConfirm.desc': 'This will revoke all {count} pinned RDP/VNC certificates on this device.',
|
||||
'knownHosts.certs.toast.revoked': 'Certificate trust revoked',
|
||||
'knownHosts.certs.toast.clearedAll': 'Cleared {count} remote desktop certificates',
|
||||
|
||||
// Host Connection Test — RDP / VNC Probe
|
||||
'hostDetails.connectionTest.rdp': 'Test RDP',
|
||||
'hostDetails.connectionTest.vnc': 'Test VNC',
|
||||
'hostDetails.connectionTest.probe.rtt': 'Latency (RTT)',
|
||||
'hostDetails.connectionTest.probe.protocol': 'Protocol',
|
||||
'hostDetails.connectionTest.probe.security': 'Negotiated Security',
|
||||
'hostDetails.connectionTest.probe.rfbVersion': 'RFB Version',
|
||||
'hostDetails.connectionTest.probe.securityTypes': 'Security Types',
|
||||
'hostDetails.connectionTest.probe.tls': 'TLS',
|
||||
'hostDetails.connectionTest.probe.fingerprint': 'SHA-256 Fingerprint',
|
||||
'hostDetails.connectionTest.probe.trustStatus.trusted': 'Trusted',
|
||||
'hostDetails.connectionTest.probe.trustStatus.firstSeen': 'First Seen',
|
||||
'hostDetails.connectionTest.probe.trustStatus.changed': 'Changed',
|
||||
'hostDetails.connectionTest.probe.trustFingerprint': 'Trust Fingerprint',
|
||||
'hostDetails.connectionTest.probe.fingerprintTrusted': 'Certificate fingerprint trusted',
|
||||
|
||||
// Remote Desktop Toolbar — SFTP, CLIPRDR, Recording, Ask AI
|
||||
'remoteDesktop.toolbar.openSftp': 'SFTP',
|
||||
'remoteDesktop.toolbar.record': 'Record session',
|
||||
'remoteDesktop.toolbar.stopRecording': 'Stop recording',
|
||||
'remoteDesktop.toolbar.recording': 'Recording',
|
||||
'remoteDesktop.toolbar.askAi': 'Ask AI',
|
||||
'remoteDesktop.toolbar.askAiFull': 'Capture Screen & Ask AI',
|
||||
'remoteDesktop.toolbar.askAiRegion': 'Select Region & Ask AI',
|
||||
'remoteDesktop.toolbar.aiReadAllowed': 'AI screen reading allowed',
|
||||
'remoteDesktop.toolbar.aiReadBlocked': 'AI screen reading blocked for this session',
|
||||
'remoteDesktop.toolbar.aiReadingBanner': 'AI is viewing this screen',
|
||||
'remoteDesktop.clipboard.dropTitle': 'Drop files to send to remote clipboard (CLIPRDR)',
|
||||
'remoteDesktop.clipboard.dropSubtitle': 'After dropping, press Ctrl+V inside the remote desktop to paste',
|
||||
'remoteDesktop.clipboard.dropFileCount': '{count} file(s)',
|
||||
'remoteDesktop.clipboard.dropBlockedViewOnly': 'File drop is disabled in View-Only mode',
|
||||
'remoteDesktop.clipboard.dropBlockedDisabled': 'Clipboard file transfer is disabled for this host',
|
||||
'remoteDesktop.clipboard.dropFolderUnsupported': 'Folders are not supported over RDP clipboard. Use SFTP or archive them as a .zip file.',
|
||||
'remoteDesktop.clipboard.stagedPill': '{count} file(s) · Ctrl+V',
|
||||
'remoteDesktop.clipboard.sendLocalFiles': 'Send Local Files...',
|
||||
'remoteDesktop.clipboard.uploading': 'Sending via clipboard',
|
||||
'remoteDesktop.clipboard.downloading': 'Receiving via clipboard',
|
||||
'remoteDesktop.clipboard.transferCompleted': 'Clipboard file transfer complete',
|
||||
'remoteDesktop.clipboard.transferFailed': 'Clipboard file transfer failed',
|
||||
'remoteDesktop.recording.started': 'Session recording started',
|
||||
'remoteDesktop.recording.saved': 'Session recording saved to Connection Logs',
|
||||
'remoteDesktop.recording.failed': 'Session recording failed',
|
||||
'remoteDesktop.recording.unsupported': 'Session recording is not supported in this environment',
|
||||
|
||||
// LogView — Remote Desktop Recordings & Metadata
|
||||
'logView.recording.download': 'Download .webm',
|
||||
'logView.recording.delete': 'Delete Recording',
|
||||
'logView.recording.loading': 'Loading session recording...',
|
||||
'logView.recording.withAudio': 'Audio',
|
||||
'logView.recording.missingTitle': 'Recording no longer on disk',
|
||||
'logView.recording.missingDesc': 'This .webm file was removed, cleaned up by retention settings, or moved from the recordings folder.',
|
||||
'logView.recording.playbackErrorTitle': 'Unable to play recording',
|
||||
'logView.recording.playbackErrorDesc': 'The video file may be incomplete or unsupported by the built-in player.',
|
||||
'logView.recording.exportSuccess': 'Recording exported',
|
||||
'logView.recording.exportFailed': 'Failed to export recording',
|
||||
'logView.recording.deleted': 'Recording deleted',
|
||||
'logView.recording.deleteFailed': 'Failed to delete recording',
|
||||
'logView.recording.deleteConfirmTitle': 'Delete this session recording?',
|
||||
'logView.recording.deleteConfirmDesc': 'The .webm video file will be permanently removed from disk. The connection log entry itself will remain.',
|
||||
'logView.remoteDesktop.noRecordingSubtitle': 'No screen recording was captured for this session',
|
||||
'logView.remoteDesktop.host': 'Host',
|
||||
'logView.remoteDesktop.protocol': 'Protocol',
|
||||
'logView.remoteDesktop.user': 'Username',
|
||||
'logView.remoteDesktop.started': 'Started',
|
||||
'logView.remoteDesktop.ended': 'Ended',
|
||||
'logView.remoteDesktop.duration': 'Duration',
|
||||
'logView.remoteDesktop.recordingTip': 'Click Record in the remote desktop toolbar or enable Auto-record in Settings -> System to save .webm replays here.',
|
||||
|
||||
// Settings -> System -> Remote Desktop Recordings
|
||||
'settings.remoteDesktopRecordings.title': 'Remote Desktop Recordings',
|
||||
'settings.remoteDesktopRecordings.autoRecord': 'Auto-record remote desktop sessions',
|
||||
'settings.remoteDesktopRecordings.autoRecordDesc': 'Automatically start recording RDP and VNC sessions once connected (off by default to conserve disk space).',
|
||||
'settings.remoteDesktopRecordings.fps': 'Recording frame rate',
|
||||
'settings.remoteDesktopRecordings.fpsDesc': 'Higher frame rates look smoother but use more CPU and disk space.',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
|
||||
'settings.remoteDesktopRecordings.includeAudio': 'Include RDP audio',
|
||||
'settings.remoteDesktopRecordings.includeAudioDesc': 'Merge remote desktop audio output into the recorded .webm video when available.',
|
||||
'settings.remoteDesktopRecordings.maxStorage': 'Maximum storage cap',
|
||||
'settings.remoteDesktopRecordings.maxStorageDesc': 'Oldest unsaved session recordings are automatically removed when total usage exceeds this limit.',
|
||||
'settings.remoteDesktopRecordings.retentionDays': 'Retention period',
|
||||
'settings.remoteDesktopRecordings.retentionDaysDesc': 'Automatically delete unsaved recordings older than this period.',
|
||||
'settings.remoteDesktopRecordings.retentionDaysOption': '{days} days',
|
||||
'settings.remoteDesktopRecordings.retentionUnlimited': 'Unlimited',
|
||||
'settings.remoteDesktopRecordings.storageUsage': 'Local recording storage',
|
||||
'settings.remoteDesktopRecordings.storageUsageSummary': '{count} files · {size}',
|
||||
'settings.remoteDesktopRecordings.storageUsageLoading': 'Calculating disk usage...',
|
||||
'settings.remoteDesktopRecordings.refresh': 'Refresh storage usage',
|
||||
'settings.remoteDesktopRecordings.openFolder': 'Open Folder',
|
||||
'settings.remoteDesktopRecordings.clearAll': 'Clear All Recordings',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmTitle': 'Clear all remote desktop recordings?',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'This will permanently delete {count} recorded .webm file(s) from this device.',
|
||||
'settings.remoteDesktopRecordings.clearResult': 'Removed {count} recording file(s).',
|
||||
'settings.remoteDesktopRecordings.hint': 'Recordings are stored locally on this device and never synced to the cloud. Bookmarked logs are protected from automatic cleanup.',
|
||||
|
||||
};
|
||||
@@ -868,4 +868,21 @@ export const esAiMessages: Messages = {
|
||||
"ai.toolSettings.conflict": "La configuración cambió en otra ventana. Se conserva el borrador. Cancela y vuelve a abrir para cargar la configuración guardada.",
|
||||
"ai.toolSettings.retry": "Reintentar",
|
||||
"ai.toolSettings.applyingHttp": "Aplicando la configuración HTTP...",
|
||||
"ai.vision.quickPrompt.explainError": "Explicar el error actual",
|
||||
"ai.vision.quickPrompt.diagnoseUi": "Diagnosticar problema de interfaz",
|
||||
"ai.vision.quickPrompt.summarizeScreen": "Resumir pantalla",
|
||||
"ai.vision.unsupportedModelWarning": "El modelo actual ({model}) no admite entrada de imágenes. Cambia a un modelo con visión para leer pantallas remotas.",
|
||||
"ai.vision.switchModel": "Cambiar modelo",
|
||||
"ai.vision.modelSupportsVision": "Admite entrada de imágenes",
|
||||
"ai.vision.snip.hint": "Arrastra para seleccionar un área · Esc para cancelar",
|
||||
"ai.vision.snip.cancel": "Cancelar selección",
|
||||
"ai.vision.snip.ariaLabel": "Seleccionar un área de la pantalla del escritorio remoto",
|
||||
"ai.vision.privacyBlocked": "La lectura de pantalla por IA está bloqueada en esta sesión.",
|
||||
"ai.vision.viewingScreen": "La IA está viendo la pantalla",
|
||||
"ai.vision.askAi": "Preguntar a la IA",
|
||||
"ai.vision.captureFullAndAsk": "Capturar pantalla y preguntar a la IA",
|
||||
"ai.vision.snipRegionAndAsk": "Recortar área y preguntar a la IA",
|
||||
"ai.vision.openAiChat": "Abrir asistente de IA",
|
||||
"ai.vision.privacyLockOn": "Lectura de pantalla por IA bloqueada",
|
||||
"ai.vision.privacyLockOff": "Permitir lectura de pantalla por IA",
|
||||
};
|
||||
@@ -106,4 +106,16 @@ export const esMonitorMessages = {
|
||||
"monitor.status.disconnected": "Desconectado",
|
||||
"monitor.status.stale": "Sin actualizar",
|
||||
"monitor.status.missing": "Equipo eliminado",
|
||||
"monitor.status.online": "En línea",
|
||||
"monitor.status.offline": "Sin conexión",
|
||||
"monitor.checkNow": "Comprobar ahora",
|
||||
"monitor.openRemoteDesktop": "Abrir {protocol}",
|
||||
"monitor.latencyTrend": "Tendencia de latencia",
|
||||
"monitor.bannerVerified": "Protocolo verificado",
|
||||
"monitor.bannerUnverified": "Puerto abierto (banner sin verificar)",
|
||||
"monitor.companionDesktops": "Servicios de escritorio remoto",
|
||||
"monitor.reachabilityOnly": "Solo sondeo de disponibilidad",
|
||||
"monitor.viaSsh": "vía SSH",
|
||||
"monitor.direct": "Directo",
|
||||
"monitor.rttStats": "Mín / Prom / Máx",
|
||||
};
|
||||
@@ -676,6 +676,7 @@ export const esVaultMessages: Messages = {
|
||||
|
||||
// Protocol select dialog
|
||||
'protocolSelect.chooseProtocol': 'Elegir protocolo',
|
||||
'protocolSelect.rememberDefault': 'Recordar como predeterminado (no preguntar la próxima vez)',
|
||||
'protocolSelect.port': 'puerto:',
|
||||
|
||||
// Host Details
|
||||
@@ -983,7 +984,22 @@ export const esVaultMessages: Messages = {
|
||||
'hostDetails.startupCommand.runMode.help': 'Elige cómo se envían los comandos de inicio multilínea después de la conexión.',
|
||||
'hostDetails.startupCommand.runMode.lineDelay': 'Enviar línea por línea',
|
||||
'hostDetails.startupCommand.runMode.paste': 'Enviar todo de una vez',
|
||||
'hostDetails.otherProtocols': 'Otros protocolos',
|
||||
'hostDetails.otherProtocols': 'Protocolos adicionales',
|
||||
'hostDetails.otherProtocolsHint': 'Adjunta métodos de acceso secundarios a este host SSH sin cambiar la conexión principal',
|
||||
'hostDetails.protocol.defaultHint': 'Predeterminado al hacer doble clic ({protocol})',
|
||||
'hostDetails.protocol.secondaryHint': 'Activado como protocolo secundario',
|
||||
'hostDetails.protocol.setDefault': 'Establecer por defecto',
|
||||
'hostDetails.protocol.remove': 'Quitar',
|
||||
'hostDetails.protocol.doubleClick': 'Al hacer doble clic',
|
||||
'hostDetails.protocol.connectOptionDefault': 'Por defecto: {protocol}',
|
||||
'hostDetails.protocol.connectOptionAsk': 'Preguntar cada vez',
|
||||
'hostDetails.protocol.alsoEnable': 'Activar también',
|
||||
'hostDetails.protocol.removeProtocol': 'Quitar {protocol}',
|
||||
'hostDetails.protocol.addProtocol': 'Añadir {protocol}',
|
||||
'hostDetails.section.connectBehavior': 'Comportamiento de conexión',
|
||||
'hostDetails.protocol.notEnabledDesc': '{protocol} aún no está habilitado en este host.',
|
||||
'hostDetails.protocol.addSecondary': 'Añadir {protocol} (mantener {defaultProtocol})',
|
||||
'hostDetails.protocol.switchOnly': 'Usar solo {protocol}',
|
||||
'hostDetails.telnetOn': 'Telnet activado',
|
||||
'hostDetails.port': 'puerto',
|
||||
'hostDetails.telnet.credentials': 'Credenciales',
|
||||
@@ -1089,4 +1105,224 @@ export const esVaultMessages: Messages = {
|
||||
'vault.import.plugins.moreItems': '{count} elementos más están incluidos en esta importación.',
|
||||
'vault.import.plugins.moreDiagnostics': '{count} diagnósticos más se omitieron de esta vista previa.',
|
||||
|
||||
// Remote Desktop (VNC / RDP / JumpServer RDP)
|
||||
'vault.hosts.newRdpHost': 'Nuevo host RDP',
|
||||
'vault.hosts.newVncHost': 'Nuevo host VNC',
|
||||
'vault.hosts.connectRdp': 'Conectar RDP',
|
||||
'vault.hosts.connectSsh': 'Conectar SSH',
|
||||
'vault.hosts.connectVnc': 'Conectar VNC',
|
||||
'vault.hosts.openInSystemRdp': 'Abrir en RDP del sistema',
|
||||
'vault.hosts.openInSystemVnc': 'Abrir en Compartir pantalla',
|
||||
'settings.jmsDeepLink.rdpLaunchMode': 'Abrir RDP de JumpServer en',
|
||||
'settings.jmsDeepLink.rdpLaunchModeDesc': 'Elige si las sesiones RDP de JumpServer jms:// se abren en el cliente integrado de Netcatty o en el cliente RDP del sistema.',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.builtin': 'Cliente integrado',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.system': 'Cliente RDP del sistema',
|
||||
'vault.import.rdp.label': 'RDP (.rdp)',
|
||||
'vault.import.rdp.hint': 'Importa uno o varios archivos .rdp de Microsoft o JumpServer.',
|
||||
'vault.import.remoteDesktopTip': 'Las importaciones de MobaXterm, CSV y .rdp también admiten hosts RDP y VNC.',
|
||||
'keychain.identity.domain': 'Dominio (RDP, opcional)',
|
||||
'keychain.identity.domainPlaceholder': 'CORP o dominio AD',
|
||||
'quickConnect.rdp.domain': 'Dominio (opcional)',
|
||||
'quickConnect.rdp.domainPlaceholder': 'CORP o déjalo vacío para cuenta local',
|
||||
'quickConnect.vnc.optionalUsername': 'Usuario (opcional, para Apple ARD / VeNCrypt)',
|
||||
'quickConnect.vnc.optionalUsernameHint': 'La mayoría de los servidores VNC solo requieren contraseña.',
|
||||
'quickConnect.vnc.passwordHint': 'Déjalo vacío si el servidor VNC no requiere autenticación.',
|
||||
'quickConnect.vnc.displayHelper': 'Pantalla {display}',
|
||||
'hostDetails.protocol.label': 'Protocolo',
|
||||
'hostDetails.rdp.portLabel': 'RDP en',
|
||||
'hostDetails.vnc.portLabel': 'VNC en',
|
||||
'hostDetails.vnc.displayHint': 'Pantalla {display}',
|
||||
'hostDetails.vnc.displayPlaceholder': '5900 o :0',
|
||||
'hostDetails.rdp.domain': 'Dominio (opcional)',
|
||||
'hostDetails.rdp.domainPlaceholder': 'CORP (opcional)',
|
||||
'hostDetails.rdp.domainLabel': 'Dominio',
|
||||
'hostDetails.rdp.usernamePlaceholder': 'Usuario, DOMINIO\\usuario o JumpServer user|uuid',
|
||||
'hostDetails.vnc.optionalUsername': 'Usuario (Apple ARD / VeNCrypt)',
|
||||
'hostDetails.vnc.optionalUsernameHint': 'Opcional. Los servidores VNC estándar solo usan contraseña.',
|
||||
'hostDetails.vnc.usernamePlaceholder': 'Usuario (opcional)',
|
||||
'hostDetails.remoteDesktop.sectionTitle': 'Pantalla y opciones de escritorio remoto',
|
||||
'hostDetails.rdp.resolutionMode': 'Modo de resolución',
|
||||
'hostDetails.rdp.resolutionMode.dynamic': 'Cambio dinámico',
|
||||
'hostDetails.rdp.resolutionMode.fit': 'Ajustar a la ventana',
|
||||
'hostDetails.rdp.resolutionMode.fixed': 'Tamaño fijo',
|
||||
'hostDetails.rdp.width': 'Ancho',
|
||||
'hostDetails.rdp.height': 'Alto',
|
||||
'hostDetails.rdp.colorDepth': 'Profundidad de color',
|
||||
'hostDetails.rdp.audio': 'Salida de audio',
|
||||
'hostDetails.rdp.audioDesc': 'Reproducir el audio del escritorio remoto localmente',
|
||||
'hostDetails.rdp.clipboard': 'Sincronización de portapapeles',
|
||||
'hostDetails.rdp.clipboardDesc': 'Compartir texto e imágenes con el escritorio remoto',
|
||||
'hostDetails.rdp.clipboardFiles': 'Transferencia de archivos por portapapeles',
|
||||
'hostDetails.rdp.clipboardFilesDesc': 'Permitir copiar y arrastrar archivos mediante el portapapeles',
|
||||
'hostDetails.rdp.securityMode': 'Modo de seguridad',
|
||||
'hostDetails.rdp.securityMode.auto': 'Automático',
|
||||
'hostDetails.rdp.securityMode.nla': 'NLA (CredSSP)',
|
||||
'hostDetails.rdp.securityMode.tls': 'TLS',
|
||||
'hostDetails.rdp.securityMode.rdp': 'RDP estándar',
|
||||
'hostDetails.rdp.ignoreCertErrors': 'Ignorar errores de certificado',
|
||||
'hostDetails.rdp.ignoreCertErrorsDesc': 'Omitir avisos de confianza de certificados TLS (no recomendado)',
|
||||
'hostDetails.rdp.advanced': 'Opciones avanzadas de RDP',
|
||||
'hostDetails.rdp.loadBalanceInfo': 'Información de balanceo de carga',
|
||||
'hostDetails.rdp.loadBalanceInfoPlaceholder': 'tsv://MS Terminal Services Plugin.1.Collection',
|
||||
'hostDetails.rdp.alternateShell': 'Shell alternativo',
|
||||
'hostDetails.rdp.alternateShellPlaceholder': 'Ruta opcional del programa inicial',
|
||||
'hostDetails.rdp.shellWorkingDir': 'Directorio de trabajo',
|
||||
'hostDetails.rdp.shellWorkingDirPlaceholder': 'Directorio inicial opcional',
|
||||
'hostDetails.vnc.scalingMode': 'Modo de escala',
|
||||
'hostDetails.vnc.scalingMode.fit': 'Ajustar a la ventana',
|
||||
'hostDetails.vnc.scalingMode.actual': 'Tamaño real (1:1)',
|
||||
'hostDetails.vnc.scalingMode.stretch': 'Estirar',
|
||||
'hostDetails.vnc.scalingMode.dynamic': 'Cambio dinámico',
|
||||
'hostDetails.vnc.quality': 'Calidad de imagen',
|
||||
'hostDetails.vnc.compression': 'Nivel de compresión',
|
||||
'hostDetails.vnc.viewOnly': 'Modo solo lectura',
|
||||
'hostDetails.vnc.viewOnlyDesc': 'Desactivar el envío de entradas de ratón y teclado',
|
||||
'hostDetails.vnc.sharedSession': 'Sesión compartida',
|
||||
'hostDetails.vnc.sharedSessionDesc': 'Mantener conectados otros clientes VNC',
|
||||
'hostDetails.vnc.clipboard': 'Sincronización de portapapeles',
|
||||
'hostDetails.vnc.clipboardDesc': 'Sincronizar texto UTF-8 del portapapeles con el escritorio remoto',
|
||||
'hostDetails.vnc.showRemoteCursor': 'Mostrar cursor remoto',
|
||||
'hostDetails.vnc.showRemoteCursorDesc': 'Mostrar la forma del cursor enviada por el servidor',
|
||||
'hostDetails.companion.addVnc': 'Añadir VNC',
|
||||
'hostDetails.companion.addRdp': 'Añadir RDP',
|
||||
'hostDetails.companion.tunnelViaSsh': 'Túnel mediante el SSH de este host',
|
||||
'hostDetails.companion.tunnelViaSshDesc': 'Reenviar automáticamente a través de la conexión SSH de este host',
|
||||
'hostDetails.companion.tunnelTargetHost': 'Dirección de destino remota',
|
||||
'hostDetails.companion.credentialsSource': 'Credenciales',
|
||||
'hostDetails.companion.credentials.host': 'Reutilizar credenciales SSH del host',
|
||||
'hostDetails.companion.credentials.manual': 'Usuario y contraseña propios',
|
||||
'hostDetails.companion.credentials.manualHint': 'Se guarda de forma segura en el llavero al guardar el host',
|
||||
'hostDetails.companion.credentials.identity': 'Identidad del llavero',
|
||||
'hostDetails.companion.credentials.ask': 'Preguntar al conectar',
|
||||
'hostDetails.companion.identityPlaceholder': 'Seleccionar una identidad guardada',
|
||||
'hostDetails.companion.saveAsIdentity': 'Guardar como identidad',
|
||||
'hostDetails.companion.saveIdentityAction': 'Crear y seleccionar identidad',
|
||||
'hostDetails.companion.identityLabelPlaceholder': 'Nombre de identidad (p. ej. Desktop VNC)',
|
||||
'hostDetails.companion.identitySaved': 'Identidad guardada y seleccionada.',
|
||||
'hostDetails.companion.setDefaultRdp': 'Conectar con RDP por defecto',
|
||||
'hostDetails.companion.setDefaultVnc': 'Conectar con VNC por defecto',
|
||||
|
||||
// Known Hosts — Remote Desktop TLS Certificates
|
||||
'knownHosts.tabs.ssh': 'Claves de host SSH',
|
||||
'knownHosts.tabs.remoteDesktopCerts': 'Certificados de escritorio remoto',
|
||||
'knownHosts.certs.clearAll': 'Borrar todo',
|
||||
'knownHosts.certs.expired': 'Caducado',
|
||||
'knownHosts.certs.expiredNotice': 'Este certificado ha superado su fecha de caducidad.',
|
||||
'knownHosts.certs.copied': 'Huella SHA-256 copiada',
|
||||
'knownHosts.certs.action.inspect': 'Inspeccionar certificado',
|
||||
'knownHosts.certs.action.copyFingerprint': 'Copiar SHA-256',
|
||||
'knownHosts.certs.action.revoke': 'Revocar confianza',
|
||||
'knownHosts.certs.empty.title': 'Sin certificados de escritorio remoto confiables',
|
||||
'knownHosts.certs.empty.desc': 'Los certificados TLS en los que confíes al conectar a hosts RDP o VNC VeNCrypt aparecerán aquí.',
|
||||
'knownHosts.certs.empty.searchTitle': 'Sin certificados coincidentes',
|
||||
'knownHosts.certs.empty.searchDesc': 'Prueba con otro nombre de host, puerto, protocolo o huella SHA-256.',
|
||||
'knownHosts.certs.detail.subtitle': 'Certificado TLS fijado en este dispositivo (TOFU)',
|
||||
'knownHosts.certs.detail.fingerprint': 'Huella SHA-256',
|
||||
'knownHosts.certs.detail.subject': 'Asunto',
|
||||
'knownHosts.certs.detail.issuer': 'Emisor',
|
||||
'knownHosts.certs.detail.validFrom': 'Válido desde',
|
||||
'knownHosts.certs.detail.validTo': 'Válido hasta',
|
||||
'knownHosts.certs.detail.trustedAt': 'Confiado el',
|
||||
'knownHosts.certs.detail.lastSeen': 'Última conexión',
|
||||
'knownHosts.certs.revokeConfirm.title': '¿Revocar el certificado de {endpoint}?',
|
||||
'knownHosts.certs.revokeConfirm.desc': 'Se te pedirá volver a verificar el certificado TLS de este servidor en la próxima conexión.',
|
||||
'knownHosts.certs.clearAllConfirm.title': '¿Borrar todos los certificados confiables de escritorio remoto?',
|
||||
'knownHosts.certs.clearAllConfirm.desc': 'Se revocarán los {count} certificados RDP/VNC fijados en este dispositivo.',
|
||||
'knownHosts.certs.toast.revoked': 'Confianza del certificado revocada',
|
||||
'knownHosts.certs.toast.clearedAll': 'Se borraron {count} certificados de escritorio remoto',
|
||||
|
||||
// Host Connection Test — RDP / VNC Probe
|
||||
'hostDetails.connectionTest.rdp': 'Probar RDP',
|
||||
'hostDetails.connectionTest.vnc': 'Probar VNC',
|
||||
'hostDetails.connectionTest.probe.rtt': 'Latencia (RTT)',
|
||||
'hostDetails.connectionTest.probe.protocol': 'Protocolo',
|
||||
'hostDetails.connectionTest.probe.security': 'Seguridad negociada',
|
||||
'hostDetails.connectionTest.probe.rfbVersion': 'Versión RFB',
|
||||
'hostDetails.connectionTest.probe.securityTypes': 'Tipos de seguridad',
|
||||
'hostDetails.connectionTest.probe.tls': 'TLS',
|
||||
'hostDetails.connectionTest.probe.fingerprint': 'Huella SHA-256',
|
||||
'hostDetails.connectionTest.probe.trustStatus.trusted': 'Confiable',
|
||||
'hostDetails.connectionTest.probe.trustStatus.firstSeen': 'Primera vez',
|
||||
'hostDetails.connectionTest.probe.trustStatus.changed': 'Modificado',
|
||||
'hostDetails.connectionTest.probe.trustFingerprint': 'Confiar en huella',
|
||||
'hostDetails.connectionTest.probe.fingerprintTrusted': 'Huella del certificado confiada',
|
||||
|
||||
// Remote Desktop Toolbar — SFTP, CLIPRDR, Recording, Ask AI
|
||||
'remoteDesktop.toolbar.openSftp': 'SFTP',
|
||||
'remoteDesktop.toolbar.record': 'Grabar sesión',
|
||||
'remoteDesktop.toolbar.stopRecording': 'Detener grabación',
|
||||
'remoteDesktop.toolbar.recording': 'Grabando',
|
||||
'remoteDesktop.toolbar.askAi': 'Preguntar a la IA',
|
||||
'remoteDesktop.toolbar.askAiFull': 'Capturar pantalla y preguntar a la IA',
|
||||
'remoteDesktop.toolbar.askAiRegion': 'Seleccionar región y preguntar a la IA',
|
||||
'remoteDesktop.toolbar.aiReadAllowed': 'Lectura de pantalla por IA permitida',
|
||||
'remoteDesktop.toolbar.aiReadBlocked': 'Lectura de pantalla por IA bloqueada en esta sesión',
|
||||
'remoteDesktop.toolbar.aiReadingBanner': 'La IA está viendo esta pantalla',
|
||||
'remoteDesktop.clipboard.dropTitle': 'Suelta archivos para enviarlos al portapapeles remoto (CLIPRDR)',
|
||||
'remoteDesktop.clipboard.dropSubtitle': 'Después de soltar, pulsa Ctrl+V en el escritorio remoto para pegar',
|
||||
'remoteDesktop.clipboard.dropFileCount': '{count} archivo(s)',
|
||||
'remoteDesktop.clipboard.dropBlockedViewOnly': 'No se pueden soltar archivos en modo solo lectura',
|
||||
'remoteDesktop.clipboard.dropBlockedDisabled': 'La transferencia de archivos por portapapeles está desactivada en este host',
|
||||
'remoteDesktop.clipboard.dropFolderUnsupported': 'Las carpetas no son compatibles por el portapapeles RDP. Usa SFTP o comprímelas en un archivo .zip.',
|
||||
'remoteDesktop.clipboard.stagedPill': '{count} archivo(s) · Ctrl+V',
|
||||
'remoteDesktop.clipboard.sendLocalFiles': 'Enviar archivos locales...',
|
||||
'remoteDesktop.clipboard.uploading': 'Enviando por portapapeles',
|
||||
'remoteDesktop.clipboard.downloading': 'Recibiendo por portapapeles',
|
||||
'remoteDesktop.clipboard.transferCompleted': 'Transferencia de archivos por portapapeles completada',
|
||||
'remoteDesktop.clipboard.transferFailed': 'Error en la transferencia de archivos por portapapeles',
|
||||
'remoteDesktop.recording.started': 'Grabación de sesión iniciada',
|
||||
'remoteDesktop.recording.saved': 'Grabación de sesión guardada en los registros de conexión',
|
||||
'remoteDesktop.recording.failed': 'Error al grabar la sesión',
|
||||
'remoteDesktop.recording.unsupported': 'La grabación de sesiones no es compatible en este entorno',
|
||||
|
||||
// LogView — Remote Desktop Recordings & Metadata
|
||||
'logView.recording.download': 'Descargar .webm',
|
||||
'logView.recording.delete': 'Eliminar grabación',
|
||||
'logView.recording.loading': 'Cargando grabación de sesión...',
|
||||
'logView.recording.withAudio': 'Audio',
|
||||
'logView.recording.missingTitle': 'La grabación ya no está en el disco',
|
||||
'logView.recording.missingDesc': 'Este archivo .webm fue eliminado, limpiado por la política de retención o movido de la carpeta de grabaciones.',
|
||||
'logView.recording.playbackErrorTitle': 'No se puede reproducir la grabación',
|
||||
'logView.recording.playbackErrorDesc': 'El archivo de vídeo puede estar incompleto o no ser compatible con el reproductor integrado.',
|
||||
'logView.recording.exportSuccess': 'Grabación exportada',
|
||||
'logView.recording.exportFailed': 'Error al exportar la grabación',
|
||||
'logView.recording.deleted': 'Grabación eliminada',
|
||||
'logView.recording.deleteFailed': 'Error al eliminar la grabación',
|
||||
'logView.recording.deleteConfirmTitle': '¿Eliminar esta grabación de sesión?',
|
||||
'logView.recording.deleteConfirmDesc': 'El archivo de vídeo .webm se eliminará permanentemente del disco. La entrada del registro de conexión se conservará.',
|
||||
'logView.remoteDesktop.noRecordingSubtitle': 'No se capturó ninguna grabación de pantalla para esta sesión',
|
||||
'logView.remoteDesktop.host': 'Host',
|
||||
'logView.remoteDesktop.protocol': 'Protocolo',
|
||||
'logView.remoteDesktop.user': 'Usuario',
|
||||
'logView.remoteDesktop.started': 'Inicio',
|
||||
'logView.remoteDesktop.ended': 'Fin',
|
||||
'logView.remoteDesktop.duration': 'Duración',
|
||||
'logView.remoteDesktop.recordingTip': 'Haz clic en Grabar en la barra de escritorio remoto o activa la grabación automática en Ajustes → Sistema para guardar repeticiones .webm aquí.',
|
||||
|
||||
// Settings -> System -> Remote Desktop Recordings
|
||||
'settings.remoteDesktopRecordings.title': 'Grabaciones de escritorio remoto',
|
||||
'settings.remoteDesktopRecordings.autoRecord': 'Grabar automáticamente sesiones de escritorio remoto',
|
||||
'settings.remoteDesktopRecordings.autoRecordDesc': 'Iniciar la grabación de sesiones RDP y VNC al conectarse (desactivado por defecto para ahorrar espacio en disco).',
|
||||
'settings.remoteDesktopRecordings.fps': 'Frecuencia de fotogramas',
|
||||
'settings.remoteDesktopRecordings.fpsDesc': 'Una mayor frecuencia ofrece más fluidez pero consume más CPU y espacio en disco.',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
|
||||
'settings.remoteDesktopRecordings.includeAudio': 'Incluir audio RDP',
|
||||
'settings.remoteDesktopRecordings.includeAudioDesc': 'Combinar la salida de audio del escritorio remoto en el vídeo .webm cuando esté disponible.',
|
||||
'settings.remoteDesktopRecordings.maxStorage': 'Límite máximo de almacenamiento',
|
||||
'settings.remoteDesktopRecordings.maxStorageDesc': 'Las grabaciones más antiguas sin guardar se eliminan automáticamente al superar este límite.',
|
||||
'settings.remoteDesktopRecordings.retentionDays': 'Periodo de retención',
|
||||
'settings.remoteDesktopRecordings.retentionDaysDesc': 'Eliminar automáticamente las grabaciones sin guardar más antiguas que este periodo.',
|
||||
'settings.remoteDesktopRecordings.retentionDaysOption': '{days} días',
|
||||
'settings.remoteDesktopRecordings.retentionUnlimited': 'Ilimitado',
|
||||
'settings.remoteDesktopRecordings.storageUsage': 'Almacenamiento local de grabaciones',
|
||||
'settings.remoteDesktopRecordings.storageUsageSummary': '{count} archivos · {size}',
|
||||
'settings.remoteDesktopRecordings.storageUsageLoading': 'Calculando uso de disco...',
|
||||
'settings.remoteDesktopRecordings.refresh': 'Actualizar uso de almacenamiento',
|
||||
'settings.remoteDesktopRecordings.openFolder': 'Abrir carpeta',
|
||||
'settings.remoteDesktopRecordings.clearAll': 'Borrar todas las grabaciones',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmTitle': '¿Borrar todas las grabaciones de escritorio remoto?',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'Se eliminarán permanentemente {count} archivo(s) .webm grabados en este dispositivo.',
|
||||
'settings.remoteDesktopRecordings.clearResult': 'Se eliminaron {count} archivo(s) de grabación.',
|
||||
'settings.remoteDesktopRecordings.hint': 'Las grabaciones se guardan solo localmente en este dispositivo y nunca se sincronizan en la nube. Los registros guardados están protegidos frente a la limpieza automática.',
|
||||
|
||||
};
|
||||
@@ -798,4 +798,21 @@ export const ruAiMessages: Messages = {
|
||||
"ai.toolSettings.conflict": "Настройки изменены в другом окне. Черновик сохранён. Отмените и откройте окно снова, чтобы загрузить сохранённые настройки.",
|
||||
"ai.toolSettings.retry": "Повторить",
|
||||
"ai.toolSettings.applyingHttp": "Применение настроек HTTP...",
|
||||
"ai.vision.quickPrompt.explainError": "Объяснить текущую ошибку",
|
||||
"ai.vision.quickPrompt.diagnoseUi": "Диагностировать проблему интерфейса",
|
||||
"ai.vision.quickPrompt.summarizeScreen": "Кратко описать экран",
|
||||
"ai.vision.unsupportedModelWarning": "Текущая модель ({model}) не поддерживает изображения. Переключитесь на модель с поддержкой зрения для просмотра удалённого экрана.",
|
||||
"ai.vision.switchModel": "Сменить модель",
|
||||
"ai.vision.modelSupportsVision": "Поддерживает изображения",
|
||||
"ai.vision.snip.hint": "Выделите область мышью · Esc для отмены",
|
||||
"ai.vision.snip.cancel": "Отменить выделение",
|
||||
"ai.vision.snip.ariaLabel": "Выделить область экрана удалённого рабочего стола",
|
||||
"ai.vision.privacyBlocked": "Чтение экрана ИИ заблокировано для этой сессии.",
|
||||
"ai.vision.viewingScreen": "ИИ просматривает экран",
|
||||
"ai.vision.askAi": "Спросить ИИ",
|
||||
"ai.vision.captureFullAndAsk": "Снимок экрана и вопрос ИИ",
|
||||
"ai.vision.snipRegionAndAsk": "Выделить область и спросить ИИ",
|
||||
"ai.vision.openAiChat": "Открыть ИИ-ассистента",
|
||||
"ai.vision.privacyLockOn": "Чтение экрана ИИ заблокировано",
|
||||
"ai.vision.privacyLockOff": "Разрешить ИИ чтение экрана",
|
||||
};
|
||||
@@ -105,4 +105,16 @@ export const ruMonitorMessages = {
|
||||
"monitor.status.disconnected": "Отключено",
|
||||
"monitor.status.stale": "Устарело",
|
||||
"monitor.status.missing": "Сервер удалён",
|
||||
"monitor.status.online": "В сети",
|
||||
"monitor.status.offline": "Не в сети",
|
||||
"monitor.checkNow": "Проверить сейчас",
|
||||
"monitor.openRemoteDesktop": "Открыть {protocol}",
|
||||
"monitor.latencyTrend": "График задержки",
|
||||
"monitor.bannerVerified": "Протокол подтверждён",
|
||||
"monitor.bannerUnverified": "Порт открыт (баннер не проверен)",
|
||||
"monitor.companionDesktops": "Службы удалённого рабочего стола",
|
||||
"monitor.reachabilityOnly": "Только проверка доступности",
|
||||
"monitor.viaSsh": "через SSH",
|
||||
"monitor.direct": "Напрямую",
|
||||
"monitor.rttStats": "Мин / Сред / Макс",
|
||||
};
|
||||
@@ -719,6 +719,7 @@ export const ruVaultMessages: Messages = {
|
||||
|
||||
// Protocol select dialog
|
||||
'protocolSelect.chooseProtocol': 'Выберите протокол',
|
||||
'protocolSelect.rememberDefault': 'Запомнить по умолчанию (больше не спрашивать)',
|
||||
'protocolSelect.port': 'порт:',
|
||||
|
||||
// Host Details
|
||||
@@ -1025,7 +1026,22 @@ export const ruVaultMessages: Messages = {
|
||||
'hostDetails.startupCommand.runMode.help': 'Выберите, как отправлять многострочные команды запуска после подключения.',
|
||||
'hostDetails.startupCommand.runMode.lineDelay': 'Отправлять построчно',
|
||||
'hostDetails.startupCommand.runMode.paste': 'Отправить сразу',
|
||||
'hostDetails.otherProtocols': 'Другие протоколы',
|
||||
'hostDetails.otherProtocols': 'Дополнительные протоколы',
|
||||
'hostDetails.otherProtocolsHint': 'Добавьте вспомогательные способы подключения к этому SSH-хосту без смены основного протокола',
|
||||
'hostDetails.protocol.defaultHint': 'По умолчанию при двойном клике ({protocol})',
|
||||
'hostDetails.protocol.secondaryHint': 'Включён как дополнительный протокол',
|
||||
'hostDetails.protocol.setDefault': 'Сделать основным',
|
||||
'hostDetails.protocol.remove': 'Удалить',
|
||||
'hostDetails.protocol.doubleClick': 'По двойному клику',
|
||||
'hostDetails.protocol.connectOptionDefault': 'По умолчанию: {protocol}',
|
||||
'hostDetails.protocol.connectOptionAsk': 'Спрашивать каждый раз',
|
||||
'hostDetails.protocol.alsoEnable': 'Также включить',
|
||||
'hostDetails.protocol.removeProtocol': 'Удалить {protocol}',
|
||||
'hostDetails.protocol.addProtocol': 'Добавить {protocol}',
|
||||
'hostDetails.section.connectBehavior': 'Поведение подключения',
|
||||
'hostDetails.protocol.notEnabledDesc': 'Протокол {protocol} ещё не включён для этого хоста.',
|
||||
'hostDetails.protocol.addSecondary': 'Добавить {protocol} (оставить {defaultProtocol})',
|
||||
'hostDetails.protocol.switchOnly': 'Использовать только {protocol}',
|
||||
'hostDetails.telnetOn': 'Telnet на',
|
||||
'hostDetails.port': 'порт',
|
||||
'hostDetails.telnet.credentials': 'Учётные данные',
|
||||
@@ -1105,4 +1121,224 @@ export const ruVaultMessages: Messages = {
|
||||
'vault.import.plugins.moreItems': 'В импорт включено ещё элементов: {count}.',
|
||||
'vault.import.plugins.moreDiagnostics': 'В предварительном просмотре скрыто ещё сообщений: {count}.',
|
||||
|
||||
// Remote Desktop (VNC / RDP / JumpServer RDP)
|
||||
'vault.hosts.newRdpHost': 'Новый хост RDP',
|
||||
'vault.hosts.newVncHost': 'Новый хост VNC',
|
||||
'vault.hosts.connectRdp': 'Подключить RDP',
|
||||
'vault.hosts.connectSsh': 'Подключить SSH',
|
||||
'vault.hosts.connectVnc': 'Подключить VNC',
|
||||
'vault.hosts.openInSystemRdp': 'Открыть в системном RDP',
|
||||
'vault.hosts.openInSystemVnc': 'Открыть в системном VNC',
|
||||
'settings.jmsDeepLink.rdpLaunchMode': 'Открывать JumpServer RDP в',
|
||||
'settings.jmsDeepLink.rdpLaunchModeDesc': 'Выберите, открывать ли RDP-сессии JumpServer jms:// во встроенном клиенте Netcatty или в системном RDP-клиенте.',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.builtin': 'Встроенный клиент',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.system': 'Системный клиент RDP',
|
||||
'vault.import.rdp.label': 'RDP (.rdp)',
|
||||
'vault.import.rdp.hint': 'Импорт одного или нескольких файлов Microsoft / JumpServer .rdp.',
|
||||
'vault.import.remoteDesktopTip': 'Импорт MobaXterm, CSV и .rdp также поддерживает хосты RDP и VNC.',
|
||||
'keychain.identity.domain': 'Домен (RDP, необязательно)',
|
||||
'keychain.identity.domainPlaceholder': 'CORP или домен AD',
|
||||
'quickConnect.rdp.domain': 'Домен (необязательно)',
|
||||
'quickConnect.rdp.domainPlaceholder': 'CORP или оставьте пустым для локальной учётной записи',
|
||||
'quickConnect.vnc.optionalUsername': 'Имя пользователя (необязательно, для Apple ARD / VeNCrypt)',
|
||||
'quickConnect.vnc.optionalUsernameHint': 'Большинство серверов VNC требуют только пароль.',
|
||||
'quickConnect.vnc.passwordHint': 'Оставьте пустым, если сервер VNC не требует аутентификации.',
|
||||
'quickConnect.vnc.displayHelper': 'Дисплей {display}',
|
||||
'hostDetails.protocol.label': 'Протокол',
|
||||
'hostDetails.rdp.portLabel': 'RDP на',
|
||||
'hostDetails.vnc.portLabel': 'VNC на',
|
||||
'hostDetails.vnc.displayHint': 'Дисплей {display}',
|
||||
'hostDetails.vnc.displayPlaceholder': '5900 или :0',
|
||||
'hostDetails.rdp.domain': 'Домен (необязательно)',
|
||||
'hostDetails.rdp.domainPlaceholder': 'CORP (необязательно)',
|
||||
'hostDetails.rdp.domainLabel': 'Домен',
|
||||
'hostDetails.rdp.usernamePlaceholder': 'Имя пользователя, DOMAIN\\user или JumpServer user|uuid',
|
||||
'hostDetails.vnc.optionalUsername': 'Имя пользователя (Apple ARD / VeNCrypt)',
|
||||
'hostDetails.vnc.optionalUsernameHint': 'Необязательно. Стандартный VNC использует только пароль.',
|
||||
'hostDetails.vnc.usernamePlaceholder': 'Имя пользователя (необязательно)',
|
||||
'hostDetails.remoteDesktop.sectionTitle': 'Экран и параметры удалённого рабочего стола',
|
||||
'hostDetails.rdp.resolutionMode': 'Режим разрешения',
|
||||
'hostDetails.rdp.resolutionMode.dynamic': 'Динамический размер',
|
||||
'hostDetails.rdp.resolutionMode.fit': 'По размеру окна',
|
||||
'hostDetails.rdp.resolutionMode.fixed': 'Фиксированный размер',
|
||||
'hostDetails.rdp.width': 'Ширина',
|
||||
'hostDetails.rdp.height': 'Высота',
|
||||
'hostDetails.rdp.colorDepth': 'Глубина цвета',
|
||||
'hostDetails.rdp.audio': 'Вывод звука',
|
||||
'hostDetails.rdp.audioDesc': 'Воспроизводить звук удалённого рабочего стола локально',
|
||||
'hostDetails.rdp.clipboard': 'Синхронизация буфера обмена',
|
||||
'hostDetails.rdp.clipboardDesc': 'Обмен текстом и изображениями с удалённым рабочим столом',
|
||||
'hostDetails.rdp.clipboardFiles': 'Передача файлов через буфер обмена',
|
||||
'hostDetails.rdp.clipboardFilesDesc': 'Разрешить копирование и перетаскивание файлов через буфер обмена',
|
||||
'hostDetails.rdp.securityMode': 'Режим безопасности',
|
||||
'hostDetails.rdp.securityMode.auto': 'Авто',
|
||||
'hostDetails.rdp.securityMode.nla': 'NLA (CredSSP)',
|
||||
'hostDetails.rdp.securityMode.tls': 'TLS',
|
||||
'hostDetails.rdp.securityMode.rdp': 'Стандартный RDP',
|
||||
'hostDetails.rdp.ignoreCertErrors': 'Игнорировать ошибки сертификатов',
|
||||
'hostDetails.rdp.ignoreCertErrorsDesc': 'Пропускать проверку доверия TLS-сертификатов (не рекомендуется)',
|
||||
'hostDetails.rdp.advanced': 'Дополнительные параметры RDP',
|
||||
'hostDetails.rdp.loadBalanceInfo': 'Информация балансировки (Load Balance Info)',
|
||||
'hostDetails.rdp.loadBalanceInfoPlaceholder': 'tsv://MS Terminal Services Plugin.1.Collection',
|
||||
'hostDetails.rdp.alternateShell': 'Альтернативная оболочка',
|
||||
'hostDetails.rdp.alternateShellPlaceholder': 'Необязательный путь к программе запуска',
|
||||
'hostDetails.rdp.shellWorkingDir': 'Рабочий каталог',
|
||||
'hostDetails.rdp.shellWorkingDirPlaceholder': 'Необязательный рабочий каталог запуска',
|
||||
'hostDetails.vnc.scalingMode': 'Масштабирование',
|
||||
'hostDetails.vnc.scalingMode.fit': 'По размеру окна',
|
||||
'hostDetails.vnc.scalingMode.actual': 'Исходный (1:1)',
|
||||
'hostDetails.vnc.scalingMode.stretch': 'Растянуть',
|
||||
'hostDetails.vnc.scalingMode.dynamic': 'Динамический размер',
|
||||
'hostDetails.vnc.quality': 'Качество изображения',
|
||||
'hostDetails.vnc.compression': 'Уровень сжатия',
|
||||
'hostDetails.vnc.viewOnly': 'Только просмотр',
|
||||
'hostDetails.vnc.viewOnlyDesc': 'Отключить передачу ввода мыши и клавиатуры',
|
||||
'hostDetails.vnc.sharedSession': 'Совместная сессия',
|
||||
'hostDetails.vnc.sharedSessionDesc': 'Не отключать другие VNC-клиенты',
|
||||
'hostDetails.vnc.clipboard': 'Синхронизация буфера обмена',
|
||||
'hostDetails.vnc.clipboardDesc': 'Синхронизировать текст UTF-8 с удалённым рабочим столом',
|
||||
'hostDetails.vnc.showRemoteCursor': 'Показывать удалённый курсор',
|
||||
'hostDetails.vnc.showRemoteCursorDesc': 'Отображать курсор, передаваемый сервером',
|
||||
'hostDetails.companion.addVnc': 'Добавить VNC',
|
||||
'hostDetails.companion.addRdp': 'Добавить RDP',
|
||||
'hostDetails.companion.tunnelViaSsh': 'Туннель через SSH этого хоста',
|
||||
'hostDetails.companion.tunnelViaSshDesc': 'Автоматическая переадресация через SSH-подключение этого хоста',
|
||||
'hostDetails.companion.tunnelTargetHost': 'Удалённый целевой адрес',
|
||||
'hostDetails.companion.credentialsSource': 'Учётные данные',
|
||||
'hostDetails.companion.credentials.host': 'Использовать SSH-данные хоста',
|
||||
'hostDetails.companion.credentials.manual': 'Свой логин и пароль',
|
||||
'hostDetails.companion.credentials.manualHint': 'Безопасно сохранится в связке ключей при сохранении хоста',
|
||||
'hostDetails.companion.credentials.identity': 'Учётные данные из связки',
|
||||
'hostDetails.companion.credentials.ask': 'Спрашивать при подключении',
|
||||
'hostDetails.companion.identityPlaceholder': 'Выберите сохранённую учётную запись',
|
||||
'hostDetails.companion.saveAsIdentity': 'Сохранить как учётную запись',
|
||||
'hostDetails.companion.saveIdentityAction': 'Создать и выбрать',
|
||||
'hostDetails.companion.identityLabelPlaceholder': 'Название (например, Desktop VNC)',
|
||||
'hostDetails.companion.identitySaved': 'Учётная запись сохранена и выбрана.',
|
||||
'hostDetails.companion.setDefaultRdp': 'Подключаться по RDP по умолчанию',
|
||||
'hostDetails.companion.setDefaultVnc': 'Подключаться по VNC по умолчанию',
|
||||
|
||||
// Known Hosts — Remote Desktop TLS Certificates
|
||||
'knownHosts.tabs.ssh': 'Ключи хостов SSH',
|
||||
'knownHosts.tabs.remoteDesktopCerts': 'Сертификаты удалённого рабочего стола',
|
||||
'knownHosts.certs.clearAll': 'Очистить все',
|
||||
'knownHosts.certs.expired': 'Истёк',
|
||||
'knownHosts.certs.expiredNotice': 'Срок действия этого сертификата истёк.',
|
||||
'knownHosts.certs.copied': 'Отпечаток SHA-256 скопирован',
|
||||
'knownHosts.certs.action.inspect': 'Просмотреть сертификат',
|
||||
'knownHosts.certs.action.copyFingerprint': 'Копировать SHA-256',
|
||||
'knownHosts.certs.action.revoke': 'Отозвать доверие',
|
||||
'knownHosts.certs.empty.title': 'Нет доверенных сертификатов удалённого рабочего стола',
|
||||
'knownHosts.certs.empty.desc': 'TLS-сертификаты, которым вы доверились при подключении к хостам RDP или VeNCrypt VNC, появятся здесь.',
|
||||
'knownHosts.certs.empty.searchTitle': 'Подходящие сертификаты не найдены',
|
||||
'knownHosts.certs.empty.searchDesc': 'Попробуйте другой хост, порт, протокол или отпечаток SHA-256.',
|
||||
'knownHosts.certs.detail.subtitle': 'Закреплённый TLS-сертификат на этом устройстве (TOFU)',
|
||||
'knownHosts.certs.detail.fingerprint': 'Отпечаток SHA-256',
|
||||
'knownHosts.certs.detail.subject': 'Субъект',
|
||||
'knownHosts.certs.detail.issuer': 'Издатель',
|
||||
'knownHosts.certs.detail.validFrom': 'Действителен с',
|
||||
'knownHosts.certs.detail.validTo': 'Действителен до',
|
||||
'knownHosts.certs.detail.trustedAt': 'Доверен с',
|
||||
'knownHosts.certs.detail.lastSeen': 'Последнее подключение',
|
||||
'knownHosts.certs.revokeConfirm.title': 'Отозвать сертификат для {endpoint}?',
|
||||
'knownHosts.certs.revokeConfirm.desc': 'При следующем подключении потребуется повторно подтвердить TLS-сертификат этого сервера.',
|
||||
'knownHosts.certs.clearAllConfirm.title': 'Очистить все доверенные сертификаты удалённого рабочего стола?',
|
||||
'knownHosts.certs.clearAllConfirm.desc': 'Будет отозвано доверие для всех закреплённых сертификатов RDP/VNC ({count}) на этом устройстве.',
|
||||
'knownHosts.certs.toast.revoked': 'Доверие к сертификату отозвано',
|
||||
'knownHosts.certs.toast.clearedAll': 'Очищено сертификатов удалённого рабочего стола: {count}',
|
||||
|
||||
// Host Connection Test — RDP / VNC Probe
|
||||
'hostDetails.connectionTest.rdp': 'Проверить RDP',
|
||||
'hostDetails.connectionTest.vnc': 'Проверить VNC',
|
||||
'hostDetails.connectionTest.probe.rtt': 'Задержка (RTT)',
|
||||
'hostDetails.connectionTest.probe.protocol': 'Протокол',
|
||||
'hostDetails.connectionTest.probe.security': 'Согласованная защита',
|
||||
'hostDetails.connectionTest.probe.rfbVersion': 'Версия RFB',
|
||||
'hostDetails.connectionTest.probe.securityTypes': 'Типы аутентификации',
|
||||
'hostDetails.connectionTest.probe.tls': 'TLS',
|
||||
'hostDetails.connectionTest.probe.fingerprint': 'Отпечаток SHA-256',
|
||||
'hostDetails.connectionTest.probe.trustStatus.trusted': 'Доверенный',
|
||||
'hostDetails.connectionTest.probe.trustStatus.firstSeen': 'Впервые встречен',
|
||||
'hostDetails.connectionTest.probe.trustStatus.changed': 'Изменён',
|
||||
'hostDetails.connectionTest.probe.trustFingerprint': 'Доверять отпечатку',
|
||||
'hostDetails.connectionTest.probe.fingerprintTrusted': 'Отпечаток сертификата добавлен в доверенные',
|
||||
|
||||
// Remote Desktop Toolbar — SFTP, CLIPRDR, Recording, Ask AI
|
||||
'remoteDesktop.toolbar.openSftp': 'SFTP',
|
||||
'remoteDesktop.toolbar.record': 'Записать сессию',
|
||||
'remoteDesktop.toolbar.stopRecording': 'Остановить запись',
|
||||
'remoteDesktop.toolbar.recording': 'Запись',
|
||||
'remoteDesktop.toolbar.askAi': 'Спросить ИИ',
|
||||
'remoteDesktop.toolbar.askAiFull': 'Снять экран и спросить ИИ',
|
||||
'remoteDesktop.toolbar.askAiRegion': 'Выбрать область и спросить ИИ',
|
||||
'remoteDesktop.toolbar.aiReadAllowed': 'Чтение экрана ИИ разрешено',
|
||||
'remoteDesktop.toolbar.aiReadBlocked': 'Чтение экрана ИИ запрещено для этой сессии',
|
||||
'remoteDesktop.toolbar.aiReadingBanner': 'ИИ просматривает экран',
|
||||
'remoteDesktop.clipboard.dropTitle': 'Перетащите файлы для отправки в удалённый буфер обмена (CLIPRDR)',
|
||||
'remoteDesktop.clipboard.dropSubtitle': 'После перетаскивания нажмите Ctrl+V на удалённом рабочем столе',
|
||||
'remoteDesktop.clipboard.dropFileCount': 'Файлов: {count}',
|
||||
'remoteDesktop.clipboard.dropBlockedViewOnly': 'Перетаскивание файлов отключено в режиме «Только просмотр»',
|
||||
'remoteDesktop.clipboard.dropBlockedDisabled': 'Передача файлов через буфер обмена отключена для этого хоста',
|
||||
'remoteDesktop.clipboard.dropFolderUnsupported': 'Папки не поддерживаются буфером обмена RDP. Используйте SFTP или упакуйте их в .zip.',
|
||||
'remoteDesktop.clipboard.stagedPill': 'Файлов: {count} · Ctrl+V',
|
||||
'remoteDesktop.clipboard.sendLocalFiles': 'Выбрать локальные файлы...',
|
||||
'remoteDesktop.clipboard.uploading': 'Отправка через буфер обмена',
|
||||
'remoteDesktop.clipboard.downloading': 'Получение через буфер обмена',
|
||||
'remoteDesktop.clipboard.transferCompleted': 'Передача файлов через буфер обмена завершена',
|
||||
'remoteDesktop.clipboard.transferFailed': 'Ошибка передачи файлов через буфер обмена',
|
||||
'remoteDesktop.recording.started': 'Запись сессии начата',
|
||||
'remoteDesktop.recording.saved': 'Запись сессии сохранена в журналах подключений',
|
||||
'remoteDesktop.recording.failed': 'Ошибка записи сессии',
|
||||
'remoteDesktop.recording.unsupported': 'Запись сессий не поддерживается в этой среде',
|
||||
|
||||
// LogView — Remote Desktop Recordings & Metadata
|
||||
'logView.recording.download': 'Скачать .webm',
|
||||
'logView.recording.delete': 'Удалить запись',
|
||||
'logView.recording.loading': 'Загрузка записи сессии...',
|
||||
'logView.recording.withAudio': 'Звук',
|
||||
'logView.recording.missingTitle': 'Файл записи отсутствует на диске',
|
||||
'logView.recording.missingDesc': 'Этот файл .webm был удалён, очищен по сроку хранения или перемещён из папки записей.',
|
||||
'logView.recording.playbackErrorTitle': 'Не удалось воспроизвести запись',
|
||||
'logView.recording.playbackErrorDesc': 'Видеофайл может быть повреждён или не поддерживается встроенным плеером.',
|
||||
'logView.recording.exportSuccess': 'Запись экспортирована',
|
||||
'logView.recording.exportFailed': 'Не удалось экспортировать запись',
|
||||
'logView.recording.deleted': 'Запись удалена',
|
||||
'logView.recording.deleteFailed': 'Не удалось удалить запись',
|
||||
'logView.recording.deleteConfirmTitle': 'Удалить эту запись сессии?',
|
||||
'logView.recording.deleteConfirmDesc': 'Видеофайл .webm будет безвозвратно удалён с диска. Сама запись в журнале подключений сохранится.',
|
||||
'logView.remoteDesktop.noRecordingSubtitle': 'Для этой сессии видеозапись экрана не велась',
|
||||
'logView.remoteDesktop.host': 'Хост',
|
||||
'logView.remoteDesktop.protocol': 'Протокол',
|
||||
'logView.remoteDesktop.user': 'Пользователь',
|
||||
'logView.remoteDesktop.started': 'Начало',
|
||||
'logView.remoteDesktop.ended': 'Окончание',
|
||||
'logView.remoteDesktop.duration': 'Длительность',
|
||||
'logView.remoteDesktop.recordingTip': 'Нажмите «Записать сессию» на панели удалённого рабочего стола или включите автозапись в Настройки → Система, чтобы сохранять повторы .webm.',
|
||||
|
||||
// Settings -> System -> Remote Desktop Recordings
|
||||
'settings.remoteDesktopRecordings.title': 'Записи удалённого рабочего стола',
|
||||
'settings.remoteDesktopRecordings.autoRecord': 'Автозапись сессий удалённого рабочего стола',
|
||||
'settings.remoteDesktopRecordings.autoRecordDesc': 'Автоматически начинать запись RDP и VNC после подключения (выключено по умолчанию для экономии места).',
|
||||
'settings.remoteDesktopRecordings.fps': 'Частота кадров записи',
|
||||
'settings.remoteDesktopRecordings.fpsDesc': 'Более высокая частота делает видео плавнее, но увеличивает нагрузку на ЦП и размер файлов.',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
|
||||
'settings.remoteDesktopRecordings.includeAudio': 'Включать звук RDP',
|
||||
'settings.remoteDesktopRecordings.includeAudioDesc': 'Записывать звук удалённого рабочего стола в видео .webm, если он доступен.',
|
||||
'settings.remoteDesktopRecordings.maxStorage': 'Лимит места на диске',
|
||||
'settings.remoteDesktopRecordings.maxStorageDesc': 'Самые старые несохранённые записи автоматически удаляются при превышении лимита.',
|
||||
'settings.remoteDesktopRecordings.retentionDays': 'Срок хранения',
|
||||
'settings.remoteDesktopRecordings.retentionDaysDesc': 'Автоматически удалять несохранённые записи старше указанного срока.',
|
||||
'settings.remoteDesktopRecordings.retentionDaysOption': '{days} дн.',
|
||||
'settings.remoteDesktopRecordings.retentionUnlimited': 'Без ограничений',
|
||||
'settings.remoteDesktopRecordings.storageUsage': 'Локальное хранилище записей',
|
||||
'settings.remoteDesktopRecordings.storageUsageSummary': 'Файлов: {count} · {size}',
|
||||
'settings.remoteDesktopRecordings.storageUsageLoading': 'Подсчёт занятого места...',
|
||||
'settings.remoteDesktopRecordings.refresh': 'Обновить статистику',
|
||||
'settings.remoteDesktopRecordings.openFolder': 'Открыть папку',
|
||||
'settings.remoteDesktopRecordings.clearAll': 'Очистить все записи',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmTitle': 'Очистить все записи удалённого рабочего стола?',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'С этого устройства будут безвозвратно удалены файлы .webm ({count}).',
|
||||
'settings.remoteDesktopRecordings.clearResult': 'Удалено файлов записей: {count}.',
|
||||
'settings.remoteDesktopRecordings.hint': 'Записи хранятся только локально на этом устройстве и не синхронизируются с облаком. Закреплённые журналы защищены от автоматической очистки.',
|
||||
|
||||
};
|
||||
@@ -868,4 +868,21 @@ export const zhCNAiMessages: Messages = {
|
||||
"ai.toolSettings.conflict": "设置已在另一窗口更改,当前草稿已保留。请取消并重新打开以加载已保存的设置。",
|
||||
"ai.toolSettings.retry": "重试",
|
||||
"ai.toolSettings.applyingHttp": "正在应用 HTTP 配置…",
|
||||
"ai.vision.quickPrompt.explainError": "解释当前报错",
|
||||
"ai.vision.quickPrompt.diagnoseUi": "诊断界面问题",
|
||||
"ai.vision.quickPrompt.summarizeScreen": "总结屏幕内容",
|
||||
"ai.vision.unsupportedModelWarning": "当前模型({model})不支持图片输入,切换至支持视觉的模型即可看图读屏。",
|
||||
"ai.vision.switchModel": "切换模型",
|
||||
"ai.vision.modelSupportsVision": "支持图片输入",
|
||||
"ai.vision.snip.hint": "拖拽框选区域 · 按 Esc 取消",
|
||||
"ai.vision.snip.cancel": "取消框选",
|
||||
"ai.vision.snip.ariaLabel": "框选远程桌面画面区域",
|
||||
"ai.vision.privacyBlocked": "当前会话已禁止 AI 读屏。",
|
||||
"ai.vision.viewingScreen": "AI 正在查看画面",
|
||||
"ai.vision.askAi": "问 AI",
|
||||
"ai.vision.captureFullAndAsk": "一键截屏问 AI",
|
||||
"ai.vision.snipRegionAndAsk": "框选区域问 AI",
|
||||
"ai.vision.openAiChat": "打开 AI 助手",
|
||||
"ai.vision.privacyLockOn": "已禁止 AI 读屏",
|
||||
"ai.vision.privacyLockOff": "允许 AI 读屏",
|
||||
};
|
||||
@@ -101,4 +101,16 @@ export const zhCNMonitorMessages = {
|
||||
"monitor.status.disconnected": "已断开",
|
||||
"monitor.status.stale": "读数过期",
|
||||
"monitor.status.missing": "主机已删除",
|
||||
"monitor.status.online": "在线",
|
||||
"monitor.status.offline": "离线",
|
||||
"monitor.checkNow": "立即检测",
|
||||
"monitor.openRemoteDesktop": "打开 {protocol}",
|
||||
"monitor.latencyTrend": "延迟趋势",
|
||||
"monitor.bannerVerified": "协议已校验",
|
||||
"monitor.bannerUnverified": "端口已开放(未校验协议)",
|
||||
"monitor.companionDesktops": "伴生远程桌面服务",
|
||||
"monitor.reachabilityOnly": "仅在线与延迟探测",
|
||||
"monitor.viaSsh": "经由 SSH",
|
||||
"monitor.direct": "直连",
|
||||
"monitor.rttStats": "最小 / 平均 / 最大",
|
||||
};
|
||||
@@ -109,6 +109,7 @@ export const zhCNVaultMessages: Messages = {
|
||||
|
||||
// Protocol select dialog
|
||||
'protocolSelect.chooseProtocol': '选择协议',
|
||||
'protocolSelect.rememberDefault': '记住为默认连接(下次不再询问)',
|
||||
'protocolSelect.port': '端口:',
|
||||
// Host Details
|
||||
'hostDetails.title.details': '主机详情',
|
||||
@@ -379,7 +380,22 @@ export const zhCNVaultMessages: Messages = {
|
||||
'hostDetails.startupCommand.runMode.help': '选择连接后如何发送多行启动命令。',
|
||||
'hostDetails.startupCommand.runMode.lineDelay': '逐行发送',
|
||||
'hostDetails.startupCommand.runMode.paste': '一次性发送',
|
||||
'hostDetails.otherProtocols': '其他协议',
|
||||
'hostDetails.otherProtocols': '附加协议',
|
||||
'hostDetails.otherProtocolsHint': '为当前 SSH 主机挂载辅助连接方式,不影响默认连接',
|
||||
'hostDetails.protocol.defaultHint': '双击默认使用 {protocol}',
|
||||
'hostDetails.protocol.secondaryHint': '已作为附加协议启用',
|
||||
'hostDetails.protocol.setDefault': '设为默认',
|
||||
'hostDetails.protocol.remove': '移除',
|
||||
'hostDetails.protocol.doubleClick': '双击连接',
|
||||
'hostDetails.protocol.connectOptionDefault': '默认 {protocol}',
|
||||
'hostDetails.protocol.connectOptionAsk': '每次询问',
|
||||
'hostDetails.protocol.alsoEnable': '同时启用',
|
||||
'hostDetails.protocol.removeProtocol': '移除 {protocol}',
|
||||
'hostDetails.protocol.addProtocol': '添加 {protocol}',
|
||||
'hostDetails.section.connectBehavior': '连接行为',
|
||||
'hostDetails.protocol.notEnabledDesc': '当前主机尚未启用 {protocol} 协议。',
|
||||
'hostDetails.protocol.addSecondary': '添加 {protocol}(保留 {defaultProtocol} 默认)',
|
||||
'hostDetails.protocol.switchOnly': '仅使用 {protocol}',
|
||||
'hostDetails.telnetOn': 'Telnet on',
|
||||
'hostDetails.port': '端口',
|
||||
'hostDetails.telnet.credentials': '凭据',
|
||||
@@ -1055,4 +1071,224 @@ export const zhCNVaultMessages: Messages = {
|
||||
'vault.import.plugins.moreItems': '本次导入还包含 {count} 个项目。',
|
||||
'vault.import.plugins.moreDiagnostics': '预览中省略了另外 {count} 条诊断信息。',
|
||||
|
||||
// Remote Desktop (VNC / RDP / JumpServer RDP)
|
||||
'vault.hosts.newRdpHost': '新建 RDP 主机',
|
||||
'vault.hosts.newVncHost': '新建 VNC 主机',
|
||||
'vault.hosts.connectRdp': '连接 RDP',
|
||||
'vault.hosts.connectSsh': '连接 SSH',
|
||||
'vault.hosts.connectVnc': '连接 VNC',
|
||||
'vault.hosts.openInSystemRdp': '在系统 RDP 客户端中打开',
|
||||
'vault.hosts.openInSystemVnc': '在系统屏幕共享中打开',
|
||||
'settings.jmsDeepLink.rdpLaunchMode': 'JumpServer RDP 打开方式',
|
||||
'settings.jmsDeepLink.rdpLaunchModeDesc': '选择通过 JumpServer jms:// 启动 Windows RDP 会话时使用 Netcatty 内置客户端还是系统 RDP 客户端。',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.builtin': '内置客户端',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.system': '系统 RDP 客户端',
|
||||
'vault.import.rdp.label': 'RDP (.rdp)',
|
||||
'vault.import.rdp.hint': '导入单个或多个 Microsoft / JumpServer .rdp 文件。',
|
||||
'vault.import.remoteDesktopTip': 'MobaXterm、CSV 与 .rdp 导入均支持 RDP 和 VNC 主机。',
|
||||
'keychain.identity.domain': '域 (RDP,可选)',
|
||||
'keychain.identity.domainPlaceholder': 'CORP 或 AD 域名',
|
||||
'quickConnect.rdp.domain': '域(可选)',
|
||||
'quickConnect.rdp.domainPlaceholder': 'CORP 或留空使用本地账户',
|
||||
'quickConnect.vnc.optionalUsername': '用户名(可选,用于 Apple ARD / VeNCrypt)',
|
||||
'quickConnect.vnc.optionalUsernameHint': '大多数 VNC 服务器仅需密码认证。',
|
||||
'quickConnect.vnc.passwordHint': '如果 VNC 服务器无需密码,可留空直接连接。',
|
||||
'quickConnect.vnc.displayHelper': '显示器 {display}',
|
||||
'hostDetails.protocol.label': '协议',
|
||||
'hostDetails.rdp.portLabel': 'RDP 端口',
|
||||
'hostDetails.vnc.portLabel': 'VNC 端口',
|
||||
'hostDetails.vnc.displayHint': '显示器 {display}',
|
||||
'hostDetails.vnc.displayPlaceholder': '5900 或 :0',
|
||||
'hostDetails.rdp.domain': '域(可选)',
|
||||
'hostDetails.rdp.domainPlaceholder': 'CORP(可选)',
|
||||
'hostDetails.rdp.domainLabel': '域',
|
||||
'hostDetails.rdp.usernamePlaceholder': '用户名、DOMAIN\\user 或 JumpServer user|uuid',
|
||||
'hostDetails.vnc.optionalUsername': '用户名(Apple ARD / VeNCrypt)',
|
||||
'hostDetails.vnc.optionalUsernameHint': '可选。标准 VNC 服务器仅使用密码认证。',
|
||||
'hostDetails.vnc.usernamePlaceholder': '用户名(可选)',
|
||||
'hostDetails.remoteDesktop.sectionTitle': '远程桌面显示与选项',
|
||||
'hostDetails.rdp.resolutionMode': '分辨率模式',
|
||||
'hostDetails.rdp.resolutionMode.dynamic': '动态自适应',
|
||||
'hostDetails.rdp.resolutionMode.fit': '适应窗口',
|
||||
'hostDetails.rdp.resolutionMode.fixed': '固定尺寸',
|
||||
'hostDetails.rdp.width': '宽度',
|
||||
'hostDetails.rdp.height': '高度',
|
||||
'hostDetails.rdp.colorDepth': '色深',
|
||||
'hostDetails.rdp.audio': '音频输出',
|
||||
'hostDetails.rdp.audioDesc': '在本地播放远程桌面声音',
|
||||
'hostDetails.rdp.clipboard': '剪贴板同步',
|
||||
'hostDetails.rdp.clipboardDesc': '与远程桌面共享文本与图片',
|
||||
'hostDetails.rdp.clipboardFiles': '剪贴板文件传输',
|
||||
'hostDetails.rdp.clipboardFilesDesc': '允许通过剪贴板复制和拖拽传输文件',
|
||||
'hostDetails.rdp.securityMode': '安全模式',
|
||||
'hostDetails.rdp.securityMode.auto': '自动',
|
||||
'hostDetails.rdp.securityMode.nla': 'NLA (CredSSP)',
|
||||
'hostDetails.rdp.securityMode.tls': 'TLS',
|
||||
'hostDetails.rdp.securityMode.rdp': '标准 RDP',
|
||||
'hostDetails.rdp.ignoreCertErrors': '忽略证书错误',
|
||||
'hostDetails.rdp.ignoreCertErrorsDesc': '跳过 TLS 证书信任提示(不推荐)',
|
||||
'hostDetails.rdp.advanced': '高级 RDP 选项',
|
||||
'hostDetails.rdp.loadBalanceInfo': '负载均衡信息 (Load Balance Info)',
|
||||
'hostDetails.rdp.loadBalanceInfoPlaceholder': 'tsv://MS Terminal Services Plugin.1.Collection',
|
||||
'hostDetails.rdp.alternateShell': '启动程序 (Alternate Shell)',
|
||||
'hostDetails.rdp.alternateShellPlaceholder': '可选的启动程序路径',
|
||||
'hostDetails.rdp.shellWorkingDir': '工作目录',
|
||||
'hostDetails.rdp.shellWorkingDirPlaceholder': '可选的启动工作目录',
|
||||
'hostDetails.vnc.scalingMode': '缩放模式',
|
||||
'hostDetails.vnc.scalingMode.fit': '适应窗口',
|
||||
'hostDetails.vnc.scalingMode.actual': '原始比例 (1:1)',
|
||||
'hostDetails.vnc.scalingMode.stretch': '拉伸填充',
|
||||
'hostDetails.vnc.scalingMode.dynamic': '动态自适应',
|
||||
'hostDetails.vnc.quality': '画质等级',
|
||||
'hostDetails.vnc.compression': '压缩等级',
|
||||
'hostDetails.vnc.viewOnly': '只读模式',
|
||||
'hostDetails.vnc.viewOnlyDesc': '禁止向远端发送鼠标和键盘输入',
|
||||
'hostDetails.vnc.sharedSession': '共享会话',
|
||||
'hostDetails.vnc.sharedSessionDesc': '连接时保持其他 VNC 客户端不断开',
|
||||
'hostDetails.vnc.clipboard': '剪贴板同步',
|
||||
'hostDetails.vnc.clipboardDesc': '与远程桌面同步 UTF-8 剪贴板文本',
|
||||
'hostDetails.vnc.showRemoteCursor': '显示远程光标',
|
||||
'hostDetails.vnc.showRemoteCursorDesc': '渲染服务端下发的光标样式',
|
||||
'hostDetails.companion.addVnc': '添加 VNC',
|
||||
'hostDetails.companion.addRdp': '添加 RDP',
|
||||
'hostDetails.companion.tunnelViaSsh': '通过当前主机 SSH 隧道直连',
|
||||
'hostDetails.companion.tunnelViaSshDesc': '自动经由当前主机的 SSH 连接转发端口',
|
||||
'hostDetails.companion.tunnelTargetHost': '远端目标地址',
|
||||
'hostDetails.companion.credentialsSource': '凭证来源',
|
||||
'hostDetails.companion.credentials.host': '复用主机 SSH 凭证',
|
||||
'hostDetails.companion.credentials.manual': '独立用户名 / 密码',
|
||||
'hostDetails.companion.credentials.manualHint': '保存主机时自动加密存入钥匙串',
|
||||
'hostDetails.companion.credentials.identity': '钥匙串身份',
|
||||
'hostDetails.companion.credentials.ask': '每次连接时询问',
|
||||
'hostDetails.companion.identityPlaceholder': '选择已保存的身份',
|
||||
'hostDetails.companion.saveAsIdentity': '保存为身份',
|
||||
'hostDetails.companion.saveIdentityAction': '创建并选择身份',
|
||||
'hostDetails.companion.identityLabelPlaceholder': '身份名称(如 Desktop VNC)',
|
||||
'hostDetails.companion.identitySaved': '已保存并选中该身份。',
|
||||
'hostDetails.companion.setDefaultRdp': '默认使用 RDP 连接',
|
||||
'hostDetails.companion.setDefaultVnc': '默认使用 VNC 连接',
|
||||
|
||||
// Known Hosts — Remote Desktop TLS Certificates
|
||||
'knownHosts.tabs.ssh': 'SSH 主机密钥',
|
||||
'knownHosts.tabs.remoteDesktopCerts': '远程桌面证书',
|
||||
'knownHosts.certs.clearAll': '全部清空',
|
||||
'knownHosts.certs.expired': '已过期',
|
||||
'knownHosts.certs.expiredNotice': '该证书已超过有效期。',
|
||||
'knownHosts.certs.copied': '已复制 SHA-256 指纹',
|
||||
'knownHosts.certs.action.inspect': '查看证书详情',
|
||||
'knownHosts.certs.action.copyFingerprint': '复制 SHA-256',
|
||||
'knownHosts.certs.action.revoke': '吊销信任',
|
||||
'knownHosts.certs.empty.title': '暂无已信任的远程桌面证书',
|
||||
'knownHosts.certs.empty.desc': '连接 RDP 或 VeNCrypt VNC 主机并选择信任的 TLS 证书将显示在此处。',
|
||||
'knownHosts.certs.empty.searchTitle': '未找到匹配的证书',
|
||||
'knownHosts.certs.empty.searchDesc': '请尝试搜索其他主机名、端口、协议或 SHA-256 指纹。',
|
||||
'knownHosts.certs.detail.subtitle': '本设备已固定信任的 TLS 证书(TOFU)',
|
||||
'knownHosts.certs.detail.fingerprint': 'SHA-256 指纹',
|
||||
'knownHosts.certs.detail.subject': '颁发给 (Subject)',
|
||||
'knownHosts.certs.detail.issuer': '颁发者 (Issuer)',
|
||||
'knownHosts.certs.detail.validFrom': '生效时间',
|
||||
'knownHosts.certs.detail.validTo': '过期时间',
|
||||
'knownHosts.certs.detail.trustedAt': '首次信任',
|
||||
'knownHosts.certs.detail.lastSeen': '最近连接',
|
||||
'knownHosts.certs.revokeConfirm.title': '吊销 {endpoint} 的证书信任?',
|
||||
'knownHosts.certs.revokeConfirm.desc': '下次连接该服务器时将重新要求验证其 TLS 证书指纹。',
|
||||
'knownHosts.certs.clearAllConfirm.title': '清空所有已信任的远程桌面证书?',
|
||||
'knownHosts.certs.clearAllConfirm.desc': '将吊销本设备上全部 {count} 条已固定的 RDP/VNC 证书信任记录。',
|
||||
'knownHosts.certs.toast.revoked': '已吊销证书信任',
|
||||
'knownHosts.certs.toast.clearedAll': '已清空 {count} 条远程桌面证书',
|
||||
|
||||
// Host Connection Test — RDP / VNC Probe
|
||||
'hostDetails.connectionTest.rdp': '测试 RDP',
|
||||
'hostDetails.connectionTest.vnc': '测试 VNC',
|
||||
'hostDetails.connectionTest.probe.rtt': '网络延迟 (RTT)',
|
||||
'hostDetails.connectionTest.probe.protocol': '协议',
|
||||
'hostDetails.connectionTest.probe.security': '协商安全模式',
|
||||
'hostDetails.connectionTest.probe.rfbVersion': 'RFB 版本',
|
||||
'hostDetails.connectionTest.probe.securityTypes': '支持的安全类型',
|
||||
'hostDetails.connectionTest.probe.tls': 'TLS',
|
||||
'hostDetails.connectionTest.probe.fingerprint': 'SHA-256 指纹',
|
||||
'hostDetails.connectionTest.probe.trustStatus.trusted': '已信任',
|
||||
'hostDetails.connectionTest.probe.trustStatus.firstSeen': '首次见到',
|
||||
'hostDetails.connectionTest.probe.trustStatus.changed': '指纹已变更',
|
||||
'hostDetails.connectionTest.probe.trustFingerprint': '信任此指纹',
|
||||
'hostDetails.connectionTest.probe.fingerprintTrusted': '已信任该证书指纹',
|
||||
|
||||
// Remote Desktop Toolbar — SFTP, CLIPRDR, Recording, Ask AI
|
||||
'remoteDesktop.toolbar.openSftp': 'SFTP',
|
||||
'remoteDesktop.toolbar.record': '录制会话',
|
||||
'remoteDesktop.toolbar.stopRecording': '停止录制',
|
||||
'remoteDesktop.toolbar.recording': '录制中',
|
||||
'remoteDesktop.toolbar.askAi': '问 AI',
|
||||
'remoteDesktop.toolbar.askAiFull': '截全屏问 AI',
|
||||
'remoteDesktop.toolbar.askAiRegion': '框选区域问 AI',
|
||||
'remoteDesktop.toolbar.aiReadAllowed': '允许 AI 读取屏幕',
|
||||
'remoteDesktop.toolbar.aiReadBlocked': '已禁止 AI 读取当前会话屏幕',
|
||||
'remoteDesktop.toolbar.aiReadingBanner': 'AI 正在查看画面',
|
||||
'remoteDesktop.clipboard.dropTitle': '拖放文件以发送到远程剪贴板 (CLIPRDR)',
|
||||
'remoteDesktop.clipboard.dropSubtitle': '松手后,在远程桌面中按 Ctrl+V 即可粘贴',
|
||||
'remoteDesktop.clipboard.dropFileCount': '{count} 个文件',
|
||||
'remoteDesktop.clipboard.dropBlockedViewOnly': '只读模式下无法拖放文件',
|
||||
'remoteDesktop.clipboard.dropBlockedDisabled': '该主机未启用剪贴板文件传输',
|
||||
'remoteDesktop.clipboard.dropFolderUnsupported': 'RDP 剪贴板不支持直接发送文件夹,请改用 SFTP 或压缩为 .zip 后发送。',
|
||||
'remoteDesktop.clipboard.stagedPill': '{count} 个文件 · Ctrl+V',
|
||||
'remoteDesktop.clipboard.sendLocalFiles': '选择本地文件发送...',
|
||||
'remoteDesktop.clipboard.uploading': '正在通过剪贴板发送',
|
||||
'remoteDesktop.clipboard.downloading': '正在通过剪贴板接收',
|
||||
'remoteDesktop.clipboard.transferCompleted': '剪贴板文件传输完成',
|
||||
'remoteDesktop.clipboard.transferFailed': '剪贴板文件传输失败',
|
||||
'remoteDesktop.recording.started': '已开始录制会话',
|
||||
'remoteDesktop.recording.saved': '会话录屏已保存到连接日志',
|
||||
'remoteDesktop.recording.failed': '会话录制失败',
|
||||
'remoteDesktop.recording.unsupported': '当前环境不支持会话录制',
|
||||
|
||||
// LogView — Remote Desktop Recordings & Metadata
|
||||
'logView.recording.download': '下载 .webm',
|
||||
'logView.recording.delete': '删除录屏',
|
||||
'logView.recording.loading': '正在加载会话录屏...',
|
||||
'logView.recording.withAudio': '含音频',
|
||||
'logView.recording.missingTitle': '录屏文件已不在磁盘上',
|
||||
'logView.recording.missingDesc': '该 .webm 文件已被删除、因保留策略自动清理或被移出录屏目录。',
|
||||
'logView.recording.playbackErrorTitle': '无法播放录屏',
|
||||
'logView.recording.playbackErrorDesc': '视频文件可能不完整,或内置播放器不支持该编码格式。',
|
||||
'logView.recording.exportSuccess': '已导出录屏文件',
|
||||
'logView.recording.exportFailed': '导出录屏失败',
|
||||
'logView.recording.deleted': '已删除录屏',
|
||||
'logView.recording.deleteFailed': '删除录屏失败',
|
||||
'logView.recording.deleteConfirmTitle': '删除这条会话录屏?',
|
||||
'logView.recording.deleteConfirmDesc': '磁盘上的 .webm 视频文件将被永久删除,连接日志记录本身会保留。',
|
||||
'logView.remoteDesktop.noRecordingSubtitle': '此次远程桌面会话未录制视频',
|
||||
'logView.remoteDesktop.host': '主机',
|
||||
'logView.remoteDesktop.protocol': '协议',
|
||||
'logView.remoteDesktop.user': '用户名',
|
||||
'logView.remoteDesktop.started': '开始时间',
|
||||
'logView.remoteDesktop.ended': '结束时间',
|
||||
'logView.remoteDesktop.duration': '持续时长',
|
||||
'logView.remoteDesktop.recordingTip': '点击远程桌面工具栏的录制按钮,或在「设置 → 系统」中开启自动录制,即可在此回放 .webm 录屏。',
|
||||
|
||||
// Settings -> System -> Remote Desktop Recordings
|
||||
'settings.remoteDesktopRecordings.title': '远程桌面录屏',
|
||||
'settings.remoteDesktopRecordings.autoRecord': '自动录制远程桌面会话',
|
||||
'settings.remoteDesktopRecordings.autoRecordDesc': 'RDP/VNC 会话连接成功后自动开始录制(默认关闭以节省磁盘空间)。',
|
||||
'settings.remoteDesktopRecordings.fps': '录制帧率',
|
||||
'settings.remoteDesktopRecordings.fpsDesc': '帧率越高画面越流畅,但会占用更多 CPU 和磁盘空间。',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
|
||||
'settings.remoteDesktopRecordings.includeAudio': '包含 RDP 音频',
|
||||
'settings.remoteDesktopRecordings.includeAudioDesc': '在可用时将远程桌面音频合并录制到 .webm 视频中。',
|
||||
'settings.remoteDesktopRecordings.maxStorage': '最大存储空间上限',
|
||||
'settings.remoteDesktopRecordings.maxStorageDesc': '总占用超出上限时,自动优先清理最早的未收藏会话录屏。',
|
||||
'settings.remoteDesktopRecordings.retentionDays': '录屏保留天数',
|
||||
'settings.remoteDesktopRecordings.retentionDaysDesc': '自动删除超过保留期的未收藏会话录屏。',
|
||||
'settings.remoteDesktopRecordings.retentionDaysOption': '{days} 天',
|
||||
'settings.remoteDesktopRecordings.retentionUnlimited': '不限制',
|
||||
'settings.remoteDesktopRecordings.storageUsage': '本地录屏存储占用',
|
||||
'settings.remoteDesktopRecordings.storageUsageSummary': '{count} 个文件 · {size}',
|
||||
'settings.remoteDesktopRecordings.storageUsageLoading': '正在计算磁盘占用...',
|
||||
'settings.remoteDesktopRecordings.refresh': '刷新存储统计',
|
||||
'settings.remoteDesktopRecordings.openFolder': '打开文件夹',
|
||||
'settings.remoteDesktopRecordings.clearAll': '清空全部录屏',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmTitle': '清空全部远程桌面录屏?',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': '将从此设备永久删除 {count} 个 .webm 录屏文件。',
|
||||
'settings.remoteDesktopRecordings.clearResult': '已删除 {count} 个录屏文件。',
|
||||
'settings.remoteDesktopRecordings.hint': '录屏文件仅保存在本设备本地,绝不上传云同步;已收藏的连接日志录屏不会在自动清理中被删除。',
|
||||
|
||||
};
|
||||
@@ -867,4 +867,21 @@ export const zhTWAiMessages: Messages = {
|
||||
"ai.toolSettings.conflict": "設定已在其他視窗變更,目前草稿已保留。請取消並重新開啟以載入已儲存的設定。",
|
||||
"ai.toolSettings.retry": "重試",
|
||||
"ai.toolSettings.applyingHttp": "正在套用 HTTP 設定…",
|
||||
"ai.vision.quickPrompt.explainError": "解釋目前錯誤",
|
||||
"ai.vision.quickPrompt.diagnoseUi": "診斷介面問題",
|
||||
"ai.vision.quickPrompt.summarizeScreen": "總結畫面內容",
|
||||
"ai.vision.unsupportedModelWarning": "目前模型({model})不支援圖片輸入,切換至支援視覺的模型即可看圖讀屏。",
|
||||
"ai.vision.switchModel": "切換模型",
|
||||
"ai.vision.modelSupportsVision": "支援圖片輸入",
|
||||
"ai.vision.snip.hint": "拖曳框選區域 · 按 Esc 取消",
|
||||
"ai.vision.snip.cancel": "取消框選",
|
||||
"ai.vision.snip.ariaLabel": "框選遠端桌面畫面區域",
|
||||
"ai.vision.privacyBlocked": "目前工作階段已禁止 AI 讀屏。",
|
||||
"ai.vision.viewingScreen": "AI 正在檢視畫面",
|
||||
"ai.vision.askAi": "問 AI",
|
||||
"ai.vision.captureFullAndAsk": "一鍵截圖問 AI",
|
||||
"ai.vision.snipRegionAndAsk": "框選區域問 AI",
|
||||
"ai.vision.openAiChat": "開啟 AI 助手",
|
||||
"ai.vision.privacyLockOn": "已禁止 AI 讀屏",
|
||||
"ai.vision.privacyLockOff": "允許 AI 讀屏",
|
||||
};
|
||||
@@ -101,4 +101,16 @@ export const zhTWMonitorMessages = {
|
||||
"monitor.status.disconnected": "已中斷",
|
||||
"monitor.status.stale": "讀數過期",
|
||||
"monitor.status.missing": "主機已刪除",
|
||||
"monitor.status.online": "線上",
|
||||
"monitor.status.offline": "離線",
|
||||
"monitor.checkNow": "立即檢測",
|
||||
"monitor.openRemoteDesktop": "開啟 {protocol}",
|
||||
"monitor.latencyTrend": "延遲趨勢",
|
||||
"monitor.bannerVerified": "協定已驗證",
|
||||
"monitor.bannerUnverified": "連接埠已開啟(未驗證協定)",
|
||||
"monitor.companionDesktops": "伴生遠端桌面服務",
|
||||
"monitor.reachabilityOnly": "僅線上與延遲探測",
|
||||
"monitor.viaSsh": "經由 SSH",
|
||||
"monitor.direct": "直連",
|
||||
"monitor.rttStats": "最小 / 平均 / 最大",
|
||||
};
|
||||
@@ -109,6 +109,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
|
||||
// Protocol select dialog
|
||||
'protocolSelect.chooseProtocol': '選擇協定',
|
||||
'protocolSelect.rememberDefault': '記住為預設連線(下次不再詢問)',
|
||||
'protocolSelect.port': '埠:',
|
||||
// Host Details
|
||||
'hostDetails.title.details': '主機詳情',
|
||||
@@ -379,7 +380,22 @@ export const zhTWVaultMessages: Messages = {
|
||||
'hostDetails.startupCommand.runMode.help': '選擇連線後如何傳送多行啟動指令。',
|
||||
'hostDetails.startupCommand.runMode.lineDelay': '逐行傳送',
|
||||
'hostDetails.startupCommand.runMode.paste': '一次性傳送',
|
||||
'hostDetails.otherProtocols': '其他協定',
|
||||
'hostDetails.otherProtocols': '附加協定',
|
||||
'hostDetails.otherProtocolsHint': '為目前 SSH 主機掛載輔助連線方式,不影響預設連線',
|
||||
'hostDetails.protocol.defaultHint': '雙擊預設使用 {protocol}',
|
||||
'hostDetails.protocol.secondaryHint': '已作為附加協定啟用',
|
||||
'hostDetails.protocol.setDefault': '設為預設',
|
||||
'hostDetails.protocol.remove': '移除',
|
||||
'hostDetails.protocol.doubleClick': '雙擊連線',
|
||||
'hostDetails.protocol.connectOptionDefault': '預設 {protocol}',
|
||||
'hostDetails.protocol.connectOptionAsk': '每次詢問',
|
||||
'hostDetails.protocol.alsoEnable': '同時啟用',
|
||||
'hostDetails.protocol.removeProtocol': '移除 {protocol}',
|
||||
'hostDetails.protocol.addProtocol': '新增 {protocol}',
|
||||
'hostDetails.section.connectBehavior': '連線行為',
|
||||
'hostDetails.protocol.notEnabledDesc': '目前主機尚未啟用 {protocol} 協定。',
|
||||
'hostDetails.protocol.addSecondary': '新增 {protocol}(保留 {defaultProtocol} 預設)',
|
||||
'hostDetails.protocol.switchOnly': '僅使用 {protocol}',
|
||||
'hostDetails.telnetOn': 'Telnet on',
|
||||
'hostDetails.port': '埠',
|
||||
'hostDetails.telnet.credentials': '憑證',
|
||||
@@ -1055,4 +1071,224 @@ export const zhTWVaultMessages: Messages = {
|
||||
'vault.import.plugins.moreItems': '本次匯入還包含 {count} 個項目。',
|
||||
'vault.import.plugins.moreDiagnostics': '預覽中省略了另外 {count} 則診斷資訊。',
|
||||
|
||||
// Remote Desktop (VNC / RDP / JumpServer RDP)
|
||||
'vault.hosts.newRdpHost': '新增 RDP 主機',
|
||||
'vault.hosts.newVncHost': '新增 VNC 主機',
|
||||
'vault.hosts.connectRdp': '連線 RDP',
|
||||
'vault.hosts.connectSsh': '連線 SSH',
|
||||
'vault.hosts.connectVnc': '連線 VNC',
|
||||
'vault.hosts.openInSystemRdp': '在系統 RDP 用戶端中開啟',
|
||||
'vault.hosts.openInSystemVnc': '在系統螢幕共享中開啟',
|
||||
'settings.jmsDeepLink.rdpLaunchMode': 'JumpServer RDP 開啟方式',
|
||||
'settings.jmsDeepLink.rdpLaunchModeDesc': '選擇透過 JumpServer jms:// 啟動 Windows RDP 工作階段時使用 Netcatty 內建用戶端或系統 RDP 用戶端。',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.builtin': '內建用戶端',
|
||||
'settings.jmsDeepLink.rdpLaunchMode.system': '系統 RDP 用戶端',
|
||||
'vault.import.rdp.label': 'RDP (.rdp)',
|
||||
'vault.import.rdp.hint': '匯入單一或多個 Microsoft / JumpServer .rdp 檔案。',
|
||||
'vault.import.remoteDesktopTip': 'MobaXterm、CSV 與 .rdp 匯入皆支援 RDP 與 VNC 主機。',
|
||||
'keychain.identity.domain': '網域 (RDP,選填)',
|
||||
'keychain.identity.domainPlaceholder': 'CORP 或 AD 網域',
|
||||
'quickConnect.rdp.domain': '網域(選填)',
|
||||
'quickConnect.rdp.domainPlaceholder': 'CORP 或留空使用本機帳戶',
|
||||
'quickConnect.vnc.optionalUsername': '使用者名稱(選填,用於 Apple ARD / VeNCrypt)',
|
||||
'quickConnect.vnc.optionalUsernameHint': '多數 VNC 伺服器僅需密碼驗證。',
|
||||
'quickConnect.vnc.passwordHint': '若 VNC 伺服器不需密碼,可留空直接連線。',
|
||||
'quickConnect.vnc.displayHelper': '顯示器 {display}',
|
||||
'hostDetails.protocol.label': '通訊協定',
|
||||
'hostDetails.rdp.portLabel': 'RDP 連接埠',
|
||||
'hostDetails.vnc.portLabel': 'VNC 連接埠',
|
||||
'hostDetails.vnc.displayHint': '顯示器 {display}',
|
||||
'hostDetails.vnc.displayPlaceholder': '5900 或 :0',
|
||||
'hostDetails.rdp.domain': '網域(選填)',
|
||||
'hostDetails.rdp.domainPlaceholder': 'CORP(選填)',
|
||||
'hostDetails.rdp.domainLabel': '網域',
|
||||
'hostDetails.rdp.usernamePlaceholder': '使用者名稱、DOMAIN\\user 或 JumpServer user|uuid',
|
||||
'hostDetails.vnc.optionalUsername': '使用者名稱(Apple ARD / VeNCrypt)',
|
||||
'hostDetails.vnc.optionalUsernameHint': '選填。標準 VNC 伺服器僅使用密碼驗證。',
|
||||
'hostDetails.vnc.usernamePlaceholder': '使用者名稱(選填)',
|
||||
'hostDetails.remoteDesktop.sectionTitle': '遠端桌面顯示與選項',
|
||||
'hostDetails.rdp.resolutionMode': '解析度模式',
|
||||
'hostDetails.rdp.resolutionMode.dynamic': '動態自適應',
|
||||
'hostDetails.rdp.resolutionMode.fit': '符合視窗',
|
||||
'hostDetails.rdp.resolutionMode.fixed': '固定尺寸',
|
||||
'hostDetails.rdp.width': '寬度',
|
||||
'hostDetails.rdp.height': '高度',
|
||||
'hostDetails.rdp.colorDepth': '色彩深度',
|
||||
'hostDetails.rdp.audio': '音訊輸出',
|
||||
'hostDetails.rdp.audioDesc': '在本機播放遠端桌面音效',
|
||||
'hostDetails.rdp.clipboard': '剪貼簿同步',
|
||||
'hostDetails.rdp.clipboardDesc': '與遠端桌面共用文字與圖片',
|
||||
'hostDetails.rdp.clipboardFiles': '剪貼簿檔案傳輸',
|
||||
'hostDetails.rdp.clipboardFilesDesc': '允許透過剪貼簿複製與拖曳傳輸檔案',
|
||||
'hostDetails.rdp.securityMode': '安全性模式',
|
||||
'hostDetails.rdp.securityMode.auto': '自動',
|
||||
'hostDetails.rdp.securityMode.nla': 'NLA (CredSSP)',
|
||||
'hostDetails.rdp.securityMode.tls': 'TLS',
|
||||
'hostDetails.rdp.securityMode.rdp': '標準 RDP',
|
||||
'hostDetails.rdp.ignoreCertErrors': '忽略憑證錯誤',
|
||||
'hostDetails.rdp.ignoreCertErrorsDesc': '略過 TLS 憑證信任提示(不建議)',
|
||||
'hostDetails.rdp.advanced': '進階 RDP 選項',
|
||||
'hostDetails.rdp.loadBalanceInfo': '負載平衡資訊 (Load Balance Info)',
|
||||
'hostDetails.rdp.loadBalanceInfoPlaceholder': 'tsv://MS Terminal Services Plugin.1.Collection',
|
||||
'hostDetails.rdp.alternateShell': '啟動程式 (Alternate Shell)',
|
||||
'hostDetails.rdp.alternateShellPlaceholder': '選填的啟動程式路徑',
|
||||
'hostDetails.rdp.shellWorkingDir': '工作目錄',
|
||||
'hostDetails.rdp.shellWorkingDirPlaceholder': '選填的啟動工作目錄',
|
||||
'hostDetails.vnc.scalingMode': '縮放模式',
|
||||
'hostDetails.vnc.scalingMode.fit': '符合視窗',
|
||||
'hostDetails.vnc.scalingMode.actual': '原始比例 (1:1)',
|
||||
'hostDetails.vnc.scalingMode.stretch': '延展填滿',
|
||||
'hostDetails.vnc.scalingMode.dynamic': '動態自適應',
|
||||
'hostDetails.vnc.quality': '畫質等級',
|
||||
'hostDetails.vnc.compression': '壓縮等級',
|
||||
'hostDetails.vnc.viewOnly': '唯讀模式',
|
||||
'hostDetails.vnc.viewOnlyDesc': '停用傳送滑鼠與鍵盤輸入',
|
||||
'hostDetails.vnc.sharedSession': '共用工作階段',
|
||||
'hostDetails.vnc.sharedSessionDesc': '連線時保持其他 VNC 用戶端不斷線',
|
||||
'hostDetails.vnc.clipboard': '剪貼簿同步',
|
||||
'hostDetails.vnc.clipboardDesc': '與遠端桌面同步 UTF-8 剪貼簿文字',
|
||||
'hostDetails.vnc.showRemoteCursor': '顯示遠端游標',
|
||||
'hostDetails.vnc.showRemoteCursorDesc': '呈現伺服器提供的游標形狀',
|
||||
'hostDetails.companion.addVnc': '新增 VNC',
|
||||
'hostDetails.companion.addRdp': '新增 RDP',
|
||||
'hostDetails.companion.tunnelViaSsh': '透過此主機 SSH 通道連線',
|
||||
'hostDetails.companion.tunnelViaSshDesc': '自動經由此主機的 SSH 連線轉發連接埠',
|
||||
'hostDetails.companion.tunnelTargetHost': '遠端目標位址',
|
||||
'hostDetails.companion.credentialsSource': '憑證來源',
|
||||
'hostDetails.companion.credentials.host': '沿用主機 SSH 憑證',
|
||||
'hostDetails.companion.credentials.manual': '獨立使用者名稱 / 密碼',
|
||||
'hostDetails.companion.credentials.manualHint': '儲存主機時自動加密存入鑰匙圈',
|
||||
'hostDetails.companion.credentials.identity': '鑰匙圈身分',
|
||||
'hostDetails.companion.credentials.ask': '每次連線時詢問',
|
||||
'hostDetails.companion.identityPlaceholder': '選擇已儲存的身分',
|
||||
'hostDetails.companion.saveAsIdentity': '儲存為身分',
|
||||
'hostDetails.companion.saveIdentityAction': '建立並選擇身分',
|
||||
'hostDetails.companion.identityLabelPlaceholder': '身分名稱(如 Desktop VNC)',
|
||||
'hostDetails.companion.identitySaved': '已儲存並選取該身分。',
|
||||
'hostDetails.companion.setDefaultRdp': '預設使用 RDP 連線',
|
||||
'hostDetails.companion.setDefaultVnc': '預設使用 VNC 連線',
|
||||
|
||||
// Known Hosts — Remote Desktop TLS Certificates
|
||||
'knownHosts.tabs.ssh': 'SSH 主機金鑰',
|
||||
'knownHosts.tabs.remoteDesktopCerts': '遠端桌面憑證',
|
||||
'knownHosts.certs.clearAll': '全部清除',
|
||||
'knownHosts.certs.expired': '已過期',
|
||||
'knownHosts.certs.expiredNotice': '此憑證已超過有效期限。',
|
||||
'knownHosts.certs.copied': '已複製 SHA-256 指紋',
|
||||
'knownHosts.certs.action.inspect': '檢視憑證詳情',
|
||||
'knownHosts.certs.action.copyFingerprint': '複製 SHA-256',
|
||||
'knownHosts.certs.action.revoke': '撤銷信任',
|
||||
'knownHosts.certs.empty.title': '尚無已信任的遠端桌面憑證',
|
||||
'knownHosts.certs.empty.desc': '連線至 RDP 或 VeNCrypt VNC 主機並選擇信任的 TLS 憑證將顯示於此處。',
|
||||
'knownHosts.certs.empty.searchTitle': '找不到符合的憑證',
|
||||
'knownHosts.certs.empty.searchDesc': '請嘗試搜尋其他主機名稱、連接埠、通訊協定或 SHA-256 指紋。',
|
||||
'knownHosts.certs.detail.subtitle': '本裝置已固定信任的 TLS 憑證(TOFU)',
|
||||
'knownHosts.certs.detail.fingerprint': 'SHA-256 指紋',
|
||||
'knownHosts.certs.detail.subject': '主體 (Subject)',
|
||||
'knownHosts.certs.detail.issuer': '簽發者 (Issuer)',
|
||||
'knownHosts.certs.detail.validFrom': '生效時間',
|
||||
'knownHosts.certs.detail.validTo': '到期時間',
|
||||
'knownHosts.certs.detail.trustedAt': '首次信任',
|
||||
'knownHosts.certs.detail.lastSeen': '最近連線',
|
||||
'knownHosts.certs.revokeConfirm.title': '要撤銷 {endpoint} 的憑證信任嗎?',
|
||||
'knownHosts.certs.revokeConfirm.desc': '下次連線至此伺服器時將重新要求驗證其 TLS 憑證指紋。',
|
||||
'knownHosts.certs.clearAllConfirm.title': '要清除所有已信任的遠端桌面憑證嗎?',
|
||||
'knownHosts.certs.clearAllConfirm.desc': '這將撤銷本裝置上全部 {count} 筆已固定的 RDP/VNC 憑證信任紀錄。',
|
||||
'knownHosts.certs.toast.revoked': '已撤銷憑證信任',
|
||||
'knownHosts.certs.toast.clearedAll': '已清除 {count} 筆遠端桌面憑證',
|
||||
|
||||
// Host Connection Test — RDP / VNC Probe
|
||||
'hostDetails.connectionTest.rdp': '測試 RDP',
|
||||
'hostDetails.connectionTest.vnc': '測試 VNC',
|
||||
'hostDetails.connectionTest.probe.rtt': '網路延遲 (RTT)',
|
||||
'hostDetails.connectionTest.probe.protocol': '通訊協定',
|
||||
'hostDetails.connectionTest.probe.security': '協商安全模式',
|
||||
'hostDetails.connectionTest.probe.rfbVersion': 'RFB 版本',
|
||||
'hostDetails.connectionTest.probe.securityTypes': '支援的安全類型',
|
||||
'hostDetails.connectionTest.probe.tls': 'TLS',
|
||||
'hostDetails.connectionTest.probe.fingerprint': 'SHA-256 指紋',
|
||||
'hostDetails.connectionTest.probe.trustStatus.trusted': '已信任',
|
||||
'hostDetails.connectionTest.probe.trustStatus.firstSeen': '首次見到',
|
||||
'hostDetails.connectionTest.probe.trustStatus.changed': '指紋已變更',
|
||||
'hostDetails.connectionTest.probe.trustFingerprint': '信任此指紋',
|
||||
'hostDetails.connectionTest.probe.fingerprintTrusted': '已信任此憑證指紋',
|
||||
|
||||
// Remote Desktop Toolbar — SFTP, CLIPRDR, Recording, Ask AI
|
||||
'remoteDesktop.toolbar.openSftp': 'SFTP',
|
||||
'remoteDesktop.toolbar.record': '錄製工作階段',
|
||||
'remoteDesktop.toolbar.stopRecording': '停止錄製',
|
||||
'remoteDesktop.toolbar.recording': '錄製中',
|
||||
'remoteDesktop.toolbar.askAi': '詢問 AI',
|
||||
'remoteDesktop.toolbar.askAiFull': '擷取全螢幕詢問 AI',
|
||||
'remoteDesktop.toolbar.askAiRegion': '框選區域詢問 AI',
|
||||
'remoteDesktop.toolbar.aiReadAllowed': '允許 AI 讀取畫面',
|
||||
'remoteDesktop.toolbar.aiReadBlocked': '已禁止 AI 讀取此工作階段畫面',
|
||||
'remoteDesktop.toolbar.aiReadingBanner': 'AI 正在檢視畫面',
|
||||
'remoteDesktop.clipboard.dropTitle': '拖放檔案以傳送到遠端剪貼簿 (CLIPRDR)',
|
||||
'remoteDesktop.clipboard.dropSubtitle': '放開後,在遠端桌面中按 Ctrl+V 即可貼上',
|
||||
'remoteDesktop.clipboard.dropFileCount': '{count} 個檔案',
|
||||
'remoteDesktop.clipboard.dropBlockedViewOnly': '唯讀模式下無法拖放檔案',
|
||||
'remoteDesktop.clipboard.dropBlockedDisabled': '此主機未啟用剪貼簿檔案傳輸',
|
||||
'remoteDesktop.clipboard.dropFolderUnsupported': 'RDP 剪貼簿不支援直接傳送資料夾,請改用 SFTP 或壓縮為 .zip 後再傳送。',
|
||||
'remoteDesktop.clipboard.stagedPill': '{count} 個檔案 · Ctrl+V',
|
||||
'remoteDesktop.clipboard.sendLocalFiles': '選擇本機檔案傳送...',
|
||||
'remoteDesktop.clipboard.uploading': '正在透過剪貼簿傳送',
|
||||
'remoteDesktop.clipboard.downloading': '正在透過剪貼簿接收',
|
||||
'remoteDesktop.clipboard.transferCompleted': '剪貼簿檔案傳輸完成',
|
||||
'remoteDesktop.clipboard.transferFailed': '剪貼簿檔案傳輸失敗',
|
||||
'remoteDesktop.recording.started': '已開始錄製工作階段',
|
||||
'remoteDesktop.recording.saved': '工作階段錄影已儲存至連線日誌',
|
||||
'remoteDesktop.recording.failed': '工作階段錄製失敗',
|
||||
'remoteDesktop.recording.unsupported': '目前環境不支援工作階段錄製',
|
||||
|
||||
// LogView — Remote Desktop Recordings & Metadata
|
||||
'logView.recording.download': '下載 .webm',
|
||||
'logView.recording.delete': '刪除錄影',
|
||||
'logView.recording.loading': '正在載入工作階段錄影...',
|
||||
'logView.recording.withAudio': '含音訊',
|
||||
'logView.recording.missingTitle': '錄影檔案已不在磁碟上',
|
||||
'logView.recording.missingDesc': '此 .webm 檔案已被刪除、因保留設定自動清理或移出錄影資料夾。',
|
||||
'logView.recording.playbackErrorTitle': '無法播放錄影',
|
||||
'logView.recording.playbackErrorDesc': '影片檔案可能不完整,或內建播放器不支援此編碼格式。',
|
||||
'logView.recording.exportSuccess': '已匯出錄影檔案',
|
||||
'logView.recording.exportFailed': '匯出錄影失敗',
|
||||
'logView.recording.deleted': '已刪除錄影',
|
||||
'logView.recording.deleteFailed': '刪除錄影失敗',
|
||||
'logView.recording.deleteConfirmTitle': '要刪除此工作階段錄影嗎?',
|
||||
'logView.recording.deleteConfirmDesc': '磁碟上的 .webm 影片檔案將被永久刪除,連線日誌紀錄本身會保留。',
|
||||
'logView.remoteDesktop.noRecordingSubtitle': '此遠端桌面工作階段未錄製影片',
|
||||
'logView.remoteDesktop.host': '主機',
|
||||
'logView.remoteDesktop.protocol': '通訊協定',
|
||||
'logView.remoteDesktop.user': '使用者名稱',
|
||||
'logView.remoteDesktop.started': '開始時間',
|
||||
'logView.remoteDesktop.ended': '結束時間',
|
||||
'logView.remoteDesktop.duration': '持續時間',
|
||||
'logView.remoteDesktop.recordingTip': '點擊遠端桌面工具列的錄製按鈕,或在「設定 → 系統」中開啟自動錄製,即可在此重播 .webm 錄影。',
|
||||
|
||||
// Settings -> System -> Remote Desktop Recordings
|
||||
'settings.remoteDesktopRecordings.title': '遠端桌面錄影',
|
||||
'settings.remoteDesktopRecordings.autoRecord': '自動錄製遠端桌面工作階段',
|
||||
'settings.remoteDesktopRecordings.autoRecordDesc': 'RDP/VNC 工作階段連線成功後自動開始錄製(預設關閉以節省磁碟空間)。',
|
||||
'settings.remoteDesktopRecordings.fps': '錄製影格率',
|
||||
'settings.remoteDesktopRecordings.fpsDesc': '影格率越高畫面越流暢,但會佔用較多 CPU 與磁碟空間。',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
|
||||
'settings.remoteDesktopRecordings.includeAudio': '包含 RDP 音訊',
|
||||
'settings.remoteDesktopRecordings.includeAudioDesc': '在可用時將遠端桌面音訊合併錄製至 .webm 影片中。',
|
||||
'settings.remoteDesktopRecordings.maxStorage': '最大儲存空間上限',
|
||||
'settings.remoteDesktopRecordings.maxStorageDesc': '總使用量超出上限時,自動優先清理最早的未收藏工作階段錄影。',
|
||||
'settings.remoteDesktopRecordings.retentionDays': '錄影保留天數',
|
||||
'settings.remoteDesktopRecordings.retentionDaysDesc': '自動刪除超過保留期限的未收藏工作階段錄影。',
|
||||
'settings.remoteDesktopRecordings.retentionDaysOption': '{days} 天',
|
||||
'settings.remoteDesktopRecordings.retentionUnlimited': '不限制',
|
||||
'settings.remoteDesktopRecordings.storageUsage': '本機錄影儲存使用量',
|
||||
'settings.remoteDesktopRecordings.storageUsageSummary': '{count} 個檔案 · {size}',
|
||||
'settings.remoteDesktopRecordings.storageUsageLoading': '正在計算磁碟使用量...',
|
||||
'settings.remoteDesktopRecordings.refresh': '重新整理儲存統計',
|
||||
'settings.remoteDesktopRecordings.openFolder': '開啟資料夾',
|
||||
'settings.remoteDesktopRecordings.clearAll': '清除全部錄影',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmTitle': '要清除全部遠端桌面錄影嗎?',
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': '將從此裝置永久刪除 {count} 個 .webm 錄影檔案。',
|
||||
'settings.remoteDesktopRecordings.clearResult': '已刪除 {count} 個錄影檔案。',
|
||||
'settings.remoteDesktopRecordings.hint': '錄影檔案僅儲存在本裝置本機,絕不上傳雲端同步;已收藏的連線日誌錄影不會在自動清理中被刪除。',
|
||||
|
||||
};
|
||||
@@ -1,4 +1,12 @@
|
||||
import type { Host, SerialConfig, TerminalSession } from "../../domain/models";
|
||||
import {
|
||||
DEFAULT_RDP_PORT,
|
||||
DEFAULT_VNC_PORT,
|
||||
isRemoteDesktopProtocol,
|
||||
sanitizeRdpConfig,
|
||||
sanitizeVncConfig,
|
||||
type RemoteDesktopProtocol,
|
||||
} from "../../domain/remoteDesktop";
|
||||
import { classifyLocalShellType } from "../../lib/localShell";
|
||||
|
||||
export interface LocalTerminalOptions {
|
||||
@@ -121,6 +129,30 @@ export const createHostTerminalSession = (
|
||||
};
|
||||
}
|
||||
|
||||
if (isRemoteDesktopProtocol(host.protocol)) {
|
||||
const protocol = host.protocol;
|
||||
const sanitizedRdp = protocol === "rdp" ? sanitizeRdpConfig(host.rdpConfig) : undefined;
|
||||
const sanitizedVnc = protocol === "vnc" ? sanitizeVncConfig(host.vncConfig) : undefined;
|
||||
const defaultPort = protocol === "rdp" ? DEFAULT_RDP_PORT : DEFAULT_VNC_PORT;
|
||||
const resolvedPort =
|
||||
(protocol === "rdp" ? sanitizedRdp?.port : sanitizedVnc?.port)
|
||||
?? host.port
|
||||
?? defaultPort;
|
||||
return {
|
||||
id: sessionId,
|
||||
hostId: host.id,
|
||||
hostLabel: host.label || host.hostname,
|
||||
hostname: host.hostname,
|
||||
username: host.username ?? "",
|
||||
status: "connecting",
|
||||
protocol,
|
||||
port: resolvedPort,
|
||||
...(sanitizedRdp ? { rdpConfig: sanitizedRdp } : {}),
|
||||
...(sanitizedVnc ? { vncConfig: sanitizedVnc } : {}),
|
||||
...(host.ephemeral ? { ephemeralHost: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
id: sessionId,
|
||||
hostId: host.id,
|
||||
@@ -165,6 +197,39 @@ export const createHostTerminalSession = (
|
||||
};
|
||||
};
|
||||
|
||||
export const createRemoteDesktopSession = (
|
||||
sessionId: string,
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
options?: { workspaceId?: string },
|
||||
): TerminalSession => {
|
||||
const isCompanion = host.protocol !== protocol;
|
||||
const sanitizedRdp = protocol === "rdp" ? sanitizeRdpConfig(host.rdpConfig) : undefined;
|
||||
const sanitizedVnc = protocol === "vnc" ? sanitizeVncConfig(host.vncConfig) : undefined;
|
||||
const defaultPort = protocol === "rdp" ? DEFAULT_RDP_PORT : DEFAULT_VNC_PORT;
|
||||
const resolvedPort = isCompanion
|
||||
? ((protocol === "rdp" ? sanitizedRdp?.port : sanitizedVnc?.port) ?? defaultPort)
|
||||
: ((protocol === "rdp" ? sanitizedRdp?.port : sanitizedVnc?.port) ?? host.port ?? defaultPort);
|
||||
const baseLabel = host.label || host.hostname;
|
||||
const hostLabel = isCompanion ? `${baseLabel} (${protocol.toUpperCase()})` : baseLabel;
|
||||
|
||||
return {
|
||||
id: sessionId,
|
||||
hostId: host.id,
|
||||
hostLabel,
|
||||
hostname: host.hostname,
|
||||
username: (protocol === "rdp" ? sanitizedRdp?.username : sanitizedVnc?.username) ?? host.username ?? "",
|
||||
status: "connecting",
|
||||
protocol,
|
||||
port: resolvedPort,
|
||||
...(sanitizedRdp ? { rdpConfig: sanitizedRdp } : {}),
|
||||
...(sanitizedVnc ? { vncConfig: sanitizedVnc } : {}),
|
||||
...(isCompanion ? { remoteDesktopCompanion: true } : {}),
|
||||
...(host.ephemeral ? { ephemeralHost: true } : {}),
|
||||
...(options?.workspaceId ? { workspaceId: options.workspaceId } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
export const createWorkspaceHostTerminalSession = (
|
||||
sessionId: string,
|
||||
host: Host,
|
||||
|
||||
@@ -84,6 +84,7 @@ test('session actions register and unregister', () => {
|
||||
createLocalTerminal: noop,
|
||||
createSerialSession: noop,
|
||||
connectToHost: noop,
|
||||
connectToHostRemoteDesktop: noop,
|
||||
updateSessionStatus: noop,
|
||||
updateSessionFontSize: noop,
|
||||
clearSessionFontSizeOverride: noop,
|
||||
|
||||
@@ -51,6 +51,7 @@ export type SessionSnapshotActions = Pick<
|
||||
| 'createLocalTerminal'
|
||||
| 'createSerialSession'
|
||||
| 'connectToHost'
|
||||
| 'connectToHostRemoteDesktop'
|
||||
| 'updateSessionStatus'
|
||||
| 'updateSessionFontSize'
|
||||
| 'clearSessionFontSizeOverride'
|
||||
|
||||
@@ -72,6 +72,11 @@ import {
|
||||
import { isTerminalSidePanelAutoOpenTab, type TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePanelAutoOpen';
|
||||
import { isStartupLanding, type StartupLanding } from '../../domain/startupLanding';
|
||||
import type { AppearanceSyncEvent } from './appearanceSync';
|
||||
import {
|
||||
isJumpServerRdpLaunchMode,
|
||||
STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE,
|
||||
type JumpServerRdpLaunchMode,
|
||||
} from './settingsStorageSync';
|
||||
|
||||
interface UseSettingsIpcSyncParams {
|
||||
enabled?: boolean;
|
||||
@@ -94,6 +99,7 @@ interface UseSettingsIpcSyncParams {
|
||||
setSshDebugLogsEnabled: Dispatch<SetStateAction<boolean>>;
|
||||
setSshDeepLinkEnabledState: (enabled: boolean) => void;
|
||||
setJmsDeepLinkEnabledState: (enabled: boolean) => void;
|
||||
setJumpServerRdpLaunchModeState: Dispatch<SetStateAction<JumpServerRdpLaunchMode>>;
|
||||
setExplorerContextMenuEnabledState: (enabled: boolean) => void;
|
||||
setHotkeyScheme: Dispatch<SetStateAction<HotkeyScheme>>;
|
||||
applyIncomingCustomKeyBindings: (incoming: { bindings: CustomKeyBindings; version: number; origin: string }) => void;
|
||||
@@ -144,6 +150,7 @@ export function useSettingsIpcSync({
|
||||
setSshDebugLogsEnabled,
|
||||
setSshDeepLinkEnabledState,
|
||||
setJmsDeepLinkEnabledState,
|
||||
setJumpServerRdpLaunchModeState,
|
||||
setExplorerContextMenuEnabledState,
|
||||
setHotkeyScheme,
|
||||
applyIncomingCustomKeyBindings,
|
||||
@@ -261,6 +268,9 @@ export function useSettingsIpcSync({
|
||||
if (key === STORAGE_KEY_JMS_DEEP_LINK_ENABLED && typeof value === 'boolean') {
|
||||
setJmsDeepLinkEnabledState(value);
|
||||
}
|
||||
if (key === STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE && isJumpServerRdpLaunchMode(value)) {
|
||||
setJumpServerRdpLaunchModeState((prev) => (prev === value ? prev : value));
|
||||
}
|
||||
if (key === STORAGE_KEY_EXPLORER_CONTEXT_MENU_ENABLED && typeof value === 'boolean') {
|
||||
setExplorerContextMenuEnabledState(value);
|
||||
}
|
||||
@@ -387,6 +397,7 @@ export function useSettingsIpcSync({
|
||||
setSessionLogsTimestampsEnabled,
|
||||
setSshDeepLinkEnabledState,
|
||||
setJmsDeepLinkEnabledState,
|
||||
setJumpServerRdpLaunchModeState,
|
||||
setExplorerContextMenuEnabledState,
|
||||
setSshDebugLogsEnabled,
|
||||
setSftpAutoOpenSidebar,
|
||||
|
||||
@@ -55,6 +55,11 @@ import {
|
||||
STORAGE_KEY_WINDOW_OPACITY,
|
||||
STORAGE_KEY_WINDOW_BACKGROUND_BLUR,
|
||||
STORAGE_KEY_APP_ICON_VARIANT,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import { resolveAppIconVariant, type AppIconVariant } from '../../domain/appIconVariant';
|
||||
import { resolveAppearanceStorageEvent } from './appearanceSync';
|
||||
@@ -66,6 +71,42 @@ import { isTerminalSidePanelAutoOpenTab, type TerminalSidePanelAutoOpenTab } fro
|
||||
import { isHostClickBehavior, type HostClickBehavior } from '../../domain/hostClickBehavior';
|
||||
import { isStartupLanding, type StartupLanding } from '../../domain/startupLanding';
|
||||
|
||||
export type JumpServerRdpLaunchMode = 'builtin' | 'system';
|
||||
|
||||
export const STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE = 'netcatty_jumpserver_rdp_launch_mode_v1';
|
||||
|
||||
export const DEFAULT_JUMPSERVER_RDP_LAUNCH_MODE: JumpServerRdpLaunchMode = 'builtin';
|
||||
|
||||
export const isJumpServerRdpLaunchMode = (value: unknown): value is JumpServerRdpLaunchMode => (
|
||||
value === 'builtin' || value === 'system'
|
||||
);
|
||||
|
||||
export type RemoteDesktopRecordingFps = 5 | 10 | 15;
|
||||
|
||||
export const DEFAULT_REMOTE_DESKTOP_AUTO_RECORD = false;
|
||||
export const DEFAULT_REMOTE_DESKTOP_RECORDING_FPS: RemoteDesktopRecordingFps = 10;
|
||||
export const DEFAULT_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO = true;
|
||||
export const DEFAULT_REMOTE_DESKTOP_RECORDING_MAX_MB = 1024;
|
||||
export const DEFAULT_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS = 30;
|
||||
|
||||
export const normalizeRemoteDesktopRecordingFps = (value: unknown): RemoteDesktopRecordingFps => {
|
||||
const num = typeof value === 'number' ? value : Number(value);
|
||||
if (num === 5 || num === 10 || num === 15) return num;
|
||||
return DEFAULT_REMOTE_DESKTOP_RECORDING_FPS;
|
||||
};
|
||||
|
||||
export const normalizeRemoteDesktopRecordingMaxMb = (value: unknown): number => {
|
||||
const num = typeof value === 'number' ? value : Number(value);
|
||||
if (Number.isFinite(num) && num >= 64 && num <= 102400) return Math.round(num);
|
||||
return DEFAULT_REMOTE_DESKTOP_RECORDING_MAX_MB;
|
||||
};
|
||||
|
||||
export const normalizeRemoteDesktopRecordingRetentionDays = (value: unknown): number => {
|
||||
const num = typeof value === 'number' ? value : Number(value);
|
||||
if (Number.isFinite(num) && num >= 0 && num <= 3650) return Math.round(num);
|
||||
return DEFAULT_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS;
|
||||
};
|
||||
|
||||
interface UseSettingsStorageSyncParams {
|
||||
enabled?: boolean;
|
||||
theme: 'dark' | 'light' | 'system';
|
||||
@@ -110,9 +151,15 @@ interface UseSettingsStorageSyncParams {
|
||||
sessionLogsDir: string;
|
||||
sessionLogsFormat: SessionLogFormat;
|
||||
sessionLogsTimestampsEnabled: boolean;
|
||||
remoteDesktopAutoRecord: boolean;
|
||||
remoteDesktopRecordingFps: RemoteDesktopRecordingFps;
|
||||
remoteDesktopRecordingIncludeAudio: boolean;
|
||||
remoteDesktopRecordingMaxMb: number;
|
||||
remoteDesktopRecordingRetentionDays: number;
|
||||
sshDebugLogsEnabled: boolean;
|
||||
sshDeepLinkEnabled: boolean;
|
||||
jmsDeepLinkEnabled: boolean;
|
||||
jumpServerRdpLaunchMode: JumpServerRdpLaunchMode;
|
||||
explorerContextMenuEnabled: boolean;
|
||||
globalHotkeyEnabled: boolean;
|
||||
autoUpdateEnabled: boolean;
|
||||
@@ -162,9 +209,15 @@ interface UseSettingsStorageSyncParams {
|
||||
setSessionLogsDir: Dispatch<SetStateAction<string>>;
|
||||
setSessionLogsFormat: Dispatch<SetStateAction<SessionLogFormat>>;
|
||||
setSessionLogsTimestampsEnabled: Dispatch<SetStateAction<boolean>>;
|
||||
setRemoteDesktopAutoRecordState: Dispatch<SetStateAction<boolean>>;
|
||||
setRemoteDesktopRecordingFpsState: Dispatch<SetStateAction<RemoteDesktopRecordingFps>>;
|
||||
setRemoteDesktopRecordingIncludeAudioState: Dispatch<SetStateAction<boolean>>;
|
||||
setRemoteDesktopRecordingMaxMbState: Dispatch<SetStateAction<number>>;
|
||||
setRemoteDesktopRecordingRetentionDaysState: Dispatch<SetStateAction<number>>;
|
||||
setSshDebugLogsEnabled: Dispatch<SetStateAction<boolean>>;
|
||||
setSshDeepLinkEnabledState: (enabled: boolean) => void;
|
||||
setJmsDeepLinkEnabledState: (enabled: boolean) => void;
|
||||
setJumpServerRdpLaunchModeState: Dispatch<SetStateAction<JumpServerRdpLaunchMode>>;
|
||||
setExplorerContextMenuEnabledState: (enabled: boolean) => void;
|
||||
setGlobalHotkeyEnabled: Dispatch<SetStateAction<boolean>>;
|
||||
setWindowOpacity: (raw: unknown) => void;
|
||||
@@ -186,7 +239,9 @@ export function useSettingsStorageSync({
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, windowBackgroundBlur, appIconVariant,
|
||||
setTheme, setLightUiThemeId, setDarkUiThemeId, setAccentMode, applyIncomingCustomAccent,
|
||||
setCustomCSS, setUiFontFamilyId, setHotkeyScheme, setUiLanguage,
|
||||
@@ -195,7 +250,9 @@ export function useSettingsStorageSync({
|
||||
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
|
||||
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled, setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setExplorerContextMenuEnabledState,
|
||||
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
|
||||
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
|
||||
setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState,
|
||||
setGlobalHotkeyEnabled, setWindowOpacity, setWindowBackgroundBlur, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState,
|
||||
setSftpTransferConcurrencyState, setSshTransportIdleTtlMsState,
|
||||
applyIncomingCustomKeyBindings, mergeIncomingTerminalSettings,
|
||||
@@ -210,7 +267,9 @@ export function useSettingsStorageSync({
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, windowBackgroundBlur, appIconVariant,
|
||||
});
|
||||
settingsSnapshotRef.current = {
|
||||
@@ -220,7 +279,9 @@ export function useSettingsStorageSync({
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, windowBackgroundBlur, appIconVariant,
|
||||
};
|
||||
|
||||
@@ -367,6 +428,36 @@ export function useSettingsStorageSync({
|
||||
setSessionLogsTimestampsEnabled(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.remoteDesktopAutoRecord) {
|
||||
setRemoteDesktopAutoRecordState(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS && e.newValue !== null) {
|
||||
const next = normalizeRemoteDesktopRecordingFps(e.newValue);
|
||||
if (next !== s.remoteDesktopRecordingFps) {
|
||||
setRemoteDesktopRecordingFpsState(next);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.remoteDesktopRecordingIncludeAudio) {
|
||||
setRemoteDesktopRecordingIncludeAudioState(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB && e.newValue !== null) {
|
||||
const next = normalizeRemoteDesktopRecordingMaxMb(e.newValue);
|
||||
if (next !== s.remoteDesktopRecordingMaxMb) {
|
||||
setRemoteDesktopRecordingMaxMbState(next);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS && e.newValue !== null) {
|
||||
const next = normalizeRemoteDesktopRecordingRetentionDays(e.newValue);
|
||||
if (next !== s.remoteDesktopRecordingRetentionDays) {
|
||||
setRemoteDesktopRecordingRetentionDaysState(next);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_SSH_DEBUG_LOGS_ENABLED && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.sshDebugLogsEnabled) {
|
||||
@@ -385,6 +476,11 @@ export function useSettingsStorageSync({
|
||||
setJmsDeepLinkEnabledState(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE && e.newValue !== null) {
|
||||
if (isJumpServerRdpLaunchMode(e.newValue) && e.newValue !== s.jumpServerRdpLaunchMode) {
|
||||
setJumpServerRdpLaunchModeState(e.newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_EXPLORER_CONTEXT_MENU_ENABLED && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.explorerContextMenuEnabled) {
|
||||
@@ -583,8 +679,14 @@ export function useSettingsStorageSync({
|
||||
setSessionLogsEnabled,
|
||||
setSessionLogsFormat,
|
||||
setSessionLogsTimestampsEnabled,
|
||||
setRemoteDesktopAutoRecordState,
|
||||
setRemoteDesktopRecordingFpsState,
|
||||
setRemoteDesktopRecordingIncludeAudioState,
|
||||
setRemoteDesktopRecordingMaxMbState,
|
||||
setRemoteDesktopRecordingRetentionDaysState,
|
||||
setSshDeepLinkEnabledState,
|
||||
setJmsDeepLinkEnabledState,
|
||||
setJumpServerRdpLaunchModeState,
|
||||
setExplorerContextMenuEnabledState,
|
||||
setSshDebugLogsEnabled,
|
||||
setSftpAutoOpenSidebar,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { TerminalSettings } from "../../domain/models";
|
||||
import type { Host, TerminalSettings } from "../../domain/models";
|
||||
import { normalizeSshAutoReconnectInterval } from "../../domain/models/terminal";
|
||||
import type { TerminalSessionExitEvent } from "./resolveTerminalSessionExitIntent";
|
||||
|
||||
@@ -11,7 +11,7 @@ export function getTerminalAutoReconnectDelayMs(
|
||||
}
|
||||
|
||||
type AutoReconnectHost = {
|
||||
protocol?: "ssh" | "telnet" | "local" | "serial" | "mosh" | "et";
|
||||
protocol?: Host["protocol"];
|
||||
hostname?: string;
|
||||
moshEnabled?: boolean;
|
||||
etEnabled?: boolean;
|
||||
|
||||
@@ -106,3 +106,107 @@ test("connection test countdown follows the probe timeouts and invalidates the a
|
||||
assert.equal(current().state.status, "disconnected");
|
||||
assert.equal(current().state.error, "Connection timed out. Please try again.");
|
||||
});
|
||||
|
||||
test("remote desktop host connection test routes to remoteDesktop.testConnection, surfaces probeResult, and cancels cleanly", async (t) => {
|
||||
const actEnvironment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previousActEnvironment = actEnvironment.IS_REACT_ACT_ENVIRONMENT;
|
||||
actEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const previousWindowDescriptor = Object.getOwnPropertyDescriptor(globalThis, "window");
|
||||
|
||||
const rdpHost: Host = {
|
||||
id: "rdp-1",
|
||||
label: "Windows Box",
|
||||
hostname: "win.example.test",
|
||||
port: 3389,
|
||||
username: "admin",
|
||||
password: "DO_NOT_SEND_PASSWORD",
|
||||
tags: [],
|
||||
os: "windows",
|
||||
protocol: "rdp",
|
||||
};
|
||||
|
||||
let receivedOptions: Record<string, unknown> | null = null;
|
||||
const cancelledIds: string[] = [];
|
||||
const bridge = {
|
||||
remoteDesktop: {
|
||||
testConnection: async (opts: Record<string, unknown>) => {
|
||||
receivedOptions = opts;
|
||||
return {
|
||||
ok: true,
|
||||
protocol: "rdp",
|
||||
host: "win.example.test",
|
||||
port: 3389,
|
||||
rttMs: 14,
|
||||
bannerVerified: true,
|
||||
rdpSecurity: "nla",
|
||||
tlsVersion: "TLSv1.3",
|
||||
cert: {
|
||||
fingerprintSha256: "AA:BB:CC",
|
||||
subject: "CN=win.example.test",
|
||||
trustStatus: "first-seen",
|
||||
},
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
},
|
||||
cancelTestConnection: async (id: string) => {
|
||||
cancelledIds.push(id);
|
||||
return { ok: true };
|
||||
},
|
||||
},
|
||||
onChainProgress: () => () => {},
|
||||
onHostKeyVerification: () => () => {},
|
||||
respondHostKeyVerification: async () => ({ success: true }),
|
||||
};
|
||||
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: { netcatty: bridge },
|
||||
});
|
||||
|
||||
let api: HookApi | null = null;
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
const Probe = () => {
|
||||
api = useHostConnectionTest({ host: rdpHost, hosts: [rdpHost], keys: [] });
|
||||
return null;
|
||||
};
|
||||
const current = () => {
|
||||
assert.ok(api);
|
||||
return api;
|
||||
};
|
||||
|
||||
t.after(async () => {
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
if (previousWindowDescriptor) Object.defineProperty(globalThis, "window", previousWindowDescriptor);
|
||||
else delete (globalThis as { window?: unknown }).window;
|
||||
actEnvironment.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
});
|
||||
await act(async () => {
|
||||
await current().startTest();
|
||||
});
|
||||
|
||||
assert.ok(receivedOptions);
|
||||
assert.equal((receivedOptions as { protocol: string }).protocol, "rdp");
|
||||
assert.ok(!JSON.stringify(receivedOptions).includes("DO_NOT_SEND_PASSWORD"));
|
||||
assert.equal(current().state.status, "connected");
|
||||
assert.equal(current().state.activeProtocol, "rdp");
|
||||
assert.equal(current().state.probeResult?.rttMs, 14);
|
||||
assert.equal(current().state.probeResult?.cert?.trustStatus, "first-seen");
|
||||
|
||||
await act(async () => {
|
||||
current().markProbeCertTrusted();
|
||||
});
|
||||
assert.equal(current().state.probeResult?.cert?.trustStatus, "trusted");
|
||||
|
||||
await act(async () => {
|
||||
current().cancelTest();
|
||||
});
|
||||
assert.equal(current().state.status, "idle");
|
||||
assert.equal(cancelledIds.length, 1);
|
||||
});
|
||||
@@ -7,8 +7,16 @@ import {
|
||||
buildHostConnectionTestPlan,
|
||||
formatConnectionTestProgressLog,
|
||||
resolveHostConnectionTestDeadlineMs,
|
||||
resolveRemoteDesktopConnectionTestDeadlineMs,
|
||||
type HostConnectionTestAuthOverride,
|
||||
type RemoteDesktopProbeResult,
|
||||
} from "../../domain/hostConnectionTest";
|
||||
import {
|
||||
isRemoteDesktopProtocol,
|
||||
resolveRemoteDesktopConnectionSpec,
|
||||
} from "../../domain/remoteDesktop";
|
||||
import { resolveEffectiveTerminalHost } from "../../domain/terminalHostResolution";
|
||||
import { getKnownRemoteDesktopFingerprints } from "../../components/remoteDesktop/knownRemoteDesktopCerts";
|
||||
import { useTerminalBackend } from "./useTerminalBackend";
|
||||
|
||||
export type ChainProgress = {
|
||||
@@ -36,6 +44,8 @@ export type HostConnectionTestState = {
|
||||
timeLeft: number;
|
||||
isAwaitingUserInput: boolean;
|
||||
isCancelling: boolean;
|
||||
probeResult: RemoteDesktopProbeResult | null;
|
||||
activeProtocol: "ssh" | "rdp" | "vnc";
|
||||
};
|
||||
|
||||
export type HostConnectionTestInput = {
|
||||
@@ -76,8 +86,14 @@ export function useHostConnectionTest(input: HostConnectionTestInput) {
|
||||
const [timeLeft, setTimeLeft] = useState(0);
|
||||
const [isAwaitingUserInput, setIsAwaitingUserInput] = useState(false);
|
||||
const [isCancelling, setIsCancelling] = useState(false);
|
||||
const [probeResult, setProbeResult] = useState<RemoteDesktopProbeResult | null>(null);
|
||||
const [activeProtocol, setActiveProtocol] = useState<"ssh" | "rdp" | "vnc">(
|
||||
isRemoteDesktopProtocol(host.protocol) ? host.protocol : "ssh",
|
||||
);
|
||||
|
||||
const sessionIdRef = useRef<string | null>(null);
|
||||
const activeKindRef = useRef<"ssh" | "remote-desktop">("ssh");
|
||||
const lastProtocolOverrideRef = useRef<"ssh" | "rdp" | "vnc" | undefined>(undefined);
|
||||
const bootEpochRef = useRef(0);
|
||||
const pendingHostKeyRequestIdRef = useRef<string | null>(null);
|
||||
const disposedRef = useRef(false);
|
||||
@@ -95,14 +111,20 @@ export function useHostConnectionTest(input: HostConnectionTestInput) {
|
||||
setIsAwaitingUserInput(false);
|
||||
setIsCancelling(false);
|
||||
setTimeLeft(0);
|
||||
setProbeResult(null);
|
||||
pendingHostKeyRequestIdRef.current = null;
|
||||
}, []);
|
||||
|
||||
const clearSession = useCallback(() => {
|
||||
const sessionId = sessionIdRef.current;
|
||||
const kind = activeKindRef.current;
|
||||
sessionIdRef.current = null;
|
||||
if (sessionId && !disposedRef.current) {
|
||||
void backend.cancelTestConnection(sessionId).catch(() => {});
|
||||
if (kind === "remote-desktop") {
|
||||
void backend.cancelRemoteDesktopTestConnection(sessionId).catch(() => {});
|
||||
} else {
|
||||
void backend.cancelTestConnection(sessionId).catch(() => {});
|
||||
}
|
||||
}
|
||||
}, [backend]);
|
||||
|
||||
@@ -179,10 +201,36 @@ export function useHostConnectionTest(input: HostConnectionTestInput) {
|
||||
}, [hostKeyVerification, respondHostKey]);
|
||||
|
||||
const startTest = useCallback(
|
||||
async (authOverride?: HostConnectionTestAuthOverride | null) => {
|
||||
async (
|
||||
authOverride?: HostConnectionTestAuthOverride | null,
|
||||
protocolOverride?: "ssh" | "rdp" | "vnc",
|
||||
) => {
|
||||
clearSession();
|
||||
resetState();
|
||||
|
||||
lastProtocolOverrideRef.current = protocolOverride;
|
||||
const targetProtocol: "ssh" | "rdp" | "vnc" =
|
||||
protocolOverride ?? (isRemoteDesktopProtocol(host.protocol) ? host.protocol : "ssh");
|
||||
setActiveProtocol(targetProtocol);
|
||||
|
||||
let knownRemoteDesktopFingerprints: string[] | undefined;
|
||||
if (targetProtocol === "rdp" || targetProtocol === "vnc") {
|
||||
const effective = resolveEffectiveTerminalHost({
|
||||
host,
|
||||
groupConfigs,
|
||||
proxyProfiles,
|
||||
});
|
||||
const spec = resolveRemoteDesktopConnectionSpec(effective, targetProtocol, identities);
|
||||
const certHost = spec.hostHostname || spec.hostname;
|
||||
if (certHost) {
|
||||
knownRemoteDesktopFingerprints = getKnownRemoteDesktopFingerprints(
|
||||
targetProtocol,
|
||||
certHost,
|
||||
spec.port,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const sessionId = crypto.randomUUID();
|
||||
const bootEpoch = (bootEpochRef.current += 1);
|
||||
sessionIdRef.current = sessionId;
|
||||
@@ -205,14 +253,43 @@ export function useHostConnectionTest(input: HostConnectionTestInput) {
|
||||
sessionId,
|
||||
bootEpoch,
|
||||
authOverride,
|
||||
protocolOverride,
|
||||
knownRemoteDesktopFingerprints,
|
||||
});
|
||||
|
||||
if (!plan.ok) {
|
||||
if (plan.ok === false) {
|
||||
setError(plan.error);
|
||||
setStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
|
||||
if (plan.kind === "remote-desktop") {
|
||||
activeKindRef.current = "remote-desktop";
|
||||
deadlineMsRef.current = resolveRemoteDesktopConnectionTestDeadlineMs(plan.options);
|
||||
setStatus("connecting");
|
||||
setIsAwaitingUserInput(false);
|
||||
|
||||
try {
|
||||
const result = await backend.testRemoteDesktopConnection(plan.options);
|
||||
if (disposedRef.current || sessionIdRef.current !== sessionId) return;
|
||||
setProbeResult(result);
|
||||
setChainProgress(null);
|
||||
if (result.ok) {
|
||||
setProgressValue(100);
|
||||
setStatus("connected");
|
||||
} else {
|
||||
setError(result.error || "Connection test failed");
|
||||
setStatus("disconnected");
|
||||
}
|
||||
} catch (err) {
|
||||
if (disposedRef.current || sessionIdRef.current !== sessionId) return;
|
||||
setError(messageOf(err));
|
||||
setStatus("disconnected");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
activeKindRef.current = "ssh";
|
||||
if (plan.needsCredentialReentry) {
|
||||
setNeedsAuth(true);
|
||||
setStatus("connecting");
|
||||
@@ -250,6 +327,19 @@ export function useHostConnectionTest(input: HostConnectionTestInput) {
|
||||
],
|
||||
);
|
||||
|
||||
const markProbeCertTrusted = useCallback(() => {
|
||||
setProbeResult((prev) => {
|
||||
if (!prev || !prev.cert) return prev;
|
||||
return {
|
||||
...prev,
|
||||
cert: {
|
||||
...prev.cert,
|
||||
trustStatus: "trusted",
|
||||
},
|
||||
};
|
||||
});
|
||||
}, []);
|
||||
|
||||
const submitAuth = useCallback(
|
||||
(auth: HostConnectionTestAuthOverride) => {
|
||||
void startTest(auth);
|
||||
@@ -317,11 +407,14 @@ export function useHostConnectionTest(input: HostConnectionTestInput) {
|
||||
timeLeft,
|
||||
isAwaitingUserInput,
|
||||
isCancelling,
|
||||
probeResult,
|
||||
activeProtocol,
|
||||
} satisfies HostConnectionTestState,
|
||||
startTest,
|
||||
submitAuth,
|
||||
cancelTest,
|
||||
retry: () => void startTest(),
|
||||
retry: () => void startTest(undefined, lastProtocolOverrideRef.current),
|
||||
markProbeCertTrusted,
|
||||
handleHostKeyContinue,
|
||||
handleHostKeyAddAndContinue,
|
||||
handleHostKeyClose,
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { hostRestrictsExtraSshChannels } from "../../domain/host";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { buildHostConnectionTestPlan } from "../../domain/hostConnectionTest";
|
||||
import {
|
||||
hasCompanionRdp,
|
||||
hasCompanionVnc,
|
||||
isRemoteDesktopProtocol,
|
||||
resolveRemoteDesktopConnectionSpec,
|
||||
} from "../../domain/remoteDesktop";
|
||||
import { resolveEffectiveTerminalHost } from "../../domain/terminalHostResolution";
|
||||
import { getEffectiveKnownHosts } from "../../infrastructure/syncHelpers";
|
||||
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
|
||||
@@ -17,7 +23,10 @@ import {
|
||||
publishMonitorSnapshot,
|
||||
publishMonitorUnavailable,
|
||||
} from "./monitorRuntimeStore";
|
||||
import type { MonitorPanelDemand } from "../../domain/monitorRuntime";
|
||||
import type {
|
||||
MonitorPanelDemand,
|
||||
MonitorRemoteDesktopProbeOptions,
|
||||
} from "../../domain/monitorRuntime";
|
||||
|
||||
/** Root lifetime, independent of Vault navigation. No runtime state is persisted. */
|
||||
export function useMonitorRuntime() {
|
||||
@@ -91,8 +100,38 @@ export function useMonitorRuntime() {
|
||||
interval: panel.interval,
|
||||
hosts: panel.hostIds.map((id) => {
|
||||
const host = hosts.find((h) => h.id === id);
|
||||
if (!host) return { id };
|
||||
if (isRemoteDesktopProtocol(host.protocol)) {
|
||||
const plan = buildHostConnectionTestPlan({
|
||||
host,
|
||||
hosts,
|
||||
keys,
|
||||
identities,
|
||||
groupConfigs,
|
||||
proxyProfiles,
|
||||
knownHosts: getEffectiveKnownHosts(knownHosts) ?? [],
|
||||
terminalSettings,
|
||||
sessionId: `monitor-probe-${id}`,
|
||||
bootEpoch: 0,
|
||||
});
|
||||
if (!plan.ok || plan.kind !== "remote-desktop") {
|
||||
return { id, status: "error" as const };
|
||||
}
|
||||
return {
|
||||
id,
|
||||
kind: "probe" as const,
|
||||
probe: {
|
||||
protocol: plan.options.protocol,
|
||||
hostname: plan.options.hostname,
|
||||
port: plan.options.port,
|
||||
proxy: plan.options.proxy,
|
||||
jumpHosts: plan.options.jumpHosts,
|
||||
bannerCheck: true,
|
||||
timeoutMs: 5000,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (
|
||||
!host ||
|
||||
(host.protocol && host.protocol !== "ssh") ||
|
||||
hostRestrictsExtraSshChannels(host)
|
||||
)
|
||||
@@ -117,17 +156,35 @@ export function useMonitorRuntime() {
|
||||
? { ...credentials.current.get(id), authMethod: "password" }
|
||||
: null,
|
||||
});
|
||||
if (!plan.ok) return { id, status: "error" as const };
|
||||
if (!plan.ok || plan.kind !== "ssh") return { id, status: "error" as const };
|
||||
if (plan.needsCredentialReentry)
|
||||
return { id, status: "login" as const };
|
||||
const companionProbes: MonitorRemoteDesktopProbeOptions[] = [];
|
||||
for (const proto of ["rdp", "vnc"] as const) {
|
||||
const enabled = proto === "rdp" ? hasCompanionRdp(effective) : hasCompanionVnc(effective);
|
||||
if (!enabled) continue;
|
||||
const spec = resolveRemoteDesktopConnectionSpec(effective, proto, identities);
|
||||
companionProbes.push({
|
||||
protocol: proto,
|
||||
hostname: spec.hostname,
|
||||
port: spec.port,
|
||||
tunnelViaHostSsh: spec.tunnelViaHostSsh,
|
||||
tunnelTargetHost: spec.tunnelTargetHost,
|
||||
proxy: spec.tunnelViaHostSsh ? undefined : plan.options.proxy,
|
||||
bannerCheck: true,
|
||||
timeoutMs: 5000,
|
||||
});
|
||||
}
|
||||
return {
|
||||
id,
|
||||
kind: "ssh" as const,
|
||||
options: {
|
||||
...plan.options,
|
||||
singleChannelSsh: hostRestrictsExtraSshChannels(effective),
|
||||
sshAuthReadyTimeoutMs: 120000,
|
||||
agentForwarding: effective.agentForwarding,
|
||||
},
|
||||
...(companionProbes.length > 0 ? { companionProbes } : {}),
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
@@ -5,10 +5,15 @@ import { addLogView, getLogViewTabId, removeLogView, type LogView } from './logV
|
||||
import {
|
||||
createHostTerminalSession,
|
||||
createLocalTerminalSession,
|
||||
createRemoteDesktopSession,
|
||||
createSerialTerminalSession,
|
||||
createWorkspaceHostTerminalSession,
|
||||
type LocalTerminalOptions,
|
||||
} from './sessionFactories';
|
||||
import {
|
||||
isRemoteDesktopProtocol,
|
||||
type RemoteDesktopProtocol,
|
||||
} from '../../domain/remoteDesktop';
|
||||
import { isScriptSnippet } from '../../domain/snippetScript.ts';
|
||||
import {
|
||||
appendPaneToWorkspaceRoot,
|
||||
@@ -57,7 +62,26 @@ import {
|
||||
LOCAL_STORAGE_ADAPTER_CHANGED_EVENT,
|
||||
localStorageAdapter,
|
||||
} from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import {
|
||||
netcattyBridge,
|
||||
type RemoteDesktopBridgeApi,
|
||||
type RemoteDesktopCertDecisionValue,
|
||||
type RemoteDesktopCertVerifyEvent,
|
||||
type RemoteDesktopOpenSystemClientOptions,
|
||||
type RemoteDesktopStartOptions,
|
||||
} from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
export type {
|
||||
RemoteDesktopBridgeApi,
|
||||
RemoteDesktopCertDecisionValue,
|
||||
RemoteDesktopCertVerifyEvent,
|
||||
RemoteDesktopOpenSystemClientOptions,
|
||||
RemoteDesktopStartOptions,
|
||||
};
|
||||
|
||||
export function getRemoteDesktopBridge(): RemoteDesktopBridgeApi | undefined {
|
||||
return netcattyBridge.get()?.remoteDesktop;
|
||||
}
|
||||
import { sessionRestoreStorage } from './sessionRestoreStorage';
|
||||
import {
|
||||
buildAndWriteSessionRestorePayload,
|
||||
@@ -596,13 +620,88 @@ export const useSessionState = ({
|
||||
|
||||
const connectToHost = useCallback((host: Host, options?: { hidden?: boolean }) => {
|
||||
const hidden = options?.hidden === true;
|
||||
const newSession = createHostTerminalSession(crypto.randomUUID(), host);
|
||||
const isSshHost = !host.protocol || host.protocol === "ssh" || host.protocol === "mosh" || host.protocol === "et";
|
||||
const defaultCompanionProto: RemoteDesktopProtocol | null = isSshHost
|
||||
? host.rdpConfig?.enabled && host.rdpConfig?.defaultConnect
|
||||
? "rdp"
|
||||
: host.vncConfig?.enabled && host.vncConfig?.defaultConnect
|
||||
? "vnc"
|
||||
: null
|
||||
: null;
|
||||
const newSession = defaultCompanionProto
|
||||
? createRemoteDesktopSession(crypto.randomUUID(), host, defaultCompanionProto)
|
||||
: createHostTerminalSession(crypto.randomUUID(), host);
|
||||
const sessionToAdd = hidden ? { ...newSession, hiddenFromTabs: true } : newSession;
|
||||
setSessions(prev => [...prev, sessionToAdd]);
|
||||
if (!hidden) setActiveTabId(newSession.id);
|
||||
return newSession.id;
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const connectToHostRemoteDesktop = useCallback((
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
options?: { splitFromSessionId?: string; direction?: SplitDirection },
|
||||
) => {
|
||||
const newSessionId = crypto.randomUUID();
|
||||
const splitFromId = options?.splitFromSessionId;
|
||||
if (splitFromId) {
|
||||
const sourceSession = sessionsRef.current.find((s) => s.id === splitFromId);
|
||||
if (sourceSession) {
|
||||
const direction: SplitDirection = options?.direction ?? 'vertical';
|
||||
const position = direction === 'horizontal' ? 'bottom' : 'right';
|
||||
if (sourceSession.workspaceId) {
|
||||
const wsId = sourceSession.workspaceId;
|
||||
const newSession = createRemoteDesktopSession(newSessionId, host, protocol, {
|
||||
workspaceId: wsId,
|
||||
});
|
||||
setSessions((prev) => addTerminalSessionIfMissing(prev, newSession));
|
||||
setWorkspaces((prev) =>
|
||||
insertWorkspacePaneIfMissing(prev, wsId, newSessionId, {
|
||||
direction,
|
||||
position,
|
||||
targetSessionId: splitFromId,
|
||||
}),
|
||||
);
|
||||
setActiveTabId(wsId);
|
||||
return newSessionId;
|
||||
}
|
||||
const standaloneHint: SplitHint = { direction, position };
|
||||
const createdWs = createWorkspaceEntity(splitFromId, newSessionId, standaloneHint);
|
||||
const newSession = createRemoteDesktopSession(newSessionId, host, protocol, {
|
||||
workspaceId: createdWs.id,
|
||||
});
|
||||
const mergedTitle = buildMergedWorkspaceTitle(
|
||||
getSessionConnectionLabel(sourceSession),
|
||||
getSessionConnectionLabel(newSession),
|
||||
);
|
||||
const newWorkspace = mergedTitle
|
||||
? { ...createdWs, title: mergedTitle, autoTitle: false, generatedTitle: true }
|
||||
: createdWs;
|
||||
setSessions((prev) => {
|
||||
const withUpdatedSource = prev.map((s) =>
|
||||
s.id === splitFromId ? { ...s, workspaceId: newWorkspace.id } : s,
|
||||
);
|
||||
return addTerminalSessionIfMissing(withUpdatedSource, newSession);
|
||||
});
|
||||
setWorkspaces((prev) => addWorkspaceIfMissing(prev, newWorkspace));
|
||||
setTabOrder((prev) => {
|
||||
const idx = prev.indexOf(splitFromId);
|
||||
if (idx === -1) return prev;
|
||||
const next = [...prev];
|
||||
next[idx] = newWorkspace.id;
|
||||
return next;
|
||||
});
|
||||
setActiveTabId(newWorkspace.id);
|
||||
return newSessionId;
|
||||
}
|
||||
}
|
||||
|
||||
const newSession = createRemoteDesktopSession(newSessionId, host, protocol);
|
||||
setSessions((prev) => [...prev, newSession]);
|
||||
setActiveTabId(newSessionId);
|
||||
return newSessionId;
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const setSessionPoppedOut = useCallback((sessionId: string, poppedOut: boolean) => {
|
||||
setSessions(prev => prev.map((s) => {
|
||||
if (s.id !== sessionId) return s;
|
||||
@@ -1360,7 +1459,7 @@ export const useSessionState = ({
|
||||
// orphanSessions changes with every session status update.
|
||||
const orphanSessionsRef = useRef(orphanSessions);
|
||||
orphanSessionsRef.current = orphanSessions;
|
||||
const canUseGlobalBroadcast = orphanSessions.length >= 2;
|
||||
const canUseGlobalBroadcast = orphanSessions.filter((s) => !isRemoteDesktopProtocol(s.protocol)).length >= 2;
|
||||
|
||||
// Losing the group must disarm broadcast before another tab can join it.
|
||||
// Compose-bar send target follows the toolbar switch back to active-only.
|
||||
@@ -1663,6 +1762,7 @@ export const useSessionState = ({
|
||||
createLocalTerminal,
|
||||
createSerialSession,
|
||||
connectToHost,
|
||||
connectToHostRemoteDesktop,
|
||||
closeSession,
|
||||
closeSessions,
|
||||
closeWorkspace,
|
||||
|
||||
@@ -62,6 +62,11 @@ import {
|
||||
STORAGE_KEY_SESSION_LOGS_DIR,
|
||||
STORAGE_KEY_SESSION_LOGS_FORMAT,
|
||||
STORAGE_KEY_SESSION_LOGS_TIMESTAMPS_ENABLED,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS,
|
||||
STORAGE_KEY_SSH_DEBUG_LOGS_ENABLED,
|
||||
STORAGE_KEY_SSH_DEEP_LINK_ENABLED,
|
||||
STORAGE_KEY_JMS_DEEP_LINK_ENABLED,
|
||||
@@ -171,7 +176,33 @@ import {
|
||||
} from '../../domain/startupLanding';
|
||||
import { resolveRestorePreviousSessionSetting, resolveRestoreTerminalCwdSetting } from './sessionRestoreSettings';
|
||||
import { sessionRestoreStorage } from './sessionRestoreStorage';
|
||||
import { useSettingsStorageSync } from './settingsStorageSync';
|
||||
import {
|
||||
DEFAULT_JUMPSERVER_RDP_LAUNCH_MODE,
|
||||
DEFAULT_REMOTE_DESKTOP_AUTO_RECORD,
|
||||
DEFAULT_REMOTE_DESKTOP_RECORDING_FPS,
|
||||
DEFAULT_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO,
|
||||
DEFAULT_REMOTE_DESKTOP_RECORDING_MAX_MB,
|
||||
DEFAULT_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS,
|
||||
isJumpServerRdpLaunchMode,
|
||||
normalizeRemoteDesktopRecordingFps,
|
||||
normalizeRemoteDesktopRecordingMaxMb,
|
||||
normalizeRemoteDesktopRecordingRetentionDays,
|
||||
STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE,
|
||||
useSettingsStorageSync,
|
||||
type JumpServerRdpLaunchMode,
|
||||
type RemoteDesktopRecordingFps,
|
||||
} from './settingsStorageSync';
|
||||
export {
|
||||
DEFAULT_JUMPSERVER_RDP_LAUNCH_MODE,
|
||||
DEFAULT_REMOTE_DESKTOP_AUTO_RECORD,
|
||||
DEFAULT_REMOTE_DESKTOP_RECORDING_FPS,
|
||||
DEFAULT_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO,
|
||||
DEFAULT_REMOTE_DESKTOP_RECORDING_MAX_MB,
|
||||
DEFAULT_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS,
|
||||
STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE,
|
||||
type JumpServerRdpLaunchMode,
|
||||
type RemoteDesktopRecordingFps,
|
||||
};
|
||||
import { useSettingsIpcSync } from './settingsIpcSync';
|
||||
import { TERMINAL_THEME_AUTO } from '../../domain/terminalAppearance';
|
||||
import { customThemeStore, useCustomThemes } from '../state/customThemeStore';
|
||||
@@ -532,6 +563,35 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
const stored = readStoredString(STORAGE_KEY_SESSION_LOGS_TIMESTAMPS_ENABLED);
|
||||
return stored === 'true' ? true : DEFAULT_SESSION_LOGS_TIMESTAMPS_ENABLED;
|
||||
});
|
||||
// Remote Desktop Session Recordings Settings (device-local)
|
||||
const [remoteDesktopAutoRecord, setRemoteDesktopAutoRecordState] = useState<boolean>(() => {
|
||||
const stored = readStoredString(STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD);
|
||||
if (stored === null) return DEFAULT_REMOTE_DESKTOP_AUTO_RECORD;
|
||||
return stored === 'true';
|
||||
});
|
||||
const [remoteDesktopRecordingFps, setRemoteDesktopRecordingFpsState] = useState<RemoteDesktopRecordingFps>(() => {
|
||||
const stored = readStoredString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS);
|
||||
return stored === null
|
||||
? DEFAULT_REMOTE_DESKTOP_RECORDING_FPS
|
||||
: normalizeRemoteDesktopRecordingFps(stored);
|
||||
});
|
||||
const [remoteDesktopRecordingIncludeAudio, setRemoteDesktopRecordingIncludeAudioState] = useState<boolean>(() => {
|
||||
const stored = readStoredString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO);
|
||||
if (stored === null) return DEFAULT_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO;
|
||||
return stored === 'true';
|
||||
});
|
||||
const [remoteDesktopRecordingMaxMb, setRemoteDesktopRecordingMaxMbState] = useState<number>(() => {
|
||||
const stored = readStoredString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB);
|
||||
return stored === null
|
||||
? DEFAULT_REMOTE_DESKTOP_RECORDING_MAX_MB
|
||||
: normalizeRemoteDesktopRecordingMaxMb(stored);
|
||||
});
|
||||
const [remoteDesktopRecordingRetentionDays, setRemoteDesktopRecordingRetentionDaysState] = useState<number>(() => {
|
||||
const stored = readStoredString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS);
|
||||
return stored === null
|
||||
? DEFAULT_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS
|
||||
: normalizeRemoteDesktopRecordingRetentionDays(stored);
|
||||
});
|
||||
const [sshDebugLogsEnabled, setSshDebugLogsEnabled] = useState<boolean>(() => {
|
||||
const stored = readStoredString(STORAGE_KEY_SSH_DEBUG_LOGS_ENABLED);
|
||||
return stored === 'true' ? true : DEFAULT_SSH_DEBUG_LOGS_ENABLED;
|
||||
@@ -544,6 +604,10 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_JMS_DEEP_LINK_ENABLED);
|
||||
return stored ?? DEFAULT_JMS_DEEP_LINK_ENABLED;
|
||||
});
|
||||
const [jumpServerRdpLaunchMode, setJumpServerRdpLaunchModeState] = useState<JumpServerRdpLaunchMode>(() => {
|
||||
const stored = readStoredString(STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE);
|
||||
return isJumpServerRdpLaunchMode(stored) ? stored : DEFAULT_JUMPSERVER_RDP_LAUNCH_MODE;
|
||||
});
|
||||
const [explorerContextMenuEnabled, setExplorerContextMenuEnabledState] = useState<boolean>(() => {
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_EXPLORER_CONTEXT_MENU_ENABLED);
|
||||
return stored ?? DEFAULT_EXPLORER_CONTEXT_MENU_ENABLED;
|
||||
@@ -1055,10 +1119,38 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
if (storedSshDebugLogsEnabled === 'true' || storedSshDebugLogsEnabled === 'false') {
|
||||
setSshDebugLogsEnabled(storedSshDebugLogsEnabled === 'true');
|
||||
}
|
||||
const storedRdAutoRecord = readStoredString(STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD);
|
||||
setRemoteDesktopAutoRecordState(
|
||||
storedRdAutoRecord === null ? DEFAULT_REMOTE_DESKTOP_AUTO_RECORD : storedRdAutoRecord === 'true',
|
||||
);
|
||||
const storedRdFps = readStoredString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS);
|
||||
setRemoteDesktopRecordingFpsState(
|
||||
storedRdFps === null ? DEFAULT_REMOTE_DESKTOP_RECORDING_FPS : normalizeRemoteDesktopRecordingFps(storedRdFps),
|
||||
);
|
||||
const storedRdAudio = readStoredString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO);
|
||||
setRemoteDesktopRecordingIncludeAudioState(
|
||||
storedRdAudio === null ? DEFAULT_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO : storedRdAudio === 'true',
|
||||
);
|
||||
const storedRdMaxMb = readStoredString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB);
|
||||
setRemoteDesktopRecordingMaxMbState(
|
||||
storedRdMaxMb === null ? DEFAULT_REMOTE_DESKTOP_RECORDING_MAX_MB : normalizeRemoteDesktopRecordingMaxMb(storedRdMaxMb),
|
||||
);
|
||||
const storedRdRetention = readStoredString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS);
|
||||
setRemoteDesktopRecordingRetentionDaysState(
|
||||
storedRdRetention === null
|
||||
? DEFAULT_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS
|
||||
: normalizeRemoteDesktopRecordingRetentionDays(storedRdRetention),
|
||||
);
|
||||
const storedSshDeepLinkEnabled = localStorageAdapter.readBoolean(STORAGE_KEY_SSH_DEEP_LINK_ENABLED);
|
||||
applyIncomingSshDeepLinkEnabled(storedSshDeepLinkEnabled ?? DEFAULT_SSH_DEEP_LINK_ENABLED);
|
||||
const storedJmsDeepLinkEnabled = localStorageAdapter.readBoolean(STORAGE_KEY_JMS_DEEP_LINK_ENABLED);
|
||||
applyIncomingJmsDeepLinkEnabled(storedJmsDeepLinkEnabled ?? DEFAULT_JMS_DEEP_LINK_ENABLED);
|
||||
const storedJumpServerRdpLaunchMode = readStoredString(STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE);
|
||||
setJumpServerRdpLaunchModeState(
|
||||
isJumpServerRdpLaunchMode(storedJumpServerRdpLaunchMode)
|
||||
? storedJumpServerRdpLaunchMode
|
||||
: DEFAULT_JUMPSERVER_RDP_LAUNCH_MODE,
|
||||
);
|
||||
const storedExplorerContextMenuEnabled = localStorageAdapter.readBoolean(STORAGE_KEY_EXPLORER_CONTEXT_MENU_ENABLED);
|
||||
applyIncomingExplorerContextMenuEnabled(storedExplorerContextMenuEnabled ?? DEFAULT_EXPLORER_CONTEXT_MENU_ENABLED);
|
||||
|
||||
@@ -1283,6 +1375,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setSshDebugLogsEnabled,
|
||||
setSshDeepLinkEnabledState: applyIncomingSshDeepLinkEnabled,
|
||||
setJmsDeepLinkEnabledState: applyIncomingJmsDeepLinkEnabled,
|
||||
setJumpServerRdpLaunchModeState,
|
||||
setExplorerContextMenuEnabledState: applyIncomingExplorerContextMenuEnabled,
|
||||
setHotkeyScheme,
|
||||
applyIncomingCustomKeyBindings,
|
||||
@@ -1396,7 +1489,9 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, windowBackgroundBlur, appIconVariant,
|
||||
setTheme, setLightUiThemeId, setDarkUiThemeId, setAccentMode,
|
||||
applyIncomingCustomAccent,
|
||||
@@ -1406,7 +1501,9 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
|
||||
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled, setSshDebugLogsEnabled, setSshDeepLinkEnabledState: applyIncomingSshDeepLinkEnabled, setJmsDeepLinkEnabledState: applyIncomingJmsDeepLinkEnabled, setExplorerContextMenuEnabledState: applyIncomingExplorerContextMenuEnabled,
|
||||
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
|
||||
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
|
||||
setSshDebugLogsEnabled, setSshDeepLinkEnabledState: applyIncomingSshDeepLinkEnabled, setJmsDeepLinkEnabledState: applyIncomingJmsDeepLinkEnabled, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState: applyIncomingExplorerContextMenuEnabled,
|
||||
setGlobalHotkeyEnabled, setWindowOpacity: applyIncomingWindowOpacity, setWindowBackgroundBlur, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState,
|
||||
setSftpTransferConcurrencyState, setSshTransportIdleTtlMsState,
|
||||
applyIncomingCustomKeyBindings, mergeIncomingTerminalSettings,
|
||||
@@ -1713,6 +1810,59 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
notifySettingsChanged(STORAGE_KEY_SESSION_LOGS_TIMESTAMPS_ENABLED, sessionLogsTimestampsEnabled);
|
||||
}, [sessionLogsTimestampsEnabled, notifySettingsChanged]);
|
||||
|
||||
// Persist Remote Desktop Recordings settings (device-local)
|
||||
const setRemoteDesktopAutoRecord = useCallback((enabled: boolean) => {
|
||||
setRemoteDesktopAutoRecordState(Boolean(enabled));
|
||||
}, []);
|
||||
const setRemoteDesktopRecordingFps = useCallback((fps: RemoteDesktopRecordingFps) => {
|
||||
setRemoteDesktopRecordingFpsState(normalizeRemoteDesktopRecordingFps(fps));
|
||||
}, []);
|
||||
const setRemoteDesktopRecordingIncludeAudio = useCallback((enabled: boolean) => {
|
||||
setRemoteDesktopRecordingIncludeAudioState(Boolean(enabled));
|
||||
}, []);
|
||||
const setRemoteDesktopRecordingMaxMb = useCallback((maxMb: number) => {
|
||||
setRemoteDesktopRecordingMaxMbState(normalizeRemoteDesktopRecordingMaxMb(maxMb));
|
||||
}, []);
|
||||
const setRemoteDesktopRecordingRetentionDays = useCallback((days: number) => {
|
||||
setRemoteDesktopRecordingRetentionDaysState(normalizeRemoteDesktopRecordingRetentionDays(days));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
localStorageAdapter.writeString(STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD, remoteDesktopAutoRecord ? 'true' : 'false');
|
||||
if (!persistMountedRef.current) return;
|
||||
notifySettingsChanged(STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD, remoteDesktopAutoRecord);
|
||||
}, [remoteDesktopAutoRecord, notifySettingsChanged]);
|
||||
|
||||
useEffect(() => {
|
||||
localStorageAdapter.writeString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS, String(remoteDesktopRecordingFps));
|
||||
if (!persistMountedRef.current) return;
|
||||
notifySettingsChanged(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS, remoteDesktopRecordingFps);
|
||||
}, [remoteDesktopRecordingFps, notifySettingsChanged]);
|
||||
|
||||
useEffect(() => {
|
||||
localStorageAdapter.writeString(
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO,
|
||||
remoteDesktopRecordingIncludeAudio ? 'true' : 'false',
|
||||
);
|
||||
if (!persistMountedRef.current) return;
|
||||
notifySettingsChanged(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO, remoteDesktopRecordingIncludeAudio);
|
||||
}, [remoteDesktopRecordingIncludeAudio, notifySettingsChanged]);
|
||||
|
||||
useEffect(() => {
|
||||
localStorageAdapter.writeString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB, String(remoteDesktopRecordingMaxMb));
|
||||
if (!persistMountedRef.current) return;
|
||||
notifySettingsChanged(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB, remoteDesktopRecordingMaxMb);
|
||||
}, [remoteDesktopRecordingMaxMb, notifySettingsChanged]);
|
||||
|
||||
useEffect(() => {
|
||||
localStorageAdapter.writeString(
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS,
|
||||
String(remoteDesktopRecordingRetentionDays),
|
||||
);
|
||||
if (!persistMountedRef.current) return;
|
||||
notifySettingsChanged(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS, remoteDesktopRecordingRetentionDays);
|
||||
}, [remoteDesktopRecordingRetentionDays, notifySettingsChanged]);
|
||||
|
||||
useEffect(() => {
|
||||
localStorageAdapter.writeString(STORAGE_KEY_SSH_DEBUG_LOGS_ENABLED, sshDebugLogsEnabled ? 'true' : 'false');
|
||||
if (!persistMountedRef.current) return;
|
||||
@@ -1839,6 +1989,17 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
notifySettingsChanged(STORAGE_KEY_JMS_DEEP_LINK_ENABLED, jmsDeepLinkEnabled);
|
||||
}, [jmsDeepLinkEnabled, notifySettingsChanged]);
|
||||
|
||||
const setJumpServerRdpLaunchMode = useCallback((mode: JumpServerRdpLaunchMode) => {
|
||||
if (!isJumpServerRdpLaunchMode(mode)) return;
|
||||
setJumpServerRdpLaunchModeState(mode);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
localStorageAdapter.writeString(STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE, jumpServerRdpLaunchMode);
|
||||
if (!persistMountedRef.current) return;
|
||||
notifySettingsChanged(STORAGE_KEY_JUMPSERVER_RDP_LAUNCH_MODE, jumpServerRdpLaunchMode);
|
||||
}, [jumpServerRdpLaunchMode, notifySettingsChanged]);
|
||||
|
||||
useEffect(() => {
|
||||
explorerContextMenuEnabledRef.current = explorerContextMenuEnabled;
|
||||
}, [explorerContextMenuEnabled]);
|
||||
@@ -2266,12 +2427,25 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setSessionLogsFormat,
|
||||
sessionLogsTimestampsEnabled,
|
||||
setSessionLogsTimestampsEnabled,
|
||||
// Remote Desktop Recordings
|
||||
remoteDesktopAutoRecord,
|
||||
setRemoteDesktopAutoRecord,
|
||||
remoteDesktopRecordingFps,
|
||||
setRemoteDesktopRecordingFps,
|
||||
remoteDesktopRecordingIncludeAudio,
|
||||
setRemoteDesktopRecordingIncludeAudio,
|
||||
remoteDesktopRecordingMaxMb,
|
||||
setRemoteDesktopRecordingMaxMb,
|
||||
remoteDesktopRecordingRetentionDays,
|
||||
setRemoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled,
|
||||
setSshDebugLogsEnabled,
|
||||
sshDeepLinkEnabled,
|
||||
setSshDeepLinkEnabled,
|
||||
jmsDeepLinkEnabled,
|
||||
setJmsDeepLinkEnabled,
|
||||
jumpServerRdpLaunchMode,
|
||||
setJumpServerRdpLaunchMode,
|
||||
explorerContextMenuEnabled,
|
||||
setExplorerContextMenuEnabled,
|
||||
explorerContextMenuSupported,
|
||||
@@ -2314,7 +2488,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
customKeyBindings, editorWordWrap,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, globalDefaultProxyProfileId,
|
||||
customThemes, workspaceFocusStyle, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
|
||||
customThemes, workspaceFocusStyle, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
]),
|
||||
};
|
||||
};
|
||||
@@ -1,5 +1,9 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
|
||||
import type {
|
||||
RemoteDesktopProbeResult,
|
||||
RemoteDesktopTestOptions,
|
||||
} from "../../domain/hostConnectionTest";
|
||||
import type { TerminalSessionExitEvent } from "./resolveTerminalSessionExitIntent";
|
||||
|
||||
type PluginConnectionStartOptions = NetcattyPluginConnectionStartRequest & {
|
||||
@@ -145,6 +149,37 @@ export const useTerminalBackend = () => {
|
||||
return bridge.cancelTestConnection(sessionId);
|
||||
}, []);
|
||||
|
||||
const testRemoteDesktopConnection = useCallback(
|
||||
async (options: RemoteDesktopTestOptions): Promise<RemoteDesktopProbeResult> => {
|
||||
const bridge = netcattyBridge.get() as
|
||||
| (NetcattyBridge & {
|
||||
remoteDesktop?: {
|
||||
testConnection?: (opts: RemoteDesktopTestOptions) => Promise<RemoteDesktopProbeResult>;
|
||||
};
|
||||
})
|
||||
| undefined;
|
||||
if (!bridge?.remoteDesktop?.testConnection) {
|
||||
throw new Error("remoteDesktop.testConnection unavailable");
|
||||
}
|
||||
return bridge.remoteDesktop.testConnection(options);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const cancelRemoteDesktopTestConnection = useCallback(async (sessionId: string) => {
|
||||
const bridge = netcattyBridge.get() as
|
||||
| (NetcattyBridge & {
|
||||
remoteDesktop?: {
|
||||
cancelTestConnection?: (id: string) => Promise<{ ok: boolean }>;
|
||||
};
|
||||
})
|
||||
| undefined;
|
||||
if (!bridge?.remoteDesktop?.cancelTestConnection) {
|
||||
return { ok: false };
|
||||
}
|
||||
return bridge.remoteDesktop.cancelTestConnection(sessionId);
|
||||
}, []);
|
||||
|
||||
const startTelnetSession = useCallback(async (options: Parameters<NonNullable<NetcattyBridge["startTelnetSession"]>>[0]) => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.startTelnetSession) throw new Error("startTelnetSession unavailable");
|
||||
@@ -610,6 +645,8 @@ export const useTerminalBackend = () => {
|
||||
startSSHSession,
|
||||
testConnection,
|
||||
cancelTestConnection,
|
||||
testRemoteDesktopConnection,
|
||||
cancelRemoteDesktopTestConnection,
|
||||
startTelnetSession,
|
||||
startMoshSession,
|
||||
startEtSession,
|
||||
@@ -697,6 +734,8 @@ export const useTerminalBackend = () => {
|
||||
startSSHSession,
|
||||
testConnection,
|
||||
cancelTestConnection,
|
||||
testRemoteDesktopConnection,
|
||||
cancelRemoteDesktopTestConnection,
|
||||
startTelnetSession,
|
||||
startMoshSession,
|
||||
startEtSession,
|
||||
|
||||
@@ -145,7 +145,9 @@ export function useVaultImportHandlers({
|
||||
? "SecureCRT"
|
||||
: format === "finalshell"
|
||||
? "FinalShell"
|
||||
: "ssh_config";
|
||||
: format === "rdp"
|
||||
? "RDP"
|
||||
: "ssh_config";
|
||||
const updateProgress = (next: Partial<VaultImportProgress>) => {
|
||||
setImportProgress((current) => ({
|
||||
status: "running",
|
||||
|
||||
@@ -53,8 +53,11 @@ import {
|
||||
STORAGE_KEY_SNIPPET_PACKAGES,
|
||||
STORAGE_KEY_SNIPPETS,
|
||||
STORAGE_KEY_TERM_SETTINGS,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS,
|
||||
} from "../../infrastructure/config/storageKeys";
|
||||
import { localStorageAdapter, LOCAL_STORAGE_ADAPTER_CHANGED_EVENT } from "../../infrastructure/persistence/localStorageAdapter";
|
||||
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
|
||||
import {
|
||||
mergeGlobalHistoryOnAppend,
|
||||
removeGlobalHistoryEntry,
|
||||
@@ -629,6 +632,27 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
|
||||
connectionLogPendingRef.current.set(log.id, { generation, log: null });
|
||||
}
|
||||
}
|
||||
const remainingRecordingIds = new Set<string>();
|
||||
for (const log of next) {
|
||||
if (log.recordingId) remainingRecordingIds.add(log.recordingId);
|
||||
}
|
||||
const removedRecordingIds: string[] = [];
|
||||
for (const log of prev) {
|
||||
if (
|
||||
!nextIds.has(log.id)
|
||||
&& log.recordingId
|
||||
&& !remainingRecordingIds.has(log.recordingId)
|
||||
) {
|
||||
removedRecordingIds.push(log.recordingId);
|
||||
}
|
||||
}
|
||||
if (removedRecordingIds.length > 0) {
|
||||
void netcattyBridge
|
||||
.get()
|
||||
?.remoteDesktopRecordings
|
||||
?.deleteMany?.({ recordingIds: removedRecordingIds })
|
||||
?.catch(() => {});
|
||||
}
|
||||
connectionLogsRef.current = next;
|
||||
setConnectionLogs(next);
|
||||
return enqueueTerminalDataTask(() => withVaultImportLock("connection-logs", async () => {
|
||||
@@ -1560,6 +1584,35 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
|
||||
publishConnectionLogsSnapshot({ connectionLogs });
|
||||
}, [connectionLogs]);
|
||||
|
||||
// One-time startup GC to sweep orphaned / expired / over-quota remote desktop recordings
|
||||
// while preserving all bookmarked/saved connection log recordings.
|
||||
const hasRunRecordingStartupGcRef = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!syncConnectionLogTerminalData || hasRunRecordingStartupGcRef.current) return;
|
||||
hasRunRecordingStartupGcRef.current = true;
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.remoteDesktopRecordings?.runGc) return;
|
||||
const logs = connectionLogsRef.current;
|
||||
const referencedIds = logs
|
||||
.map((log) => log.recordingId)
|
||||
.filter((id): id is string => typeof id === "string" && id.length > 0);
|
||||
const protectedIds = logs
|
||||
.filter((log) => log.saved && typeof log.recordingId === "string" && log.recordingId.length > 0)
|
||||
.map((log) => log.recordingId as string);
|
||||
const storedMaxMb = localStorageAdapter.readNumber(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB);
|
||||
const maxMb = storedMaxMb != null && storedMaxMb >= 64 ? storedMaxMb : 1024;
|
||||
const storedRetention = localStorageAdapter.readNumber(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS);
|
||||
const retentionDays = storedRetention != null && storedRetention >= 0 ? storedRetention : 30;
|
||||
void bridge.remoteDesktopRecordings
|
||||
.runGc({
|
||||
maxBytes: maxMb * 1024 * 1024,
|
||||
retentionDays,
|
||||
referencedIds,
|
||||
protectedIds,
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [syncConnectionLogTerminalData]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
registerConnectionLogsActions({
|
||||
updateConnectionLog,
|
||||
|
||||
@@ -12,6 +12,12 @@ export function getVaultImportPickerMode(
|
||||
directory: boolean;
|
||||
multiple: boolean;
|
||||
} {
|
||||
if (format === "rdp") {
|
||||
return {
|
||||
directory: false,
|
||||
multiple: true,
|
||||
};
|
||||
}
|
||||
const isBatchFolder = (format === "securecrt" || format === "finalshell")
|
||||
&& source === "folder";
|
||||
return {
|
||||
@@ -25,7 +31,7 @@ export function selectVaultImportFiles(
|
||||
files: ArrayLike<File>,
|
||||
): File[] {
|
||||
const selected = Array.from(files);
|
||||
return format === "securecrt" || format === "finalshell"
|
||||
return format === "securecrt" || format === "finalshell" || format === "rdp"
|
||||
? selected
|
||||
: selected.slice(0, 1);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ type TerminalSessionSummary = {
|
||||
hostname: string;
|
||||
label: string;
|
||||
connected: boolean;
|
||||
protocol?: string;
|
||||
};
|
||||
|
||||
interface AIChatPanelContentProps {
|
||||
@@ -56,6 +57,7 @@ interface AIChatPanelContentProps {
|
||||
inputValue: string;
|
||||
setInputValue: (value: string) => void;
|
||||
handleSend: (textOverride?: string) => void;
|
||||
handleSendQuickPrompt?: (promptText: string) => void;
|
||||
handleCompact: () => void;
|
||||
/** Rename a chat by id (history drawer edit affordance). Panel action, never agent content. */
|
||||
onRenameSession?: (sessionId: string, title: string) => void;
|
||||
@@ -158,6 +160,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
inputValue,
|
||||
setInputValue,
|
||||
handleSend,
|
||||
handleSendQuickPrompt,
|
||||
handleCompact,
|
||||
onRenameSession,
|
||||
onRenameActiveChat,
|
||||
@@ -223,6 +226,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
hostname: session.hostname,
|
||||
label: session.label,
|
||||
connected: session.connected,
|
||||
protocol: session.protocol,
|
||||
})),
|
||||
[terminalSessions],
|
||||
);
|
||||
@@ -443,6 +447,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
value={inputValue}
|
||||
onChange={setInputValue}
|
||||
onSend={handleSend}
|
||||
onSendQuickPrompt={handleSendQuickPrompt}
|
||||
onCompact={handleCompact}
|
||||
onRenameSession={onRenameActiveChat}
|
||||
onListChats={onListChats}
|
||||
|
||||
@@ -1709,14 +1709,18 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
}, [currentAgentId, enterScopeDraftMode, updateScopeDraft]);
|
||||
|
||||
|
||||
const handleSend = useCallback(async (textOverride?: string) => {
|
||||
const handleSend = useCallback(async (
|
||||
textOverride?: string,
|
||||
options?: { includeDraftAttachments?: boolean },
|
||||
) => {
|
||||
const draft = currentDraftRef.current;
|
||||
const currentPanelView = panelViewRef.current;
|
||||
const currentSessionView = activeSessionRef.current;
|
||||
if (textOverride === undefined && !validateNoteMentions(draft?.attachments ?? [])) return;
|
||||
const useDraftAttachments = textOverride === undefined || options?.includeDraftAttachments === true;
|
||||
if (useDraftAttachments && !validateNoteMentions(draft?.attachments ?? [])) return;
|
||||
const trimmed = (textOverride ?? draft?.text ?? '').trim();
|
||||
const sendScopeKey = scopeKey;
|
||||
const attachments = (textOverride === undefined ? draft?.attachments ?? [] : []).map((file) => ({
|
||||
const attachments = (useDraftAttachments ? draft?.attachments ?? [] : []).map((file) => ({
|
||||
base64Data: file.base64Data,
|
||||
mediaType: file.mediaType,
|
||||
filename: file.filename,
|
||||
@@ -1728,30 +1732,35 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
lineCount: file.lineCount,
|
||||
}));
|
||||
const hasInlineTextAttachments = attachments.some(isInlineTextAttachment);
|
||||
if ((!trimmed && !hasInlineTextAttachments) || isStreaming) return;
|
||||
const hasImageAttachments = attachments.some((attachment) => attachment.mediaType.startsWith('image/'));
|
||||
if ((!trimmed && !hasInlineTextAttachments && !hasImageAttachments) || isStreaming) return;
|
||||
// While undo-last-turn is creating the branch, the target is still the source; a
|
||||
// turn submitted now would run in the soon-hidden source session, so
|
||||
// block it until the branch settles.
|
||||
if (isUndoingLastTurn) return;
|
||||
// Note-only sends (empty text + a mentioned note) still need a usable
|
||||
// session title: fall back to the first mentioned note's title so these
|
||||
// Note-only / image-only sends (empty text + attachment) still need a usable
|
||||
// session title: fall back to the note title or image filename so these
|
||||
// conversations don't all show up as "Untitled" in history.
|
||||
const noteOnlyTitle = attachments.find(
|
||||
(attachment) => isVaultNoteAttachment(attachment) && attachment.vaultNoteTitle,
|
||||
)?.vaultNoteTitle ?? '';
|
||||
const titleText = trimmed || noteOnlyTitle.trim();
|
||||
const imageOnlyTitle = attachments.find(
|
||||
(attachment) => attachment.mediaType.startsWith('image/') && attachment.filename,
|
||||
)?.filename ?? '';
|
||||
const titleText = trimmed || noteOnlyTitle.trim() || imageOnlyTitle.trim();
|
||||
const sendAgentId = currentSessionView?.agentId ?? draft?.agentId ?? currentAgentId;
|
||||
const agentConfig = sendAgentId !== 'catty' ? findEnabledExternalAgent(externalAgents, sendAgentId) : undefined;
|
||||
if (sendAgentId !== 'catty' && !agentConfig) return;
|
||||
|
||||
const selectedSkillSlugs = textOverride === undefined ? draft?.selectedUserSkillSlugs ?? [] : [];
|
||||
const selectedSkillSlugs = useDraftAttachments ? draft?.selectedUserSkillSlugs ?? [] : [];
|
||||
const modelPrompt = buildPromptWithTerminalSelectionAttachments(trimmed, attachments);
|
||||
const modelAttachments = attachments.filter((attachment) => !isInlineTextAttachment(attachment));
|
||||
const isDraftMode = currentPanelView.mode === 'draft';
|
||||
|
||||
if (textOverride === undefined) flushDraftText();
|
||||
if (useDraftAttachments) flushDraftText();
|
||||
const submittedText = draft?.text ?? '';
|
||||
const keepPendingAfterSend = () => {
|
||||
if (options?.includeDraftAttachments) return false;
|
||||
const pending = pendingComposerTextRef.current;
|
||||
return pending != null && pending !== submittedText;
|
||||
};
|
||||
@@ -1838,7 +1847,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
const createdSession = createSession(scope, sendAgentId);
|
||||
sessionId = createdSession.id;
|
||||
currentSession = createdSession;
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (useDraftAttachments) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(createdSession.id);
|
||||
setActiveSessionId(createdSession.id);
|
||||
sessionSendGateKey = sessionId;
|
||||
@@ -1869,7 +1878,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
});
|
||||
addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: t('ai.chat.noProvider'), timestamp: Date.now() });
|
||||
if (currentPanelView.mode === 'session') {
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (useDraftAttachments) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(sessionId);
|
||||
}
|
||||
return;
|
||||
@@ -1884,7 +1893,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
});
|
||||
addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: t('ai.chat.noProviderModel'), timestamp: Date.now() });
|
||||
if (currentPanelView.mode === 'session') {
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (useDraftAttachments) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(sessionId);
|
||||
}
|
||||
return;
|
||||
@@ -1897,7 +1906,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
...(selectedSkillSlugs.length > 0 ? { selectedUserSkillSlugs: selectedSkillSlugs } : {}),
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (useDraftAttachments) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(sessionId);
|
||||
setActiveSessionId(sessionId);
|
||||
setStreamingForScope(sessionId, true);
|
||||
@@ -2133,6 +2142,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
return registerGrantPersister((rule) => { addGrant(rule); });
|
||||
}, [addGrant]);
|
||||
|
||||
const handleSendQuickPrompt = useCallback((promptText: string) => {
|
||||
void handleSend(promptText, { includeDraftAttachments: true });
|
||||
}, [handleSend]);
|
||||
|
||||
const handleStop = useCallback(() => {
|
||||
if (!activeSessionId) return;
|
||||
setSteeringSessionId(current => current === activeSessionId ? null : current);
|
||||
@@ -2490,6 +2503,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
inputValue={inputValue}
|
||||
setInputValue={setInputValue}
|
||||
handleSend={handleSend}
|
||||
handleSendQuickPrompt={handleSendQuickPrompt}
|
||||
handleCompact={handleCompact}
|
||||
onRenameSession={handleRenameSession}
|
||||
onRenameActiveChat={handleRenameSlashCommand}
|
||||
|
||||
@@ -1,64 +1,84 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
|
||||
import type { ConnectionLog } from "../types.ts";
|
||||
import ConnectionLogsManager from "./ConnectionLogsManager.tsx";
|
||||
import type { ConnectionLog } from "../domain/models/history.ts";
|
||||
import { TooltipProvider } from "./ui/tooltip.tsx";
|
||||
import ConnectionLogsManager, {
|
||||
formatRecordingBytes,
|
||||
formatRecordingDuration,
|
||||
} from "./ConnectionLogsManager.tsx";
|
||||
|
||||
const baseLog: ConnectionLog = {
|
||||
id: "log-1",
|
||||
hostId: "host-1",
|
||||
hostLabel: "Database",
|
||||
hostname: "db.example.com",
|
||||
username: "root",
|
||||
protocol: "ssh",
|
||||
hostOs: "linux",
|
||||
hostDistro: "ubuntu",
|
||||
startTime: 1_700_000_000_000,
|
||||
localUsername: "alice",
|
||||
localHostname: "workstation",
|
||||
saved: false,
|
||||
};
|
||||
|
||||
const renderLogs = (log: ConnectionLog) =>
|
||||
const renderWithI18n = (node: React.ReactElement) =>
|
||||
renderToStaticMarkup(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<ConnectionLogsManager
|
||||
logs={[log]}
|
||||
hosts={[]}
|
||||
onToggleSaved={() => {}}
|
||||
onDelete={() => {}}
|
||||
onClearUnsaved={() => {}}
|
||||
onOpenLogView={() => {}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
<TooltipProvider>{node}</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
test("ConnectionLogsManager renders saved custom host icon snapshots", () => {
|
||||
const markup = renderLogs({
|
||||
...baseLog,
|
||||
hostIconMode: "custom",
|
||||
hostIconId: "database",
|
||||
hostIconColor: "blue",
|
||||
});
|
||||
test("formatRecordingDuration and formatRecordingBytes format human-readable pills", () => {
|
||||
assert.equal(formatRecordingDuration(0), "00:00");
|
||||
assert.equal(formatRecordingDuration(134_000), "02:14");
|
||||
assert.equal(formatRecordingDuration(3_661_000), "1:01:01");
|
||||
|
||||
assert.match(markup, /background-color:#2563EB/i);
|
||||
assert.doesNotMatch(markup, /bg-\[#E95420\]/);
|
||||
assert.equal(formatRecordingBytes(0), "");
|
||||
assert.equal(formatRecordingBytes(512), "512 B");
|
||||
assert.equal(formatRecordingBytes(4_404_019), "4.2 MB");
|
||||
});
|
||||
|
||||
test("ConnectionLogsManager renders saved distro icon snapshots with custom colors", () => {
|
||||
const markup = renderLogs({
|
||||
...baseLog,
|
||||
hostIconMode: "auto",
|
||||
hostIconColor: "violet",
|
||||
});
|
||||
test("ConnectionLogsManager renders RDP/VNC icons and compact recording pill when recordingId is present", () => {
|
||||
const logs: ConnectionLog[] = [
|
||||
{
|
||||
id: "log-rdp-rec",
|
||||
hostId: "h-1",
|
||||
hostLabel: "Windows Prod",
|
||||
hostname: "10.0.0.10",
|
||||
username: "Administrator",
|
||||
protocol: "rdp",
|
||||
startTime: 1_700_000_000_000,
|
||||
endTime: 1_700_000_134_000,
|
||||
localUsername: "alice",
|
||||
localHostname: "macbook",
|
||||
saved: true,
|
||||
recordingId: "123e4567-e89b-12d3-a456-426614174000",
|
||||
recordingMimeType: "video/webm;codecs=vp9,opus",
|
||||
recordingDurationMs: 134_000,
|
||||
recordingBytes: 4_404_019,
|
||||
recordingHasAudio: true,
|
||||
},
|
||||
{
|
||||
id: "log-vnc-plain",
|
||||
hostId: "h-2",
|
||||
hostLabel: "Linux Desktop",
|
||||
hostname: "10.0.0.20",
|
||||
username: "",
|
||||
protocol: "vnc",
|
||||
startTime: 1_699_999_000_000,
|
||||
endTime: 1_699_999_060_000,
|
||||
localUsername: "alice",
|
||||
localHostname: "macbook",
|
||||
saved: false,
|
||||
},
|
||||
];
|
||||
|
||||
assert.match(markup, /background-color:#7C3AED/i);
|
||||
assert.match(markup, /src="\/distro\/ubuntu.svg"/);
|
||||
assert.doesNotMatch(markup, /bg-\[#E95420\]/);
|
||||
const markup = renderWithI18n(
|
||||
React.createElement(ConnectionLogsManager, {
|
||||
logs,
|
||||
hosts: [],
|
||||
onToggleSaved: () => {},
|
||||
onDelete: () => {},
|
||||
onClearUnsaved: () => {},
|
||||
onOpenLogView: () => {},
|
||||
}),
|
||||
);
|
||||
|
||||
assert.match(markup, /Windows Prod/);
|
||||
assert.match(markup, /Linux Desktop/);
|
||||
assert.match(markup, /data-recording-badge="123e4567-e89b-12d3-a456-426614174000"/);
|
||||
assert.match(markup, /02:14 · 4\.2 MB/);
|
||||
assert.match(markup, /vnc, 10\.0\.0\.20/);
|
||||
assert.match(markup, /bg-blue-500\/15 text-blue-600/);
|
||||
assert.match(markup, /bg-teal-500\/15 text-teal-600/);
|
||||
});
|
||||
@@ -6,13 +6,16 @@ import {
|
||||
Terminal,
|
||||
Trash2,
|
||||
Usb,
|
||||
Video,
|
||||
} from "lucide-react";
|
||||
import React, { memo, useCallback, useMemo, useState } from "react";
|
||||
import { useI18n } from "../application/i18n/I18nProvider";
|
||||
import { resolveHostIconAppearance } from "../domain/hostIcon";
|
||||
import { isRdpProtocol, isVncProtocol } from "../domain/remoteDesktop";
|
||||
import { cn } from "../lib/utils";
|
||||
import { ConnectionLog, Host } from "../types";
|
||||
import { DistroAvatar } from "./DistroAvatar";
|
||||
import { RdpProtocolIcon, VncProtocolIcon } from "./icons/RemoteDesktopIcons";
|
||||
import { ScrollArea } from "./ui/scroll-area";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
|
||||
|
||||
@@ -25,6 +28,34 @@ interface ConnectionLogsManagerProps {
|
||||
onOpenLogView: (log: ConnectionLog) => void;
|
||||
}
|
||||
|
||||
export function formatRecordingDuration(durationMs?: number): string {
|
||||
if (!durationMs || !Number.isFinite(durationMs) || durationMs <= 0) {
|
||||
return "00:00";
|
||||
}
|
||||
const totalSeconds = Math.max(0, Math.round(durationMs / 1000));
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
const mm = String(minutes).padStart(2, "0");
|
||||
const ss = String(seconds).padStart(2, "0");
|
||||
return hours > 0 ? `${hours}:${mm}:${ss}` : `${mm}:${ss}`;
|
||||
}
|
||||
|
||||
export function formatRecordingBytes(bytes?: number): string {
|
||||
if (!bytes || !Number.isFinite(bytes) || bytes <= 0) return "";
|
||||
const units = ["B", "KB", "MB", "GB"];
|
||||
let size = bytes;
|
||||
let unitIdx = 0;
|
||||
while (size >= 1024 && unitIdx < units.length - 1) {
|
||||
size /= 1024;
|
||||
unitIdx += 1;
|
||||
}
|
||||
const formatted = unitIdx === 0
|
||||
? String(Math.round(size))
|
||||
: String(parseFloat(size.toFixed(size >= 10 ? 1 : 2)));
|
||||
return `${formatted} ${units[unitIdx]}`;
|
||||
}
|
||||
|
||||
// Format date for display
|
||||
const formatDate = (timestamp: number, locale: string) => {
|
||||
const date = new Date(timestamp);
|
||||
@@ -68,6 +99,9 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
|
||||
const { t, resolvedLocale } = useI18n();
|
||||
const isLocal = log.protocol === "local" || log.hostname === "localhost";
|
||||
const isSerial = log.protocol === "serial";
|
||||
const isRdp = isRdpProtocol(log.protocol);
|
||||
const isVnc = isVncProtocol(log.protocol);
|
||||
const isRemoteDesktop = isRdp || isVnc;
|
||||
const customHostIcon = resolveHostIconAppearance({
|
||||
iconMode: log.hostIconMode,
|
||||
iconId: log.hostIconId,
|
||||
@@ -75,7 +109,9 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
|
||||
iconColor: log.hostIconColor,
|
||||
iconColorCustom: log.hostIconColorCustom,
|
||||
});
|
||||
const hasPersistedHostIcon = !isLocal && !isSerial && (!!log.hostDistro || !!customHostIcon);
|
||||
const hasPersistedHostIcon = !isLocal && !isSerial && !isRemoteDesktop && (!!log.hostDistro || !!customHostIcon);
|
||||
const recordingSizeText = formatRecordingBytes(log.recordingBytes);
|
||||
const recordingDurationText = formatRecordingDuration(log.recordingDurationMs);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -121,19 +157,55 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
|
||||
) : (
|
||||
<div className={cn(
|
||||
"h-9 w-9 rounded-xl flex items-center justify-center shrink-0",
|
||||
isSerial
|
||||
? "bg-amber-600 text-white dark:bg-amber-400 dark:text-slate-950"
|
||||
: isLocal
|
||||
? "bg-slate-600 text-white dark:bg-slate-300 dark:text-slate-950"
|
||||
: "bg-primary text-primary-foreground"
|
||||
isRdp
|
||||
? "bg-blue-500/15 text-blue-600 dark:text-blue-400"
|
||||
: isVnc
|
||||
? "bg-teal-500/15 text-teal-600 dark:text-teal-400"
|
||||
: isSerial
|
||||
? "bg-amber-600 text-white dark:bg-amber-400 dark:text-slate-950"
|
||||
: isLocal
|
||||
? "bg-slate-600 text-white dark:bg-slate-300 dark:text-slate-950"
|
||||
: "bg-primary text-primary-foreground"
|
||||
)}>
|
||||
{isSerial ? <Usb size={17} /> : isLocal ? <Terminal size={17} /> : <Server size={17} />}
|
||||
{isRdp ? (
|
||||
<RdpProtocolIcon size={17} />
|
||||
) : isVnc ? (
|
||||
<VncProtocolIcon size={17} />
|
||||
) : isSerial ? (
|
||||
<Usb size={17} />
|
||||
) : isLocal ? (
|
||||
<Terminal size={17} />
|
||||
) : (
|
||||
<Server size={17} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium truncate">{isLocal ? t("logs.localTerminal") : log.hostLabel}</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<div className="text-sm font-medium truncate">
|
||||
{isLocal ? t("logs.localTerminal") : log.hostLabel}
|
||||
</div>
|
||||
{log.recordingId && (
|
||||
<span
|
||||
data-recording-badge={log.recordingId}
|
||||
className="inline-flex items-center gap-1 rounded-md border border-primary/25 bg-primary/10 px-1.5 py-0.5 text-[11px] font-medium tabular-nums text-primary shrink-0"
|
||||
>
|
||||
<Video size={12} />
|
||||
<span>
|
||||
{recordingDurationText}
|
||||
{recordingSizeText ? ` · ${recordingSizeText}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground truncate">
|
||||
{isLocal ? "local" : isSerial ? `serial, ${log.hostname}` : `${log.protocol}, ${log.username}`}
|
||||
{isLocal
|
||||
? "local"
|
||||
: isSerial
|
||||
? `serial, ${log.hostname}`
|
||||
: log.username
|
||||
? `${log.protocol}, ${log.username}`
|
||||
: `${log.protocol}, ${log.hostname}`}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getHostOsSelection, HOST_OS_SELECTIONS, resolveHostOs } from '../domain/host';
|
||||
import { applyGroupDefaults } from "../domain/groupConfig";
|
||||
import { isRemoteDesktopProtocol } from "../domain/remoteDesktop";
|
||||
import React from "react";
|
||||
import { AlertTriangle, ChevronDown, Forward, Globe, HeartPulse, KeyRound, Link2, Palette, Plus, Router, ShieldAlert, TerminalSquare, Timer, Wifi, X, Variable } from "lucide-react";
|
||||
import { customThemeStore } from "../application/state/customThemeStore";
|
||||
@@ -37,7 +38,11 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
form,
|
||||
setForm,
|
||||
update,
|
||||
activeProtocolTab,
|
||||
isCurrentTabEnabled = true,
|
||||
effectiveThemeId,
|
||||
effectiveTelnetThemeId,
|
||||
onOpenTelnetThemeSelect,
|
||||
hasEffectiveThemeOverride,
|
||||
effectiveFontSize,
|
||||
hasEffectiveFontSizeOverride,
|
||||
@@ -74,34 +79,57 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
&& !effectiveConnectionHost.moshEnabled
|
||||
&& !effectiveConnectionHost.etEnabled;
|
||||
const effectiveX11Forwarding = !!effectiveConnectionHost.x11Forwarding;
|
||||
const viewedProtocol: "ssh" | "rdp" | "vnc" | "telnet" =
|
||||
activeProtocolTab
|
||||
?? (isRemoteDesktopProtocol(form.protocol)
|
||||
? form.protocol
|
||||
: form.protocol === "telnet"
|
||||
? "telnet"
|
||||
: "ssh");
|
||||
const showTabSections = isCurrentTabEnabled !== false;
|
||||
const isSshView = showTabSections && viewedProtocol === "ssh";
|
||||
const isTelnetView = showTabSections && viewedProtocol === "telnet";
|
||||
const isRemoteDesktopView = showTabSections && (viewedProtocol === "rdp" || viewedProtocol === "vnc");
|
||||
const isCompanionTelnetTheme = isTelnetView && form.protocol !== "telnet" && Boolean(onOpenTelnetThemeSelect);
|
||||
const displayedThemeId = isCompanionTelnetTheme && effectiveTelnetThemeId
|
||||
? effectiveTelnetThemeId
|
||||
: effectiveThemeId;
|
||||
|
||||
return (
|
||||
<>
|
||||
{(isSshView || isTelnetView) && (
|
||||
<>
|
||||
<HostDetailsSection
|
||||
icon={<Palette size={14} className="text-muted-foreground" />}
|
||||
title={t("hostDetails.section.appearance")}
|
||||
>
|
||||
|
||||
{/* SSH Theme Selection */}
|
||||
{/* Terminal Theme Selection (SSH or Telnet) */}
|
||||
<div className="flex w-full items-center gap-1 rounded-lg bg-secondary/50 p-2 transition-colors hover:bg-secondary">
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-w-0 flex-1 items-center gap-3 text-left"
|
||||
onClick={() => setActiveSubPanel("theme-select")}
|
||||
onClick={() => {
|
||||
if (isCompanionTelnetTheme && onOpenTelnetThemeSelect) {
|
||||
onOpenTelnetThemeSelect();
|
||||
} else {
|
||||
setActiveSubPanel("theme-select");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="w-12 h-8 rounded-md border border-border/60 flex items-center justify-center text-[6px] font-mono overflow-hidden shrink-0"
|
||||
style={{
|
||||
backgroundColor:
|
||||
customThemeStore.getThemeById(effectiveThemeId)?.colors.background || "#100F0F",
|
||||
customThemeStore.getThemeById(displayedThemeId)?.colors.background || "#100F0F",
|
||||
color:
|
||||
customThemeStore.getThemeById(effectiveThemeId)?.colors.foreground || "#CECDC3",
|
||||
customThemeStore.getThemeById(displayedThemeId)?.colors.foreground || "#CECDC3",
|
||||
}}
|
||||
>
|
||||
<div className="p-0.5">
|
||||
<div
|
||||
style={{
|
||||
color: customThemeStore.getThemeById(effectiveThemeId)?.colors.green,
|
||||
color: customThemeStore.getThemeById(displayedThemeId)?.colors.green,
|
||||
}}
|
||||
>
|
||||
$
|
||||
@@ -109,10 +137,10 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
</div>
|
||||
</div>
|
||||
<span className="text-sm flex-1 truncate">
|
||||
{customThemeStore.getThemeById(effectiveThemeId)?.name || "Flexoki Dark"}
|
||||
{customThemeStore.getThemeById(displayedThemeId)?.name || "Flexoki Dark"}
|
||||
</span>
|
||||
</button>
|
||||
{hasEffectiveThemeOverride && (
|
||||
{!isCompanionTelnetTheme && hasEffectiveThemeOverride && (
|
||||
<HostDetailsOverrideReset
|
||||
label={t("common.useGlobal")}
|
||||
onClick={(event) => {
|
||||
@@ -191,6 +219,8 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
</HostDetailsSettingRow>
|
||||
</HostDetailsSection>
|
||||
|
||||
{isSshView && (
|
||||
<>
|
||||
<HostDetailsSection
|
||||
icon={<Wifi size={14} className="text-muted-foreground" />}
|
||||
title={t("hostDetails.section.mosh")}
|
||||
@@ -361,13 +391,15 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
/>
|
||||
</HostDetailsSection>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{(!form.protocol || ['ssh', 'telnet', 'mosh', 'et'].includes(form.protocol)) && (
|
||||
{(isSshView || isTelnetView) && (
|
||||
<HostDetailsSection
|
||||
icon={<Router size={14} className="text-muted-foreground" />}
|
||||
title={t("hostDetails.section.deviceType")}
|
||||
>
|
||||
{(!form.protocol || form.protocol === 'ssh') && !form.moshEnabled && !form.etEnabled && (<>
|
||||
{isSshView && !form.moshEnabled && !form.etEnabled && (<>
|
||||
<ToggleRow
|
||||
label={t("hostDetails.deviceType")}
|
||||
hint={t("hostDetails.deviceType.desc")}
|
||||
@@ -419,6 +451,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
)}
|
||||
|
||||
{/* SSH Algorithms */}
|
||||
{isSshView && (
|
||||
<HostDetailsSection
|
||||
icon={<ShieldAlert size={14} className="text-muted-foreground" />}
|
||||
title={t("hostDetails.section.sshAlgorithms")}
|
||||
@@ -473,6 +506,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
t={t}
|
||||
/>
|
||||
</HostDetailsSection>
|
||||
)}
|
||||
|
||||
{/* Terminal Behavior — input/output key mappings (backspace, etc.) */}
|
||||
<HostDetailsSection
|
||||
@@ -485,7 +519,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
enabled={!!form.showLineTimestamps}
|
||||
onToggle={() => update("showLineTimestamps", !form.showLineTimestamps)}
|
||||
/>
|
||||
{(form.protocol === undefined || form.protocol === "ssh") && !form.moshEnabled && !form.etEnabled && (
|
||||
{isSshView && !form.moshEnabled && !form.etEnabled && (
|
||||
<>
|
||||
<ToggleRow
|
||||
label={t("hostDetails.sshInputCompatibility")}
|
||||
@@ -515,6 +549,8 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
</HostDetailsSection>
|
||||
|
||||
{/* Per-host keepalive override */}
|
||||
{isSshView && (
|
||||
<>
|
||||
<HostDetailsSection
|
||||
icon={<HeartPulse size={14} className="text-muted-foreground" />}
|
||||
title={t("hostDetails.section.keepalive")}
|
||||
@@ -616,8 +652,13 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
</HostDetailsSection>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Proxy via Hosts (Jump Hosts / ProxyJump) */}
|
||||
{(isSshView || isRemoteDesktopView) && (
|
||||
<HostDetailsSection
|
||||
icon={<Link2 size={14} className="text-muted-foreground" />}
|
||||
title={t("hostDetails.jumpHosts")}
|
||||
@@ -695,8 +736,10 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
</Button>
|
||||
)}
|
||||
</HostDetailsSection>
|
||||
)}
|
||||
|
||||
{/* Proxy Configuration */}
|
||||
{showTabSections && (
|
||||
<HostDetailsSection
|
||||
icon={<Globe size={14} className="text-muted-foreground" />}
|
||||
title={t("hostDetails.proxy")}
|
||||
@@ -775,8 +818,12 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
</Button>
|
||||
)}
|
||||
</HostDetailsSection>
|
||||
)}
|
||||
|
||||
{/* Environment Variables */}
|
||||
{(isSshView || isTelnetView) && (
|
||||
<>
|
||||
{isSshView && (
|
||||
<HostDetailsSection
|
||||
icon={<Variable size={14} className="text-muted-foreground" />}
|
||||
title={t("hostDetails.envVars")}
|
||||
@@ -813,6 +860,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
</Button>
|
||||
)}
|
||||
</HostDetailsSection>
|
||||
)}
|
||||
|
||||
{/* Startup Command */}
|
||||
<HostDetailsSection
|
||||
@@ -848,6 +896,8 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
</Select>
|
||||
</HostDetailsSettingRow>
|
||||
</HostDetailsSection>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -138,7 +138,7 @@ test("host credentials expose automatic and password-only choices", () => {
|
||||
// Login method uses the same option-style setting row as other host form controls.
|
||||
assert.match(
|
||||
markup,
|
||||
/hostDetails\.auth\.method[\s\S]*?role="combobox"[\s\S]*?hostDetails\.auth\.auto[\s\S]*?<\/div>\s*<div class="flex h-12 items-center justify-between gap-3 rounded-lg border border-border\/60 bg-secondary\/40 px-3">[\s\S]*hostDetails\.auth\.mfaFirst/,
|
||||
/hostDetails\.auth\.method[\s\S]*?role="combobox"[\s\S]*?hostDetails\.auth\.auto[\s\S]*?<\/div>\s*<div class="flex h-10 items-center justify-between gap-3 bg-transparent px-1">[\s\S]*hostDetails\.auth\.mfaFirst/,
|
||||
);
|
||||
assert.match(markup, /class="[^"]*h-8 w-32[^"]*"/);
|
||||
assert.match(
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
import React from "react";
|
||||
import { ChevronDown, Eye, EyeOff, FileKey, FolderLock, Key, KeyRound, MapPin, Shapes, Shield, Trash2, User, X } from "lucide-react";
|
||||
import type { Host } from "../types";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Building2, ChevronDown, Eye, EyeOff, FileKey, FolderLock, Key, KeyRound, MapPin, Plug, Plus, Shapes, Shield, Terminal, Trash2, User, UserCheck, X } from "lucide-react";
|
||||
import type { Host, Identity } from "../types";
|
||||
import { applyHostAuthMethodSelection } from "../domain/sshAuth";
|
||||
import {
|
||||
DEFAULT_RDP_PORT,
|
||||
DEFAULT_VNC_PORT,
|
||||
formatVncDisplayNumber,
|
||||
isRdpProtocol,
|
||||
isRemoteDesktopProtocol,
|
||||
isVncProtocol,
|
||||
parseVncPortOrDisplay,
|
||||
} from "../domain/remoteDesktop";
|
||||
import { cn } from "../lib/utils";
|
||||
import { RdpProtocolIcon, VncProtocolIcon } from "./icons/RemoteDesktopIcons";
|
||||
import { HostTotpFields } from "./HostTotpFields";
|
||||
import { HostIconPicker } from "./HostIconPicker";
|
||||
import { parseOptionalPortInput } from "./HostDetailsPanel.helpers";
|
||||
import { TerminalEncodingSelect } from "./TerminalEncodingSelect";
|
||||
import { Button } from "./ui/button";
|
||||
import { HostDetailsSection, HostDetailsSettingRow } from "./host-details";
|
||||
import { CompanionRemoteDesktopInlineFields } from "./host-details/CompanionRemoteDesktopSections";
|
||||
import { IdentitySuggestInput } from "./host-details/IdentitySuggestInput";
|
||||
import { Input } from "./ui/input";
|
||||
import { Popover, PopoverAnchor, PopoverContent } from "./ui/popover";
|
||||
import { ScrollArea } from "./ui/scroll-area";
|
||||
@@ -103,7 +118,104 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
effectiveFormDistro,
|
||||
getDistroOptionLabel,
|
||||
totpFlushRef,
|
||||
onSelectPrimaryProtocol,
|
||||
activeProtocolTab,
|
||||
enabledProtocols,
|
||||
defaultConnectProtocol,
|
||||
effectiveConnectBehavior,
|
||||
onSelectProtocolTab,
|
||||
onEnableSecondaryProtocol,
|
||||
onSwitchOnlyProtocol,
|
||||
onSetDefaultProtocol,
|
||||
onSetConnectBehavior,
|
||||
onRemoveProtocol,
|
||||
onCreateIdentity,
|
||||
companionCredentialDrafts,
|
||||
onCompanionCredentialDraftChange,
|
||||
effectiveTelnetPort,
|
||||
effectiveTelnetUsername,
|
||||
effectiveTelnetPassword,
|
||||
selectedTelnetIdentity,
|
||||
updateTelnetIdentity,
|
||||
showTelnetPassword = false,
|
||||
setShowTelnetPassword,
|
||||
}) => {
|
||||
const fallbackPrimary: "ssh" | "rdp" | "vnc" | "telnet" =
|
||||
form.protocol === "rdp" || form.protocol === "vnc" || form.protocol === "telnet"
|
||||
? form.protocol
|
||||
: "ssh";
|
||||
const resolvedEnabledProtocols: Record<"ssh" | "rdp" | "vnc" | "telnet", boolean> =
|
||||
enabledProtocols ?? {
|
||||
ssh:
|
||||
!form.protocol
|
||||
|| form.protocol === "ssh"
|
||||
|| form.protocol === "mosh"
|
||||
|| form.protocol === "et"
|
||||
|| Boolean(form.protocols?.some((p: { protocol?: string; enabled?: boolean }) => p.protocol === "ssh" && p.enabled)),
|
||||
rdp: form.protocol === "rdp" || form.rdpConfig?.enabled === true,
|
||||
vnc: form.protocol === "vnc" || form.vncConfig?.enabled === true,
|
||||
telnet: form.protocol === "telnet" || form.telnetEnabled === true,
|
||||
};
|
||||
const resolvedDefaultProtocol: "ssh" | "rdp" | "vnc" | "telnet" =
|
||||
defaultConnectProtocol ?? fallbackPrimary;
|
||||
const resolvedConnectBehavior: "ask" | "ssh" | "rdp" | "vnc" | "telnet" =
|
||||
effectiveConnectBehavior ?? resolvedDefaultProtocol;
|
||||
const currentTab: "ssh" | "rdp" | "vnc" | "telnet" =
|
||||
activeProtocolTab ?? fallbackPrimary;
|
||||
const enabledProtocolList = (["ssh", "rdp", "vnc", "telnet"] as const).filter(
|
||||
(proto) => resolvedEnabledProtocols[proto],
|
||||
);
|
||||
const enabledCount = enabledProtocolList.length;
|
||||
const isCurrentTabEnabled = resolvedEnabledProtocols[currentTab];
|
||||
const isRdpPrimary = isRdpProtocol(form.protocol);
|
||||
const isVncPrimary = isVncProtocol(form.protocol);
|
||||
const isRemoteDesktopPrimary = isRemoteDesktopProtocol(form.protocol);
|
||||
const isCompanionRdpTab = currentTab === "rdp" && resolvedEnabledProtocols.ssh && isCurrentTabEnabled;
|
||||
const isCompanionVncTab = currentTab === "vnc" && resolvedEnabledProtocols.ssh && isCurrentTabEnabled;
|
||||
const isStandaloneRdpTab = currentTab === "rdp" && !resolvedEnabledProtocols.ssh && isCurrentTabEnabled;
|
||||
const isStandaloneVncTab = currentTab === "vnc" && !resolvedEnabledProtocols.ssh && isCurrentTabEnabled;
|
||||
const isTelnetTab = currentTab === "telnet" && isCurrentTabEnabled;
|
||||
const protocolLabels: Record<"ssh" | "rdp" | "vnc" | "telnet", string> = {
|
||||
ssh: "SSH",
|
||||
rdp: "RDP",
|
||||
vnc: "VNC",
|
||||
telnet: "Telnet",
|
||||
};
|
||||
const canAddCurrentAsSecondary =
|
||||
!isCurrentTabEnabled
|
||||
&& Boolean(onEnableSecondaryProtocol)
|
||||
&& (
|
||||
(resolvedEnabledProtocols.ssh && (currentTab === "rdp" || currentTab === "vnc" || currentTab === "telnet"))
|
||||
|| (!resolvedEnabledProtocols.ssh && currentTab === "ssh" && (resolvedEnabledProtocols.rdp || resolvedEnabledProtocols.vnc || resolvedEnabledProtocols.telnet))
|
||||
);
|
||||
|
||||
const [vncPortText, setVncPortText] = useState<string>(() =>
|
||||
String(form.port ?? DEFAULT_VNC_PORT),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (isVncPrimary) {
|
||||
setVncPortText(String(form.port ?? DEFAULT_VNC_PORT));
|
||||
}
|
||||
}, [form.id, form.port, isVncPrimary]);
|
||||
|
||||
const handleTabClick = (next: "ssh" | "rdp" | "vnc" | "telnet") => {
|
||||
if (onSelectProtocolTab) {
|
||||
onSelectProtocolTab(next);
|
||||
} else if (onSelectPrimaryProtocol) {
|
||||
onSelectPrimaryProtocol(next);
|
||||
} else {
|
||||
update("protocol", next);
|
||||
}
|
||||
};
|
||||
|
||||
const passwordCompatibleIdentities: Identity[] = (identities || []).filter(
|
||||
(identity: Identity) => identity.authMethod === "password" || Boolean(identity.password),
|
||||
);
|
||||
const vncDisplayLabel = isVncPrimary
|
||||
? formatVncDisplayNumber(form.port ?? DEFAULT_VNC_PORT)
|
||||
: null;
|
||||
|
||||
const selectAuthMethod = (authMethod: "auto" | "password" | "key" | "certificate") => {
|
||||
setForm((previous: Host) => applyEffectiveHostAuthMethodSelection(
|
||||
previous,
|
||||
@@ -149,9 +261,410 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
title={t("hostDetails.section.portCredentials")}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
{/* Primary protocol selector: minimalist flat segmented control */}
|
||||
<div
|
||||
className="grid grid-cols-4 gap-1 rounded-lg bg-secondary/60 p-1"
|
||||
role="radiogroup"
|
||||
aria-label={t("hostDetails.protocol.label")}
|
||||
>
|
||||
{(
|
||||
[
|
||||
{
|
||||
id: "ssh",
|
||||
label: "SSH",
|
||||
icon: <Shield size={13} />,
|
||||
activeIcon: "text-sky-500",
|
||||
},
|
||||
{
|
||||
id: "rdp",
|
||||
label: "RDP",
|
||||
icon: <RdpProtocolIcon size={13} />,
|
||||
activeIcon: "text-blue-500",
|
||||
},
|
||||
{
|
||||
id: "vnc",
|
||||
label: "VNC",
|
||||
icon: <VncProtocolIcon size={13} />,
|
||||
activeIcon: "text-teal-500",
|
||||
},
|
||||
{
|
||||
id: "telnet",
|
||||
label: "Telnet",
|
||||
icon: <Terminal size={13} />,
|
||||
activeIcon: "text-amber-500",
|
||||
},
|
||||
] as const
|
||||
).map((item) => {
|
||||
const active = currentTab === item.id;
|
||||
const isEnabled = resolvedEnabledProtocols[item.id];
|
||||
const isDefault = resolvedDefaultProtocol === item.id;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={active}
|
||||
data-primary-protocol={item.id}
|
||||
onClick={() => handleTabClick(item.id)}
|
||||
className={cn(
|
||||
"relative flex h-8 items-center justify-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors",
|
||||
active
|
||||
? "bg-background text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0 transition-colors",
|
||||
active || isEnabled ? item.activeIcon : "opacity-60",
|
||||
)}
|
||||
>
|
||||
{item.icon}
|
||||
</span>
|
||||
<span className="truncate leading-none">{item.label}</span>
|
||||
{enabledCount >= 2 && isEnabled && (
|
||||
<span
|
||||
className={cn(
|
||||
"h-1.5 w-1.5 rounded-full shrink-0",
|
||||
resolvedConnectBehavior !== "ask" && isDefault
|
||||
? "bg-primary"
|
||||
: "bg-muted-foreground/45",
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{!isCurrentTabEnabled ? (
|
||||
<div className="rounded-lg border border-dashed border-border/60 bg-transparent px-3 py-5 text-center space-y-3">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("hostDetails.protocol.notEnabledDesc", { protocol: protocolLabels[currentTab] })}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-9 gap-1.5 px-4 text-xs font-medium"
|
||||
onClick={() => {
|
||||
if (canAddCurrentAsSecondary && onEnableSecondaryProtocol) {
|
||||
onEnableSecondaryProtocol(currentTab);
|
||||
} else {
|
||||
onSwitchOnlyProtocol?.(currentTab);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Plus size={14} />
|
||||
{canAddCurrentAsSecondary
|
||||
? t("hostDetails.protocol.addProtocol", { protocol: protocolLabels[currentTab] })
|
||||
: t("hostDetails.protocol.switchOnly", { protocol: protocolLabels[currentTab] })}
|
||||
</Button>
|
||||
</div>
|
||||
) : isCompanionVncTab ? (
|
||||
<CompanionRemoteDesktopInlineFields
|
||||
protocol="vnc"
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
identities={identities}
|
||||
availableKeys={availableKeys}
|
||||
onCreateIdentity={onCreateIdentity}
|
||||
credentialDraft={companionCredentialDrafts?.vnc}
|
||||
onCredentialDraftChange={(draft) => onCompanionCredentialDraftChange?.("vnc", draft)}
|
||||
t={t}
|
||||
/>
|
||||
) : isCompanionRdpTab ? (
|
||||
<CompanionRemoteDesktopInlineFields
|
||||
protocol="rdp"
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
identities={identities}
|
||||
availableKeys={availableKeys}
|
||||
onCreateIdentity={onCreateIdentity}
|
||||
credentialDraft={companionCredentialDrafts?.rdp}
|
||||
onCredentialDraftChange={(draft) => onCompanionCredentialDraftChange?.("rdp", draft)}
|
||||
t={t}
|
||||
/>
|
||||
) : (isStandaloneRdpTab || isStandaloneVncTab) ? (
|
||||
<div className="space-y-2">
|
||||
<HostDetailsSettingRow
|
||||
icon={<Plug />}
|
||||
label={isRdpPrimary ? t("hostDetails.rdp.portLabel") : t("hostDetails.vnc.portLabel")}
|
||||
>
|
||||
{isVncPrimary ? (
|
||||
<div className="flex items-center gap-1.5 w-44">
|
||||
<Input
|
||||
value={vncPortText}
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value;
|
||||
setVncPortText(raw);
|
||||
const parsed = parseVncPortOrDisplay(raw);
|
||||
if (parsed !== null) {
|
||||
update("port", parsed);
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
const parsed = parseVncPortOrDisplay(vncPortText);
|
||||
const resolved = parsed ?? DEFAULT_VNC_PORT;
|
||||
setVncPortText(String(resolved));
|
||||
update("port", resolved);
|
||||
}}
|
||||
placeholder={t("hostDetails.vnc.displayPlaceholder")}
|
||||
className="h-8 flex-1 min-w-0 text-center font-mono text-sm"
|
||||
/>
|
||||
{vncDisplayLabel ? (
|
||||
<span className="rounded border border-border/60 bg-background px-1.5 py-0.5 text-xs font-mono text-muted-foreground shrink-0">
|
||||
{vncDisplayLabel}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
<Input
|
||||
type="number"
|
||||
value={form.port ?? ""}
|
||||
onChange={(e) =>
|
||||
update("port", e.target.value ? Number(e.target.value) : undefined)
|
||||
}
|
||||
placeholder={String(DEFAULT_RDP_PORT)}
|
||||
className="h-8 w-44 text-center font-mono text-sm"
|
||||
/>
|
||||
)}
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<div className="grid gap-2">
|
||||
{selectedIdentity ? (
|
||||
<div className="flex items-center gap-2 h-10 px-3 rounded-lg border border-border/60 bg-transparent">
|
||||
<UserCheck size={14} className="text-muted-foreground shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-medium truncate">
|
||||
{selectedIdentity.label}
|
||||
</div>
|
||||
</div>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
onClick={clearIdentity}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t("common.clear")}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : effectiveIdentityId ? (
|
||||
<div className="flex items-center gap-2 h-10 px-3 rounded-lg border border-border/60 bg-transparent">
|
||||
<User size={16} className="text-muted-foreground" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-medium truncate">
|
||||
{t("hostDetails.identity.missing")}
|
||||
</div>
|
||||
</div>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
onClick={clearIdentity}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t("common.clear")}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<IdentitySuggestInput
|
||||
value={form.username ?? ""}
|
||||
onChange={(next) => update("username", next)}
|
||||
placeholder={
|
||||
isRdpPrimary
|
||||
? t("hostDetails.rdp.usernamePlaceholder")
|
||||
: t("hostDetails.vnc.usernamePlaceholder")
|
||||
}
|
||||
identities={passwordCompatibleIdentities}
|
||||
availableKeys={availableKeys}
|
||||
onSelectIdentity={(identity) => {
|
||||
applyIdentity(identity);
|
||||
if (isRdpPrimary && identity.domain) {
|
||||
setForm((prev: Host) => ({
|
||||
...prev,
|
||||
rdpConfig: {
|
||||
...(prev.rdpConfig ?? {}),
|
||||
domain: identity.domain,
|
||||
},
|
||||
}));
|
||||
}
|
||||
}}
|
||||
t={t}
|
||||
/>
|
||||
|
||||
<div className="relative">
|
||||
<Input
|
||||
placeholder={t("hostDetails.password.placeholder")}
|
||||
type={showPassword ? "text" : "password"}
|
||||
value={form.password || ""}
|
||||
onChange={(e) => update("password", e.target.value)}
|
||||
className="h-10 rounded-lg pr-10"
|
||||
/>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{showPassword ? t("hostDetails.password.hide") : t("hostDetails.password.show")}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{form.password && (
|
||||
<div className="flex items-center justify-between py-1">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("hostDetails.password.save")}
|
||||
</span>
|
||||
<Switch
|
||||
checked={form.savePassword ?? true}
|
||||
onCheckedChange={(val) => update("savePassword" as keyof Host, val)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isRdpPrimary ? (
|
||||
<HostDetailsSettingRow
|
||||
icon={<Building2 />}
|
||||
label={t("hostDetails.rdp.domainLabel")}
|
||||
>
|
||||
<Input
|
||||
placeholder={t("hostDetails.rdp.domainPlaceholder")}
|
||||
value={form.rdpConfig?.domain ?? ""}
|
||||
onChange={(e) =>
|
||||
setForm((prev: Host) => ({
|
||||
...prev,
|
||||
rdpConfig: {
|
||||
...(prev.rdpConfig ?? {}),
|
||||
domain: e.target.value || undefined,
|
||||
},
|
||||
}))
|
||||
}
|
||||
className="h-8 w-44 text-sm"
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : isTelnetTab ? (
|
||||
<>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1 min-w-0 h-10 flex items-center gap-2 bg-transparent px-1">
|
||||
<Plug size={14} className="text-muted-foreground shrink-0" />
|
||||
<span className="text-sm font-medium text-foreground">{t("hostDetails.telnetOn")}</span>
|
||||
<div className="ml-auto w-1/2 min-w-0 flex items-center gap-2 justify-end">
|
||||
<Input
|
||||
type="number"
|
||||
value={effectiveTelnetPort ?? form.telnetPort ?? form.port ?? 23}
|
||||
onChange={(e) => {
|
||||
const parsed = parseOptionalPortInput(e.target.value);
|
||||
setForm((prev: Host) => ({
|
||||
...prev,
|
||||
...(resolvedEnabledProtocols.ssh ? {} : { port: parsed }),
|
||||
telnetPort: parsed,
|
||||
}));
|
||||
}}
|
||||
placeholder="23"
|
||||
className="h-8 flex-1 min-w-0 text-center font-mono text-sm"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground shrink-0">
|
||||
{t("hostDetails.port")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
{form.telnetIdentityId ? (
|
||||
<div className="flex items-center gap-2 h-10 px-3 rounded-lg border border-border/60 bg-transparent">
|
||||
<UserCheck size={14} className="text-muted-foreground shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-medium truncate">
|
||||
{selectedTelnetIdentity
|
||||
? `${selectedTelnetIdentity.username} - ${selectedTelnetIdentity.label}`
|
||||
: t("hostDetails.identity.missing")}
|
||||
</div>
|
||||
</div>
|
||||
{updateTelnetIdentity && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
onClick={() => updateTelnetIdentity("")}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<IdentitySuggestInput
|
||||
value={effectiveTelnetUsername ?? form.telnetUsername ?? ""}
|
||||
onChange={(next) =>
|
||||
update("telnetUsername" as keyof Host, next)
|
||||
}
|
||||
placeholder={t("hostDetails.telnet.username")}
|
||||
identities={updateTelnetIdentity ? passwordCompatibleIdentities : []}
|
||||
availableKeys={availableKeys}
|
||||
onSelectIdentity={(identity) => updateTelnetIdentity?.(identity.id)}
|
||||
t={t}
|
||||
/>
|
||||
<div className="relative">
|
||||
<Input
|
||||
placeholder={t("hostDetails.telnet.password")}
|
||||
type={showTelnetPassword ? "text" : "password"}
|
||||
value={effectiveTelnetPassword ?? form.telnetPassword ?? ""}
|
||||
onChange={(e) =>
|
||||
update("telnetPassword" as keyof Host, e.target.value)
|
||||
}
|
||||
className="h-10 rounded-lg pr-10"
|
||||
/>
|
||||
{setShowTelnetPassword && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowTelnetPassword(!showTelnetPassword)}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{showTelnetPassword ? <EyeOff size={16} /> : <Eye size={16} />}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<TerminalEncodingSelect
|
||||
value={form.charset}
|
||||
inheritedValue={groupDefaults?.charset}
|
||||
onValueChange={(value) => update("charset", value)}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1 min-w-0 h-10 flex items-center gap-2 bg-secondary/70 border border-border/70 rounded-md px-3">
|
||||
<span className="text-xs text-muted-foreground">SSH on</span>
|
||||
<div className="flex-1 min-w-0 h-10 flex items-center gap-2 bg-transparent px-1">
|
||||
<Plug size={14} className="text-muted-foreground shrink-0" />
|
||||
<span className="text-sm font-medium text-foreground">SSH on</span>
|
||||
<div className="ml-auto w-1/2 min-w-0 flex items-center gap-2 justify-end">
|
||||
<Input
|
||||
type="number"
|
||||
@@ -581,8 +1094,68 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
flushRef={totpFlushRef}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{enabledCount >= 2 && isCurrentTabEnabled && onRemoveProtocol && (
|
||||
<div className="flex items-center justify-end border-t border-border/40 pt-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 gap-1.5 px-2 text-xs text-muted-foreground hover:text-destructive"
|
||||
onClick={() => onRemoveProtocol(currentTab)}
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
{t("hostDetails.protocol.removeProtocol", {
|
||||
protocol: protocolLabels[currentTab],
|
||||
})}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</HostDetailsSection>
|
||||
|
||||
{enabledCount >= 2 && (
|
||||
<HostDetailsSection
|
||||
icon={<Plug size={14} className="text-muted-foreground" />}
|
||||
title={t("hostDetails.section.connectBehavior")}
|
||||
>
|
||||
<HostDetailsSettingRow label={t("hostDetails.protocol.doubleClick")}>
|
||||
<Select
|
||||
value={resolvedConnectBehavior}
|
||||
onValueChange={(value) => {
|
||||
const next = value as "ask" | "ssh" | "rdp" | "vnc" | "telnet";
|
||||
if (onSetConnectBehavior) {
|
||||
onSetConnectBehavior(next);
|
||||
} else if (next !== "ask" && onSetDefaultProtocol) {
|
||||
onSetDefaultProtocol(next);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
className="h-8 w-44 text-sm"
|
||||
aria-label={t("hostDetails.protocol.doubleClick")}
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{enabledProtocolList.map((proto) => (
|
||||
<SelectItem key={proto} value={proto}>
|
||||
{t("hostDetails.protocol.connectOptionDefault", {
|
||||
protocol: protocolLabels[proto],
|
||||
})}
|
||||
</SelectItem>
|
||||
))}
|
||||
<SelectItem value="ask">
|
||||
{t("hostDetails.protocol.connectOptionAsk")}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</HostDetailsSettingRow>
|
||||
</HostDetailsSection>
|
||||
)}
|
||||
|
||||
{isCurrentTabEnabled && currentTab === "ssh" && (
|
||||
<HostDetailsSection
|
||||
icon={<FolderLock size={14} className="text-muted-foreground" />}
|
||||
title={t("hostDetails.section.sftp")}
|
||||
@@ -646,6 +1219,7 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
</Select>
|
||||
</HostDetailsSettingRow>
|
||||
</HostDetailsSection>
|
||||
)}
|
||||
|
||||
<HostDetailsSection
|
||||
icon={<Shapes size={14} className="text-muted-foreground" />}
|
||||
@@ -654,6 +1228,7 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
>
|
||||
<HostIconPicker
|
||||
previewHost={form as Host}
|
||||
hideAutoDistro={isRemoteDesktopPrimary && !resolvedEnabledProtocols.ssh}
|
||||
distroMode={form.distroMode}
|
||||
manualDistro={form.manualDistro}
|
||||
effectiveDistro={effectiveFormDistro}
|
||||
|
||||
@@ -20,19 +20,32 @@ export const parseOptionalPortInput = (value: string): number | undefined =>
|
||||
|
||||
export const resolvePrimaryProtocolSwitchPort = (
|
||||
currentPort: number | undefined,
|
||||
nextProtocol: "ssh" | "telnet",
|
||||
nextProtocol: "ssh" | "telnet" | "rdp" | "vnc",
|
||||
hasGroupTelnetPortDefault: boolean,
|
||||
hasGroupSshPortDefault: boolean,
|
||||
): number | undefined => {
|
||||
const isKnownDefaultPort =
|
||||
currentPort === undefined ||
|
||||
currentPort === 22 ||
|
||||
currentPort === 23 ||
|
||||
currentPort === 3389 ||
|
||||
currentPort === 5900;
|
||||
|
||||
if (nextProtocol === "rdp") {
|
||||
return isKnownDefaultPort ? 3389 : currentPort;
|
||||
}
|
||||
if (nextProtocol === "vnc") {
|
||||
return isKnownDefaultPort ? 5900 : currentPort;
|
||||
}
|
||||
if (nextProtocol === "telnet") {
|
||||
// Don't override if group provides a Telnet default
|
||||
if (hasGroupTelnetPortDefault || hasGroupSshPortDefault) return currentPort;
|
||||
if (currentPort === 22 || currentPort === undefined) return 23;
|
||||
if (isKnownDefaultPort) return 23;
|
||||
return currentPort;
|
||||
}
|
||||
if (nextProtocol === "ssh") {
|
||||
if (hasGroupSshPortDefault) return currentPort;
|
||||
if (currentPort === 23 || currentPort === undefined) return 22;
|
||||
if (isKnownDefaultPort) return 22;
|
||||
return currentPort;
|
||||
}
|
||||
return currentPort;
|
||||
@@ -44,6 +57,12 @@ export const resolvePrimaryProtocolSavePort = (
|
||||
hasGroupSshPortDefault: boolean,
|
||||
hasGroupTelnetPortDefault: boolean,
|
||||
): number | undefined => {
|
||||
if (protocol === "rdp") {
|
||||
return currentPort ?? 3389;
|
||||
}
|
||||
if (protocol === "vnc") {
|
||||
return currentPort ?? 5900;
|
||||
}
|
||||
if (protocol === "telnet") {
|
||||
if (currentPort !== undefined) return currentPort;
|
||||
if (hasGroupTelnetPortDefault || hasGroupSshPortDefault) return undefined;
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
mapProxySaveErrorKey,
|
||||
prepareProxyConfigForSave,
|
||||
prepareTelnetCredentialsForSave,
|
||||
resolveDetailsTelnetPort,
|
||||
resolvePrimaryProtocolSavePort,
|
||||
resolvePrimaryProtocolSwitchPort,
|
||||
validateProxyConfigForSave,
|
||||
@@ -284,9 +285,27 @@ test("HostDetailsPanel uses group telnet port instead of ssh port for optional t
|
||||
),
|
||||
);
|
||||
|
||||
const telnetMarkup = markup.slice(markup.indexOf("Telnet on"));
|
||||
assert.match(findInputByValue(telnetMarkup, "2325"), /type="number"/);
|
||||
assert.doesNotMatch(telnetMarkup, /value="2222"/);
|
||||
const telnetTabMarkup = markup.match(/data-primary-protocol="telnet"[\s\S]*?<\/button>/);
|
||||
assert.ok(telnetTabMarkup);
|
||||
// Multi-protocol SSH + Telnet host shows enabled dot on the unified Telnet tab
|
||||
assert.match(telnetTabMarkup[0], /rounded-full/);
|
||||
// No duplicate bottom Additional Protocols section
|
||||
assert.doesNotMatch(markup, /Additional Protocols/);
|
||||
// Resolved telnet port still prefers group telnetPort (2325) over host SSH port (2222)
|
||||
assert.equal(
|
||||
resolveDetailsTelnetPort(
|
||||
{
|
||||
...hostWithMissingProxyProfile,
|
||||
protocol: "ssh",
|
||||
telnetEnabled: true,
|
||||
telnetPort: undefined,
|
||||
port: 2222,
|
||||
group: "network",
|
||||
},
|
||||
{ telnetPort: 2325 },
|
||||
),
|
||||
2325,
|
||||
);
|
||||
});
|
||||
|
||||
test("HostDetailsPanel displays inherited telnet credentials", () => {
|
||||
@@ -501,10 +520,11 @@ test("HostDetailsPanel does not offer to disable telnet when telnet is the prima
|
||||
telnetPort: 23,
|
||||
proxyProfileId: undefined,
|
||||
});
|
||||
const telnetHeader = markup.match(/Telnet on[\s\S]*?Credentials/);
|
||||
const telnetHeader = markup.match(/Telnet on[\s\S]*?Telnet Username/);
|
||||
|
||||
assert.ok(telnetHeader);
|
||||
assert.doesNotMatch(telnetHeader[0], /hover:text-destructive/);
|
||||
assert.doesNotMatch(markup, /Additional Protocols/);
|
||||
});
|
||||
|
||||
test("HostDetailsPanel shows color and icon controls in the connection settings", () => {
|
||||
|
||||
+491
-169
@@ -1,14 +1,10 @@
|
||||
import {
|
||||
Check,
|
||||
Eye,
|
||||
EyeOff,
|
||||
FileText,
|
||||
FolderPlus,
|
||||
PlugZap,
|
||||
Plus,
|
||||
Settings2,
|
||||
Tag,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import React, { useEffect, useMemo, useState, useCallback, useRef } from "react";
|
||||
import { useI18n } from "../application/i18n/I18nProvider";
|
||||
@@ -25,7 +21,6 @@ import {
|
||||
} from "../domain/proxyProfiles";
|
||||
import { hasRequiredHostAuthCredential, resolveHostAuth, resolveHostAuthMethodForPersistence } from "../domain/sshAuth";
|
||||
import { canServeAsSshJumpHost } from "../domain/terminalProtocol";
|
||||
import { customThemeStore } from "../application/state/customThemeStore";
|
||||
import {
|
||||
hasHostFontSizeOverride,
|
||||
hasHostThemeOverride,
|
||||
@@ -47,7 +42,6 @@ import { detachEffectiveHostIdentity, HostDetailsConnectionSections } from "./Ho
|
||||
import type { HostTotpFlushResult } from "./HostTotpFields";
|
||||
import {
|
||||
LINUX_DISTRO_OPTION_IDS,
|
||||
parseOptionalPortInput,
|
||||
resolveDetailsTelnetPassword,
|
||||
resolveDetailsTelnetPort,
|
||||
resolveDetailsTelnetUsername,
|
||||
@@ -63,7 +57,6 @@ import {
|
||||
resolveDisplayProxyProfileId,
|
||||
} from "./HostDetailsPanel.helpers";
|
||||
export { parseOptionalPortInput } from "./HostDetailsPanel.helpers";
|
||||
import { TerminalEncodingSelect } from "./TerminalEncodingSelect";
|
||||
import { Button } from "./ui/button";
|
||||
import { Combobox, ComboboxOption, MultiCombobox } from "./ui/combobox";
|
||||
import { Input } from "./ui/input";
|
||||
@@ -86,9 +79,25 @@ import {
|
||||
sanitizePluginConnection,
|
||||
stripBuiltInConnectionFieldsForPluginHost,
|
||||
} from "../domain/pluginConnection";
|
||||
import {
|
||||
applyHostDefaultConnectProtocol,
|
||||
DEFAULT_RDP_CONFIG,
|
||||
DEFAULT_RDP_PORT,
|
||||
DEFAULT_VNC_CONFIG,
|
||||
DEFAULT_VNC_PORT,
|
||||
getHostEnabledProtocols,
|
||||
isRemoteDesktopProtocol,
|
||||
resolveHostDefaultConnectProtocol,
|
||||
sanitizeRdpConfig,
|
||||
sanitizeVncConfig,
|
||||
shouldPromptHostProtocolOnConnect,
|
||||
} from "../domain/remoteDesktop";
|
||||
import { PluginConnectionSection } from "./PluginConnectionSection";
|
||||
import { useHostConnectionTest } from "../application/state/useHostConnectionTest";
|
||||
import { HostConnectionTestDialog } from "./host-details/HostConnectionTestDialog";
|
||||
import { RemoteDesktopOptionsSection } from "./host-details/RemoteDesktopOptionsSection";
|
||||
|
||||
type EditableHostProtocol = "ssh" | "rdp" | "vnc" | "telnet";
|
||||
|
||||
type CredentialType = "sshid" | "key" | "certificate" | "localKeyFile" | null;
|
||||
type SubPanel =
|
||||
@@ -102,8 +111,10 @@ type SubPanel =
|
||||
|
||||
interface HostDetailsPanelProps {
|
||||
initialData?: Host | null;
|
||||
initialProtocol?: "ssh" | "rdp" | "vnc";
|
||||
availableKeys: SSHKey[];
|
||||
identities: Identity[];
|
||||
onCreateIdentity?: (identity: Identity) => void;
|
||||
proxyProfiles?: ProxyProfile[];
|
||||
groups: string[];
|
||||
managedSources?: ManagedSource[];
|
||||
@@ -133,8 +144,10 @@ type HostDetailsPanelPropsWithResize = HostDetailsPanelProps & AsidePanelResizeP
|
||||
|
||||
const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
initialData,
|
||||
initialProtocol,
|
||||
availableKeys,
|
||||
identities,
|
||||
onCreateIdentity,
|
||||
proxyProfiles = [],
|
||||
groups,
|
||||
managedSources = [],
|
||||
@@ -175,9 +188,46 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
const baselineHydratedRef = useRef(snippets.length > 0);
|
||||
const openingQueueIdsRef = useRef<string[]>([]);
|
||||
const [form, setForm] = useState<Host>(
|
||||
() =>
|
||||
(initialData ? normalizePrimaryTelnetState(initialData) : null) ||
|
||||
({
|
||||
() => {
|
||||
if (initialData) return normalizePrimaryTelnetState(initialData);
|
||||
const startProto = initialProtocol ?? "ssh";
|
||||
if (startProto === "rdp") {
|
||||
return {
|
||||
id: crypto.randomUUID(),
|
||||
label: "",
|
||||
hostname: "",
|
||||
port: DEFAULT_RDP_PORT,
|
||||
username: "",
|
||||
protocol: "rdp",
|
||||
tags: [],
|
||||
os: "windows",
|
||||
authMethod: "password",
|
||||
authPolicyVersion: 1,
|
||||
distroMode: "auto",
|
||||
rdpConfig: { ...DEFAULT_RDP_CONFIG },
|
||||
createdAt: Date.now(),
|
||||
group: defaultGroup || undefined,
|
||||
} as Host;
|
||||
}
|
||||
if (startProto === "vnc") {
|
||||
return {
|
||||
id: crypto.randomUUID(),
|
||||
label: "",
|
||||
hostname: "",
|
||||
port: DEFAULT_VNC_PORT,
|
||||
username: "",
|
||||
protocol: "vnc",
|
||||
tags: [],
|
||||
os: "linux",
|
||||
authMethod: "password",
|
||||
authPolicyVersion: 1,
|
||||
distroMode: "auto",
|
||||
vncConfig: { ...DEFAULT_VNC_CONFIG },
|
||||
createdAt: Date.now(),
|
||||
group: defaultGroup || undefined,
|
||||
} as Host;
|
||||
}
|
||||
return {
|
||||
id: crypto.randomUUID(),
|
||||
label: "",
|
||||
hostname: "",
|
||||
@@ -193,7 +243,8 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
distroMode: "auto",
|
||||
createdAt: Date.now(),
|
||||
group: defaultGroup || undefined, // Pre-fill with current navigation group
|
||||
} as Host),
|
||||
} as Host;
|
||||
},
|
||||
);
|
||||
|
||||
const [activeSubPanel, setActiveSubPanel] = useState<SubPanel>("none");
|
||||
@@ -206,6 +257,13 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showTelnetPassword, setShowTelnetPassword] = useState(false);
|
||||
const [companionCredentialDrafts, setCompanionCredentialDrafts] = useState<{
|
||||
rdp?: { username: string; password: string };
|
||||
vnc?: { username: string; password: string };
|
||||
}>({});
|
||||
const [activeProtocolTab, setActiveProtocolTab] = useState<EditableHostProtocol>(() =>
|
||||
resolveHostDefaultConnectProtocol(initialData ? normalizePrimaryTelnetState(initialData) : { protocol: initialProtocol ?? "ssh" }),
|
||||
);
|
||||
const [showAlgorithmOverrides, setShowAlgorithmOverrides] = useState(false);
|
||||
const [showNotesEditor, setShowNotesEditor] = useState(() => Boolean(initialData?.notes?.trim()));
|
||||
const [pluginConnectionValid, setPluginConnectionValid] = useState(true);
|
||||
@@ -234,7 +292,11 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
|
||||
const handleStartTest = () => {
|
||||
setTestOpen(true);
|
||||
void hostConnectionTest.startTest();
|
||||
const protocolOverride =
|
||||
isCurrentTabEnabled && (activeProtocolTab === "rdp" || activeProtocolTab === "vnc")
|
||||
? activeProtocolTab
|
||||
: undefined;
|
||||
void hostConnectionTest.startTest(undefined, protocolOverride);
|
||||
};
|
||||
|
||||
const handleCloseTest = () => {
|
||||
@@ -326,6 +388,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
setPendingReferenceKeyPath(null);
|
||||
setShowPassword(false);
|
||||
setShowTelnetPassword(false);
|
||||
setActiveProtocolTab(resolveHostDefaultConnectProtocol(normalized));
|
||||
setShowNotesEditor(Boolean(normalized.notes?.trim()));
|
||||
// Reset only when opening a different host — not when snippets list updates.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -545,21 +608,295 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
});
|
||||
};
|
||||
const pluginProtocolActive = isPluginHostProtocol(form.protocol);
|
||||
const isRemoteDesktopPrimary = isRemoteDesktopProtocol(form.protocol);
|
||||
const hasHostname = form.hostname.trim().length > 0;
|
||||
const canSaveHost = pluginProtocolActive
|
||||
? pluginConnectionValid && Boolean(sanitizePluginConnection(form.pluginConnection, form.protocol))
|
||||
: hasHostname;
|
||||
|
||||
const enabledProtocols: Record<EditableHostProtocol, boolean> = useMemo(() => {
|
||||
const list = getHostEnabledProtocols(form);
|
||||
return {
|
||||
ssh: list.includes("ssh"),
|
||||
rdp: list.includes("rdp"),
|
||||
vnc: list.includes("vnc"),
|
||||
telnet: list.includes("telnet"),
|
||||
};
|
||||
}, [form]);
|
||||
const enabledProtocolCount = (["ssh", "rdp", "vnc", "telnet"] as const).filter(
|
||||
(proto) => enabledProtocols[proto],
|
||||
).length;
|
||||
const isCurrentTabEnabled = enabledProtocols[activeProtocolTab];
|
||||
const defaultConnectProtocol = resolveHostDefaultConnectProtocol(form);
|
||||
const effectiveConnectBehavior: "ask" | EditableHostProtocol =
|
||||
enabledProtocolCount >= 2 && shouldPromptHostProtocolOnConnect(form)
|
||||
? "ask"
|
||||
: defaultConnectProtocol;
|
||||
|
||||
const handleSwitchOnlyProtocol = useCallback(
|
||||
(nextProtocol: EditableHostProtocol) => {
|
||||
setActiveProtocolTab(nextProtocol);
|
||||
setForm((prev) => {
|
||||
const nextPort = resolvePrimaryProtocolSwitchPort(
|
||||
prev.port,
|
||||
nextProtocol,
|
||||
Boolean(effectiveGroupDefaults?.telnetPort),
|
||||
Boolean(effectiveGroupDefaults?.port),
|
||||
);
|
||||
const isFreshHost = !initialData;
|
||||
if (nextProtocol === "rdp") {
|
||||
return {
|
||||
...prev,
|
||||
protocol: "rdp",
|
||||
port: prev.rdpConfig?.port ?? nextPort ?? DEFAULT_RDP_PORT,
|
||||
os: isFreshHost && prev.os === "linux" ? "windows" : prev.os,
|
||||
username: isFreshHost && prev.username === "root" ? "" : (prev.username ?? ""),
|
||||
authMethod: "password",
|
||||
moshEnabled: false,
|
||||
etEnabled: false,
|
||||
telnetEnabled: false,
|
||||
vncConfig: undefined,
|
||||
rdpConfig: {
|
||||
...DEFAULT_RDP_CONFIG,
|
||||
...(prev.rdpConfig ?? {}),
|
||||
enabled: undefined,
|
||||
defaultConnect: undefined,
|
||||
tunnelViaHostSsh: undefined,
|
||||
tunnelTargetHost: undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (nextProtocol === "vnc") {
|
||||
return {
|
||||
...prev,
|
||||
protocol: "vnc",
|
||||
port: prev.vncConfig?.port ?? nextPort ?? DEFAULT_VNC_PORT,
|
||||
username: isFreshHost && prev.username === "root" ? "" : (prev.username ?? ""),
|
||||
authMethod: "password",
|
||||
moshEnabled: false,
|
||||
etEnabled: false,
|
||||
telnetEnabled: false,
|
||||
rdpConfig: undefined,
|
||||
vncConfig: {
|
||||
...DEFAULT_VNC_CONFIG,
|
||||
...(prev.vncConfig ?? {}),
|
||||
enabled: undefined,
|
||||
defaultConnect: undefined,
|
||||
tunnelViaHostSsh: undefined,
|
||||
tunnelTargetHost: undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (nextProtocol === "telnet") {
|
||||
return {
|
||||
...prev,
|
||||
protocol: "telnet",
|
||||
port: nextPort,
|
||||
telnetPort: prev.telnetPort ?? nextPort,
|
||||
telnetEnabled: true,
|
||||
moshEnabled: false,
|
||||
etEnabled: false,
|
||||
rdpConfig: undefined,
|
||||
vncConfig: undefined,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...prev,
|
||||
protocol: "ssh",
|
||||
port: nextPort,
|
||||
telnetEnabled: false,
|
||||
rdpConfig: undefined,
|
||||
vncConfig: undefined,
|
||||
username: isFreshHost && !prev.username && !effectiveGroupDefaults?.username ? "root" : (prev.username ?? ""),
|
||||
};
|
||||
});
|
||||
},
|
||||
[effectiveGroupDefaults?.port, effectiveGroupDefaults?.telnetPort, effectiveGroupDefaults?.username, initialData],
|
||||
);
|
||||
|
||||
const handleSelectProtocolTab = useCallback(
|
||||
(tab: EditableHostProtocol) => {
|
||||
setActiveProtocolTab(tab);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleEnableSecondaryProtocol = useCallback(
|
||||
(proto: EditableHostProtocol) => {
|
||||
setActiveProtocolTab(proto);
|
||||
setForm((prev) => {
|
||||
const hasSsh = !prev.protocol || prev.protocol === "ssh" || prev.protocol === "mosh" || prev.protocol === "et";
|
||||
if (hasSsh) {
|
||||
if (proto === "vnc") {
|
||||
return {
|
||||
...prev,
|
||||
vncConfig: {
|
||||
...DEFAULT_VNC_CONFIG,
|
||||
...(prev.vncConfig ?? {}),
|
||||
enabled: true,
|
||||
port: prev.vncConfig?.port ?? DEFAULT_VNC_PORT,
|
||||
tunnelViaHostSsh: prev.vncConfig?.tunnelViaHostSsh ?? true,
|
||||
useHostCredentials: prev.vncConfig?.identityId ? false : (prev.vncConfig?.useHostCredentials ?? true),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (proto === "rdp") {
|
||||
return {
|
||||
...prev,
|
||||
rdpConfig: {
|
||||
...DEFAULT_RDP_CONFIG,
|
||||
...(prev.rdpConfig ?? {}),
|
||||
enabled: true,
|
||||
port: prev.rdpConfig?.port ?? DEFAULT_RDP_PORT,
|
||||
tunnelViaHostSsh: prev.rdpConfig?.tunnelViaHostSsh ?? true,
|
||||
useHostCredentials: prev.rdpConfig?.identityId ? false : (prev.rdpConfig?.useHostCredentials ?? true),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (proto === "telnet") {
|
||||
return {
|
||||
...prev,
|
||||
telnetEnabled: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
// Adding SSH to a standalone RDP/VNC/Telnet host: promote host.protocol to SSH
|
||||
// while keeping the existing protocol enabled (and default for RDP/VNC).
|
||||
if (proto === "ssh") {
|
||||
if (prev.protocol === "rdp") {
|
||||
return {
|
||||
...prev,
|
||||
protocol: "ssh",
|
||||
port: effectiveGroupDefaults?.port ? undefined : 22,
|
||||
username: prev.username || (effectiveGroupDefaults?.username ? "" : "root"),
|
||||
rdpConfig: {
|
||||
...DEFAULT_RDP_CONFIG,
|
||||
...(prev.rdpConfig ?? {}),
|
||||
enabled: true,
|
||||
defaultConnect: true,
|
||||
port: prev.port ?? prev.rdpConfig?.port ?? DEFAULT_RDP_PORT,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: prev.identityId ? false : true,
|
||||
...(prev.identityId ? { identityId: prev.identityId } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (prev.protocol === "vnc") {
|
||||
return {
|
||||
...prev,
|
||||
protocol: "ssh",
|
||||
port: effectiveGroupDefaults?.port ? undefined : 22,
|
||||
username: prev.username || (effectiveGroupDefaults?.username ? "" : "root"),
|
||||
vncConfig: {
|
||||
...DEFAULT_VNC_CONFIG,
|
||||
...(prev.vncConfig ?? {}),
|
||||
enabled: true,
|
||||
defaultConnect: true,
|
||||
port: prev.port ?? prev.vncConfig?.port ?? DEFAULT_VNC_PORT,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: prev.identityId ? false : true,
|
||||
...(prev.identityId ? { identityId: prev.identityId } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (prev.protocol === "telnet") {
|
||||
return {
|
||||
...prev,
|
||||
protocol: "ssh",
|
||||
port: effectiveGroupDefaults?.port ? undefined : 22,
|
||||
telnetPort: prev.telnetPort ?? prev.port ?? 23,
|
||||
telnetEnabled: true,
|
||||
username: prev.username || (effectiveGroupDefaults?.username ? "" : "root"),
|
||||
};
|
||||
}
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
},
|
||||
[effectiveGroupDefaults?.port, effectiveGroupDefaults?.username],
|
||||
);
|
||||
|
||||
const handleSetDefaultProtocol = useCallback((proto: EditableHostProtocol) => {
|
||||
setForm((prev) => applyHostDefaultConnectProtocol(prev, proto));
|
||||
}, []);
|
||||
|
||||
const handleSetConnectBehavior = useCallback((choice: "ask" | EditableHostProtocol) => {
|
||||
if (choice === "ask") {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
connectProtocolBehavior: "ask",
|
||||
}));
|
||||
return;
|
||||
}
|
||||
setForm((prev) => applyHostDefaultConnectProtocol(prev, choice));
|
||||
}, []);
|
||||
|
||||
const handleRemoveProtocol = useCallback(
|
||||
(proto: EditableHostProtocol) => {
|
||||
if (enabledProtocolCount <= 1) return;
|
||||
const clearAskIfSingle = enabledProtocolCount <= 2
|
||||
? { connectProtocolBehavior: undefined }
|
||||
: {};
|
||||
if (proto === "vnc") {
|
||||
setForm((prev) => ({ ...prev, ...clearAskIfSingle, vncConfig: undefined }));
|
||||
setActiveProtocolTab("ssh");
|
||||
return;
|
||||
}
|
||||
if (proto === "rdp") {
|
||||
setForm((prev) => ({ ...prev, ...clearAskIfSingle, rdpConfig: undefined }));
|
||||
setActiveProtocolTab("ssh");
|
||||
return;
|
||||
}
|
||||
if (proto === "telnet") {
|
||||
setForm((prev) => {
|
||||
const savedSshPort = prev.protocols?.find((p) => p.protocol === "ssh")?.port;
|
||||
const remainingProtocols = prev.protocols?.filter((p) => p.protocol !== "telnet" && p.protocol !== "ssh");
|
||||
return {
|
||||
...prev,
|
||||
...clearAskIfSingle,
|
||||
telnetEnabled: false,
|
||||
...(prev.protocol === "telnet"
|
||||
? { protocol: "ssh", ...(savedSshPort ? { port: savedSshPort } : {}) }
|
||||
: {}),
|
||||
...(prev.protocols ? { protocols: remainingProtocols && remainingProtocols.length > 0 ? remainingProtocols : undefined } : {}),
|
||||
};
|
||||
});
|
||||
setActiveProtocolTab("ssh");
|
||||
return;
|
||||
}
|
||||
if (proto === "ssh") {
|
||||
// Promote remaining enabled protocol to standalone primary
|
||||
const nextPrimary: EditableHostProtocol =
|
||||
form.rdpConfig?.enabled && form.rdpConfig?.defaultConnect
|
||||
? "rdp"
|
||||
: form.vncConfig?.enabled && form.vncConfig?.defaultConnect
|
||||
? "vnc"
|
||||
: form.rdpConfig?.enabled
|
||||
? "rdp"
|
||||
: form.vncConfig?.enabled
|
||||
? "vnc"
|
||||
: "telnet";
|
||||
handleSwitchOnlyProtocol(nextPrimary);
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
connectProtocolBehavior: undefined,
|
||||
protocols: prev.protocols?.filter((p) => p.protocol !== "ssh"),
|
||||
}));
|
||||
}
|
||||
},
|
||||
[enabledProtocolCount, form.rdpConfig?.defaultConnect, form.rdpConfig?.enabled, form.vncConfig?.defaultConnect, form.vncConfig?.enabled, handleSwitchOnlyProtocol],
|
||||
);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (savingHostRef.current) return;
|
||||
savingHostRef.current = true;
|
||||
try {
|
||||
const flushed = await totpFlushRef.current?.();
|
||||
const flushed = isRemoteDesktopPrimary ? undefined : await totpFlushRef.current?.();
|
||||
if (flushed && !flushed.ok) return;
|
||||
const hostname = form.hostname.trim()
|
||||
|| (pluginProtocolActive ? form.label.trim() || form.pluginConnection?.providerId || "plugin" : "");
|
||||
if (!hostname || !canSaveHost) return;
|
||||
if (!pluginProtocolActive && !hasRequiredHostAuthCredential({ host: effectiveAuthHost, keys: availableKeys, identities })) {
|
||||
if (!pluginProtocolActive && !isRemoteDesktopPrimary && !hasRequiredHostAuthCredential({ host: effectiveAuthHost, keys: availableKeys, identities })) {
|
||||
toast.error(t("hostDetails.auth.credentialRequired"));
|
||||
return;
|
||||
}
|
||||
@@ -634,6 +971,99 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
if (!pluginConnection) return;
|
||||
cleaned = stripBuiltInConnectionFieldsForPluginHost({ ...cleaned, pluginConnection });
|
||||
}
|
||||
if (isRemoteDesktopPrimary) {
|
||||
const sanitizedRdp = cleaned.protocol === "rdp"
|
||||
? sanitizeRdpConfig({
|
||||
...(cleaned.rdpConfig ?? {}),
|
||||
port: finalPort ?? DEFAULT_RDP_PORT,
|
||||
enabled: undefined,
|
||||
tunnelViaHostSsh: undefined,
|
||||
tunnelTargetHost: undefined,
|
||||
})
|
||||
: undefined;
|
||||
const sanitizedVnc = cleaned.protocol === "vnc"
|
||||
? sanitizeVncConfig({
|
||||
...(cleaned.vncConfig ?? {}),
|
||||
port: finalPort ?? DEFAULT_VNC_PORT,
|
||||
enabled: undefined,
|
||||
tunnelViaHostSsh: undefined,
|
||||
tunnelTargetHost: undefined,
|
||||
})
|
||||
: undefined;
|
||||
const hasInlinePassword = !cleaned.identityId && typeof cleaned.password === "string" && cleaned.password.length > 0;
|
||||
cleaned = {
|
||||
...cleaned,
|
||||
username: typeof cleaned.username === "string" ? cleaned.username.trim() : "",
|
||||
tags: Array.isArray(cleaned.tags) ? cleaned.tags : [],
|
||||
os: cleaned.os || (cleaned.protocol === "rdp" ? "windows" : "linux"),
|
||||
port: finalPort ?? (cleaned.protocol === "rdp" ? DEFAULT_RDP_PORT : DEFAULT_VNC_PORT),
|
||||
authMethod: hasInlinePassword || cleaned.identityId ? "password" : undefined,
|
||||
authPolicyVersion: 1,
|
||||
identityFileId: undefined,
|
||||
identityFilePaths: undefined,
|
||||
password: cleaned.identityId || cleaned.savePassword === false ? undefined : cleaned.password,
|
||||
rdpConfig: sanitizedRdp,
|
||||
vncConfig: sanitizedVnc,
|
||||
moshEnabled: undefined,
|
||||
etEnabled: undefined,
|
||||
telnetEnabled: undefined,
|
||||
};
|
||||
} else if (!pluginProtocolActive) {
|
||||
let nextRdpConfig = cleaned.rdpConfig?.enabled ? sanitizeRdpConfig(cleaned.rdpConfig) : undefined;
|
||||
let nextVncConfig = cleaned.vncConfig?.enabled ? sanitizeVncConfig(cleaned.vncConfig) : undefined;
|
||||
const rdpDraft = companionCredentialDrafts.rdp;
|
||||
if (
|
||||
nextRdpConfig &&
|
||||
onCreateIdentity &&
|
||||
rdpDraft &&
|
||||
rdpDraft.password.length > 0
|
||||
) {
|
||||
const identity: Identity = {
|
||||
id: crypto.randomUUID(),
|
||||
label: `${finalLabel} RDP`,
|
||||
username: rdpDraft.username.trim(),
|
||||
...(nextRdpConfig.domain ? { domain: nextRdpConfig.domain } : {}),
|
||||
authMethod: "password",
|
||||
password: rdpDraft.password,
|
||||
created: Date.now(),
|
||||
};
|
||||
onCreateIdentity(identity);
|
||||
nextRdpConfig = {
|
||||
...nextRdpConfig,
|
||||
useHostCredentials: false,
|
||||
identityId: identity.id,
|
||||
username: undefined,
|
||||
};
|
||||
}
|
||||
const vncDraft = companionCredentialDrafts.vnc;
|
||||
if (
|
||||
nextVncConfig &&
|
||||
onCreateIdentity &&
|
||||
vncDraft &&
|
||||
vncDraft.password.length > 0
|
||||
) {
|
||||
const identity: Identity = {
|
||||
id: crypto.randomUUID(),
|
||||
label: `${finalLabel} VNC`,
|
||||
username: vncDraft.username.trim(),
|
||||
authMethod: "password",
|
||||
password: vncDraft.password,
|
||||
created: Date.now(),
|
||||
};
|
||||
onCreateIdentity(identity);
|
||||
nextVncConfig = {
|
||||
...nextVncConfig,
|
||||
useHostCredentials: false,
|
||||
identityId: identity.id,
|
||||
username: undefined,
|
||||
};
|
||||
}
|
||||
cleaned = {
|
||||
...cleaned,
|
||||
rdpConfig: nextRdpConfig,
|
||||
vncConfig: nextVncConfig,
|
||||
};
|
||||
}
|
||||
cleaned = prepareTelnetCredentialsForSave(normalizePrimaryTelnetState(cleaned));
|
||||
if (
|
||||
onImportKey &&
|
||||
@@ -866,6 +1296,9 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
password: undefined,
|
||||
identityFileId: undefined,
|
||||
identityFilePaths: undefined,
|
||||
...(prev.protocol === "rdp" && identity.domain
|
||||
? { rdpConfig: { ...(prev.rdpConfig ?? {}), domain: identity.domain } }
|
||||
: {}),
|
||||
}));
|
||||
setPendingReferenceKeyPath(null);
|
||||
setSelectedCredentialType(null);
|
||||
@@ -1110,7 +1543,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-10 w-10 rounded-lg bg-secondary/80 flex items-center justify-center shrink-0">
|
||||
<div className="h-10 w-10 rounded-lg border border-border/60 bg-transparent flex items-center justify-center shrink-0">
|
||||
<FolderPlus size={16} className="text-muted-foreground" />
|
||||
</div>
|
||||
<Combobox
|
||||
@@ -1133,7 +1566,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-10 w-10 rounded-lg bg-secondary/80 flex items-center justify-center shrink-0">
|
||||
<div className="h-10 w-10 rounded-lg border border-border/60 bg-transparent flex items-center justify-center shrink-0">
|
||||
<Tag size={16} className="text-muted-foreground" />
|
||||
</div>
|
||||
<MultiCombobox
|
||||
@@ -1192,9 +1625,46 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
distroOptions={distroOptions}
|
||||
effectiveFormDistro={effectiveFormDistro}
|
||||
getDistroOptionLabel={getDistroOptionLabel}
|
||||
onSelectPrimaryProtocol={handleSwitchOnlyProtocol}
|
||||
activeProtocolTab={activeProtocolTab}
|
||||
enabledProtocols={enabledProtocols}
|
||||
defaultConnectProtocol={defaultConnectProtocol}
|
||||
effectiveConnectBehavior={effectiveConnectBehavior}
|
||||
onSelectProtocolTab={handleSelectProtocolTab}
|
||||
onEnableSecondaryProtocol={handleEnableSecondaryProtocol}
|
||||
onSwitchOnlyProtocol={handleSwitchOnlyProtocol}
|
||||
onSetDefaultProtocol={handleSetDefaultProtocol}
|
||||
onSetConnectBehavior={handleSetConnectBehavior}
|
||||
onRemoveProtocol={handleRemoveProtocol}
|
||||
onCreateIdentity={onCreateIdentity}
|
||||
companionCredentialDrafts={companionCredentialDrafts}
|
||||
onCompanionCredentialDraftChange={(proto: "rdp" | "vnc", draft: { username: string; password: string } | undefined) => {
|
||||
setCompanionCredentialDrafts((prev) => ({
|
||||
...prev,
|
||||
[proto]: draft,
|
||||
}));
|
||||
}}
|
||||
effectiveTelnetPort={effectiveTelnetPort}
|
||||
effectiveTelnetUsername={effectiveTelnetUsername}
|
||||
effectiveTelnetPassword={effectiveTelnetPassword}
|
||||
effectiveTelnetThemeId={effectiveTelnetThemeId}
|
||||
telnetIdentityOptions={telnetIdentityOptions}
|
||||
selectedTelnetIdentity={selectedTelnetIdentity}
|
||||
updateTelnetIdentity={updateTelnetIdentity}
|
||||
showTelnetPassword={showTelnetPassword}
|
||||
setShowTelnetPassword={setShowTelnetPassword}
|
||||
onOpenTelnetThemeSelect={() => setActiveSubPanel("telnet-theme-select")}
|
||||
/> : null}
|
||||
|
||||
{onSnippetsChange ? (
|
||||
{isRemoteDesktopPrimary && isCurrentTabEnabled && (activeProtocolTab === "rdp" || activeProtocolTab === "vnc") ? (
|
||||
<RemoteDesktopOptionsSection
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
t={t}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{onSnippetsChange && isCurrentTabEnabled && (activeProtocolTab === "ssh" || activeProtocolTab === "telnet") ? (
|
||||
<HostDetailsScriptsSection
|
||||
host={form}
|
||||
onHostChange={setForm}
|
||||
@@ -1235,7 +1705,11 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
update={update}
|
||||
activeProtocolTab={activeProtocolTab}
|
||||
isCurrentTabEnabled={isCurrentTabEnabled}
|
||||
effectiveThemeId={effectiveThemeId}
|
||||
effectiveTelnetThemeId={effectiveTelnetThemeId}
|
||||
onOpenTelnetThemeSelect={() => setActiveSubPanel("telnet-theme-select")}
|
||||
hasEffectiveThemeOverride={hasEffectiveThemeOverride}
|
||||
effectiveFontSize={effectiveFontSize}
|
||||
hasEffectiveFontSizeOverride={hasEffectiveFontSizeOverride}
|
||||
@@ -1255,158 +1729,6 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
proxyInherited={proxyInherited}
|
||||
clearProxyConfig={clearProxyConfig}
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-3 py-2">
|
||||
<div className="flex-1 h-px bg-border/60" />
|
||||
<span className="text-xs text-muted-foreground">{t("hostDetails.otherProtocols")}</span>
|
||||
<div className="flex-1 h-px bg-border/60" />
|
||||
</div>
|
||||
|
||||
{form.telnetEnabled || form.protocol === "telnet" ? (
|
||||
<HostDetailsSection
|
||||
icon={<Plus size={14} className="text-muted-foreground" />}
|
||||
title="Telnet"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex-1 min-w-0 h-10 flex items-center gap-2 bg-secondary/70 border border-border/70 rounded-md px-3">
|
||||
<span className="text-xs text-muted-foreground">{t("hostDetails.telnetOn")}</span>
|
||||
<div className="ml-auto w-1/2 min-w-0 flex items-center gap-2 justify-end">
|
||||
<Input
|
||||
type="number"
|
||||
value={effectiveTelnetPort}
|
||||
onChange={(e) => update("telnetPort", parseOptionalPortInput(e.target.value))}
|
||||
className="h-8 flex-1 min-w-0 text-center"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">{t("hostDetails.port")}</span>
|
||||
</div>
|
||||
</div>
|
||||
{form.protocol !== "telnet" && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => update("telnetEnabled", false)}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-xs text-muted-foreground">{t("hostDetails.telnet.setDefault")}</span>
|
||||
<Switch
|
||||
checked={form.protocol === "telnet"}
|
||||
onCheckedChange={(checked) => {
|
||||
const nextProtocol = checked ? "telnet" : "ssh";
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
protocol: nextProtocol,
|
||||
port: resolvePrimaryProtocolSwitchPort(
|
||||
prev.port,
|
||||
nextProtocol,
|
||||
Boolean(groupDefaults?.telnetPort),
|
||||
Boolean(groupDefaults?.port),
|
||||
),
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className="text-xs font-semibold">{t("hostDetails.telnet.credentials")}</p>
|
||||
{identities.length > 0 && (
|
||||
<Combobox
|
||||
options={telnetIdentityOptions}
|
||||
value={form.telnetIdentityId || ""}
|
||||
onValueChange={updateTelnetIdentity}
|
||||
placeholder={t("hostDetails.telnet.identity.placeholder")}
|
||||
emptyText={t("common.noResultsFound")}
|
||||
className="w-full"
|
||||
/>
|
||||
)}
|
||||
{form.telnetIdentityId ? (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{selectedTelnetIdentity
|
||||
? `${selectedTelnetIdentity.username} - ${selectedTelnetIdentity.label}`
|
||||
: t("hostDetails.identity.missing")}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Input
|
||||
placeholder={t("hostDetails.telnet.username")}
|
||||
value={effectiveTelnetUsername}
|
||||
onChange={(e) =>
|
||||
update("telnetUsername" as keyof Host, e.target.value)
|
||||
}
|
||||
className="h-10"
|
||||
/>
|
||||
<div className="relative">
|
||||
<Input
|
||||
placeholder={t("hostDetails.telnet.password")}
|
||||
type={showTelnetPassword ? "text" : "password"}
|
||||
value={effectiveTelnetPassword}
|
||||
onChange={(e) =>
|
||||
update("telnetPassword" as keyof Host, e.target.value)
|
||||
}
|
||||
className="h-10 pr-10"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowTelnetPassword(!showTelnetPassword)}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{showTelnetPassword ? <EyeOff size={16} /> : <Eye size={16} />}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<TerminalEncodingSelect
|
||||
value={form.charset}
|
||||
inheritedValue={effectiveGroupDefaults?.charset}
|
||||
onValueChange={(value) => update("charset", value)}
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="w-full flex items-center gap-3 p-2 rounded-lg bg-secondary/50 hover:bg-secondary transition-colors text-left"
|
||||
onClick={() => setActiveSubPanel("telnet-theme-select")}
|
||||
>
|
||||
<div
|
||||
className="w-12 h-8 rounded-md border border-border/60 flex items-center justify-center text-[6px] font-mono overflow-hidden"
|
||||
style={{
|
||||
backgroundColor:
|
||||
customThemeStore.getThemeById(effectiveTelnetThemeId)?.colors.background || "#100F0F",
|
||||
color:
|
||||
customThemeStore.getThemeById(effectiveTelnetThemeId)?.colors.foreground || "#CECDC3",
|
||||
}}
|
||||
>
|
||||
<div className="p-0.5">
|
||||
<div
|
||||
style={{
|
||||
color: customThemeStore.getThemeById(effectiveTelnetThemeId)?.colors.green,
|
||||
}}
|
||||
>
|
||||
$
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<span className="text-sm flex-1">
|
||||
{customThemeStore.getThemeById(effectiveTelnetThemeId)?.name || "Flexoki Dark"}
|
||||
</span>
|
||||
</button>
|
||||
</HostDetailsSection>
|
||||
) : (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full h-10 justify-start gap-2 border border-dashed border-border/60"
|
||||
onClick={() => {
|
||||
update("telnetEnabled", true);
|
||||
}}
|
||||
>
|
||||
<Plus size={14} />
|
||||
{t("hostDetails.telnet.add")}
|
||||
</Button>
|
||||
)}
|
||||
</AsidePanelContent>
|
||||
<AsidePanelFooter>
|
||||
<Button
|
||||
|
||||
@@ -27,6 +27,7 @@ type DistroOption = {
|
||||
|
||||
type HostIconPickerProps = {
|
||||
previewHost?: Host;
|
||||
hideAutoDistro?: boolean;
|
||||
distroMode?: "auto" | "manual";
|
||||
manualDistro?: string;
|
||||
effectiveDistro?: string;
|
||||
@@ -98,6 +99,7 @@ const colorHexForId = (colorId?: HostIconColorId) =>
|
||||
|
||||
export const HostIconPicker: React.FC<HostIconPickerProps> = ({
|
||||
previewHost,
|
||||
hideAutoDistro = false,
|
||||
distroMode,
|
||||
manualDistro,
|
||||
effectiveDistro,
|
||||
@@ -112,8 +114,8 @@ export const HostIconPicker: React.FC<HostIconPickerProps> = ({
|
||||
onChange,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const manualSource = distroMode === "manual" || iconMode === "custom";
|
||||
const selectedBrandId = manualDistro || effectiveDistro || "linux";
|
||||
const manualSource = hideAutoDistro || distroMode === "manual" || iconMode === "custom";
|
||||
const selectedBrandId = manualDistro || effectiveDistro || previewHost?.os || "linux";
|
||||
const selectedBrand = distroOptions.find((option) => option.value === selectedBrandId);
|
||||
const selectedIconId = isHostIconId(iconId) ? iconId : DEFAULT_HOST_ICON_ID;
|
||||
const selectedIconTab = iconMode === "custom" ? "type" : "brand";
|
||||
@@ -226,7 +228,8 @@ export const HostIconPicker: React.FC<HostIconPickerProps> = ({
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="grid gap-2 md:grid-cols-2">
|
||||
<div className={cn("grid gap-2", !hideAutoDistro && "md:grid-cols-2")}>
|
||||
{!hideAutoDistro && (
|
||||
<div className="space-y-1">
|
||||
<span className="text-xs text-muted-foreground">{t("hostDetails.icon.source")}</span>
|
||||
<Select value={manualSource ? "manual" : "auto"} onValueChange={(value) => setSource(value as "auto" | "manual")}>
|
||||
@@ -241,6 +244,7 @@ export const HostIconPicker: React.FC<HostIconPickerProps> = ({
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{manualSource ? (
|
||||
<div className="space-y-1">
|
||||
|
||||
@@ -17,7 +17,19 @@ import {
|
||||
} from '../domain/hostClickBehavior';
|
||||
import { sortByVaultOrder } from '../domain/vaultOrder';
|
||||
import { getVaultHostRowSubtitle } from '../domain/localShellHost';
|
||||
import {
|
||||
DEFAULT_RDP_PORT,
|
||||
DEFAULT_VNC_PORT,
|
||||
hasCompanionRdp,
|
||||
hasCompanionVnc,
|
||||
isRdpProtocol,
|
||||
isRemoteDesktopProtocol,
|
||||
isVncProtocol,
|
||||
type RemoteDesktopProtocol,
|
||||
} from '../domain/remoteDesktop';
|
||||
import { isVaultHostDraggable } from '../domain/vaultHostDrag';
|
||||
import { getProtocolBadgeClass } from './protocolVisuals';
|
||||
import { RdpProtocolIcon, VncProtocolIcon } from './icons/RemoteDesktopIcons';
|
||||
import { STORAGE_KEY_VAULT_HOSTS_TREE_EXPANDED } from '../infrastructure/config/storageKeys';
|
||||
import { GroupConfig, GroupNode, Host } from '../types';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from './ui/collapsible';
|
||||
@@ -289,6 +301,8 @@ interface HostTreeViewProps {
|
||||
onExpandAll?: (paths: string[]) => void;
|
||||
onCollapseAll?: () => void;
|
||||
onConnect: (host: Host) => void;
|
||||
onConnectRemoteDesktop?: (host: Host, protocol: RemoteDesktopProtocol) => void;
|
||||
onOpenSystemRemoteDesktop?: (host: Host, protocol: RemoteDesktopProtocol) => void;
|
||||
onOpenBrowser?: (host: Host) => void;
|
||||
onEditHost: (host: Host) => void;
|
||||
onDuplicateHost: (host: Host) => void;
|
||||
@@ -331,6 +345,8 @@ interface TreeNodeProps {
|
||||
expandedPaths: Set<string>;
|
||||
onToggle: (path: string) => void;
|
||||
onConnect: (host: Host) => void;
|
||||
onConnectRemoteDesktop?: (host: Host, protocol: RemoteDesktopProtocol) => void;
|
||||
onOpenSystemRemoteDesktop?: (host: Host, protocol: RemoteDesktopProtocol) => void;
|
||||
onOpenBrowser?: (host: Host) => void;
|
||||
onEditHost: (host: Host) => void;
|
||||
onDuplicateHost: (host: Host) => void;
|
||||
@@ -379,6 +395,8 @@ const TreeNode: React.FC<TreeNodeProps> = ({
|
||||
expandedPaths,
|
||||
onToggle,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onOpenSystemRemoteDesktop,
|
||||
onOpenBrowser,
|
||||
onEditHost,
|
||||
onDuplicateHost,
|
||||
@@ -602,6 +620,8 @@ const TreeNode: React.FC<TreeNodeProps> = ({
|
||||
expandedPaths={expandedPaths}
|
||||
onToggle={onToggle}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
|
||||
onOpenBrowser={onOpenBrowser}
|
||||
onEditHost={onEditHost}
|
||||
onDuplicateHost={onDuplicateHost}
|
||||
@@ -647,6 +667,8 @@ const TreeNode: React.FC<TreeNodeProps> = ({
|
||||
host={host}
|
||||
depth={depth + 1}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
|
||||
onOpenBrowser={onOpenBrowser}
|
||||
onEditHost={onEditHost}
|
||||
onDuplicateHost={onDuplicateHost}
|
||||
@@ -681,6 +703,8 @@ interface HostTreeItemProps {
|
||||
host: Host;
|
||||
depth: number;
|
||||
onConnect: (host: Host) => void;
|
||||
onConnectRemoteDesktop?: (host: Host, protocol: RemoteDesktopProtocol) => void;
|
||||
onOpenSystemRemoteDesktop?: (host: Host, protocol: RemoteDesktopProtocol) => void;
|
||||
onOpenBrowser?: (host: Host) => void;
|
||||
onEditHost: (host: Host) => void;
|
||||
onDuplicateHost: (host: Host) => void;
|
||||
@@ -713,14 +737,19 @@ export const getHostTreeDisplayDetails = (
|
||||
? applyGroupDefaults(host, groupDefaultsByPath?.get(host.group) ?? resolveGroupDefaults(host.group, groupConfigs))
|
||||
: host;
|
||||
const isTelnet = displayHost.protocol === 'telnet';
|
||||
const defaultPort = isTelnet
|
||||
? resolveTelnetPort(displayHost)
|
||||
: isRdpProtocol(displayHost.protocol)
|
||||
? (displayHost.port ?? displayHost.rdpConfig?.port ?? DEFAULT_RDP_PORT)
|
||||
: isVncProtocol(displayHost.protocol)
|
||||
? (displayHost.port ?? displayHost.vncConfig?.port ?? DEFAULT_VNC_PORT)
|
||||
: (displayHost.port ?? 22);
|
||||
return {
|
||||
protocol: displayHost.protocol,
|
||||
username: isTelnet
|
||||
? (resolveTelnetUsername(displayHost) || '')
|
||||
: (displayHost.username?.trim() || ''),
|
||||
port: isTelnet
|
||||
? resolveTelnetPort(displayHost)
|
||||
: (displayHost.port ?? 22),
|
||||
port: defaultPort,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -728,6 +757,8 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
host,
|
||||
depth,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onOpenSystemRemoteDesktop,
|
||||
onOpenBrowser,
|
||||
onEditHost,
|
||||
onDuplicateHost,
|
||||
@@ -760,6 +791,10 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
const displayProtocol = displayDetails.protocol;
|
||||
const displayUsername = displayDetails.username;
|
||||
const displayPort = displayDetails.port;
|
||||
const isStandaloneRdp = isRdpProtocol(safeHost.protocol);
|
||||
const isStandaloneVnc = isVncProtocol(safeHost.protocol);
|
||||
const companionRdp = hasCompanionRdp(safeHost);
|
||||
const companionVnc = hasCompanionVnc(safeHost);
|
||||
const isMultiSelected = Boolean(isMultiSelectMode && selectedHostIds?.has(host.id));
|
||||
const isFocusSelected = !isMultiSelectMode && hostClickBehavior === 'select' && focusedHostId === host.id;
|
||||
const isSelected = isMultiSelected || isFocusSelected;
|
||||
@@ -858,6 +893,50 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-center gap-1.5 font-medium leading-5">
|
||||
<span className="min-w-0 truncate">{host.label}</span>
|
||||
{isStandaloneRdp && (
|
||||
<span
|
||||
className={`inline-flex items-center gap-0.5 rounded-md border px-1.5 py-0 text-[10px] font-semibold leading-4 shrink-0 ${getProtocolBadgeClass('rdp')}`}
|
||||
>
|
||||
<RdpProtocolIcon size={10} />
|
||||
RDP
|
||||
</span>
|
||||
)}
|
||||
{isStandaloneVnc && (
|
||||
<span
|
||||
className={`inline-flex items-center gap-0.5 rounded-md border px-1.5 py-0 text-[10px] font-semibold leading-4 shrink-0 ${getProtocolBadgeClass('vnc')}`}
|
||||
>
|
||||
<VncProtocolIcon size={10} />
|
||||
VNC
|
||||
</span>
|
||||
)}
|
||||
{companionRdp && (
|
||||
<button
|
||||
type="button"
|
||||
title={t('vault.hosts.connectRdp')}
|
||||
className={`inline-flex items-center gap-0.5 rounded-md border px-1.5 py-0 text-[10px] font-semibold leading-4 shrink-0 transition-all hover:brightness-110 ${getProtocolBadgeClass('rdp')}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onConnectRemoteDesktop?.(safeHost, 'rdp');
|
||||
}}
|
||||
>
|
||||
<RdpProtocolIcon size={10} />
|
||||
+RDP
|
||||
</button>
|
||||
)}
|
||||
{companionVnc && (
|
||||
<button
|
||||
type="button"
|
||||
title={t('vault.hosts.connectVnc')}
|
||||
className={`inline-flex items-center gap-0.5 rounded-md border px-1.5 py-0 text-[10px] font-semibold leading-4 shrink-0 transition-all hover:brightness-110 ${getProtocolBadgeClass('vnc')}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onConnectRemoteDesktop?.(safeHost, 'vnc');
|
||||
}}
|
||||
>
|
||||
<VncProtocolIcon size={10} />
|
||||
+VNC
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
aria-label={`Edit ${host.label}`}
|
||||
tabIndex={-1}
|
||||
@@ -873,15 +952,15 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
<HostNotesIndicator notes={host.notes} />
|
||||
</div>
|
||||
<div className="truncate text-[11px] leading-4 text-muted-foreground">
|
||||
{displayProtocol === 'local'
|
||||
{displayProtocol === 'local' || isRemoteDesktopProtocol(displayProtocol)
|
||||
? getVaultHostRowSubtitle(safeHost, { localFallback: t('localShell.subtitle') })
|
||||
: `${displayUsername}@${host.hostname}:${displayPort}`}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
actions={(displayProtocol && displayProtocol !== 'ssh') || tags.length > 0 ? (
|
||||
actions={(displayProtocol && displayProtocol !== 'ssh' && !isRemoteDesktopProtocol(displayProtocol)) || tags.length > 0 ? (
|
||||
<div className="ml-2 flex shrink-0 items-center gap-1.5 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
{displayProtocol && displayProtocol !== 'ssh' && (
|
||||
{displayProtocol && displayProtocol !== 'ssh' && !isRemoteDesktopProtocol(displayProtocol) && (
|
||||
<span className="rounded bg-primary/10 px-1.5 py-0.5 text-[10px] leading-none text-primary">
|
||||
{displayProtocol.toUpperCase()}
|
||||
</span>
|
||||
@@ -899,6 +978,8 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
<HostTreeHostContextMenuContent
|
||||
host={host}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
|
||||
onOpenBrowser={onOpenBrowser}
|
||||
onEditHost={onEditHost}
|
||||
onDuplicateHost={onDuplicateHost}
|
||||
@@ -919,6 +1000,8 @@ const HostTreeViewInner: React.FC<HostTreeViewProps> = ({
|
||||
onExpandAll: externalOnExpandAll,
|
||||
onCollapseAll: externalOnCollapseAll,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onOpenSystemRemoteDesktop,
|
||||
onOpenBrowser,
|
||||
onEditHost,
|
||||
onDuplicateHost,
|
||||
@@ -1230,6 +1313,8 @@ const HostTreeViewInner: React.FC<HostTreeViewProps> = ({
|
||||
expandedPaths={expandedPaths}
|
||||
onToggle={togglePath}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
|
||||
onOpenBrowser={onOpenBrowser}
|
||||
onEditHost={onEditHost}
|
||||
onDuplicateHost={onDuplicateHost}
|
||||
@@ -1273,6 +1358,8 @@ const HostTreeViewInner: React.FC<HostTreeViewProps> = ({
|
||||
host={item.host}
|
||||
depth={item.depth}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
|
||||
onOpenBrowser={onOpenBrowser}
|
||||
onEditHost={onEditHost}
|
||||
onDuplicateHost={onDuplicateHost}
|
||||
@@ -1323,6 +1410,8 @@ function hostTreeViewAreEqual(prev: HostTreeViewProps, next: HostTreeViewProps):
|
||||
&& prev.onExpandAll === next.onExpandAll
|
||||
&& prev.onCollapseAll === next.onCollapseAll
|
||||
&& prev.onConnect === next.onConnect
|
||||
&& prev.onConnectRemoteDesktop === next.onConnectRemoteDesktop
|
||||
&& prev.onOpenSystemRemoteDesktop === next.onOpenSystemRemoteDesktop
|
||||
&& prev.onOpenBrowser === next.onOpenBrowser
|
||||
&& prev.onEditHost === next.onEditHost
|
||||
&& prev.onDuplicateHost === next.onDuplicateHost
|
||||
|
||||
@@ -468,6 +468,7 @@ echo $3 >> "$FILE"`);
|
||||
id: draftIdentity.id || crypto.randomUUID(),
|
||||
label: draftIdentity.label.trim(),
|
||||
username: draftIdentity.username.trim(),
|
||||
...(draftIdentity.domain?.trim() ? { domain: draftIdentity.domain.trim() } : {}),
|
||||
authMethod: draftIdentity.authMethod || "password",
|
||||
password: draftIdentity.password,
|
||||
keyId: draftIdentity.keyId,
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
|
||||
import { TooltipProvider } from "./ui/tooltip.tsx";
|
||||
import {
|
||||
clearAllKnownRemoteDesktopCerts,
|
||||
trustKnownRemoteDesktopCert,
|
||||
} from "./remoteDesktop/knownRemoteDesktopCerts.ts";
|
||||
import KnownHostsManager from "./KnownHostsManager.tsx";
|
||||
import {
|
||||
RemoteDesktopCertList,
|
||||
filterAndSortRemoteDesktopCerts,
|
||||
isRemoteDesktopCertExpired,
|
||||
truncateFingerprint,
|
||||
} from "./vault/RemoteDesktopCertList.tsx";
|
||||
|
||||
const renderWithI18n = (node: React.ReactElement) =>
|
||||
renderToStaticMarkup(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>{node}</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
const installStorageStub = () => {
|
||||
const values = new Map<string, string>();
|
||||
Object.defineProperty(globalThis, "localStorage", {
|
||||
configurable: true,
|
||||
value: {
|
||||
getItem: (key: string) => values.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => {
|
||||
values.set(key, value);
|
||||
},
|
||||
removeItem: (key: string) => {
|
||||
values.delete(key);
|
||||
},
|
||||
},
|
||||
});
|
||||
return values;
|
||||
};
|
||||
|
||||
test("KnownHostsManager renders SSH Host Keys and Remote Desktop Certificates tabs with counts", () => {
|
||||
installStorageStub();
|
||||
trustKnownRemoteDesktopCert(
|
||||
"rdp",
|
||||
"win-prod.local",
|
||||
3389,
|
||||
{
|
||||
fingerprintSha256: "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99",
|
||||
subject: "CN=win-prod.local",
|
||||
issuer: "CN=Corp CA",
|
||||
validTo: "2030-01-01T00:00:00Z",
|
||||
},
|
||||
1_700_000_000_000,
|
||||
);
|
||||
|
||||
const markup = renderWithI18n(
|
||||
React.createElement(KnownHostsManager, {
|
||||
knownHosts: [
|
||||
{
|
||||
id: "kh-1",
|
||||
hostname: "bastion.example.com",
|
||||
port: 22,
|
||||
keyType: "ssh-ed25519",
|
||||
publicKey: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5",
|
||||
discoveredAt: 1_700_000_000_000,
|
||||
},
|
||||
],
|
||||
hosts: [],
|
||||
onSave: () => {},
|
||||
onUpdate: () => {},
|
||||
onReorder: () => {},
|
||||
onDelete: () => {},
|
||||
onConvertToHost: () => {},
|
||||
onImportFromFile: () => {},
|
||||
onRefresh: () => {},
|
||||
}),
|
||||
);
|
||||
|
||||
assert.match(markup, /role="tablist"/);
|
||||
assert.match(markup, /data-known-hosts-tab="ssh"/);
|
||||
assert.match(markup, /data-known-hosts-tab="certs"/);
|
||||
assert.match(markup, /bastion\.example\.com/);
|
||||
});
|
||||
|
||||
test("RemoteDesktopCertList renders protocol badges, truncated SHA-256, and expired badge", () => {
|
||||
installStorageStub();
|
||||
clearAllKnownRemoteDesktopCerts();
|
||||
|
||||
const certs = [
|
||||
{
|
||||
key: "rdp:win-prod.local:3389",
|
||||
protocol: "rdp" as const,
|
||||
host: "win-prod.local",
|
||||
port: 3389,
|
||||
fingerprintSha256: "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99",
|
||||
subject: "CN=win-prod.local",
|
||||
issuer: "CN=Corp CA",
|
||||
validFrom: "2020-01-01T00:00:00Z",
|
||||
validTo: "2021-01-01T00:00:00Z",
|
||||
trustedAt: 2000,
|
||||
lastSeenAt: 2500,
|
||||
},
|
||||
{
|
||||
key: "vnc:::1:5901",
|
||||
protocol: "vnc" as const,
|
||||
host: "::1",
|
||||
port: 5901,
|
||||
fingerprintSha256: "11:22:33:44:55:66",
|
||||
trustedAt: 1000,
|
||||
lastSeenAt: 1500,
|
||||
},
|
||||
];
|
||||
|
||||
const markup = renderWithI18n(
|
||||
React.createElement(RemoteDesktopCertList, {
|
||||
certs,
|
||||
search: "",
|
||||
viewMode: "grid",
|
||||
sortMode: "newest",
|
||||
onRequestRevoke: () => {},
|
||||
}),
|
||||
);
|
||||
|
||||
assert.match(markup, /data-section="known-remote-desktop-certs"/);
|
||||
assert.match(markup, /win-prod\.local:3389/);
|
||||
assert.match(markup, /\[::1\]:5901/);
|
||||
assert.match(markup, />RDP</);
|
||||
assert.match(markup, />VNC</);
|
||||
assert.equal(isRemoteDesktopCertExpired("2021-01-01T00:00:00Z", Date.parse("2026-01-01T00:00:00Z")), true);
|
||||
assert.equal(isRemoteDesktopCertExpired("2030-01-01T00:00:00Z", Date.parse("2026-01-01T00:00:00Z")), false);
|
||||
|
||||
const filtered = filterAndSortRemoteDesktopCerts(certs, "corp ca", "az");
|
||||
assert.equal(filtered.length, 1);
|
||||
assert.equal(filtered[0].key, "rdp:win-prod.local:3389");
|
||||
|
||||
const sortedAz = filterAndSortRemoteDesktopCerts(certs, "", "az");
|
||||
assert.equal(sortedAz[0].host, "::1");
|
||||
assert.equal(sortedAz[1].host, "win-prod.local");
|
||||
|
||||
assert.equal(truncateFingerprint("AA:BB:CC", 20), "AA:BB:CC");
|
||||
assert.ok(truncateFingerprint("AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66", 20).includes("…"));
|
||||
});
|
||||
@@ -56,6 +56,15 @@ import {
|
||||
import { VaultDeleteConfirmDialog } from "./vault/VaultDeleteConfirmDialog";
|
||||
import { VaultEntityIcon, vaultPrimaryIconClass } from "./vault/VaultEntityIcon";
|
||||
import { useVaultItemReorder } from "./vault/vaultReorderDrag";
|
||||
import { RemoteDesktopCertList } from "./vault/RemoteDesktopCertList";
|
||||
import {
|
||||
clearAllKnownRemoteDesktopCerts,
|
||||
listKnownRemoteDesktopCerts,
|
||||
removeKnownRemoteDesktopCertByKey,
|
||||
subscribeKnownRemoteDesktopCerts,
|
||||
type KnownRemoteDesktopCertEntry,
|
||||
} from "./remoteDesktop/knownRemoteDesktopCerts";
|
||||
import { formatHostPort } from "../domain/host";
|
||||
|
||||
interface KnownHostsManagerProps {
|
||||
knownHosts: KnownHost[];
|
||||
@@ -315,8 +324,46 @@ const KnownHostsManager: React.FC<KnownHostsManagerProps> = ({
|
||||
const { readKnownHosts } = useKnownHostsBackend();
|
||||
const [search, setSearch] = useState("");
|
||||
const deferredSearch = useDeferredValue(search);
|
||||
const [activeTab, setActiveTab] = useState<"ssh" | "certs">("ssh");
|
||||
const [remoteCerts, setRemoteCerts] = useState<KnownRemoteDesktopCertEntry[]>(() =>
|
||||
listKnownRemoteDesktopCerts(),
|
||||
);
|
||||
const [revokeCertTarget, setRevokeCertTarget] = useState<KnownRemoteDesktopCertEntry | null>(null);
|
||||
const [clearAllCertsOpen, setClearAllCertsOpen] = useState(false);
|
||||
const [isScanning, setIsScanning] = useState(false);
|
||||
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setRemoteCerts(listKnownRemoteDesktopCerts());
|
||||
return subscribeKnownRemoteDesktopCerts(() => {
|
||||
setRemoteCerts(listKnownRemoteDesktopCerts());
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleConfirmRevokeCert = useCallback(() => {
|
||||
if (!revokeCertTarget) return;
|
||||
const removed = removeKnownRemoteDesktopCertByKey(revokeCertTarget.key);
|
||||
setRemoteCerts(listKnownRemoteDesktopCerts());
|
||||
if (removed) {
|
||||
toast.success(
|
||||
t("knownHosts.certs.toast.revoked"),
|
||||
formatHostPort(revokeCertTarget.host, revokeCertTarget.port),
|
||||
);
|
||||
}
|
||||
setRevokeCertTarget(null);
|
||||
}, [revokeCertTarget, t]);
|
||||
|
||||
const handleConfirmClearAllCerts = useCallback(() => {
|
||||
const count = clearAllKnownRemoteDesktopCerts();
|
||||
setRemoteCerts(listKnownRemoteDesktopCerts());
|
||||
if (count > 0) {
|
||||
toast.success(
|
||||
t("knownHosts.certs.toast.clearedAll", { count }),
|
||||
t("vault.nav.knownHosts"),
|
||||
);
|
||||
}
|
||||
setClearAllCertsOpen(false);
|
||||
}, [t]);
|
||||
const [viewMode, setViewMode] = useStoredViewMode(
|
||||
STORAGE_KEY_VAULT_KNOWN_HOSTS_VIEW_MODE,
|
||||
"grid",
|
||||
@@ -625,39 +672,111 @@ const KnownHostsManager: React.FC<KnownHostsManagerProps> = ({
|
||||
/>
|
||||
</div>
|
||||
<div className="w-px h-5 bg-border/50" />
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
className={vaultHeaderSecondaryButtonClass}
|
||||
onClick={() => handleScanSystem()}
|
||||
disabled={isScanning}
|
||||
>
|
||||
<RefreshCw
|
||||
size={14}
|
||||
className={cn("mr-2", isScanning && "animate-spin")}
|
||||
{activeTab === "ssh" ? (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
className={vaultHeaderSecondaryButtonClass}
|
||||
onClick={() => handleScanSystem()}
|
||||
disabled={isScanning}
|
||||
>
|
||||
<RefreshCw
|
||||
size={14}
|
||||
className={cn("mr-2", isScanning && "animate-spin")}
|
||||
/>
|
||||
{t("knownHosts.action.scanSystem")}
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".txt,known_hosts"
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
{t("knownHosts.action.scanSystem")}
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".txt,known_hosts"
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
className={vaultHeaderSecondaryButtonClass}
|
||||
onClick={openFilePicker}
|
||||
>
|
||||
<Import size={14} className="mr-2" />
|
||||
{t("knownHosts.action.importFile")}
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
variant="secondary"
|
||||
className={vaultHeaderSecondaryButtonClass}
|
||||
onClick={openFilePicker}
|
||||
>
|
||||
<Import size={14} className="mr-2" />
|
||||
{t("knownHosts.action.importFile")}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
className={cn(
|
||||
vaultHeaderSecondaryButtonClass,
|
||||
"text-destructive hover:text-destructive hover:bg-destructive/10",
|
||||
)}
|
||||
onClick={() => setClearAllCertsOpen(true)}
|
||||
disabled={remoteCerts.length === 0}
|
||||
>
|
||||
<Trash2 size={14} className="mr-2" />
|
||||
{t("knownHosts.certs.clearAll")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</VaultPageHeader>
|
||||
|
||||
{/* Segmented Tab Strip: SSH Host Keys | Remote Desktop Certificates */}
|
||||
<div className="px-4 py-2 border-b border-border/50 bg-background/60 shrink-0">
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={t("vault.nav.knownHosts")}
|
||||
className="inline-flex items-center rounded-lg bg-secondary/70 p-0.5 gap-0.5"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "ssh"}
|
||||
data-known-hosts-tab="ssh"
|
||||
onClick={() => setActiveTab("ssh")}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-all",
|
||||
activeTab === "ssh"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.ssh")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{filteredHosts.length}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "certs"}
|
||||
data-known-hosts-tab="certs"
|
||||
onClick={() => setActiveTab("certs")}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-all",
|
||||
activeTab === "certs"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.remoteDesktopCerts")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{remoteCerts.length}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<ScrollArea className="flex-1">
|
||||
{activeTab === "certs" ? (
|
||||
<RemoteDesktopCertList
|
||||
certs={remoteCerts}
|
||||
search={deferredSearch}
|
||||
viewMode={viewMode}
|
||||
sortMode={sortMode}
|
||||
onRequestRevoke={setRevokeCertTarget}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
ref={listRef}
|
||||
className={cn(
|
||||
@@ -724,6 +843,7 @@ const KnownHostsManager: React.FC<KnownHostsManagerProps> = ({
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
<VaultDeleteConfirmDialog
|
||||
open={Boolean(deleteTargetId)}
|
||||
@@ -736,6 +856,28 @@ const KnownHostsManager: React.FC<KnownHostsManagerProps> = ({
|
||||
}}
|
||||
onConfirm={confirmDelete}
|
||||
/>
|
||||
<VaultDeleteConfirmDialog
|
||||
open={Boolean(revokeCertTarget)}
|
||||
title={t("knownHosts.certs.revokeConfirm.title", {
|
||||
endpoint: revokeCertTarget
|
||||
? formatHostPort(revokeCertTarget.host, revokeCertTarget.port)
|
||||
: "",
|
||||
})}
|
||||
description={t("knownHosts.certs.revokeConfirm.desc")}
|
||||
confirmLabel={t("knownHosts.certs.action.revoke")}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setRevokeCertTarget(null);
|
||||
}}
|
||||
onConfirm={handleConfirmRevokeCert}
|
||||
/>
|
||||
<VaultDeleteConfirmDialog
|
||||
open={clearAllCertsOpen}
|
||||
title={t("knownHosts.certs.clearAllConfirm.title")}
|
||||
description={t("knownHosts.certs.clearAllConfirm.desc", { count: remoteCerts.length })}
|
||||
confirmLabel={t("knownHosts.certs.clearAll")}
|
||||
onOpenChange={setClearAllCertsOpen}
|
||||
onConfirm={handleConfirmClearAllCerts}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { registerHooks } from "node:module";
|
||||
import test from "node:test";
|
||||
import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
|
||||
import type { ConnectionLog } from "../domain/models/history.ts";
|
||||
import { TERMINAL_THEMES } from "../infrastructure/config/terminalThemes.ts";
|
||||
import { TooltipProvider } from "./ui/tooltip.tsx";
|
||||
|
||||
registerHooks({
|
||||
load(url, context, nextLoad) {
|
||||
if (url.endsWith(".css")) {
|
||||
return { format: "module", source: "export default {};", shortCircuit: true };
|
||||
}
|
||||
if (url.includes("/@xterm/xterm/")) {
|
||||
return { format: "module", source: "export class Terminal {}", shortCircuit: true };
|
||||
}
|
||||
if (url.includes("/@xterm/addon-fit/")) {
|
||||
return { format: "module", source: "export class FitAddon {}", shortCircuit: true };
|
||||
}
|
||||
if (url.includes("/@xterm/addon-webgl/")) {
|
||||
return { format: "module", source: "export class WebglAddon {}", shortCircuit: true };
|
||||
}
|
||||
if (url.endsWith("/customThemeStore.ts")) {
|
||||
return {
|
||||
format: "module",
|
||||
source: "export const useCustomThemes = () => []; export const useCustomThemeActions = () => ({}); export const customThemeStore = {};",
|
||||
shortCircuit: true,
|
||||
};
|
||||
}
|
||||
if (url.endsWith("/appearanceChromeStore.ts")) {
|
||||
return {
|
||||
format: "module",
|
||||
source: "export const useAppearanceChromeStore = () => ({ accentMode: 'theme', customAccent: '' });",
|
||||
shortCircuit: true,
|
||||
};
|
||||
}
|
||||
return nextLoad(url, context);
|
||||
},
|
||||
});
|
||||
|
||||
const { default: LogView } = await import("./LogView.tsx");
|
||||
|
||||
const renderWithI18n = (node: React.ReactElement) =>
|
||||
renderToStaticMarkup(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>{node}</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
const defaultTheme = TERMINAL_THEMES[0];
|
||||
|
||||
test("LogView renders remote desktop recording viewport with download/delete actions and hides terminal appearance button", () => {
|
||||
const log: ConnectionLog = {
|
||||
id: "log-1",
|
||||
hostId: "h-1",
|
||||
hostLabel: "Windows Prod",
|
||||
hostname: "10.0.0.10",
|
||||
username: "Administrator",
|
||||
protocol: "rdp",
|
||||
startTime: 1_700_000_000_000,
|
||||
endTime: 1_700_000_120_000,
|
||||
localUsername: "alice",
|
||||
localHostname: "macbook",
|
||||
saved: true,
|
||||
recordingId: "123e4567-e89b-12d3-a456-426614174000",
|
||||
recordingMimeType: "video/webm;codecs=vp9,opus",
|
||||
recordingDurationMs: 120_000,
|
||||
recordingBytes: 5_242_880,
|
||||
recordingHasAudio: true,
|
||||
};
|
||||
|
||||
const markup = renderWithI18n(
|
||||
React.createElement(LogView, {
|
||||
log,
|
||||
defaultTerminalTheme: defaultTheme,
|
||||
defaultFontSize: 13,
|
||||
isVisible: true,
|
||||
onClose: () => {},
|
||||
onUpdateLog: () => {},
|
||||
}),
|
||||
);
|
||||
|
||||
assert.match(markup, /data-log-view="remote-desktop-recording"/);
|
||||
assert.match(markup, /Windows Prod/);
|
||||
assert.match(markup, /02:00/);
|
||||
assert.match(markup, /5 MB/);
|
||||
assert.match(markup, /Download \.webm/);
|
||||
assert.match(markup, /Delete Recording/);
|
||||
assert.doesNotMatch(markup, /Appearance/);
|
||||
});
|
||||
|
||||
test("LogView renders clean non-terminal metadata card for unrecorded VNC/RDP sessions", () => {
|
||||
const log: ConnectionLog = {
|
||||
id: "log-2",
|
||||
hostId: "h-2",
|
||||
hostLabel: "Ubuntu VNC",
|
||||
hostname: "192.168.1.50",
|
||||
username: "ubuntu",
|
||||
protocol: "vnc",
|
||||
startTime: 1_700_000_000_000,
|
||||
endTime: 1_700_000_095_000,
|
||||
localUsername: "alice",
|
||||
localHostname: "macbook",
|
||||
saved: false,
|
||||
};
|
||||
|
||||
const markup = renderWithI18n(
|
||||
React.createElement(LogView, {
|
||||
log,
|
||||
defaultTerminalTheme: defaultTheme,
|
||||
defaultFontSize: 13,
|
||||
isVisible: true,
|
||||
onClose: () => {},
|
||||
onUpdateLog: () => {},
|
||||
}),
|
||||
);
|
||||
|
||||
assert.match(markup, /data-log-view="remote-desktop-metadata"/);
|
||||
assert.match(markup, /Ubuntu VNC/);
|
||||
assert.match(markup, /192\.168\.1\.50/);
|
||||
assert.match(markup, /1m 35s/);
|
||||
assert.doesNotMatch(markup, /Appearance/);
|
||||
});
|
||||
|
||||
test("LogView memo comparator checks recordingId and recordingBytes", () => {
|
||||
const source = readFileSync(new URL("./LogView.tsx", import.meta.url), "utf8");
|
||||
const comparator = source.match(/const logViewAreEqual[\s\S]*?^};/m)?.[0] ?? "";
|
||||
assert.ok(comparator, "expected logViewAreEqual in LogView.tsx");
|
||||
assert.match(comparator, /prev\.log\.recordingId === next\.log\.recordingId/);
|
||||
assert.match(comparator, /prev\.log\.recordingBytes === next\.log\.recordingBytes/);
|
||||
});
|
||||
+426
-52
@@ -2,17 +2,37 @@ import { Terminal as XTerm } from "@xterm/xterm";
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { WebglAddon } from "@xterm/addon-webgl";
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import { FileText, Download, Palette, X } from "lucide-react";
|
||||
import {
|
||||
AlertCircle,
|
||||
Clock,
|
||||
Download,
|
||||
FileText,
|
||||
HardDrive,
|
||||
Palette,
|
||||
Server,
|
||||
Trash2,
|
||||
User,
|
||||
Video,
|
||||
VideoOff,
|
||||
Volume2,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useI18n } from "../application/i18n/I18nProvider";
|
||||
import { useAppearanceChromeStore } from "../application/state/appearanceChromeStore";
|
||||
import { useCustomThemes } from "../application/state/customThemeStore";
|
||||
import { isRdpProtocol, isRemoteDesktopProtocol } from "../domain/remoteDesktop";
|
||||
import { applyCustomAccentToTerminalTheme } from "../domain/terminalAppearance";
|
||||
import { TERMINAL_THEMES } from "../infrastructure/config/terminalThemes";
|
||||
import { cn } from "../lib/utils";
|
||||
import { ConnectionLog, TerminalTheme } from "../types";
|
||||
import { TERMINAL_THEMES } from "../infrastructure/config/terminalThemes";
|
||||
import { useCustomThemes } from "../application/state/customThemeStore";
|
||||
import { useAppearanceChromeStore } from "../application/state/appearanceChromeStore";
|
||||
import { applyCustomAccentToTerminalTheme } from "../domain/terminalAppearance";
|
||||
import { Button } from "./ui/button";
|
||||
import { formatRecordingBytes, formatRecordingDuration } from "./ConnectionLogsManager";
|
||||
import { RdpProtocolIcon, VncProtocolIcon } from "./icons/RemoteDesktopIcons";
|
||||
import { getProtocolBadgeClass } from "./protocolVisuals";
|
||||
import ThemeCustomizeModal from "./terminal/ThemeCustomizeModal";
|
||||
import { Button } from "./ui/button";
|
||||
import { toast } from "./ui/toast";
|
||||
import { VaultDeleteConfirmDialog } from "./vault/VaultDeleteConfirmDialog";
|
||||
|
||||
interface LogViewProps {
|
||||
log: ConnectionLog;
|
||||
@@ -23,6 +43,31 @@ interface LogViewProps {
|
||||
onUpdateLog: (logId: string, updates: Partial<ConnectionLog>) => void;
|
||||
}
|
||||
|
||||
async function getDesktopBridge(): Promise<NetcattyBridge | undefined> {
|
||||
const { netcattyBridge } = await import("../infrastructure/services/netcattyBridge");
|
||||
return netcattyBridge.get();
|
||||
}
|
||||
|
||||
function buildDefaultRecordingExportName(log: ConnectionLog): string {
|
||||
const safeHost = (log.hostLabel || log.hostname || "remote-desktop")
|
||||
.replace(/[^a-zA-Z0-9._-]+/g, "_")
|
||||
.replace(/^_+|_+$/g, "")
|
||||
|| "remote-desktop";
|
||||
const iso = new Date(log.startTime).toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
||||
return `${safeHost}_${log.protocol}_${iso}.webm`;
|
||||
}
|
||||
|
||||
function formatSessionDuration(startTime: number, endTime?: number): string | null {
|
||||
if (!endTime || endTime < startTime) return null;
|
||||
const totalSeconds = Math.round((endTime - startTime) / 1000);
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`;
|
||||
if (minutes > 0) return `${minutes}m ${seconds}s`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
|
||||
const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
log,
|
||||
defaultTerminalTheme,
|
||||
@@ -32,6 +77,8 @@ const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
onUpdateLog,
|
||||
}) => {
|
||||
const { t, resolvedLocale } = useI18n();
|
||||
const isRemoteDesktop = isRemoteDesktopProtocol(log.protocol);
|
||||
const isRdp = isRdpProtocol(log.protocol);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const termRef = useRef<XTerm | null>(null);
|
||||
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||
@@ -40,6 +87,12 @@ const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
const [previewTheme, setPreviewTheme] = useState<TerminalTheme | null>(null);
|
||||
|
||||
// Remote desktop recording playback state
|
||||
const [playbackUrl, setPlaybackUrl] = useState<string | null>(null);
|
||||
const [recordingStatus, setRecordingStatus] = useState<"idle" | "loading" | "ready" | "missing" | "error">("idle");
|
||||
const [deleteRecordingOpen, setDeleteRecordingOpen] = useState(false);
|
||||
const [isDeletingRecording, setIsDeletingRecording] = useState(false);
|
||||
|
||||
// Subscribe to custom theme changes so editing triggers re-render
|
||||
const customThemes = useCustomThemes();
|
||||
// Leaf accent: published defaultTerminalTheme is the stable base catalog
|
||||
@@ -59,14 +112,55 @@ const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
}
|
||||
}, [explicitThemeId, log.id, log.themeId, onUpdateLog]);
|
||||
|
||||
// Resolve recording playback URL for remote desktop logs
|
||||
useEffect(() => {
|
||||
if (!isRemoteDesktop || !log.recordingId) {
|
||||
setPlaybackUrl(null);
|
||||
setRecordingStatus("idle");
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
setRecordingStatus("loading");
|
||||
setPlaybackUrl(null);
|
||||
void getDesktopBridge()
|
||||
.then((bridge) => {
|
||||
if (cancelled) return;
|
||||
if (!bridge?.remoteDesktopRecordings?.getPlaybackUrl) {
|
||||
setRecordingStatus("missing");
|
||||
return;
|
||||
}
|
||||
return bridge.remoteDesktopRecordings
|
||||
.getPlaybackUrl({ recordingId: log.recordingId as string })
|
||||
.then((res) => {
|
||||
if (cancelled) return;
|
||||
if (res?.exists && res.url) {
|
||||
setPlaybackUrl(res.url);
|
||||
setRecordingStatus("ready");
|
||||
} else {
|
||||
setPlaybackUrl(null);
|
||||
setRecordingStatus("missing");
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
if (cancelled) return;
|
||||
setPlaybackUrl(null);
|
||||
setRecordingStatus("missing");
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [isRemoteDesktop, log.recordingId]);
|
||||
|
||||
// Use log's saved theme/fontSize or fall back to defaults
|
||||
const currentTheme = useMemo(() => {
|
||||
if (previewTheme) {
|
||||
return previewTheme;
|
||||
}
|
||||
const baseTheme = explicitThemeId
|
||||
? (TERMINAL_THEMES.find(t => t.id === explicitThemeId)
|
||||
|| customThemes.find(t => t.id === explicitThemeId)
|
||||
? (TERMINAL_THEMES.find(theme => theme.id === explicitThemeId)
|
||||
|| customThemes.find(theme => theme.id === explicitThemeId)
|
||||
|| defaultTerminalTheme)
|
||||
: defaultTerminalTheme;
|
||||
return applyCustomAccentToTerminalTheme(baseTheme, accentMode, customAccent);
|
||||
@@ -86,6 +180,17 @@ const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
});
|
||||
}, [log.startTime, resolvedLocale]);
|
||||
|
||||
const formattedEndDate = useMemo(() => {
|
||||
if (!log.endTime) return null;
|
||||
return new Date(log.endTime).toLocaleString(resolvedLocale || undefined, {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}, [log.endTime, resolvedLocale]);
|
||||
|
||||
// Handle theme change
|
||||
const handleThemeChange = useCallback((themeId: string) => {
|
||||
onUpdateLog(log.id, { themeId });
|
||||
@@ -102,33 +207,86 @@ const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
onUpdateLog(log.id, { fontSize });
|
||||
}, [log.id, onUpdateLog]);
|
||||
|
||||
// Handle export
|
||||
// Handle terminal log export
|
||||
const handleExport = useCallback(async () => {
|
||||
if (!log.terminalData || isExporting) return;
|
||||
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const { netcattyBridge } = await import("../infrastructure/services/netcattyBridge");
|
||||
const bridge = netcattyBridge.get();
|
||||
const bridge = await getDesktopBridge();
|
||||
if (bridge?.exportSessionLog) {
|
||||
await bridge.exportSessionLog({
|
||||
terminalData: log.terminalData,
|
||||
hostLabel: log.hostLabel,
|
||||
hostname: log.hostname,
|
||||
startTime: log.startTime,
|
||||
format: 'txt',
|
||||
format: "txt",
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to export session log:', err);
|
||||
console.error("Failed to export session log:", err);
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
}, [log.terminalData, log.hostLabel, log.hostname, log.startTime, isExporting]);
|
||||
|
||||
// Initialize terminal
|
||||
// Handle WebM recording export
|
||||
const handleExportRecording = useCallback(async () => {
|
||||
if (!log.recordingId || isExporting) return;
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const bridge = await getDesktopBridge();
|
||||
if (!bridge?.remoteDesktopRecordings?.export) return;
|
||||
const res = await bridge.remoteDesktopRecordings.export({
|
||||
recordingId: log.recordingId,
|
||||
defaultFileName: buildDefaultRecordingExportName(log),
|
||||
});
|
||||
if (res?.saved) {
|
||||
toast.success(t("logView.recording.exportSuccess"), res.filePath || log.hostLabel);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to export recording:", err);
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : t("logView.recording.exportFailed"),
|
||||
log.hostLabel,
|
||||
);
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
}, [isExporting, log, t]);
|
||||
|
||||
// Handle WebM recording delete
|
||||
const handleConfirmDeleteRecording = useCallback(async () => {
|
||||
if (!log.recordingId || isDeletingRecording) return;
|
||||
setIsDeletingRecording(true);
|
||||
try {
|
||||
const bridge = await getDesktopBridge();
|
||||
await bridge?.remoteDesktopRecordings?.delete?.({ recordingId: log.recordingId });
|
||||
onUpdateLog(log.id, {
|
||||
recordingId: undefined,
|
||||
recordingMimeType: undefined,
|
||||
recordingDurationMs: undefined,
|
||||
recordingBytes: undefined,
|
||||
recordingHasAudio: undefined,
|
||||
});
|
||||
setPlaybackUrl(null);
|
||||
setRecordingStatus("idle");
|
||||
setDeleteRecordingOpen(false);
|
||||
toast.success(t("logView.recording.deleted"), log.hostLabel);
|
||||
} catch (err) {
|
||||
console.error("Failed to delete recording:", err);
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : t("logView.recording.deleteFailed"),
|
||||
log.hostLabel,
|
||||
);
|
||||
} finally {
|
||||
setIsDeletingRecording(false);
|
||||
}
|
||||
}, [isDeletingRecording, log.hostLabel, log.id, log.recordingId, onUpdateLog, t]);
|
||||
|
||||
// Initialize terminal (skipped completely for remote desktop sessions)
|
||||
useEffect(() => {
|
||||
if (!containerRef.current || !isVisible) return;
|
||||
if (isRemoteDesktop || !containerRef.current || !isVisible) return;
|
||||
|
||||
// Create terminal
|
||||
const term = new XTerm({
|
||||
@@ -201,7 +359,7 @@ const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
// Only re-create terminal when visibility or terminalData changes
|
||||
// Theme and font size updates are handled separately
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isVisible, log.id, log.terminalData]);
|
||||
}, [isRemoteDesktop, isVisible, log.id, log.terminalData]);
|
||||
|
||||
// Update theme instantly without recreating terminal
|
||||
useEffect(() => {
|
||||
@@ -227,7 +385,7 @@ const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
|
||||
// Handle resize
|
||||
useEffect(() => {
|
||||
if (!isVisible || !fitAddonRef.current) return;
|
||||
if (isRemoteDesktop || !isVisible || !fitAddonRef.current) return;
|
||||
|
||||
const handleResize = () => {
|
||||
if (fitAddonRef.current) {
|
||||
@@ -247,9 +405,10 @@ const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
return () => {
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [isVisible]);
|
||||
}, [isRemoteDesktop, isVisible]);
|
||||
|
||||
const isLocal = log.protocol === "local" || log.hostname === "localhost";
|
||||
const sessionDuration = formatSessionDuration(log.startTime, log.endTime);
|
||||
|
||||
return (
|
||||
<div className="h-full w-full flex flex-col bg-background">
|
||||
@@ -259,16 +418,24 @@ const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
<div
|
||||
className={cn(
|
||||
"h-6 w-6 shrink-0 rounded-md flex items-center justify-center",
|
||||
isLocal
|
||||
? "bg-emerald-500/10 text-emerald-500"
|
||||
: "bg-blue-500/10 text-blue-500"
|
||||
isRemoteDesktop
|
||||
? isRdp
|
||||
? "bg-blue-500/15 text-blue-600 dark:text-blue-400"
|
||||
: "bg-teal-500/15 text-teal-600 dark:text-teal-400"
|
||||
: isLocal
|
||||
? "bg-emerald-500/10 text-emerald-500"
|
||||
: "bg-blue-500/10 text-blue-500",
|
||||
)}
|
||||
>
|
||||
<FileText size={14} />
|
||||
{isRemoteDesktop ? (
|
||||
isRdp ? <RdpProtocolIcon size={14} /> : <VncProtocolIcon size={14} />
|
||||
) : (
|
||||
<FileText size={14} />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 items-baseline gap-2">
|
||||
<div className="min-w-0 text-sm font-medium leading-5 truncate">
|
||||
{isLocal ? t("logs.localTerminal") : log.hostname}
|
||||
{isLocal ? t("logs.localTerminal") : (log.hostLabel || log.hostname)}
|
||||
</div>
|
||||
<div className="text-xs leading-4 truncate text-muted-foreground">
|
||||
{formattedDate} • {log.localUsername}@{log.localHostname}
|
||||
@@ -276,8 +443,34 @@ const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex h-7 shrink-0 items-center gap-1.5">
|
||||
{/* Export button */}
|
||||
{log.terminalData && (
|
||||
{/* Remote Desktop Recording actions */}
|
||||
{isRemoteDesktop && log.recordingId && (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-1.5 h-7 px-2 text-xs"
|
||||
onClick={handleExportRecording}
|
||||
disabled={isExporting || recordingStatus === "missing"}
|
||||
>
|
||||
<Download size={14} />
|
||||
<span className="text-xs">{t("logView.recording.download")}</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-1.5 h-7 px-2 text-xs text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => setDeleteRecordingOpen(true)}
|
||||
disabled={isDeletingRecording}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
<span className="text-xs">{t("logView.recording.delete")}</span>
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Terminal Export button */}
|
||||
{!isRemoteDesktop && log.terminalData && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@@ -290,16 +483,18 @@ const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Theme & font customization button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-1.5 h-7 px-2 text-xs"
|
||||
onClick={() => setThemeModalOpen(true)}
|
||||
>
|
||||
<Palette size={14} />
|
||||
<span className="text-xs">{t("logView.appearance")}</span>
|
||||
</Button>
|
||||
{/* Theme & font customization button (terminal logs only) */}
|
||||
{!isRemoteDesktop && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-1.5 h-7 px-2 text-xs"
|
||||
onClick={() => setThemeModalOpen(true)}
|
||||
>
|
||||
<Palette size={14} />
|
||||
<span className="text-xs">{t("logView.appearance")}</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<span className="h-6 inline-flex items-center rounded bg-secondary px-2 text-xs text-muted-foreground">
|
||||
{t("logView.readOnly")}
|
||||
@@ -310,25 +505,200 @@ const LogViewComponent: React.FC<LogViewProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Terminal container */}
|
||||
<div
|
||||
className="flex-1 overflow-hidden p-2"
|
||||
style={{ backgroundColor: currentTheme?.colors?.background || '#000000' }}
|
||||
>
|
||||
<div ref={containerRef} className="h-full w-full" />
|
||||
</div>
|
||||
{/* Body */}
|
||||
{isRemoteDesktop ? (
|
||||
log.recordingId ? (
|
||||
<div
|
||||
data-log-view="remote-desktop-recording"
|
||||
className="flex-1 min-h-0 flex flex-col bg-neutral-950 text-neutral-100"
|
||||
>
|
||||
<div className="flex-1 min-h-0 flex items-center justify-center p-4 overflow-hidden">
|
||||
{recordingStatus === "ready" && playbackUrl ? (
|
||||
<video
|
||||
data-recording-player={log.recordingId}
|
||||
controls
|
||||
playsInline
|
||||
preload="metadata"
|
||||
src={playbackUrl}
|
||||
className="max-h-full max-w-full rounded-lg bg-black shadow-2xl"
|
||||
onError={() => setRecordingStatus("error")}
|
||||
/>
|
||||
) : recordingStatus === "missing" || recordingStatus === "error" ? (
|
||||
<div
|
||||
data-recording-missing="true"
|
||||
className="max-w-md rounded-xl border border-neutral-800 bg-neutral-900/90 p-6 text-center space-y-3"
|
||||
>
|
||||
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-amber-500/15 text-amber-400">
|
||||
{recordingStatus === "missing" ? (
|
||||
<VideoOff size={22} />
|
||||
) : (
|
||||
<AlertCircle size={22} />
|
||||
)}
|
||||
</div>
|
||||
<h3 className="text-sm font-semibold text-neutral-100">
|
||||
{recordingStatus === "missing"
|
||||
? t("logView.recording.missingTitle")
|
||||
: t("logView.recording.playbackErrorTitle")}
|
||||
</h3>
|
||||
<p className="text-xs text-neutral-400 leading-relaxed">
|
||||
{recordingStatus === "missing"
|
||||
? t("logView.recording.missingDesc")
|
||||
: t("logView.recording.playbackErrorDesc")}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 text-xs text-neutral-400">
|
||||
<Video size={16} className="animate-pulse" />
|
||||
<span>{t("logView.recording.loading")}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Metadata Bar */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-t border-neutral-800 bg-neutral-900/90 px-4 py-2.5 text-xs text-neutral-300 shrink-0">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-md border px-1.5 py-0 text-[10px] font-semibold uppercase leading-4",
|
||||
getProtocolBadgeClass(isRdp ? "rdp" : "vnc"),
|
||||
)}
|
||||
>
|
||||
{log.protocol.toUpperCase()}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1.5 font-mono text-neutral-200">
|
||||
<Server size={12} className="text-neutral-400" />
|
||||
{log.hostname}
|
||||
</span>
|
||||
{log.username && (
|
||||
<span className="inline-flex items-center gap-1.5 text-neutral-300">
|
||||
<User size={12} className="text-neutral-400" />
|
||||
{log.username}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3 tabular-nums text-neutral-400">
|
||||
{typeof log.recordingDurationMs === "number" && (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<Clock size={12} />
|
||||
{formatRecordingDuration(log.recordingDurationMs)}
|
||||
</span>
|
||||
)}
|
||||
{typeof log.recordingBytes === "number" && log.recordingBytes > 0 && (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<HardDrive size={12} />
|
||||
{formatRecordingBytes(log.recordingBytes)}
|
||||
</span>
|
||||
)}
|
||||
{log.recordingHasAudio && (
|
||||
<span className="inline-flex items-center gap-1 text-emerald-400">
|
||||
<Volume2 size={12} />
|
||||
{t("logView.recording.withAudio")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
data-log-view="remote-desktop-metadata"
|
||||
className="flex-1 min-h-0 flex items-center justify-center p-6 overflow-auto"
|
||||
>
|
||||
<div className="w-full max-w-lg rounded-2xl border border-border/70 bg-card p-6 shadow-sm space-y-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<div
|
||||
className={cn(
|
||||
"h-11 w-11 rounded-xl flex items-center justify-center shrink-0",
|
||||
isRdp
|
||||
? "bg-blue-500/12 text-blue-600 dark:text-blue-400"
|
||||
: "bg-teal-500/12 text-teal-600 dark:text-teal-400",
|
||||
)}
|
||||
>
|
||||
{isRdp ? <RdpProtocolIcon size={22} /> : <VncProtocolIcon size={22} />}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-base font-semibold truncate">
|
||||
{log.hostLabel || log.hostname}
|
||||
</h3>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-md border px-1.5 py-0 text-[10px] font-semibold uppercase leading-4 shrink-0",
|
||||
getProtocolBadgeClass(isRdp ? "rdp" : "vnc"),
|
||||
)}
|
||||
>
|
||||
{log.protocol.toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("logView.remoteDesktop.noRecordingSubtitle")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-[110px_1fr] gap-x-4 gap-y-2.5 rounded-xl border border-border/60 bg-secondary/35 p-4 text-xs">
|
||||
<span className="text-muted-foreground">{t("logView.remoteDesktop.host")}</span>
|
||||
<span className="font-mono break-all text-foreground">{log.hostname}</span>
|
||||
|
||||
<span className="text-muted-foreground">{t("logView.remoteDesktop.protocol")}</span>
|
||||
<span className="uppercase text-foreground">{log.protocol}</span>
|
||||
|
||||
<span className="text-muted-foreground">{t("logView.remoteDesktop.user")}</span>
|
||||
<span className="text-foreground">{log.username || "—"}</span>
|
||||
|
||||
<span className="text-muted-foreground">{t("logView.remoteDesktop.started")}</span>
|
||||
<span className="text-foreground">{formattedDate}</span>
|
||||
|
||||
<span className="text-muted-foreground">{t("logView.remoteDesktop.ended")}</span>
|
||||
<span className="text-foreground">{formattedEndDate || t("logs.ongoing")}</span>
|
||||
|
||||
{sessionDuration && (
|
||||
<>
|
||||
<span className="text-muted-foreground">{t("logView.remoteDesktop.duration")}</span>
|
||||
<span className="text-foreground">{sessionDuration}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-2.5 rounded-xl border border-border/60 bg-background px-3.5 py-3 text-xs text-muted-foreground">
|
||||
<Video size={15} className="mt-0.5 shrink-0 text-primary" />
|
||||
<span>{t("logView.remoteDesktop.recordingTip")}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<div
|
||||
className="flex-1 overflow-hidden p-2"
|
||||
style={{ backgroundColor: currentTheme?.colors?.background || "#000000" }}
|
||||
>
|
||||
<div ref={containerRef} className="h-full w-full" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Theme Customize Modal */}
|
||||
<ThemeCustomizeModal
|
||||
open={themeModalOpen}
|
||||
onClose={() => setThemeModalOpen(false)}
|
||||
currentThemeId={explicitThemeId}
|
||||
displayThemeId={currentTheme.id}
|
||||
currentFontSize={currentFontSize}
|
||||
onThemeChange={handleThemeChange}
|
||||
onThemeReset={() => onUpdateLog(log.id, { themeId: undefined })}
|
||||
onFontSizeChange={handleFontSizeChange}
|
||||
onPreviewThemeChange={setPreviewTheme}
|
||||
{!isRemoteDesktop && (
|
||||
<ThemeCustomizeModal
|
||||
open={themeModalOpen}
|
||||
onClose={() => setThemeModalOpen(false)}
|
||||
currentThemeId={explicitThemeId}
|
||||
displayThemeId={currentTheme.id}
|
||||
currentFontSize={currentFontSize}
|
||||
onThemeChange={handleThemeChange}
|
||||
onThemeReset={() => onUpdateLog(log.id, { themeId: undefined })}
|
||||
onFontSizeChange={handleFontSizeChange}
|
||||
onPreviewThemeChange={setPreviewTheme}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Delete Recording Confirm Dialog */}
|
||||
<VaultDeleteConfirmDialog
|
||||
open={deleteRecordingOpen}
|
||||
title={t("logView.recording.deleteConfirmTitle")}
|
||||
description={t("logView.recording.deleteConfirmDesc")}
|
||||
confirmLabel={t("logView.recording.delete")}
|
||||
disabled={isDeletingRecording}
|
||||
onOpenChange={setDeleteRecordingOpen}
|
||||
onConfirm={handleConfirmDeleteRecording}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -340,6 +710,10 @@ const logViewAreEqual = (prev: LogViewProps, next: LogViewProps): boolean => {
|
||||
prev.log.id === next.log.id &&
|
||||
prev.log.themeId === next.log.themeId &&
|
||||
prev.log.fontSize === next.log.fontSize &&
|
||||
prev.log.recordingId === next.log.recordingId &&
|
||||
prev.log.recordingBytes === next.log.recordingBytes &&
|
||||
prev.log.recordingDurationMs === next.log.recordingDurationMs &&
|
||||
prev.log.endTime === next.log.endTime &&
|
||||
prev.isVisible === next.isVisible &&
|
||||
prev.defaultFontSize === next.defaultFontSize &&
|
||||
prev.defaultTerminalTheme.id === next.defaultTerminalTheme.id
|
||||
|
||||
@@ -91,3 +91,34 @@ test("plugin protocol hosts default to the plugin provider when optional built-i
|
||||
}
|
||||
assert.ok(!telnetButton.includes("border-primary"));
|
||||
});
|
||||
|
||||
test("protocol select dialog lists companion RDP and VNC protocols with remember-default toggle", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<I18nProvider locale="en">
|
||||
<ProtocolSelectDialog
|
||||
host={host({
|
||||
moshEnabled: false,
|
||||
etEnabled: false,
|
||||
telnetEnabled: false,
|
||||
rdpConfig: { enabled: true, port: 13389, tunnelViaHostSsh: true, defaultConnect: true },
|
||||
vncConfig: { enabled: true, port: 5902, tunnelViaHostSsh: false },
|
||||
connectProtocolBehavior: "ask",
|
||||
})}
|
||||
onSelect={() => undefined}
|
||||
onCancel={() => undefined}
|
||||
/>
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
assert.match(markup, /data-protocol="ssh"/);
|
||||
assert.match(markup, /data-protocol="rdp"/);
|
||||
assert.match(markup, /data-protocol="vnc"/);
|
||||
assert.match(markup, /via SSH/);
|
||||
assert.match(markup, /13389/);
|
||||
assert.match(markup, /5902/);
|
||||
assert.match(markup, /Remember as default/);
|
||||
// RDP is flagged defaultConnect, so it is pre-selected in the dialog
|
||||
const rdpStart = markup.lastIndexOf("<button", markup.indexOf('data-protocol="rdp"'));
|
||||
const rdpEnd = markup.indexOf("</button>", markup.indexOf('data-protocol="rdp"'));
|
||||
assert.match(markup.slice(rdpStart, rdpEnd), /aria-pressed="true"/);
|
||||
});
|
||||
@@ -1,8 +1,13 @@
|
||||
import { Plug } from "lucide-react";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import { useI18n } from "../application/i18n/I18nProvider";
|
||||
import { formatHostPort } from "../domain/host";
|
||||
import { isPluginHostProtocol } from "../domain/pluginConnection";
|
||||
import {
|
||||
DEFAULT_RDP_PORT,
|
||||
DEFAULT_VNC_PORT,
|
||||
resolveHostDefaultConnectProtocol,
|
||||
} from "../domain/remoteDesktop";
|
||||
import { cn } from "../lib/utils";
|
||||
import { Host, HostProtocol } from "../types";
|
||||
import {
|
||||
@@ -27,7 +32,7 @@ interface ProtocolOption {
|
||||
|
||||
interface ProtocolSelectDialogProps {
|
||||
host: Host;
|
||||
onSelect: (protocol: HostProtocol, port: number) => void;
|
||||
onSelect: (protocol: HostProtocol, port: number, rememberDefault?: boolean) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
@@ -60,7 +65,7 @@ const ProtocolSelectDialog: React.FC<ProtocolSelectDialogProps> = ({
|
||||
const sshConfig = host.protocols?.find((p) => p.protocol === "ssh");
|
||||
options.push({
|
||||
protocol: "ssh",
|
||||
port: sshConfig?.port || host.port || 22,
|
||||
port: sshConfig?.port || (host.protocol === "telnet" ? 22 : host.port) || 22,
|
||||
label: "SSH",
|
||||
description: `ssh ${host.hostname}`,
|
||||
enabled: true,
|
||||
@@ -88,6 +93,36 @@ const ProtocolSelectDialog: React.FC<ProtocolSelectDialogProps> = ({
|
||||
});
|
||||
}
|
||||
|
||||
if (host.protocol === "rdp" || host.rdpConfig?.enabled) {
|
||||
const rdpPort =
|
||||
host.protocol === "rdp"
|
||||
? host.port || host.rdpConfig?.port || DEFAULT_RDP_PORT
|
||||
: host.rdpConfig?.port || DEFAULT_RDP_PORT;
|
||||
const viaSsh = host.protocol !== "rdp" && host.rdpConfig?.tunnelViaHostSsh === true;
|
||||
options.push({
|
||||
protocol: "rdp",
|
||||
port: rdpPort,
|
||||
label: "RDP",
|
||||
description: viaSsh ? `rdp ${host.hostname} · via SSH` : `rdp ${host.hostname}`,
|
||||
enabled: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (host.protocol === "vnc" || host.vncConfig?.enabled) {
|
||||
const vncPort =
|
||||
host.protocol === "vnc"
|
||||
? host.port || host.vncConfig?.port || DEFAULT_VNC_PORT
|
||||
: host.vncConfig?.port || DEFAULT_VNC_PORT;
|
||||
const viaSsh = host.protocol !== "vnc" && host.vncConfig?.tunnelViaHostSsh === true;
|
||||
options.push({
|
||||
protocol: "vnc",
|
||||
port: vncPort,
|
||||
label: "VNC",
|
||||
description: viaSsh ? `vnc ${host.hostname} · via SSH` : `vnc ${host.hostname}`,
|
||||
enabled: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
host.telnetEnabled ||
|
||||
host.protocol === "telnet" ||
|
||||
@@ -96,7 +131,7 @@ const ProtocolSelectDialog: React.FC<ProtocolSelectDialogProps> = ({
|
||||
const telnetConfig = host.protocols?.find((p) => p.protocol === "telnet");
|
||||
options.push({
|
||||
protocol: "telnet",
|
||||
port: telnetConfig?.port || host.telnetPort || 23,
|
||||
port: telnetConfig?.port || host.telnetPort || (host.protocol === "telnet" ? host.port : undefined) || 23,
|
||||
label: "Telnet",
|
||||
description: `telnet ${host.hostname}`,
|
||||
enabled: true,
|
||||
@@ -114,9 +149,20 @@ const ProtocolSelectDialog: React.FC<ProtocolSelectDialogProps> = ({
|
||||
return initial as Record<HostProtocol, number>;
|
||||
});
|
||||
|
||||
const [selectedProtocol, setSelectedProtocol] = useState<HostProtocol>(
|
||||
protocolOptions[0]?.protocol || "ssh",
|
||||
);
|
||||
const [selectedProtocol, setSelectedProtocol] = useState<HostProtocol>(() => {
|
||||
if (isPluginHostProtocol(host.protocol)) {
|
||||
return protocolOptions[0]?.protocol || host.protocol;
|
||||
}
|
||||
const defaultProto = resolveHostDefaultConnectProtocol(host);
|
||||
if (protocolOptions.some((opt) => opt.protocol === defaultProto)) {
|
||||
return defaultProto;
|
||||
}
|
||||
return protocolOptions[0]?.protocol || "ssh";
|
||||
});
|
||||
const [rememberDefault, setRememberDefault] = useState(false);
|
||||
|
||||
const canRememberDefault =
|
||||
!isPluginHostProtocol(host.protocol) && protocolOptions.length >= 2;
|
||||
|
||||
const handlePortChange = (protocol: HostProtocol, value: string) => {
|
||||
const port = parseInt(value, 10);
|
||||
@@ -126,9 +172,29 @@ const ProtocolSelectDialog: React.FC<ProtocolSelectDialogProps> = ({
|
||||
};
|
||||
|
||||
const handleContinue = () => {
|
||||
onSelect(selectedProtocol, ports[selectedProtocol] || 22);
|
||||
const fallbackPort =
|
||||
protocolOptions.find((opt) => opt.protocol === selectedProtocol)?.port || 22;
|
||||
onSelect(selectedProtocol, ports[selectedProtocol] || fallbackPort, rememberDefault);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
onCancel();
|
||||
} else if (event.key === "Enter" && !event.isComposing) {
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target?.tagName === "BUTTON") return;
|
||||
event.preventDefault();
|
||||
const fallbackPort =
|
||||
protocolOptions.find((opt) => opt.protocol === selectedProtocol)?.port || 22;
|
||||
onSelect(selectedProtocol, ports[selectedProtocol] || fallbackPort, rememberDefault);
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [onCancel, onSelect, ports, protocolOptions, rememberDefault, selectedProtocol]);
|
||||
|
||||
const hostEndpoint = isPluginHostProtocol(selectedProtocol)
|
||||
? host.hostname
|
||||
: formatHostPort(
|
||||
@@ -237,6 +303,20 @@ const ProtocolSelectDialog: React.FC<ProtocolSelectDialogProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{canRememberDefault && (
|
||||
<div className="px-6 pb-3">
|
||||
<label className="inline-flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground cursor-pointer select-none">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={rememberDefault}
|
||||
onChange={(e) => setRememberDefault(e.target.checked)}
|
||||
className="h-3.5 w-3.5 rounded border border-border accent-primary cursor-pointer"
|
||||
/>
|
||||
<span>{t("protocolSelect.rememberDefault")}</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="px-6 py-4 border-t border-border/50 flex items-center justify-between">
|
||||
<Button variant="secondary" onClick={onCancel}>
|
||||
{t("common.close")}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
ArrowLeft,
|
||||
Building2,
|
||||
ChevronDown,
|
||||
Eye,
|
||||
EyeOff,
|
||||
@@ -23,9 +24,14 @@ import {
|
||||
type QuickConnectAuthMethod,
|
||||
type QuickConnectProtocol,
|
||||
} from "../domain/quickConnectHost";
|
||||
import {
|
||||
formatVncDisplayNumber,
|
||||
parseVncPortOrDisplay,
|
||||
} from "../domain/remoteDesktop";
|
||||
import { cn } from "../lib/utils";
|
||||
import { Host, Identity, SSHKey } from "../types";
|
||||
import { Button } from "./ui/button";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
|
||||
import { Combobox } from "./ui/combobox";
|
||||
import { Input } from "./ui/input";
|
||||
import { Label } from "./ui/label";
|
||||
@@ -49,6 +55,8 @@ const QUICK_CONNECT_PROTOCOLS: ReadonlyArray<{
|
||||
defaultPort: number;
|
||||
}> = [
|
||||
{ protocol: "ssh", label: "SSH", commandPrefix: "ssh", defaultPort: 22 },
|
||||
{ protocol: "rdp", label: "RDP", commandPrefix: "rdp://", defaultPort: 3389 },
|
||||
{ protocol: "vnc", label: "VNC", commandPrefix: "vnc://", defaultPort: 5900 },
|
||||
{ protocol: "mosh", label: "Mosh", commandPrefix: "mosh", defaultPort: 22 },
|
||||
{ protocol: "et", label: "Eternal Terminal", commandPrefix: "et", defaultPort: 22 },
|
||||
{ protocol: "telnet", label: "Telnet", commandPrefix: "telnet", defaultPort: 23 },
|
||||
@@ -84,10 +92,17 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
// Wizard state
|
||||
const initialProtocol: QuickConnectProtocol = target.protocol ?? "ssh";
|
||||
const [step, setStep] = useState<WizardStep>("protocol");
|
||||
const [protocol, setProtocol] = useState<QuickConnectProtocol>("ssh");
|
||||
const [protocol, setProtocol] = useState<QuickConnectProtocol>(initialProtocol);
|
||||
const [username, setUsername] = useState(target.username || "");
|
||||
const [port, setPort] = useState<number>(target.port || 22);
|
||||
const [domain, setDomain] = useState(target.domain || "");
|
||||
const [port, setPort] = useState<number>(
|
||||
target.port || getQuickConnectDefaultPort(initialProtocol),
|
||||
);
|
||||
const [vncUsernameOpen, setVncUsernameOpen] = useState<boolean>(
|
||||
Boolean(target.username),
|
||||
);
|
||||
|
||||
// Known host verification state
|
||||
const [knownHostInfo, setKnownHostInfo] = useState<{
|
||||
@@ -110,10 +125,14 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
// Reset state when target changes
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
const nextProto: QuickConnectProtocol = target.protocol ?? "ssh";
|
||||
setStep("protocol");
|
||||
setProtocol("ssh");
|
||||
setProtocol(nextProto);
|
||||
setUsername(target.username || "");
|
||||
setPort(target.port || 22);
|
||||
setDomain(target.domain || "");
|
||||
setPort(target.port || getQuickConnectDefaultPort(nextProto));
|
||||
setVncUsernameOpen(Boolean(target.username));
|
||||
setAuthMethod("password");
|
||||
setPassword("");
|
||||
setSelectedKeyId(null);
|
||||
setSelectedIdentityId(null);
|
||||
@@ -158,6 +177,7 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
if (!identity || !isQuickConnectIdentityCompatible(identity, target)) return;
|
||||
setSelectedIdentityId(identity.id);
|
||||
setUsername(identity.username);
|
||||
if (identity.domain) setDomain(identity.domain);
|
||||
setAuthMethod(identity.authMethod);
|
||||
setPassword("");
|
||||
setSelectedKeyId(identity.keyId || null);
|
||||
@@ -169,6 +189,11 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
if (proto === "telnet") {
|
||||
if (selectedIdentityId) clearSelectedIdentity();
|
||||
setAuthMethod("password");
|
||||
} else if (proto === "rdp" || proto === "vnc") {
|
||||
setAuthMethod("password");
|
||||
if (selectedIdentity && !isQuickConnectIdentityUsable(selectedIdentity, keys, proto)) {
|
||||
clearSelectedIdentity();
|
||||
}
|
||||
}
|
||||
if (port === getQuickConnectDefaultPort(protocol)) {
|
||||
setPort(getQuickConnectDefaultPort(proto));
|
||||
@@ -181,7 +206,12 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
fallbackPort: number,
|
||||
) => {
|
||||
handleProtocolSelect(proto);
|
||||
setPort(parseInt(rawValue) || fallbackPort);
|
||||
if (proto === "vnc") {
|
||||
const parsedVnc = parseVncPortOrDisplay(rawValue);
|
||||
setPort(parsedVnc ?? (parseInt(rawValue, 10) || fallbackPort));
|
||||
return;
|
||||
}
|
||||
setPort(parseInt(rawValue, 10) || fallbackPort);
|
||||
};
|
||||
|
||||
// Navigate to next step
|
||||
@@ -192,6 +222,11 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
handleConnect();
|
||||
break;
|
||||
}
|
||||
// VNC does not require a username; jump directly to auth step
|
||||
if (protocol === "vnc") {
|
||||
setStep("auth");
|
||||
break;
|
||||
}
|
||||
// Always go to username step to let user confirm/edit username
|
||||
setStep("username");
|
||||
break;
|
||||
@@ -217,15 +252,17 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
setStep("username");
|
||||
break;
|
||||
case "auth":
|
||||
// Always go back to username step
|
||||
setStep("username");
|
||||
setStep(protocol === "vnc" ? "protocol" : "username");
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
// Create host and connect
|
||||
const handleConnect = (save = false) => {
|
||||
const effectiveUsername = username || target.username || "root";
|
||||
const isRemoteDesktop = protocol === "rdp" || protocol === "vnc";
|
||||
const effectiveUsername = isRemoteDesktop
|
||||
? (username.trim() || target.username?.trim() || "")
|
||||
: (username || target.username || "root");
|
||||
const effectivePort = port || getQuickConnectDefaultPort(protocol);
|
||||
const now = Date.now();
|
||||
const tempHost = buildQuickConnectHost({
|
||||
@@ -235,7 +272,8 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
protocol,
|
||||
port: effectivePort,
|
||||
username: effectiveUsername,
|
||||
authMethod,
|
||||
domain: protocol === "rdp" ? (domain.trim() || undefined) : undefined,
|
||||
authMethod: isRemoteDesktop ? "password" : authMethod,
|
||||
password,
|
||||
selectedKeyId,
|
||||
selectedIdentityId: selectedIdentity?.id,
|
||||
@@ -261,7 +299,11 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
return true;
|
||||
case "auth":
|
||||
if (selectedIdentity && protocol !== "telnet") return canUseSelectedIdentity;
|
||||
if (authMethod === "password") {
|
||||
if (protocol === "vnc") {
|
||||
// VNC servers may allow passwordless auth (SecurityType None) or password auth.
|
||||
return true;
|
||||
}
|
||||
if (protocol === "rdp" || authMethod === "password") {
|
||||
// Whitespace-only passwords are valid SSH secrets (issue #2036).
|
||||
return password.length > 0;
|
||||
}
|
||||
@@ -308,14 +350,26 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
{visual.icon}
|
||||
</div>
|
||||
<div>
|
||||
<div
|
||||
className={
|
||||
isSelected
|
||||
? PROTOCOL_OPTION_TITLE_SELECTED_CLASS
|
||||
: PROTOCOL_OPTION_TITLE_IDLE_CLASS
|
||||
}
|
||||
>
|
||||
{item.label}
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={
|
||||
isSelected
|
||||
? PROTOCOL_OPTION_TITLE_SELECTED_CLASS
|
||||
: PROTOCOL_OPTION_TITLE_IDLE_CLASS
|
||||
}
|
||||
>
|
||||
{item.label}
|
||||
</span>
|
||||
{(item.protocol === "rdp" || item.protocol === "vnc") && (
|
||||
<span
|
||||
className={cn(
|
||||
"rounded-md border px-1.5 py-0 text-[10px] font-medium leading-4",
|
||||
visual.badge,
|
||||
)}
|
||||
>
|
||||
{item.protocol === "rdp" ? "Remote Desktop" : "RFB Desktop"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={
|
||||
@@ -324,11 +378,18 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
: PROTOCOL_OPTION_SUBTITLE_IDLE_CLASS
|
||||
}
|
||||
>
|
||||
{item.commandPrefix} {target.hostname}
|
||||
{item.commandPrefix.endsWith("://")
|
||||
? `${item.commandPrefix}${target.hostname}`
|
||||
: `${item.commandPrefix} ${target.hostname}`}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{item.protocol === "vnc" && isSelected && formatVncDisplayNumber(port) && (
|
||||
<span className="rounded border border-teal-500/25 bg-teal-500/12 px-1.5 py-0.5 text-[11px] font-mono font-medium text-teal-600 dark:text-teal-400">
|
||||
{formatVncDisplayNumber(port)}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground">{t("protocolSelect.port")}</span>
|
||||
<Input
|
||||
type="number"
|
||||
@@ -337,7 +398,7 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
handleProtocolPortChange(item.protocol, e.target.value, item.defaultPort)
|
||||
}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="w-16 h-7 text-xs text-center"
|
||||
className="w-[78px] h-7 px-1.5 text-xs text-center font-mono tabular-nums [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
|
||||
min={1}
|
||||
max={65535}
|
||||
/>
|
||||
@@ -375,7 +436,10 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
const renderUsernameStep = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="quick-username">{t("terminal.auth.username")}</Label>
|
||||
<Label htmlFor="quick-username" className="inline-flex items-center gap-1.5">
|
||||
<User size={13} className="text-muted-foreground" />
|
||||
{t("terminal.auth.username")}
|
||||
</Label>
|
||||
<Input
|
||||
id="quick-username"
|
||||
value={username}
|
||||
@@ -383,7 +447,11 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
if (selectedIdentityId) detachSelectedIdentity();
|
||||
setUsername(e.target.value);
|
||||
}}
|
||||
placeholder={t("terminal.auth.username.placeholder")}
|
||||
placeholder={
|
||||
protocol === "rdp"
|
||||
? t("hostDetails.rdp.usernamePlaceholder")
|
||||
: t("terminal.auth.username.placeholder")
|
||||
}
|
||||
autoFocus
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && username.trim()) {
|
||||
@@ -392,6 +460,25 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{protocol === "rdp" && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="quick-domain" className="inline-flex items-center gap-1.5">
|
||||
<Building2 size={13} className="text-muted-foreground" />
|
||||
{t("quickConnect.rdp.domain")}
|
||||
</Label>
|
||||
<Input
|
||||
id="quick-domain"
|
||||
value={domain}
|
||||
onChange={(e) => setDomain(e.target.value)}
|
||||
placeholder={t("quickConnect.rdp.domainPlaceholder")}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && username.trim()) {
|
||||
handleContinue();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -445,7 +532,8 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Auth method tabs */}
|
||||
{/* Auth method tabs — hidden for RDP/VNC (password-only) */}
|
||||
{protocol !== "rdp" && protocol !== "vnc" && (
|
||||
<div className="flex gap-1 p-1 bg-secondary/80 rounded-lg border border-border/60">
|
||||
<button
|
||||
type="button"
|
||||
@@ -484,39 +572,77 @@ const QuickConnectWizard: React.FC<QuickConnectWizardProps> = ({
|
||||
{t("terminal.auth.sshKey")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Password field */}
|
||||
{authMethod === "password" && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="quick-password">{t("terminal.auth.passwordLabel")}</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="quick-password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder={t("terminal.auth.password.placeholder")}
|
||||
className="pr-10"
|
||||
autoFocus
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && password.length > 0) {
|
||||
handleConnect();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
>
|
||||
{showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
|
||||
</button>
|
||||
{(authMethod === "password" || protocol === "rdp" || protocol === "vnc") && (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="quick-password">{t("terminal.auth.passwordLabel")}</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="quick-password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder={t("terminal.auth.password.placeholder")}
|
||||
className="pr-10"
|
||||
autoFocus
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && (protocol === "vnc" || password.length > 0)) {
|
||||
handleConnect();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
>
|
||||
{showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
|
||||
</button>
|
||||
</div>
|
||||
{protocol === "vnc" && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("quickConnect.vnc.passwordHint")}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{protocol === "vnc" && (
|
||||
<Collapsible open={vncUsernameOpen} onOpenChange={setVncUsernameOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="group w-full justify-between px-2 h-8 text-xs text-muted-foreground"
|
||||
>
|
||||
<span>{t("quickConnect.vnc.optionalUsername")}</span>
|
||||
<ChevronDown
|
||||
size={14}
|
||||
className="group-data-[state=open]:rotate-180 transition-transform"
|
||||
/>
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="pt-2 space-y-1.5">
|
||||
<Input
|
||||
id="quick-vnc-username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder={t("hostDetails.vnc.usernamePlaceholder")}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("quickConnect.vnc.optionalUsernameHint")}
|
||||
</p>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Key selection */}
|
||||
{authMethod === "key" && (
|
||||
{protocol !== "rdp" && protocol !== "vnc" && authMethod === "key" && (
|
||||
<div className="space-y-2">
|
||||
{keys.filter((k) => k.category === "key").length === 0 ? (
|
||||
<div className="text-sm text-muted-foreground p-3 border border-dashed border-border/60 rounded-lg text-center">
|
||||
|
||||
@@ -12,11 +12,19 @@ import {
|
||||
} from "lucide-react";
|
||||
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useI18n } from "../application/i18n/I18nProvider";
|
||||
import { RdpProtocolIcon, VncProtocolIcon } from "./icons/RemoteDesktopIcons";
|
||||
import { Host, TerminalSession, TerminalSettings, Workspace } from "../types";
|
||||
import { KeyBinding } from "../domain/models";
|
||||
import type { PaneMagnificationState } from "../domain/paneMagnification";
|
||||
import { isSwitcherQuickConnectInput } from "../domain/quickConnect";
|
||||
import {
|
||||
hasCompanionRdp,
|
||||
hasCompanionVnc,
|
||||
isRdpProtocol,
|
||||
isVncProtocol,
|
||||
} from "../domain/remoteDesktop";
|
||||
import { matchesSearchQuery } from "../domain/searchMatcher";
|
||||
import { getProtocolBadgeClass } from "./protocolVisuals";
|
||||
import { buildQuickSwitcherShells, useDiscoveredShells, getShellIconPath, isMonochromeShellIcon } from "../lib/useDiscoveredShells";
|
||||
import { usePluginContributions } from "../application/state/usePluginContributions";
|
||||
import { requestOpenPluginView } from "./plugins/PluginContributionHost";
|
||||
@@ -606,6 +614,12 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
|
||||
const rowClass = `flex h-full min-h-0 items-center gap-3 overflow-hidden px-4 py-2.5 cursor-pointer transition-colors ${getQuickSwitcherRowStateClass(isSelected, isKeyboardNavigating)}`;
|
||||
|
||||
if (item.type === "quick-connect") {
|
||||
const lowerInput = (item.quickConnectInput || "").toLowerCase();
|
||||
const qcProto = lowerInput.startsWith("rdp://")
|
||||
? "rdp"
|
||||
: lowerInput.startsWith("vnc://")
|
||||
? "vnc"
|
||||
: null;
|
||||
return (
|
||||
<div
|
||||
className={rowClass}
|
||||
@@ -615,6 +629,14 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
|
||||
<Zap className="h-3 w-3" fill="currentColor" />
|
||||
</div>
|
||||
<span className="min-w-0 truncate text-sm font-medium">{item.title}</span>
|
||||
{qcProto && (
|
||||
<span
|
||||
className={`ml-auto inline-flex items-center gap-1 shrink-0 rounded-md border px-1.5 py-0 text-[10px] font-semibold leading-4 ${getProtocolBadgeClass(qcProto)}`}
|
||||
>
|
||||
{qcProto === "rdp" ? <RdpProtocolIcon size={10} /> : <VncProtocolIcon size={10} />}
|
||||
{qcProto.toUpperCase()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -633,6 +655,38 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
|
||||
size="sm"
|
||||
/>
|
||||
<span className="truncate text-sm font-medium">{host.label}</span>
|
||||
{isRdpProtocol(host.protocol) && (
|
||||
<span
|
||||
className={`inline-flex items-center gap-0.5 shrink-0 rounded-md border px-1.5 py-0 text-[10px] font-semibold leading-4 ${getProtocolBadgeClass("rdp")}`}
|
||||
>
|
||||
<RdpProtocolIcon size={10} />
|
||||
RDP
|
||||
</span>
|
||||
)}
|
||||
{isVncProtocol(host.protocol) && (
|
||||
<span
|
||||
className={`inline-flex items-center gap-0.5 shrink-0 rounded-md border px-1.5 py-0 text-[10px] font-semibold leading-4 ${getProtocolBadgeClass("vnc")}`}
|
||||
>
|
||||
<VncProtocolIcon size={10} />
|
||||
VNC
|
||||
</span>
|
||||
)}
|
||||
{hasCompanionRdp(host) && (
|
||||
<span
|
||||
className={`inline-flex items-center gap-0.5 shrink-0 rounded-md border px-1.5 py-0 text-[10px] font-semibold leading-4 ${getProtocolBadgeClass("rdp")}`}
|
||||
>
|
||||
<RdpProtocolIcon size={10} />
|
||||
+RDP
|
||||
</span>
|
||||
)}
|
||||
{hasCompanionVnc(host) && (
|
||||
<span
|
||||
className={`inline-flex items-center gap-0.5 shrink-0 rounded-md border px-1.5 py-0 text-[10px] font-semibold leading-4 ${getProtocolBadgeClass("vnc")}`}
|
||||
>
|
||||
<VncProtocolIcon size={10} />
|
||||
+VNC
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="ml-3 max-w-[12rem] shrink-0 truncate text-[11px] text-muted-foreground">
|
||||
{host.group ? `Personal / ${host.group}` : "Personal"}
|
||||
@@ -676,6 +730,8 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
|
||||
);
|
||||
}
|
||||
const session = item.data as TerminalSession | undefined;
|
||||
const sessionIsRdp = isRdpProtocol(session?.protocol);
|
||||
const sessionIsVnc = isVncProtocol(session?.protocol);
|
||||
return (
|
||||
<div
|
||||
className={rowClass}
|
||||
@@ -684,12 +740,42 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
<div className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground">
|
||||
<TerminalSquare size={16} />
|
||||
<div
|
||||
className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-md ${
|
||||
sessionIsRdp
|
||||
? "bg-blue-500/12 text-blue-500"
|
||||
: sessionIsVnc
|
||||
? "bg-teal-500/12 text-teal-500"
|
||||
: "text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{sessionIsRdp ? (
|
||||
<RdpProtocolIcon size={15} />
|
||||
) : sessionIsVnc ? (
|
||||
<VncProtocolIcon size={15} />
|
||||
) : (
|
||||
<TerminalSquare size={16} />
|
||||
)}
|
||||
</div>
|
||||
<span className="min-w-0 truncate text-sm font-medium">
|
||||
{session?.hostLabel ?? item.id}
|
||||
</span>
|
||||
{sessionIsRdp && (
|
||||
<span
|
||||
className={`ml-auto inline-flex items-center gap-0.5 shrink-0 rounded-md border px-1.5 py-0 text-[10px] font-semibold leading-4 ${getProtocolBadgeClass("rdp")}`}
|
||||
>
|
||||
<RdpProtocolIcon size={10} />
|
||||
RDP
|
||||
</span>
|
||||
)}
|
||||
{sessionIsVnc && (
|
||||
<span
|
||||
className={`ml-auto inline-flex items-center gap-0.5 shrink-0 rounded-md border px-1.5 py-0 text-[10px] font-semibold leading-4 ${getProtocolBadgeClass("vnc")}`}
|
||||
>
|
||||
<VncProtocolIcon size={10} />
|
||||
VNC
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -688,6 +688,8 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
|
||||
setSshDeepLinkEnabled={settings.setSshDeepLinkEnabled}
|
||||
jmsDeepLinkEnabled={settings.jmsDeepLinkEnabled}
|
||||
setJmsDeepLinkEnabled={settings.setJmsDeepLinkEnabled}
|
||||
jumpServerRdpLaunchMode={settings.jumpServerRdpLaunchMode}
|
||||
setJumpServerRdpLaunchMode={settings.setJumpServerRdpLaunchMode}
|
||||
explorerContextMenuEnabled={settings.explorerContextMenuEnabled}
|
||||
setExplorerContextMenuEnabled={settings.setExplorerContextMenuEnabled}
|
||||
explorerContextMenuSupported={settings.explorerContextMenuSupported}
|
||||
|
||||
@@ -22,6 +22,11 @@ import {
|
||||
import { createPromptHostnameSessionSignalController } from '../application/state/promptHostnameSessionSignalController';
|
||||
import { collectSessionIds } from '../domain/workspace';
|
||||
import { isPluginHostProtocol } from '../domain/pluginConnection';
|
||||
import {
|
||||
isRemoteDesktopProtocol,
|
||||
sanitizeRdpConfig,
|
||||
sanitizeVncConfig,
|
||||
} from '../domain/remoteDesktop';
|
||||
import { isSameSftpHostSelection } from '../domain/sftpTerminalIdentity';
|
||||
|
||||
import { cn, normalizeLineEndings } from '../lib/utils';
|
||||
@@ -146,6 +151,10 @@ import {
|
||||
} from '../application/state/terminalSidePanelWidth';
|
||||
import { isSidePanelDockPosition } from '../domain/sidePanelLayout';
|
||||
|
||||
import {
|
||||
dispatchAddRemoteScreenToAI,
|
||||
type RemoteDesktopScreenshotDraftPayload,
|
||||
} from './ai/remoteDesktopAiDraft';
|
||||
import {
|
||||
AIChatPanelsHost,
|
||||
AISidePanelStateRoot,
|
||||
@@ -153,6 +162,8 @@ import {
|
||||
AIStateProvider,
|
||||
ChunkedEscapeFilter,
|
||||
clearHostTreePreviewVars,
|
||||
enqueuePendingRemoteScreenForAI,
|
||||
publishRemoteDesktopLayerBridge,
|
||||
TerminalPanesHost,
|
||||
clearTerminalPreviewVars,
|
||||
clearTopTabsPreviewVars,
|
||||
@@ -263,6 +274,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
onCopySessionToNewWindow,
|
||||
onSplitSession,
|
||||
onConnectToHost,
|
||||
onConnectRemoteDesktop,
|
||||
onCreateLocalTerminal,
|
||||
isBroadcastEnabled,
|
||||
onToggleBroadcast,
|
||||
@@ -1303,6 +1315,38 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
const sessionHostsMap = useMemo(() => {
|
||||
const map = new Map<string, Host>();
|
||||
for (const session of sessions) {
|
||||
if (session.remoteDesktopCompanion === true && isRemoteDesktopProtocol(session.protocol)) {
|
||||
const vaultHost = hosts.find((candidate) => candidate.id === session.hostId);
|
||||
if (vaultHost) {
|
||||
const effectiveVaultHost = resolveEffectiveTerminalHost({
|
||||
host: vaultHost,
|
||||
groupConfigs,
|
||||
proxyProfiles,
|
||||
validProxyProfileIds: proxyProfileIdSet,
|
||||
defaultLocalShell,
|
||||
});
|
||||
const mergedRdp = session.protocol === 'rdp'
|
||||
? sanitizeRdpConfig({
|
||||
...(effectiveVaultHost.rdpConfig ?? {}),
|
||||
...(session.rdpConfig ?? {}),
|
||||
...(session.port ? { port: session.port } : {}),
|
||||
})
|
||||
: undefined;
|
||||
const mergedVnc = session.protocol === 'vnc'
|
||||
? sanitizeVncConfig({
|
||||
...(effectiveVaultHost.vncConfig ?? {}),
|
||||
...(session.vncConfig ?? {}),
|
||||
...(session.port ? { port: session.port } : {}),
|
||||
})
|
||||
: undefined;
|
||||
map.set(session.id, {
|
||||
...effectiveVaultHost,
|
||||
...(mergedRdp ? { rdpConfig: mergedRdp } : {}),
|
||||
...(mergedVnc ? { vncConfig: mergedVnc } : {}),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const hostForSession = resolveTerminalSessionHost({
|
||||
session,
|
||||
hosts,
|
||||
@@ -1314,7 +1358,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
map.set(session.id, applySessionFontSizeToHost(hostForSession, session));
|
||||
}
|
||||
return map;
|
||||
}, [sessions, hosts, groupConfigs, proxyProfiles, defaultLocalShell]);
|
||||
}, [sessions, hosts, groupConfigs, proxyProfiles, proxyProfileIdSet, defaultLocalShell]);
|
||||
const resolvedSessionHostIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const session of sessions) {
|
||||
@@ -1356,7 +1400,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
&& (passwordBypass || !isTerminalSensitiveInputActive(target.sessionId)));
|
||||
}
|
||||
const targetSessionIds = resolveTerminalBroadcastTargetIds({
|
||||
sessions: sessionsRef.current,
|
||||
sessions: sessionsRef.current.filter((session) => !isRemoteDesktopProtocol(session.protocol)),
|
||||
sourceSessionId,
|
||||
globalBroadcastEnabled: isGlobalBroadcastEnabled,
|
||||
directTargetSessionIds: options?.kittyKeyboardTargetSessionIds,
|
||||
@@ -2261,6 +2305,34 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
handleSwitchSidePanelTab('ai');
|
||||
}, [handleSwitchSidePanelTab]);
|
||||
|
||||
const handleAddRemoteScreenToAI = useCallback(
|
||||
(sourceSessionId: string, payload: RemoteDesktopScreenshotDraftPayload | null) => {
|
||||
const ws = activeWorkspaceRef.current;
|
||||
if (ws && ws.focusedSessionId !== sourceSessionId) {
|
||||
onSetWorkspaceFocusedSessionRef.current?.(ws.id, sourceSessionId);
|
||||
}
|
||||
if (payload) {
|
||||
const enriched: RemoteDesktopScreenshotDraftPayload = {
|
||||
...payload,
|
||||
workspaceId: payload.workspaceId ?? ws?.id,
|
||||
};
|
||||
enqueuePendingRemoteScreenForAI(enriched);
|
||||
handleSwitchSidePanelTab('ai');
|
||||
dispatchAddRemoteScreenToAI(enriched);
|
||||
return;
|
||||
}
|
||||
handleSwitchSidePanelTab('ai');
|
||||
},
|
||||
[handleSwitchSidePanelTab],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
publishRemoteDesktopLayerBridge({
|
||||
sidePanelOpenTabs,
|
||||
onAddRemoteScreenToAI: handleAddRemoteScreenToAI,
|
||||
});
|
||||
}, [handleAddRemoteScreenToAI, sidePanelOpenTabs]);
|
||||
|
||||
const handlePendingTerminalSelectionConsumed = useCallback((requestId: string) => {
|
||||
setPendingTerminalSelectionForAI((current) => (
|
||||
current?.requestId === requestId ? null : current
|
||||
@@ -2593,7 +2665,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
|
||||
if (composeSendToAll && (broadcastPasswordBypass || !focusedSensitive)) {
|
||||
const allSessionIds = sessionsRef.current
|
||||
.filter((session) => session.workspaceId === activeWorkspace.id)
|
||||
.filter((session) => session.workspaceId === activeWorkspace.id && !isRemoteDesktopProtocol(session.protocol))
|
||||
.map((session) => session.id);
|
||||
for (const sid of allSessionIds) {
|
||||
const recipientSensitive = isTerminalSensitiveInputActive(sid);
|
||||
@@ -2631,7 +2703,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const workspaceSessions = sessionsRef.current.filter((session) => session.workspaceId === activeWorkspace.id);
|
||||
const workspaceSessions = sessionsRef.current.filter(
|
||||
(session) => session.workspaceId === activeWorkspace.id && !isRemoteDesktopProtocol(session.protocol),
|
||||
);
|
||||
const validFocusedId = focusedSessionId && workspaceSessions.some((session) => session.id === focusedSessionId)
|
||||
? focusedSessionId
|
||||
: undefined;
|
||||
@@ -2818,6 +2892,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
onAddSessionToWorkspace,
|
||||
onMoveWorkspacePane,
|
||||
onConnectToHost,
|
||||
onConnectRemoteDesktop,
|
||||
onCreateLocalTerminal,
|
||||
onCreateWorkspaceFromSessions,
|
||||
onHotkeyAction,
|
||||
|
||||
@@ -12,8 +12,18 @@ import {
|
||||
} from '../application/state/resolveTerminalSessionExitIntent';
|
||||
import { upsertKnownHost } from '../domain/knownHosts';
|
||||
import { isPluginHostProtocol, sanitizePluginConnection } from '../domain/pluginConnection';
|
||||
import {
|
||||
isRemoteDesktopProtocol,
|
||||
sanitizeRdpConfig,
|
||||
sanitizeVncConfig,
|
||||
type RemoteDesktopProtocol,
|
||||
} from '../domain/remoteDesktop';
|
||||
import type { ResolveDefaultLocalShellContext } from '../domain/localShellHost';
|
||||
import { resolveTerminalChainHosts, resolveTerminalSessionHost } from '../domain/terminalHostResolution';
|
||||
import {
|
||||
resolveEffectiveTerminalHost,
|
||||
resolveTerminalChainHosts,
|
||||
resolveTerminalSessionHost,
|
||||
} from '../domain/terminalHostResolution';
|
||||
import type { TerminalPopupPayload } from '../domain/systemManager/types';
|
||||
import type { GroupConfig, Host, ProxyProfile, TerminalTheme } from '../domain/models';
|
||||
import type { KnownHost } from '../types';
|
||||
@@ -25,6 +35,7 @@ import type { AppLockGateRenderContext } from './AppLockGate';
|
||||
import { PluginAuthenticationHost } from './plugins/PluginAuthenticationHost';
|
||||
|
||||
const Terminal = lazy(() => import('./Terminal'));
|
||||
const LazyRemoteDesktopPane = lazy(() => import('./remoteDesktop/RemoteDesktopPane'));
|
||||
|
||||
const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);
|
||||
const POPUP_STARTUP_REVEAL_EXTRA_DELAY_MS = 900;
|
||||
@@ -193,6 +204,7 @@ function resolveHostProtocolFromSourceSession(
|
||||
if (
|
||||
source.protocol === 'local' ||
|
||||
source.protocol === 'telnet' ||
|
||||
isRemoteDesktopProtocol(source.protocol) ||
|
||||
isPluginHostProtocol(source.protocol) ||
|
||||
(attachExistingSession && source.protocol === 'serial')
|
||||
) {
|
||||
@@ -206,28 +218,77 @@ function applySourceSessionConnectionOverrides(
|
||||
source: TerminalPopupPayload['sourceSession'],
|
||||
attachExistingSession: boolean,
|
||||
): Host {
|
||||
// Companion RDP/VNC sessions tunnel over the underlying SSH host; preserve
|
||||
// the host's primary protocol, SSH port, and SSH credentials while merging
|
||||
// sanitized companion desktop config from the source session.
|
||||
if (source.remoteDesktopCompanion === true && isRemoteDesktopProtocol(source.protocol)) {
|
||||
const companionProtocol = source.protocol;
|
||||
const mergedRdp = companionProtocol === 'rdp'
|
||||
? sanitizeRdpConfig({
|
||||
...(host.rdpConfig ?? {}),
|
||||
...(source.rdpConfig ?? {}),
|
||||
...(source.port ? { port: source.port } : {}),
|
||||
})
|
||||
: undefined;
|
||||
const mergedVnc = companionProtocol === 'vnc'
|
||||
? sanitizeVncConfig({
|
||||
...(host.vncConfig ?? {}),
|
||||
...(source.vncConfig ?? {}),
|
||||
...(source.port ? { port: source.port } : {}),
|
||||
})
|
||||
: undefined;
|
||||
const baseProtocol = isRemoteDesktopProtocol(host.protocol) ? 'ssh' : (host.protocol ?? 'ssh');
|
||||
return {
|
||||
...host,
|
||||
protocol: baseProtocol,
|
||||
...(mergedRdp ? { rdpConfig: mergedRdp } : {}),
|
||||
...(mergedVnc ? { vncConfig: mergedVnc } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const protocol = resolveHostProtocolFromSourceSession(source, attachExistingSession);
|
||||
const pluginConnection = isPluginHostProtocol(protocol)
|
||||
? sanitizePluginConnection(source.pluginConnection, protocol)
|
||||
?? sanitizePluginConnection(host.pluginConnection, protocol)
|
||||
: undefined;
|
||||
const rdpConfig = protocol === 'rdp'
|
||||
? (sanitizeRdpConfig(source.rdpConfig) ?? sanitizeRdpConfig(host.rdpConfig))
|
||||
: undefined;
|
||||
const vncConfig = protocol === 'vnc'
|
||||
? (sanitizeVncConfig(source.vncConfig) ?? sanitizeVncConfig(host.vncConfig))
|
||||
: undefined;
|
||||
const { pluginConnection: _pluginConnection, ...baseHost } = host;
|
||||
return {
|
||||
...baseHost,
|
||||
hostname: source.hostname || host.hostname,
|
||||
username: source.username || host.username,
|
||||
username: source.username ?? host.username,
|
||||
port: source.port ?? (protocol === 'local' ? undefined : host.port),
|
||||
protocol,
|
||||
moshEnabled: source.moshEnabled === true,
|
||||
etEnabled: source.etEnabled === true,
|
||||
charset: source.charset ?? host.charset,
|
||||
...(pluginConnection ? { pluginConnection } : {}),
|
||||
...(rdpConfig ? { rdpConfig } : {}),
|
||||
...(vncConfig ? { vncConfig } : {}),
|
||||
...(protocol === 'serial' && source.serialConfig
|
||||
? { serialConfig: source.serialConfig }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveTerminalPopupRemoteDesktopProtocol(
|
||||
config: Pick<TerminalPopupPayload, 'sourceSession'> | null | undefined,
|
||||
host: Pick<Host, 'protocol'> | null | undefined,
|
||||
): RemoteDesktopProtocol | null {
|
||||
if (isRemoteDesktopProtocol(config?.sourceSession?.protocol)) {
|
||||
return config.sourceSession.protocol;
|
||||
}
|
||||
if (isRemoteDesktopProtocol(host?.protocol)) {
|
||||
return host.protocol;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveTerminalPopupHost(
|
||||
config: TerminalPopupPayload,
|
||||
hosts: Host[],
|
||||
@@ -238,8 +299,25 @@ export function resolveTerminalPopupHost(
|
||||
defaultLocalShell?: ResolveDefaultLocalShellContext;
|
||||
} = {},
|
||||
): Host {
|
||||
const source = config.sourceSession;
|
||||
if (source.remoteDesktopCompanion === true && isRemoteDesktopProtocol(source.protocol)) {
|
||||
const vaultHost = hosts.find((candidate) => candidate.id === source.hostId);
|
||||
if (vaultHost) {
|
||||
const effectiveVaultHost = resolveEffectiveTerminalHost({
|
||||
host: vaultHost,
|
||||
groupConfigs: options.groupConfigs ?? [],
|
||||
proxyProfiles: options.proxyProfiles ?? [],
|
||||
defaultLocalShell: options.defaultLocalShell,
|
||||
});
|
||||
return applySourceSessionConnectionOverrides(
|
||||
effectiveVaultHost,
|
||||
source,
|
||||
Boolean(config.attachSessionId),
|
||||
);
|
||||
}
|
||||
}
|
||||
const resolvedHost = resolveTerminalSessionHost({
|
||||
session: config.sourceSession,
|
||||
session: source,
|
||||
hosts,
|
||||
groupConfigs: options.groupConfigs ?? [],
|
||||
proxyProfiles: options.proxyProfiles ?? [],
|
||||
@@ -248,7 +326,7 @@ export function resolveTerminalPopupHost(
|
||||
});
|
||||
return applySourceSessionConnectionOverrides(
|
||||
resolvedHost,
|
||||
config.sourceSession,
|
||||
source,
|
||||
Boolean(config.attachSessionId),
|
||||
);
|
||||
}
|
||||
@@ -394,6 +472,11 @@ function TerminalPopupPageInner({
|
||||
return resolveTerminalPopupReuseId(config);
|
||||
}, [config]);
|
||||
|
||||
const remoteDesktopProtocol = useMemo(
|
||||
() => resolveTerminalPopupRemoteDesktopProtocol(config, host),
|
||||
[config, host],
|
||||
);
|
||||
|
||||
// Defer *first* backend start while app-locked so startup commands/credentials
|
||||
// do not run behind the overlay. Once a session has started, keep it mounted
|
||||
// across re-locks so the popup is not torn down mid-session (Codex P2).
|
||||
@@ -466,6 +549,25 @@ function TerminalPopupPageInner({
|
||||
closeLabel={t('common.close')}
|
||||
onClose={() => void handleClose()}
|
||||
/>
|
||||
) : remoteDesktopProtocol ? (
|
||||
<div className="relative flex-1 min-h-0 flex flex-col bg-black">
|
||||
<Suspense fallback={<TerminalPopupBlank />}>
|
||||
<LazyRemoteDesktopPane
|
||||
sessionId={sessionId}
|
||||
protocol={remoteDesktopProtocol}
|
||||
host={host}
|
||||
chainHosts={chainHosts}
|
||||
keys={keys}
|
||||
identities={identities}
|
||||
knownHosts={effectiveKnownHosts}
|
||||
isVisible
|
||||
isFocused
|
||||
onCloseSession={() => {
|
||||
void handleClose();
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
</div>
|
||||
) : (
|
||||
<div className="relative flex-1 min-h-0 flex flex-col bg-[color:var(--terminal-popup-bg)]">
|
||||
<Suspense fallback={<TerminalPopupBlank />}>
|
||||
|
||||
+72
-18
@@ -16,11 +16,13 @@ import {
|
||||
Key,
|
||||
LayoutGrid,
|
||||
List,
|
||||
Monitor,
|
||||
Network,
|
||||
NotebookText,
|
||||
Pin,
|
||||
Plug,
|
||||
Plus,
|
||||
ScreenShare,
|
||||
Search,
|
||||
Settings,
|
||||
Square,
|
||||
@@ -74,6 +76,11 @@ import {
|
||||
sanitizeHost,
|
||||
upsertHostById,
|
||||
} from "../domain/host";
|
||||
import {
|
||||
applyHostDefaultConnectProtocol,
|
||||
buildHostForProtocolOverride,
|
||||
shouldPromptHostProtocolOnConnect,
|
||||
} from "../domain/remoteDesktop";
|
||||
import { exportHostsToCsvWithStats } from "../domain/vaultImport";
|
||||
import { saveWorkSurfaceHostDraft, type WorkSurfaceHostEditorTarget } from "../application/state/useWorkSurfaceHostEditor";
|
||||
import { upsertKnownHost } from "../domain/knownHosts";
|
||||
@@ -243,6 +250,8 @@ interface VaultViewProps {
|
||||
) => void;
|
||||
onDeleteHost: (id: string) => void;
|
||||
onConnect: (host: Host) => void;
|
||||
onConnectRemoteDesktop?: (host: Host, protocol: "vnc" | "rdp") => void;
|
||||
onOpenSystemRemoteDesktop?: (host: Host, protocol: "vnc" | "rdp") => void;
|
||||
onOpenHostFromNote?: (host: Host, source?: { noteId: string }) => void;
|
||||
onUpdateHosts: (
|
||||
hosts: Host[] | ((prev: Host[]) => Host[]),
|
||||
@@ -332,6 +341,8 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
onConnectSerial,
|
||||
onDeleteHost,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onOpenSystemRemoteDesktop,
|
||||
onOpenHostFromNote,
|
||||
onUpdateHosts,
|
||||
onReadPersistedHosts,
|
||||
@@ -466,6 +477,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
// Host panel state (local to hosts section)
|
||||
const [isHostPanelOpen, setIsHostPanelOpen] = useState(false);
|
||||
const [editingHost, setEditingHost] = useState<Host | null>(null);
|
||||
const [newHostProtocol, setNewHostProtocol] = useState<"ssh" | "rdp" | "vnc">("ssh");
|
||||
const [newHostGroupPath, setNewHostGroupPath] = useState<string | null>(null);
|
||||
// Local shell (CMD) host panel state — a vault host entry with protocol 'local'
|
||||
const [isLocalShellHostPanelOpen, setIsLocalShellHostPanelOpen] = useState(false);
|
||||
@@ -626,12 +638,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
{},
|
||||
{ validProxyProfileIds: proxyProfileIdSet },
|
||||
);
|
||||
// Only prompt when Telnet is available but isn't the host's default
|
||||
// protocol, and only for SSH hosts: local-shell and serial hosts must
|
||||
// always launch their own transport, never an inherited group Telnet
|
||||
// flag. Hosts without an explicit protocol are legacy SSH entries.
|
||||
const effectiveProtocol = effective.protocol ?? "ssh";
|
||||
if (effectiveProtocol === "ssh" && effective.telnetEnabled) {
|
||||
if (shouldPromptHostProtocolOnConnect(effective)) {
|
||||
setProtocolSelectHost(effective);
|
||||
} else if (effective.protocol === "telnet") {
|
||||
// Telnet-as-default wins over a stray moshEnabled flag.
|
||||
@@ -645,20 +652,35 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
|
||||
// Handle protocol selection
|
||||
const handleProtocolSelect = useCallback(
|
||||
(protocol: HostProtocol, port: number) => {
|
||||
(protocol: HostProtocol, port: number, rememberDefault?: boolean) => {
|
||||
if (protocolSelectHost) {
|
||||
const hostWithProtocol: Host = {
|
||||
...protocolSelectHost,
|
||||
protocol: protocol === "mosh" || protocol === "et" ? "ssh" : protocol,
|
||||
port,
|
||||
moshEnabled: protocol === "mosh",
|
||||
etEnabled: protocol === "et",
|
||||
};
|
||||
onConnect(hostWithProtocol);
|
||||
if (
|
||||
rememberDefault &&
|
||||
(protocol === "ssh" ||
|
||||
protocol === "mosh" ||
|
||||
protocol === "et" ||
|
||||
protocol === "rdp" ||
|
||||
protocol === "vnc" ||
|
||||
protocol === "telnet")
|
||||
) {
|
||||
onUpdateHosts(
|
||||
hosts.map((h) =>
|
||||
h.id === protocolSelectHost.id
|
||||
? applyHostDefaultConnectProtocol(h, protocol)
|
||||
: h,
|
||||
),
|
||||
);
|
||||
}
|
||||
const dispatch = buildHostForProtocolOverride(protocolSelectHost, protocol, port);
|
||||
if (dispatch.mode === "remoteDesktop" && onConnectRemoteDesktop) {
|
||||
onConnectRemoteDesktop(dispatch.host, dispatch.protocol);
|
||||
} else {
|
||||
onConnect(dispatch.host);
|
||||
}
|
||||
setProtocolSelectHost(null);
|
||||
}
|
||||
},
|
||||
[protocolSelectHost, onConnect],
|
||||
[protocolSelectHost, onConnect, onConnectRemoteDesktop, onUpdateHosts, hosts],
|
||||
);
|
||||
|
||||
// Handle quick connect
|
||||
@@ -685,6 +707,29 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
setIsGroupPanelOpen(false);
|
||||
setEditingGroupPath(null);
|
||||
setEditingHost(null);
|
||||
setNewHostProtocol("ssh");
|
||||
setIsLocalShellHostPanelOpen(false);
|
||||
setEditingLocalShellHost(null);
|
||||
setNewHostGroupPath(null);
|
||||
setIsHostPanelOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleNewRdpHost = useCallback(() => {
|
||||
setIsGroupPanelOpen(false);
|
||||
setEditingGroupPath(null);
|
||||
setEditingHost(null);
|
||||
setNewHostProtocol("rdp");
|
||||
setIsLocalShellHostPanelOpen(false);
|
||||
setEditingLocalShellHost(null);
|
||||
setNewHostGroupPath(null);
|
||||
setIsHostPanelOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleNewVncHost = useCallback(() => {
|
||||
setIsGroupPanelOpen(false);
|
||||
setEditingGroupPath(null);
|
||||
setEditingHost(null);
|
||||
setNewHostProtocol("vnc");
|
||||
setIsLocalShellHostPanelOpen(false);
|
||||
setEditingLocalShellHost(null);
|
||||
setNewHostGroupPath(null);
|
||||
@@ -897,11 +942,13 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
// Only use telnet-specific port and credentials when protocol is explicitly telnet
|
||||
// Don't treat telnetEnabled as primary - that's just an optional protocol
|
||||
const isTelnet = effective.protocol === "telnet";
|
||||
const isRdp = effective.protocol === "rdp";
|
||||
const isVnc = effective.protocol === "vnc";
|
||||
|
||||
const defaultPort = isTelnet ? 23 : 22;
|
||||
const defaultPort = isTelnet ? 23 : isRdp ? 3389 : isVnc ? 5900 : 22;
|
||||
const effectivePort = isTelnet
|
||||
? resolveTelnetPort(effective)
|
||||
: (effective.port ?? 22);
|
||||
: (effective.port ?? defaultPort);
|
||||
|
||||
// Bracket IPv6 addresses when appending non-default port
|
||||
let address: string;
|
||||
@@ -1571,6 +1618,8 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
handleHostConnect,
|
||||
handleImportFileSelected,
|
||||
handleNewHost,
|
||||
handleNewRdpHost,
|
||||
handleNewVncHost,
|
||||
handleNewLocalShellHost,
|
||||
handleCancelLocalShellHost,
|
||||
handleSaveLocalShellHost,
|
||||
@@ -1618,16 +1667,19 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
List,
|
||||
managedGroupPaths,
|
||||
managedSources,
|
||||
Monitor,
|
||||
moveGroup,
|
||||
moveHostToGroup,
|
||||
moveHostsToGroup,
|
||||
Network,
|
||||
newFolderName,
|
||||
newHostGroupPath,
|
||||
newHostProtocol,
|
||||
NotebookText,
|
||||
NotesManager,
|
||||
onCommitPluginImporterData,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onConnectSerial,
|
||||
onCreateLocalTerminal,
|
||||
onDeleteHost,
|
||||
@@ -1635,6 +1687,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
onOpenHostFromNote,
|
||||
onOpenLogView,
|
||||
onOpenSettings,
|
||||
onOpenSystemRemoteDesktop,
|
||||
onRunSnippet,
|
||||
onUpdateCustomGroups,
|
||||
onUpdateGroupConfigs,
|
||||
@@ -1670,6 +1723,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
RippleButton,
|
||||
rootRef,
|
||||
sanitizeHost,
|
||||
ScreenShare,
|
||||
search,
|
||||
Search,
|
||||
selectedGroupPath,
|
||||
|
||||
+116
-4
@@ -6,7 +6,7 @@
|
||||
* and a bottom toolbar with muted controls + subtle send button.
|
||||
*/
|
||||
|
||||
import { ArrowUp, AtSign, BookOpen, Check, ChevronDown, ChevronRight, Cpu, Eye, FileText, ImageIcon, Loader2, MessageSquare, Package, Plus, ShieldCheck, SquareTerminal, X, Zap } from 'lucide-react';
|
||||
import { AlertTriangle, ArrowUp, AtSign, BookOpen, Check, ChevronDown, ChevronRight, Cpu, Eye, FileText, ImageIcon, Loader2, MessageSquare, Package, Plus, ShieldCheck, Sparkles, SquareTerminal, X, Zap } from 'lucide-react';
|
||||
import {
|
||||
resolveModelSelectionWithThinking,
|
||||
resolveThinkingSelection,
|
||||
@@ -75,6 +75,11 @@ import {
|
||||
resolveVisibleChatInputHeight,
|
||||
resolveVisibleChatInputMaxHeight,
|
||||
} from './chatInputResize';
|
||||
import { resolveModelVisionSupport } from '../../infrastructure/ai/visionCapability';
|
||||
import {
|
||||
isRemoteDesktopScreenshotFile,
|
||||
REMOTE_DESKTOP_QUICK_PROMPTS,
|
||||
} from './remoteDesktopAiDraft';
|
||||
|
||||
const PERMISSION_PICKER_WIDTH = 200;
|
||||
const THINKING_PICKER_WIDTH = 168;
|
||||
@@ -203,7 +208,7 @@ const ComposerSendUi = React.memo(function ComposerSendUi({
|
||||
interface ChatInputProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
onSend: () => void;
|
||||
onSend: (textOverride?: string) => void;
|
||||
onCompact?: () => void;
|
||||
/** When false, hide/ignore `/compact` so the composer is not cleared as a silent no-op. */
|
||||
canCompact?: boolean;
|
||||
@@ -249,7 +254,13 @@ interface ChatInputProps {
|
||||
/** Callback to remove a file */
|
||||
onRemoveFile?: (id: string) => void;
|
||||
/** Available hosts for @ mention */
|
||||
hosts?: Array<{ sessionId: string; hostname: string; label: string; connected: boolean }>;
|
||||
hosts?: Array<{ sessionId: string; hostname: string; label: string; connected: boolean; protocol?: string }>;
|
||||
/** Explicit signal that the active tab/scope is a VNC or RDP remote desktop. */
|
||||
isRemoteDesktopContext?: boolean;
|
||||
/** Optional handler invoked when a remote desktop quick prompt chip is clicked. */
|
||||
onSendQuickPrompt?: (promptText: string) => void;
|
||||
/** Force-show remote desktop quick prompt chips (auto-shown when a remote screen image is attached). */
|
||||
showRemoteScreenQuickPrompts?: boolean;
|
||||
/** Available Vault → Notes entries for the Mention Note picker */
|
||||
notes?: VaultNote[];
|
||||
/** Callback when the user picks a note to attach as context */
|
||||
@@ -322,6 +333,9 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
onAddFiles,
|
||||
onRemoveFile,
|
||||
hosts = [],
|
||||
isRemoteDesktopContext = false,
|
||||
onSendQuickPrompt,
|
||||
showRemoteScreenQuickPrompts,
|
||||
notes = [],
|
||||
onMentionNote,
|
||||
selectedUserSkills = [],
|
||||
@@ -341,7 +355,11 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
onRebindChat,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const hasTerminalSelectionAttachment = files.some((file) => file.terminalSelection || file.vaultNoteId);
|
||||
const hasImageAttachment = files.some((file) => file.mediaType.startsWith('image/'));
|
||||
const hasRemoteScreenAttachment = files.some((file) => isRemoteDesktopScreenshotFile(file));
|
||||
const hasTerminalSelectionAttachment = files.some(
|
||||
(file) => file.terminalSelection || file.vaultNoteId || file.mediaType.startsWith('image/'),
|
||||
);
|
||||
const composerDisabled = disabled || isSteering;
|
||||
const composerTextRef = useRef(value);
|
||||
const hasTextStoreRef = useRef<ComposerHasTextStore | null>(null);
|
||||
@@ -1117,6 +1135,49 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
const popoverMaxWidth = hasProviderSwitcher
|
||||
? COMPOSER_PROVIDER_PICKER_WIDTH
|
||||
: COMPOSER_MODEL_PICKER_WIDTH;
|
||||
const activeVisionProviderId = hasProviderSwitcher
|
||||
? selectedSwitcherProvider?.providerId
|
||||
: undefined;
|
||||
const activeVisionModelId = hasProviderSwitcher
|
||||
? (providerSwitcher?.selectedModelId || selectedSwitcherProvider?.defaultModel)
|
||||
: (selectedBaseModelId || selectedModelId || modelName);
|
||||
const hasRemoteDesktopHostInScope = hosts.some((host) => {
|
||||
const protocol = host.protocol?.toLowerCase();
|
||||
return protocol === 'vnc' || protocol === 'rdp';
|
||||
});
|
||||
const hasVisionContext = hasImageAttachment || isRemoteDesktopContext || hasRemoteDesktopHostInScope;
|
||||
const activeModelVisionSupport = useMemo(
|
||||
() => resolveModelVisionSupport({
|
||||
providerId: activeVisionProviderId,
|
||||
modelId: activeVisionModelId,
|
||||
}),
|
||||
[activeVisionProviderId, activeVisionModelId],
|
||||
);
|
||||
const showVisionWarningBanner = hasVisionContext && activeModelVisionSupport === 'no';
|
||||
const showQuickPromptChips = (showRemoteScreenQuickPrompts ?? hasRemoteScreenAttachment)
|
||||
&& !isStreaming
|
||||
&& !composerDisabled;
|
||||
|
||||
const openModelPickerPopover = useCallback(() => {
|
||||
if (!hasModelPicker || lockTurnConfiguration) return;
|
||||
const rect = modelBtnRef.current?.getBoundingClientRect();
|
||||
if (rect) {
|
||||
const left = Math.max(8, Math.min(rect.left, window.innerWidth - popoverMaxWidth - 8));
|
||||
setMenuPos({ left, bottom: window.innerHeight - rect.top + 6 });
|
||||
}
|
||||
setActiveMenu('model');
|
||||
if (!hasProviderSwitcher) onModelPickerOpen?.();
|
||||
}, [hasModelPicker, hasProviderSwitcher, lockTurnConfiguration, onModelPickerOpen, popoverMaxWidth]);
|
||||
|
||||
const handleQuickPromptClick = useCallback((promptText: string) => {
|
||||
if (composerDisabled || isStreaming) return;
|
||||
if (onSendQuickPrompt) {
|
||||
onSendQuickPrompt(promptText);
|
||||
return;
|
||||
}
|
||||
commitComposerText(promptText);
|
||||
onSend(promptText);
|
||||
}, [commitComposerText, composerDisabled, isStreaming, onSend, onSendQuickPrompt]);
|
||||
const contextUsagePercent = contextUsage
|
||||
? Math.min(100, Math.max(0, (contextUsage.inputTokens / contextUsage.contextWindow) * 100))
|
||||
: 0;
|
||||
@@ -1141,6 +1202,48 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
|
||||
return (
|
||||
<div className="shrink-0 px-4 pb-4">
|
||||
{showVisionWarningBanner && (
|
||||
<div
|
||||
role="status"
|
||||
data-testid="ai-vision-model-warning"
|
||||
className="mb-2 flex items-center gap-2 rounded-md border border-amber-500/30 bg-amber-500/10 px-2.5 py-1.5 text-[11px] leading-4 text-amber-600 dark:text-amber-400"
|
||||
>
|
||||
<AlertTriangle size={12} className="shrink-0 text-amber-500" aria-hidden="true" />
|
||||
<span className="min-w-0 flex-1">
|
||||
{t('ai.vision.unsupportedModelWarning').replace('{model}', activeVisionModelId || modelLabel)}
|
||||
</span>
|
||||
{hasModelPicker && !lockTurnConfiguration && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={openModelPickerPopover}
|
||||
className="shrink-0 rounded px-1.5 py-0.5 text-[11px] font-medium text-amber-700 underline-offset-2 transition-colors hover:bg-amber-500/15 hover:underline cursor-pointer dark:text-amber-300"
|
||||
>
|
||||
{t('ai.vision.switchModel')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{showQuickPromptChips && (
|
||||
<div
|
||||
data-testid="ai-remote-screen-quick-prompts"
|
||||
className="mb-1.5 flex flex-wrap items-center gap-1.5"
|
||||
>
|
||||
{REMOTE_DESKTOP_QUICK_PROMPTS.map((chip) => {
|
||||
const label = t(chip.labelKey);
|
||||
return (
|
||||
<button
|
||||
key={chip.id}
|
||||
type="button"
|
||||
onClick={() => handleQuickPromptClick(label)}
|
||||
className="inline-flex h-6 items-center gap-1 rounded-full border border-border/60 bg-muted/30 px-2.5 text-[11px] text-foreground/82 transition-colors hover:border-primary/40 hover:bg-primary/10 hover:text-foreground cursor-pointer"
|
||||
>
|
||||
<Sparkles size={10} className="shrink-0 text-primary/70" aria-hidden="true" />
|
||||
<span>{label}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
ref={inputShellRef}
|
||||
className="relative"
|
||||
@@ -1193,6 +1296,12 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
<SquareTerminal size={12} className="text-muted-foreground/70 shrink-0" />
|
||||
) : file.vaultNoteId ? (
|
||||
<BookOpen size={11} className="text-muted-foreground/60 shrink-0" />
|
||||
) : file.mediaType.startsWith('image/') && file.dataUrl ? (
|
||||
<img
|
||||
src={file.dataUrl}
|
||||
alt={file.filename}
|
||||
className="h-4 w-4 rounded-[3px] object-cover shrink-0 border border-border/40"
|
||||
/>
|
||||
) : file.mediaType.startsWith('image/') ? (
|
||||
<ImageIcon size={11} className="text-muted-foreground/60 shrink-0" />
|
||||
) : (
|
||||
@@ -1898,6 +2007,9 @@ function chatInputPropsAreEqual(prev: ChatInputProps, next: ChatInputProps): boo
|
||||
&& prev.onAddFiles === next.onAddFiles
|
||||
&& prev.onRemoveFile === next.onRemoveFile
|
||||
&& prev.hosts === next.hosts
|
||||
&& prev.isRemoteDesktopContext === next.isRemoteDesktopContext
|
||||
&& prev.onSendQuickPrompt === next.onSendQuickPrompt
|
||||
&& prev.showRemoteScreenQuickPrompts === next.showRemoteScreenQuickPrompts
|
||||
&& prev.notes === next.notes
|
||||
&& prev.onMentionNote === next.onMentionNote
|
||||
&& prev.selectedUserSkills === next.selectedUserSkills
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Check, ChevronLeft, ChevronRight, Loader2, Pin, RotateCw, Search, Star } from 'lucide-react';
|
||||
import { Check, ChevronLeft, ChevronRight, Eye, Loader2, Pin, RotateCw, Search, Star } from 'lucide-react';
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import {
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type ComposerModelPrefs,
|
||||
type ComposerPickerModel,
|
||||
} from '../../infrastructure/ai/composerPicker';
|
||||
import { resolveModelVisionSupport } from '../../infrastructure/ai/visionCapability';
|
||||
import type { AgentModelPreset, ProviderConfig } from '../../infrastructure/ai/types';
|
||||
import { formatRelativeTime } from '../AIChatSessionHistoryDrawer';
|
||||
import { ProviderIconBadge } from '../settings/tabs/ai/ProviderIconBadge';
|
||||
@@ -60,6 +61,8 @@ export interface ComposerModelPickerProps {
|
||||
onSelectProviderModel?: (providerId: string, modelId: string, contextWindow?: number) => void;
|
||||
onSelectModel?: (modelId: string, options?: { custom?: boolean }) => void;
|
||||
onTogglePinned: (entry: ComposerModelPrefEntry) => void;
|
||||
/** Show subtle eye icons next to vision-capable models (default true). */
|
||||
showVisionBadges?: boolean;
|
||||
}
|
||||
|
||||
const rowClassName =
|
||||
@@ -75,23 +78,44 @@ const ModelRow: React.FC<{
|
||||
model: ComposerPickerModel;
|
||||
selected: boolean;
|
||||
pinned: boolean;
|
||||
supportsVision: boolean;
|
||||
visionLabel: string;
|
||||
onSelect: () => void;
|
||||
onTogglePinned: () => void;
|
||||
pinLabel: string;
|
||||
unpinLabel: string;
|
||||
}> = ({ model, selected, pinned, onSelect, onTogglePinned, pinLabel, unpinLabel }) => (
|
||||
}> = ({
|
||||
model,
|
||||
selected,
|
||||
pinned,
|
||||
supportsVision,
|
||||
visionLabel,
|
||||
onSelect,
|
||||
onTogglePinned,
|
||||
pinLabel,
|
||||
unpinLabel,
|
||||
}) => (
|
||||
<div className="group/row relative">
|
||||
<button
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={selected}
|
||||
onClick={onSelect}
|
||||
className={rowClassName}
|
||||
className={`${rowClassName} pr-7`}
|
||||
>
|
||||
{selected
|
||||
? <Check size={11} className="text-primary shrink-0" />
|
||||
: <span className="w-[11px] shrink-0" />}
|
||||
<span className="min-w-0 flex-1 truncate text-foreground/88" title={model.name}>{model.name}</span>
|
||||
{supportsVision && (
|
||||
<span
|
||||
className="inline-flex shrink-0 items-center text-muted-foreground/45"
|
||||
title={visionLabel}
|
||||
data-vision-capable="true"
|
||||
>
|
||||
<Eye size={10} aria-hidden="true" />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -127,6 +151,7 @@ export const ComposerModelPicker: React.FC<ComposerModelPickerProps> = ({
|
||||
onSelectProviderModel,
|
||||
onSelectModel,
|
||||
onTogglePinned,
|
||||
showVisionBadges = true,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const hasProviders = providers.length > 0;
|
||||
@@ -248,6 +273,15 @@ export const ComposerModelPicker: React.FC<ComposerModelPickerProps> = ({
|
||||
: { modelId, ...(customPrefIds.has(modelId.toLowerCase()) ? { custom: true as const } : {}) }
|
||||
);
|
||||
|
||||
const visionBadgeLabel = t('ai.vision.modelSupportsVision');
|
||||
const modelSupportsVision = (model: ComposerPickerModel): boolean => {
|
||||
if (!showVisionBadges) return false;
|
||||
return resolveModelVisionSupport({
|
||||
providerId: previewProvider?.providerId,
|
||||
modelId: model.id,
|
||||
}) === 'yes';
|
||||
};
|
||||
|
||||
if (hasProviders && view === 'providers') {
|
||||
return (
|
||||
<div className="w-[260px] max-w-[calc(100vw-16px)] py-1">
|
||||
@@ -360,6 +394,8 @@ export const ComposerModelPicker: React.FC<ComposerModelPickerProps> = ({
|
||||
model={model}
|
||||
selected={model.id === selectedModelId && (!hasProviders || previewProvider?.id === selectedProviderId)}
|
||||
pinned
|
||||
supportsVision={modelSupportsVision(model)}
|
||||
visionLabel={visionBadgeLabel}
|
||||
onSelect={() => selectModel(model.id)}
|
||||
onTogglePinned={() => onTogglePinned(prefEntryFor(model.id))}
|
||||
pinLabel={t('ai.chat.pinModel')}
|
||||
@@ -378,6 +414,8 @@ export const ComposerModelPicker: React.FC<ComposerModelPickerProps> = ({
|
||||
model={model}
|
||||
selected={model.id === selectedModelId && (!hasProviders || previewProvider?.id === selectedProviderId)}
|
||||
pinned={pinnedKeys.has(model.id)}
|
||||
supportsVision={modelSupportsVision(model)}
|
||||
visionLabel={visionBadgeLabel}
|
||||
onSelect={() => selectModel(model.id)}
|
||||
onTogglePinned={() => onTogglePinned(prefEntryFor(model.id))}
|
||||
pinLabel={t('ai.chat.pinModel')}
|
||||
@@ -397,6 +435,8 @@ export const ComposerModelPicker: React.FC<ComposerModelPickerProps> = ({
|
||||
model={model}
|
||||
selected={model.id === selectedModelId && (!hasProviders || previewProvider?.id === selectedProviderId)}
|
||||
pinned={pinnedKeys.has(model.id)}
|
||||
supportsVision={modelSupportsVision(model)}
|
||||
visionLabel={visionBadgeLabel}
|
||||
onSelect={() => selectModel(model.id)}
|
||||
onTogglePinned={() => onTogglePinned(prefEntryFor(model.id))}
|
||||
pinLabel={t('ai.chat.pinModel')}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { UploadedFile } from '../../infrastructure/ai/types';
|
||||
import type {
|
||||
RemoteDesktopCropRect,
|
||||
RemoteDesktopImageMediaType,
|
||||
} from '../../infrastructure/remoteDesktop/remoteDesktopSnapshotRegistry';
|
||||
|
||||
export const REMOTE_SCREEN_FILENAME_PREFIX = 'remote-screen-';
|
||||
|
||||
export interface RemoteDesktopScreenshotDraftPayload {
|
||||
/** Remote desktop session ID (used to route to the owning AI panel/tab). */
|
||||
sessionId: string;
|
||||
/** Optional workspace ID when the remote desktop belongs to a workspace. */
|
||||
workspaceId?: string;
|
||||
/** Raw base64 payload (or data URL — prefix is stripped automatically). */
|
||||
base64Data: string;
|
||||
mediaType: RemoteDesktopImageMediaType;
|
||||
filename?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
naturalWidth?: number;
|
||||
naturalHeight?: number;
|
||||
crop?: RemoteDesktopCropRect;
|
||||
hostLabel?: string;
|
||||
protocol?: 'vnc' | 'rdp';
|
||||
}
|
||||
|
||||
export interface RemoteDesktopQuickPromptSpec {
|
||||
id: 'explainError' | 'diagnoseUi' | 'summarizeScreen';
|
||||
labelKey: string;
|
||||
}
|
||||
|
||||
export const REMOTE_DESKTOP_QUICK_PROMPTS: readonly RemoteDesktopQuickPromptSpec[] = [
|
||||
{ id: 'explainError', labelKey: 'ai.vision.quickPrompt.explainError' },
|
||||
{ id: 'diagnoseUi', labelKey: 'ai.vision.quickPrompt.diagnoseUi' },
|
||||
{ id: 'summarizeScreen', labelKey: 'ai.vision.quickPrompt.summarizeScreen' },
|
||||
];
|
||||
|
||||
type RemoteScreenDraftListener = (payload: RemoteDesktopScreenshotDraftPayload) => void;
|
||||
|
||||
const draftListeners = new Set<RemoteScreenDraftListener>();
|
||||
|
||||
function stripBase64Prefix(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
const commaIndex = trimmed.indexOf(',');
|
||||
if (trimmed.startsWith('data:') && commaIndex !== -1) {
|
||||
return trimmed.slice(commaIndex + 1).trim();
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
export function buildRemoteDesktopScreenshotFilename(
|
||||
payload: Pick<RemoteDesktopScreenshotDraftPayload, 'filename' | 'protocol' | 'crop' | 'width' | 'height' | 'mediaType'>,
|
||||
): string {
|
||||
if (payload.filename && payload.filename.startsWith(REMOTE_SCREEN_FILENAME_PREFIX)) {
|
||||
return payload.filename;
|
||||
}
|
||||
const proto = payload.protocol ?? 'desktop';
|
||||
const kind = payload.crop ? 'snip' : 'full';
|
||||
const dims = payload.width && payload.height ? `-${payload.width}x${payload.height}` : '';
|
||||
const ext = payload.mediaType === 'image/png' ? 'png' : 'jpg';
|
||||
return `${REMOTE_SCREEN_FILENAME_PREFIX}${proto}-${kind}${dims}.${ext}`;
|
||||
}
|
||||
|
||||
export function isRemoteDesktopScreenshotFile(
|
||||
file: Pick<UploadedFile, 'filename' | 'mediaType'>,
|
||||
): boolean {
|
||||
return Boolean(
|
||||
file.mediaType?.startsWith('image/')
|
||||
&& file.filename?.startsWith(REMOTE_SCREEN_FILENAME_PREFIX),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a captured remote desktop screenshot payload into a browser `File`
|
||||
* ready to pass directly into `AIChatSidePanel`'s existing `addFiles([file])`.
|
||||
*/
|
||||
export function createRemoteDesktopScreenshotFile(
|
||||
payload: RemoteDesktopScreenshotDraftPayload,
|
||||
): File {
|
||||
const base64 = stripBase64Prefix(payload.base64Data);
|
||||
const binary = typeof atob === 'function'
|
||||
? atob(base64)
|
||||
: Buffer.from(base64, 'base64').toString('binary');
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i += 1) {
|
||||
bytes[i] = binary.charCodeAt(i);
|
||||
}
|
||||
const filename = buildRemoteDesktopScreenshotFilename(payload);
|
||||
return new File([bytes], filename, { type: payload.mediaType });
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a captured remote desktop screenshot payload directly into an
|
||||
* `UploadedFile` record for draft state updates when `FileReader` is bypassed.
|
||||
*/
|
||||
export function createRemoteDesktopUploadedFile(
|
||||
payload: RemoteDesktopScreenshotDraftPayload,
|
||||
id?: string,
|
||||
): UploadedFile {
|
||||
const base64Data = stripBase64Prefix(payload.base64Data);
|
||||
const filename = buildRemoteDesktopScreenshotFilename(payload);
|
||||
return {
|
||||
id: id || `remote-screen-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
|
||||
filename,
|
||||
dataUrl: `data:${payload.mediaType};base64,${base64Data}`,
|
||||
base64Data,
|
||||
mediaType: payload.mediaType,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pub/sub helper so `TerminalLayer` / `RemoteDesktopPane` can hand a captured
|
||||
* full-screen or region-snip screenshot directly to the active AI chat draft.
|
||||
*/
|
||||
export function dispatchAddRemoteScreenToAI(payload: RemoteDesktopScreenshotDraftPayload): void {
|
||||
for (const listener of draftListeners) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
// Ignore subscriber errors.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function subscribeAddRemoteScreenToAI(
|
||||
listener: RemoteScreenDraftListener,
|
||||
): () => void {
|
||||
draftListeners.add(listener);
|
||||
return () => {
|
||||
draftListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
import test, { before } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
|
||||
import ChatInput from './ChatInput';
|
||||
import { ComposerModelPicker } from './ComposerModelPicker';
|
||||
import { TooltipProvider } from '../ui/tooltip';
|
||||
import { I18nProvider } from '../../application/i18n/I18nProvider';
|
||||
import { loadLocaleMessages } from '../../application/i18n/messages';
|
||||
import {
|
||||
buildRemoteDesktopScreenshotFilename,
|
||||
createRemoteDesktopScreenshotFile,
|
||||
createRemoteDesktopUploadedFile,
|
||||
dispatchAddRemoteScreenToAI,
|
||||
isRemoteDesktopScreenshotFile,
|
||||
subscribeAddRemoteScreenToAI,
|
||||
} from './remoteDesktopAiDraft';
|
||||
import {
|
||||
computeSnipSelectionRect,
|
||||
RemoteDesktopSnipOverlay,
|
||||
} from '../remoteDesktop/RemoteDesktopSnipOverlay';
|
||||
|
||||
before(async () => {
|
||||
for (const locale of ['zh-CN', 'zh-TW', 'es', 'ru']) await loadLocaleMessages(locale);
|
||||
});
|
||||
|
||||
test('ChatInput allows image-only submission, shows quick prompt chips for remote desktop screenshots, and renders non-blocking vision warning for text-only models', () => {
|
||||
const uploaded = createRemoteDesktopUploadedFile({
|
||||
sessionId: 'rdp-1',
|
||||
protocol: 'rdp',
|
||||
base64Data: 'QUJDRA==',
|
||||
mediaType: 'image/png',
|
||||
width: 480,
|
||||
height: 210,
|
||||
crop: { x: 100, y: 100, width: 250, height: 200 },
|
||||
}, 'rd-img-1');
|
||||
|
||||
assert.equal(isRemoteDesktopScreenshotFile(uploaded), true);
|
||||
assert.equal(uploaded.filename, 'remote-screen-rdp-snip-480x210.png');
|
||||
|
||||
const html = renderToStaticMarkup(
|
||||
<I18nProvider locale="zh-CN">
|
||||
<TooltipProvider>
|
||||
<ChatInput
|
||||
value=""
|
||||
onChange={() => {}}
|
||||
onSend={() => {}}
|
||||
agentName="Catty Agent"
|
||||
files={[uploaded]}
|
||||
providerSwitcher={{
|
||||
providers: [{
|
||||
id: 'p-ds',
|
||||
providerId: 'deepseek',
|
||||
name: 'DeepSeek',
|
||||
defaultModel: 'deepseek-reasoner',
|
||||
enabled: true,
|
||||
}],
|
||||
selectedProviderId: 'p-ds',
|
||||
selectedModelId: 'deepseek-reasoner',
|
||||
onSelect: () => {},
|
||||
}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
assert.match(html, /data-allow-empty-submit="true"/);
|
||||
assert.match(html, /data-testid="ai-vision-model-warning"/);
|
||||
assert.match(html, /deepseek-reasoner/);
|
||||
assert.match(html, /切换模型/);
|
||||
assert.match(html, /data-testid="ai-remote-screen-quick-prompts"/);
|
||||
assert.match(html, /解释当前报错/);
|
||||
assert.match(html, /诊断界面问题/);
|
||||
assert.match(html, /总结屏幕内容/);
|
||||
});
|
||||
|
||||
test('ChatInput hides vision warning banner for vision-capable and unknown custom models', () => {
|
||||
const visionHtml = renderToStaticMarkup(
|
||||
<TooltipProvider>
|
||||
<ChatInput
|
||||
value=""
|
||||
onChange={() => {}}
|
||||
onSend={() => {}}
|
||||
isRemoteDesktopContext
|
||||
providerSwitcher={{
|
||||
providers: [{
|
||||
id: 'p-anth',
|
||||
providerId: 'anthropic',
|
||||
name: 'Anthropic',
|
||||
defaultModel: 'claude-sonnet-4-20250514',
|
||||
enabled: true,
|
||||
}],
|
||||
selectedProviderId: 'p-anth',
|
||||
selectedModelId: 'claude-sonnet-4-20250514',
|
||||
onSelect: () => {},
|
||||
}}
|
||||
/>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
assert.doesNotMatch(visionHtml, /ai-vision-model-warning/);
|
||||
|
||||
const unknownHtml = renderToStaticMarkup(
|
||||
<TooltipProvider>
|
||||
<ChatInput
|
||||
value=""
|
||||
onChange={() => {}}
|
||||
onSend={() => {}}
|
||||
isRemoteDesktopContext
|
||||
providerSwitcher={{
|
||||
providers: [{
|
||||
id: 'p-custom',
|
||||
providerId: 'custom',
|
||||
name: 'Custom Relay',
|
||||
defaultModel: 'internal-company-model-v3',
|
||||
enabled: true,
|
||||
}],
|
||||
selectedProviderId: 'p-custom',
|
||||
selectedModelId: 'internal-company-model-v3',
|
||||
onSelect: () => {},
|
||||
}}
|
||||
/>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
assert.doesNotMatch(unknownHtml, /ai-vision-model-warning/);
|
||||
});
|
||||
|
||||
test('ComposerModelPicker displays vision indicator badges only for vision-capable models', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ComposerModelPicker
|
||||
modelPresets={[
|
||||
{ id: 'gpt-4o', name: 'GPT-4o' },
|
||||
{ id: 'deepseek-reasoner', name: 'DeepSeek Reasoner' },
|
||||
]}
|
||||
selectedModelId="gpt-4o"
|
||||
prefs={{ recent: [], pinned: [] }}
|
||||
onSelectModel={() => {}}
|
||||
onTogglePinned={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
const matches = html.match(/data-vision-capable="true"/g) ?? [];
|
||||
assert.equal(matches.length, 1);
|
||||
});
|
||||
|
||||
test('remoteDesktopAiDraft builds File payloads and dispatches to subscribers', () => {
|
||||
const file = createRemoteDesktopScreenshotFile({
|
||||
sessionId: 'vnc-1',
|
||||
protocol: 'vnc',
|
||||
base64Data: 'data:image/jpeg;base64,QUJDRA==',
|
||||
mediaType: 'image/jpeg',
|
||||
width: 1280,
|
||||
height: 720,
|
||||
});
|
||||
assert.equal(file.name, 'remote-screen-vnc-full-1280x720.jpg');
|
||||
assert.equal(file.type, 'image/jpeg');
|
||||
assert.equal(file.size, 4);
|
||||
assert.equal(
|
||||
buildRemoteDesktopScreenshotFilename({ mediaType: 'image/png', protocol: 'rdp', crop: { x: 0, y: 0, width: 100, height: 100 } }),
|
||||
'remote-screen-rdp-snip.png',
|
||||
);
|
||||
|
||||
const received: string[] = [];
|
||||
const unsub = subscribeAddRemoteScreenToAI((payload) => received.push(payload.sessionId));
|
||||
dispatchAddRemoteScreenToAI({
|
||||
sessionId: 'vnc-1',
|
||||
base64Data: 'QUJDRA==',
|
||||
mediaType: 'image/jpeg',
|
||||
});
|
||||
unsub();
|
||||
assert.deepEqual(received, ['vnc-1']);
|
||||
});
|
||||
|
||||
test('RemoteDesktopSnipOverlay computes normalized 0..1000 crop coordinates across letterboxed canvas rects and renders overlay UI', () => {
|
||||
// Overlay is 1000x800, while letterboxed canvas is centered at left=100, top=100, 800x600.
|
||||
const overlayRect = { left: 0, top: 0, width: 1000, height: 800 };
|
||||
const canvasRect = { left: 100, top: 100, width: 800, height: 600 };
|
||||
|
||||
// Reverse drag (bottom-right to top-left), slightly outside left edge (clamped to canvas left=100).
|
||||
const computed = computeSnipSelectionRect(
|
||||
{ x: 500, y: 400 },
|
||||
{ x: 50, y: 250 },
|
||||
overlayRect,
|
||||
canvasRect,
|
||||
1920,
|
||||
1080,
|
||||
);
|
||||
assert.ok(computed);
|
||||
assert.deepEqual(computed.displayRect, { left: 100, top: 250, width: 400, height: 150 });
|
||||
assert.deepEqual(computed.normalizedRect, {
|
||||
x: 0,
|
||||
y: 250,
|
||||
width: 500,
|
||||
height: 250,
|
||||
pixelWidth: 960,
|
||||
pixelHeight: 270,
|
||||
});
|
||||
|
||||
// Tiny accidental click (< MIN_SNIP_DRAG_PX) returns null.
|
||||
assert.equal(
|
||||
computeSnipSelectionRect({ x: 200, y: 200 }, { x: 203, y: 204 }, overlayRect, canvasRect, 1920, 1080),
|
||||
null,
|
||||
);
|
||||
|
||||
const closedHtml = renderToStaticMarkup(
|
||||
<RemoteDesktopSnipOverlay
|
||||
open={false}
|
||||
naturalWidth={1920}
|
||||
naturalHeight={1080}
|
||||
onSelect={() => {}}
|
||||
onCancel={() => {}}
|
||||
/>,
|
||||
);
|
||||
assert.equal(closedHtml, '');
|
||||
|
||||
const openHtml = renderToStaticMarkup(
|
||||
<I18nProvider locale="en">
|
||||
<RemoteDesktopSnipOverlay
|
||||
open
|
||||
naturalWidth={1920}
|
||||
naturalHeight={1080}
|
||||
onSelect={() => {}}
|
||||
onCancel={() => {}}
|
||||
/>
|
||||
</I18nProvider>,
|
||||
);
|
||||
assert.match(openHtml, /data-testid="remote-desktop-snip-overlay"/);
|
||||
assert.match(openHtml, /Drag to select a region/);
|
||||
assert.match(openHtml, /Cancel region snip/);
|
||||
});
|
||||
|
||||
test('AIChatSidePanel and AIChatPanelContent wire image-only send, quick prompts with draft attachments, and VNC/RDP host protocol', () => {
|
||||
const sidePanelSrc = readFileSync(new URL('../AIChatSidePanel.tsx', import.meta.url), 'utf8');
|
||||
const panelContentSrc = readFileSync(new URL('../AIChatPanelContent.tsx', import.meta.url), 'utf8');
|
||||
|
||||
// 1. Image-only submit guard + filename fallback title
|
||||
assert.match(sidePanelSrc, /const hasImageAttachments = attachments\.some\(\(attachment\) => attachment\.mediaType\.startsWith\('image\/'\)\);/);
|
||||
assert.match(sidePanelSrc, /if \(\(!trimmed && !hasInlineTextAttachments && !hasImageAttachments\) \|\| isStreaming\) return;/);
|
||||
assert.match(sidePanelSrc, /const titleText = trimmed \|\| noteOnlyTitle\.trim\(\) \|\| imageOnlyTitle\.trim\(\);/);
|
||||
|
||||
// 2. Quick prompt chips preserve & clear draft attachments via includeDraftAttachments
|
||||
assert.match(sidePanelSrc, /includeDraftAttachments:\s*true/);
|
||||
assert.match(sidePanelSrc, /handleSendQuickPrompt=\{handleSendQuickPrompt\}/);
|
||||
assert.match(panelContentSrc, /onSendQuickPrompt=\{handleSendQuickPrompt\}/);
|
||||
|
||||
// 3. mentionHosts forwards session protocol so amber vision banner shows on VNC/RDP tabs before screenshot attach
|
||||
assert.match(panelContentSrc, /protocol:\s*session\.protocol/);
|
||||
});
|
||||
@@ -0,0 +1,771 @@
|
||||
import {
|
||||
Building2,
|
||||
ChevronDown,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Globe,
|
||||
KeyRound,
|
||||
Maximize2,
|
||||
Plug,
|
||||
Plus,
|
||||
Scaling,
|
||||
ShieldCheck,
|
||||
User,
|
||||
Volume2,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
DEFAULT_RDP_CONFIG,
|
||||
DEFAULT_RDP_PORT,
|
||||
DEFAULT_VNC_CONFIG,
|
||||
DEFAULT_VNC_PORT,
|
||||
formatVncDisplayNumber,
|
||||
normalizeRdpConfig,
|
||||
normalizeVncConfig,
|
||||
parseVncPortOrDisplay,
|
||||
} from "../../domain/remoteDesktop";
|
||||
import { cn } from "../../lib/utils";
|
||||
import type {
|
||||
Host,
|
||||
Identity,
|
||||
RdpConfig,
|
||||
RdpResolutionMode,
|
||||
RdpSecurityMode,
|
||||
SSHKey,
|
||||
VncConfig,
|
||||
VncScalingMode,
|
||||
} from "../../types";
|
||||
import {
|
||||
RdpProtocolIcon,
|
||||
SshTunnelIcon,
|
||||
VncProtocolIcon,
|
||||
} from "../icons/RemoteDesktopIcons";
|
||||
import { Button } from "../ui/button";
|
||||
import { Input } from "../ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
|
||||
import { HostDetailsSettingRow } from "./HostDetailsSection";
|
||||
import { IdentitySuggestInput } from "./IdentitySuggestInput";
|
||||
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||
|
||||
interface CompanionCredentialDraft {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
interface CompanionRemoteDesktopSectionsProps {
|
||||
form: Host;
|
||||
setForm: React.Dispatch<React.SetStateAction<Host>>;
|
||||
identities: Identity[];
|
||||
availableKeys?: SSHKey[];
|
||||
onCreateIdentity?: (identity: Identity) => void;
|
||||
t: Translate;
|
||||
}
|
||||
|
||||
interface CompanionRemoteDesktopInlineFieldsProps extends CompanionRemoteDesktopSectionsProps {
|
||||
protocol: "vnc" | "rdp";
|
||||
credentialDraft?: CompanionCredentialDraft;
|
||||
onCredentialDraftChange?: (draft: CompanionCredentialDraft | undefined) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline configuration fields for a companion VNC or RDP protocol attached to an SSH host.
|
||||
* Rendered directly inside the unified top protocol tabs (no nested box chrome).
|
||||
*/
|
||||
export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktopInlineFieldsProps> = ({
|
||||
protocol,
|
||||
form,
|
||||
setForm,
|
||||
identities,
|
||||
availableKeys = [],
|
||||
credentialDraft,
|
||||
onCredentialDraftChange,
|
||||
t,
|
||||
}) => {
|
||||
const [vncPortInput, setVncPortInput] = useState<string>(() =>
|
||||
String(form.vncConfig?.port ?? DEFAULT_VNC_PORT),
|
||||
);
|
||||
const [showManualPassword, setShowManualPassword] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (protocol === "vnc") {
|
||||
setVncPortInput(String(form.vncConfig?.port ?? DEFAULT_VNC_PORT));
|
||||
}
|
||||
}, [form.id, protocol, form.vncConfig?.port]);
|
||||
|
||||
const passwordCompatibleIdentities = useMemo(
|
||||
() =>
|
||||
identities.filter(
|
||||
(identity) => identity.authMethod === "password" || Boolean(identity.password),
|
||||
),
|
||||
[identities],
|
||||
);
|
||||
|
||||
const updateVncConfig = (patch: Partial<VncConfig>) => {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
vncConfig: {
|
||||
...(prev.vncConfig ?? {
|
||||
...DEFAULT_VNC_CONFIG,
|
||||
enabled: true,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: true,
|
||||
}),
|
||||
...patch,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const updateRdpConfig = (patch: Partial<RdpConfig>) => {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
rdpConfig: {
|
||||
...(prev.rdpConfig ?? {
|
||||
...DEFAULT_RDP_CONFIG,
|
||||
enabled: true,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: true,
|
||||
}),
|
||||
...patch,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
if (protocol === "vnc") {
|
||||
const vncTunneled = form.vncConfig?.tunnelViaHostSsh ?? true;
|
||||
const vncNormalized = normalizeVncConfig(form.vncConfig);
|
||||
const vncDisplayLabel = formatVncDisplayNumber(vncNormalized.port);
|
||||
const useHostCreds =
|
||||
!form.vncConfig?.identityId && form.vncConfig?.useHostCredentials !== false;
|
||||
const selectedVncIdentity = form.vncConfig?.identityId
|
||||
? identities.find((i) => i.id === form.vncConfig?.identityId)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<HostDetailsSettingRow
|
||||
icon={<Plug />}
|
||||
label={t("hostDetails.vnc.portLabel")}
|
||||
>
|
||||
<div className="flex items-center gap-1.5 w-44">
|
||||
<Input
|
||||
value={vncPortInput}
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value;
|
||||
setVncPortInput(raw);
|
||||
const parsed = parseVncPortOrDisplay(raw);
|
||||
if (parsed !== null) {
|
||||
updateVncConfig({ port: parsed });
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
const parsed = parseVncPortOrDisplay(vncPortInput);
|
||||
const resolved = parsed ?? DEFAULT_VNC_PORT;
|
||||
setVncPortInput(String(resolved));
|
||||
updateVncConfig({ port: resolved });
|
||||
}}
|
||||
placeholder={t("hostDetails.vnc.displayPlaceholder")}
|
||||
className="h-8 flex-1 min-w-0 text-center font-mono text-sm"
|
||||
/>
|
||||
{vncDisplayLabel ? (
|
||||
<span className="rounded border border-border/60 bg-background px-1.5 py-0.5 text-xs font-mono text-muted-foreground shrink-0">
|
||||
{vncDisplayLabel}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<SshTunnelIcon />}
|
||||
label={t("hostDetails.companion.tunnelViaSsh")}
|
||||
hint={t("hostDetails.companion.tunnelViaSshDesc")}
|
||||
>
|
||||
<Switch
|
||||
checked={vncTunneled}
|
||||
onCheckedChange={(checked) => updateVncConfig({ tunnelViaHostSsh: checked })}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
{vncTunneled && (
|
||||
<HostDetailsSettingRow
|
||||
icon={<Globe />}
|
||||
label={t("hostDetails.companion.tunnelTargetHost")}
|
||||
>
|
||||
<Input
|
||||
value={form.vncConfig?.tunnelTargetHost ?? ""}
|
||||
onChange={(e) =>
|
||||
updateVncConfig({ tunnelTargetHost: e.target.value || undefined })
|
||||
}
|
||||
placeholder="127.0.0.1"
|
||||
className="h-8 w-44 font-mono text-sm"
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
)}
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<KeyRound />}
|
||||
label={t("hostDetails.companion.credentials.host")}
|
||||
>
|
||||
<Switch
|
||||
checked={useHostCreds}
|
||||
onCheckedChange={(checked) => {
|
||||
if (checked) {
|
||||
onCredentialDraftChange?.(undefined);
|
||||
updateVncConfig({ useHostCredentials: true, identityId: undefined });
|
||||
} else {
|
||||
updateVncConfig({ useHostCredentials: false });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
{!useHostCreds && (
|
||||
<div className="space-y-2">
|
||||
{form.vncConfig?.identityId ? (
|
||||
<div className="flex items-center gap-2 h-10 px-3 rounded-lg border border-border/60 bg-transparent">
|
||||
<User size={16} className="text-muted-foreground shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-medium truncate">
|
||||
{selectedVncIdentity
|
||||
? selectedVncIdentity.label
|
||||
: t("hostDetails.identity.missing")}
|
||||
</div>
|
||||
</div>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
onClick={() => updateVncConfig({ identityId: undefined, useHostCredentials: false })}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t("common.clear")}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<IdentitySuggestInput
|
||||
value={credentialDraft?.username ?? form.vncConfig?.username ?? ""}
|
||||
onChange={(next) => {
|
||||
updateVncConfig({ username: next || undefined, useHostCredentials: false });
|
||||
onCredentialDraftChange?.({
|
||||
username: next,
|
||||
password: credentialDraft?.password ?? "",
|
||||
});
|
||||
}}
|
||||
placeholder={t("hostDetails.vnc.usernamePlaceholder")}
|
||||
identities={passwordCompatibleIdentities}
|
||||
availableKeys={availableKeys}
|
||||
onSelectIdentity={(identity) => {
|
||||
onCredentialDraftChange?.(undefined);
|
||||
updateVncConfig({
|
||||
useHostCredentials: false,
|
||||
identityId: identity.id,
|
||||
username: undefined,
|
||||
});
|
||||
}}
|
||||
t={t}
|
||||
/>
|
||||
<div className="relative">
|
||||
<Input
|
||||
type={showManualPassword ? "text" : "password"}
|
||||
value={credentialDraft?.password ?? ""}
|
||||
onChange={(e) =>
|
||||
onCredentialDraftChange?.({
|
||||
username: credentialDraft?.username ?? form.vncConfig?.username ?? "",
|
||||
password: e.target.value,
|
||||
})
|
||||
}
|
||||
placeholder={t("hostDetails.password.placeholder")}
|
||||
className="h-10 rounded-lg pr-10 text-sm"
|
||||
/>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowManualPassword((prev) => !prev)}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{showManualPassword ? <EyeOff size={16} /> : <Eye size={16} />}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{showManualPassword ? t("hostDetails.password.hide") : t("hostDetails.password.show")}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
{credentialDraft?.password ? (
|
||||
<p className="px-1 text-[11px] text-muted-foreground">
|
||||
{t("hostDetails.companion.credentials.manualHint")}
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<Scaling />}
|
||||
label={t("hostDetails.vnc.scalingMode")}
|
||||
>
|
||||
<Select
|
||||
value={vncNormalized.scalingMode}
|
||||
onValueChange={(value) =>
|
||||
updateVncConfig({ scalingMode: value as VncScalingMode })
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-44 text-sm">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="fit">{t("hostDetails.vnc.scalingMode.fit")}</SelectItem>
|
||||
<SelectItem value="actual">{t("hostDetails.vnc.scalingMode.actual")}</SelectItem>
|
||||
<SelectItem value="stretch">{t("hostDetails.vnc.scalingMode.stretch")}</SelectItem>
|
||||
<SelectItem value="dynamic">{t("hostDetails.vnc.scalingMode.dynamic")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<Eye />}
|
||||
label={t("hostDetails.vnc.viewOnly")}
|
||||
hint={t("hostDetails.vnc.viewOnlyDesc")}
|
||||
>
|
||||
<Switch
|
||||
checked={vncNormalized.viewOnly}
|
||||
onCheckedChange={(checked) => updateVncConfig({ viewOnly: checked })}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const rdpTunneled = form.rdpConfig?.tunnelViaHostSsh ?? true;
|
||||
const rdpNormalized = normalizeRdpConfig(form.rdpConfig);
|
||||
const useHostCreds =
|
||||
!form.rdpConfig?.identityId && form.rdpConfig?.useHostCredentials !== false;
|
||||
const selectedRdpIdentity = form.rdpConfig?.identityId
|
||||
? identities.find((i) => i.id === form.rdpConfig?.identityId)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<HostDetailsSettingRow
|
||||
icon={<Plug />}
|
||||
label={t("hostDetails.rdp.portLabel")}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
value={form.rdpConfig?.port ?? DEFAULT_RDP_PORT}
|
||||
onChange={(e) => {
|
||||
const n = Number.parseInt(e.target.value, 10);
|
||||
updateRdpConfig({ port: Number.isFinite(n) ? n : undefined });
|
||||
}}
|
||||
className="h-8 w-44 text-center font-mono text-sm"
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<SshTunnelIcon />}
|
||||
label={t("hostDetails.companion.tunnelViaSsh")}
|
||||
hint={t("hostDetails.companion.tunnelViaSshDesc")}
|
||||
>
|
||||
<Switch
|
||||
checked={rdpTunneled}
|
||||
onCheckedChange={(checked) => updateRdpConfig({ tunnelViaHostSsh: checked })}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
{rdpTunneled && (
|
||||
<HostDetailsSettingRow
|
||||
icon={<Globe />}
|
||||
label={t("hostDetails.companion.tunnelTargetHost")}
|
||||
>
|
||||
<Input
|
||||
value={form.rdpConfig?.tunnelTargetHost ?? ""}
|
||||
onChange={(e) =>
|
||||
updateRdpConfig({ tunnelTargetHost: e.target.value || undefined })
|
||||
}
|
||||
placeholder="127.0.0.1"
|
||||
className="h-8 w-44 font-mono text-sm"
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
)}
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<KeyRound />}
|
||||
label={t("hostDetails.companion.credentials.host")}
|
||||
>
|
||||
<Switch
|
||||
checked={useHostCreds}
|
||||
onCheckedChange={(checked) => {
|
||||
if (checked) {
|
||||
onCredentialDraftChange?.(undefined);
|
||||
updateRdpConfig({ useHostCredentials: true, identityId: undefined });
|
||||
} else {
|
||||
updateRdpConfig({ useHostCredentials: false });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
{!useHostCreds && (
|
||||
<div className="space-y-2">
|
||||
{form.rdpConfig?.identityId ? (
|
||||
<div className="flex items-center gap-2 h-10 px-3 rounded-lg border border-border/60 bg-transparent">
|
||||
<User size={16} className="text-muted-foreground shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-medium truncate">
|
||||
{selectedRdpIdentity
|
||||
? selectedRdpIdentity.label
|
||||
: t("hostDetails.identity.missing")}
|
||||
</div>
|
||||
</div>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
onClick={() => updateRdpConfig({ identityId: undefined, useHostCredentials: false })}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t("common.clear")}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<IdentitySuggestInput
|
||||
value={credentialDraft?.username ?? form.rdpConfig?.username ?? ""}
|
||||
onChange={(next) => {
|
||||
updateRdpConfig({ username: next || undefined, useHostCredentials: false });
|
||||
onCredentialDraftChange?.({
|
||||
username: next,
|
||||
password: credentialDraft?.password ?? "",
|
||||
});
|
||||
}}
|
||||
placeholder={t("hostDetails.rdp.usernamePlaceholder")}
|
||||
identities={passwordCompatibleIdentities}
|
||||
availableKeys={availableKeys}
|
||||
onSelectIdentity={(identity) => {
|
||||
onCredentialDraftChange?.(undefined);
|
||||
updateRdpConfig({
|
||||
useHostCredentials: false,
|
||||
identityId: identity.id,
|
||||
username: undefined,
|
||||
...(identity.domain ? { domain: identity.domain } : {}),
|
||||
});
|
||||
}}
|
||||
t={t}
|
||||
/>
|
||||
<div className="relative">
|
||||
<Input
|
||||
type={showManualPassword ? "text" : "password"}
|
||||
value={credentialDraft?.password ?? ""}
|
||||
onChange={(e) =>
|
||||
onCredentialDraftChange?.({
|
||||
username: credentialDraft?.username ?? form.rdpConfig?.username ?? "",
|
||||
password: e.target.value,
|
||||
})
|
||||
}
|
||||
placeholder={t("hostDetails.password.placeholder")}
|
||||
className="h-10 rounded-lg pr-10 text-sm"
|
||||
/>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowManualPassword((prev) => !prev)}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{showManualPassword ? <EyeOff size={16} /> : <Eye size={16} />}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{showManualPassword ? t("hostDetails.password.hide") : t("hostDetails.password.show")}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
{credentialDraft?.password ? (
|
||||
<p className="px-1 text-[11px] text-muted-foreground">
|
||||
{t("hostDetails.companion.credentials.manualHint")}
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<Building2 />}
|
||||
label={t("hostDetails.rdp.domainLabel")}
|
||||
>
|
||||
<Input
|
||||
value={form.rdpConfig?.domain ?? ""}
|
||||
onChange={(e) =>
|
||||
updateRdpConfig({ domain: e.target.value || undefined })
|
||||
}
|
||||
placeholder={t("hostDetails.rdp.domainPlaceholder")}
|
||||
className="h-8 w-44 text-sm"
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<Maximize2 />}
|
||||
label={t("hostDetails.rdp.resolutionMode")}
|
||||
>
|
||||
<Select
|
||||
value={rdpNormalized.resolutionMode}
|
||||
onValueChange={(value) =>
|
||||
updateRdpConfig({ resolutionMode: value as RdpResolutionMode })
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-44 text-sm">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="dynamic">{t("hostDetails.rdp.resolutionMode.dynamic")}</SelectItem>
|
||||
<SelectItem value="fit">{t("hostDetails.rdp.resolutionMode.fit")}</SelectItem>
|
||||
<SelectItem value="fixed">{t("hostDetails.rdp.resolutionMode.fixed")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<ShieldCheck />}
|
||||
label={t("hostDetails.rdp.securityMode")}
|
||||
>
|
||||
<Select
|
||||
value={rdpNormalized.securityMode}
|
||||
onValueChange={(value) =>
|
||||
updateRdpConfig({ securityMode: value as RdpSecurityMode })
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-44 text-sm">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="auto">{t("hostDetails.rdp.securityMode.auto")}</SelectItem>
|
||||
<SelectItem value="nla">{t("hostDetails.rdp.securityMode.nla")}</SelectItem>
|
||||
<SelectItem value="tls">{t("hostDetails.rdp.securityMode.tls")}</SelectItem>
|
||||
<SelectItem value="rdp">{t("hostDetails.rdp.securityMode.rdp")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<Volume2 />}
|
||||
label={t("hostDetails.rdp.audio")}
|
||||
hint={t("hostDetails.rdp.audioDesc")}
|
||||
>
|
||||
<Switch
|
||||
checked={rdpNormalized.audioEnabled}
|
||||
onCheckedChange={(checked) => updateRdpConfig({ audioEnabled: checked })}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Legacy collapsible wrapper kept exported for standalone/unit reuse.
|
||||
*/
|
||||
export const CompanionRemoteDesktopSections: React.FC<CompanionRemoteDesktopSectionsProps> = ({
|
||||
form,
|
||||
setForm,
|
||||
identities,
|
||||
onCreateIdentity,
|
||||
t,
|
||||
}) => {
|
||||
const [vncExpanded, setVncExpanded] = useState(false);
|
||||
const [rdpExpanded, setRdpExpanded] = useState(false);
|
||||
|
||||
const vncEnabled = form.vncConfig?.enabled === true;
|
||||
const rdpEnabled = form.rdpConfig?.enabled === true;
|
||||
const vncTunneled = form.vncConfig?.tunnelViaHostSsh ?? true;
|
||||
const rdpTunneled = form.rdpConfig?.tunnelViaHostSsh ?? true;
|
||||
const vncNormalized = normalizeVncConfig(form.vncConfig);
|
||||
const rdpNormalized = normalizeRdpConfig(form.rdpConfig);
|
||||
|
||||
return (
|
||||
<>
|
||||
{vncEnabled ? (
|
||||
<div className="rounded-lg border border-border/70 bg-card/50 overflow-hidden">
|
||||
<div className="flex items-center gap-2 px-3 py-2.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setVncExpanded((prev) => !prev)}
|
||||
aria-expanded={vncExpanded}
|
||||
className="flex flex-1 min-w-0 items-center gap-2 text-left"
|
||||
>
|
||||
<span className="flex h-6 w-6 items-center justify-center rounded-md bg-teal-500/12 text-teal-600 dark:text-teal-400 shrink-0">
|
||||
<VncProtocolIcon size={14} />
|
||||
</span>
|
||||
<span className="text-xs font-semibold text-foreground">VNC</span>
|
||||
<span className="text-[11px] font-mono text-muted-foreground">:{vncNormalized.port}</span>
|
||||
{vncTunneled && (
|
||||
<span className="inline-flex items-center gap-1 rounded-md border border-emerald-500/25 bg-emerald-500/10 px-1.5 py-0 text-[10px] font-medium leading-4 text-emerald-600 dark:text-emerald-400 shrink-0">
|
||||
<SshTunnelIcon size={10} />
|
||||
SSH
|
||||
</span>
|
||||
)}
|
||||
<ChevronDown
|
||||
size={14}
|
||||
className={cn("ml-auto text-muted-foreground transition-transform shrink-0", vncExpanded && "rotate-180")}
|
||||
/>
|
||||
</button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 text-muted-foreground hover:text-destructive shrink-0"
|
||||
onClick={() => {
|
||||
setVncExpanded(false);
|
||||
setForm((prev) => ({ ...prev, vncConfig: undefined }));
|
||||
}}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
{vncExpanded && (
|
||||
<div className="border-t border-border/50 px-3 py-3">
|
||||
<CompanionRemoteDesktopInlineFields
|
||||
protocol="vnc"
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
identities={identities}
|
||||
onCreateIdentity={onCreateIdentity}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="group w-full h-11 justify-between px-3 border border-dashed border-border/70 hover:border-teal-500/40 hover:bg-teal-500/5"
|
||||
onClick={() => {
|
||||
setVncExpanded(true);
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
vncConfig: {
|
||||
...DEFAULT_VNC_CONFIG,
|
||||
enabled: true,
|
||||
port: DEFAULT_VNC_PORT,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: true,
|
||||
},
|
||||
}));
|
||||
}}
|
||||
>
|
||||
<span className="flex items-center gap-2.5">
|
||||
<span className="flex h-6 w-6 items-center justify-center rounded-md bg-teal-500/12 text-teal-600 dark:text-teal-400">
|
||||
<VncProtocolIcon size={14} />
|
||||
</span>
|
||||
<span className="text-xs font-medium text-foreground">{t("hostDetails.companion.addVnc")}</span>
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1 text-[10px] font-mono text-muted-foreground">
|
||||
<span>:{DEFAULT_VNC_PORT}</span>
|
||||
<Plus size={13} className="text-muted-foreground group-hover:text-teal-500 transition-colors" />
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{rdpEnabled ? (
|
||||
<div className="rounded-lg border border-border/70 bg-card/50 overflow-hidden">
|
||||
<div className="flex items-center gap-2 px-3 py-2.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setRdpExpanded((prev) => !prev)}
|
||||
aria-expanded={rdpExpanded}
|
||||
className="flex flex-1 min-w-0 items-center gap-2 text-left"
|
||||
>
|
||||
<span className="flex h-6 w-6 items-center justify-center rounded-md bg-blue-500/12 text-blue-600 dark:text-blue-400 shrink-0">
|
||||
<RdpProtocolIcon size={14} />
|
||||
</span>
|
||||
<span className="text-xs font-semibold text-foreground">RDP</span>
|
||||
<span className="text-[11px] font-mono text-muted-foreground">:{rdpNormalized.port}</span>
|
||||
{rdpTunneled && (
|
||||
<span className="inline-flex items-center gap-1 rounded-md border border-emerald-500/25 bg-emerald-500/10 px-1.5 py-0 text-[10px] font-medium leading-4 text-emerald-600 dark:text-emerald-400 shrink-0">
|
||||
<SshTunnelIcon size={10} />
|
||||
SSH
|
||||
</span>
|
||||
)}
|
||||
<ChevronDown
|
||||
size={14}
|
||||
className={cn("ml-auto text-muted-foreground transition-transform shrink-0", rdpExpanded && "rotate-180")}
|
||||
/>
|
||||
</button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 text-muted-foreground hover:text-destructive shrink-0"
|
||||
onClick={() => {
|
||||
setRdpExpanded(false);
|
||||
setForm((prev) => ({ ...prev, rdpConfig: undefined }));
|
||||
}}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
{rdpExpanded && (
|
||||
<div className="border-t border-border/50 px-3 py-3">
|
||||
<CompanionRemoteDesktopInlineFields
|
||||
protocol="rdp"
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
identities={identities}
|
||||
onCreateIdentity={onCreateIdentity}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="group w-full h-11 justify-between px-3 border border-dashed border-border/70 hover:border-blue-500/40 hover:bg-blue-500/5"
|
||||
onClick={() => {
|
||||
setRdpExpanded(true);
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
rdpConfig: {
|
||||
...DEFAULT_RDP_CONFIG,
|
||||
enabled: true,
|
||||
port: DEFAULT_RDP_PORT,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: true,
|
||||
},
|
||||
}));
|
||||
}}
|
||||
>
|
||||
<span className="flex items-center gap-2.5">
|
||||
<span className="flex h-6 w-6 items-center justify-center rounded-md bg-blue-500/12 text-blue-600 dark:text-blue-400">
|
||||
<RdpProtocolIcon size={14} />
|
||||
</span>
|
||||
<span className="text-xs font-medium text-foreground">{t("hostDetails.companion.addRdp")}</span>
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1 text-[10px] font-mono text-muted-foreground">
|
||||
<span>:{DEFAULT_RDP_PORT}</span>
|
||||
<Plus size={13} className="text-muted-foreground group-hover:text-blue-500 transition-colors" />
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -1,13 +1,167 @@
|
||||
import React, { useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { CheckCircle2, ShieldAlert, ShieldCheck, ShieldQuestion } from "lucide-react";
|
||||
import { useI18n } from "../../application/i18n/I18nProvider";
|
||||
import type { Host, SSHKey } from "../../types";
|
||||
import type { RemoteDesktopProbeResult } from "../../domain/hostConnectionTest";
|
||||
import { formatHostPort } from "../../domain/host";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { RdpProtocolIcon, VncProtocolIcon } from "../icons/RemoteDesktopIcons";
|
||||
import { getProtocolBadgeClass } from "../protocolVisuals";
|
||||
import { trustKnownRemoteDesktopCert } from "../remoteDesktop/knownRemoteDesktopCerts";
|
||||
import { Button } from "../ui/button";
|
||||
import { TerminalConnectionDialog } from "../terminal/TerminalConnectionDialog";
|
||||
import type { TerminalAuthMethod } from "../terminal/TerminalAuthDialog";
|
||||
import type { useHostConnectionTest } from "../../application/state/useHostConnectionTest";
|
||||
|
||||
type HostConnectionTest = ReturnType<typeof useHostConnectionTest>;
|
||||
|
||||
const RDP_SECURITY_LABELS: Record<NonNullable<RemoteDesktopProbeResult["rdpSecurity"]>, string> = {
|
||||
nla: "NLA / CredSSP",
|
||||
"nla-ext": "NLA / CredSSP Extended",
|
||||
tls: "TLS",
|
||||
rdstls: "RDSTLS",
|
||||
rdp: "Standard RDP",
|
||||
};
|
||||
|
||||
const RemoteDesktopProbeSummaryCard: React.FC<{
|
||||
probe: RemoteDesktopProbeResult;
|
||||
certHost: string;
|
||||
onTrusted: () => void;
|
||||
}> = ({ probe, certHost, onTrusted }) => {
|
||||
const isRdp = probe.protocol === "rdp";
|
||||
const cert = probe.cert;
|
||||
|
||||
const handleTrust = () => {
|
||||
if (!cert) return;
|
||||
const info = {
|
||||
fingerprintSha256: cert.fingerprintSha256,
|
||||
...(cert.subject ? { subject: cert.subject } : {}),
|
||||
...(cert.issuer ? { issuer: cert.issuer } : {}),
|
||||
...(cert.validFrom ? { validFrom: cert.validFrom } : {}),
|
||||
...(cert.validTo ? { validTo: cert.validTo } : {}),
|
||||
} as Parameters<typeof trustKnownRemoteDesktopCert>[3];
|
||||
trustKnownRemoteDesktopCert(probe.protocol, certHost, probe.port, info);
|
||||
onTrusted();
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="remote-desktop-probe-summary"
|
||||
className="rounded-lg border border-border/50 bg-background/50 p-3 space-y-2.5 text-xs"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-[10px] font-semibold uppercase",
|
||||
getProtocolBadgeClass(probe.protocol),
|
||||
)}
|
||||
>
|
||||
{isRdp ? <RdpProtocolIcon size={11} /> : <VncProtocolIcon size={11} />}
|
||||
{probe.protocol.toUpperCase()}
|
||||
</span>
|
||||
<span className="font-mono text-[11px] text-muted-foreground truncate">
|
||||
{formatHostPort(probe.host, probe.port)}
|
||||
</span>
|
||||
</div>
|
||||
{probe.rttMs != null && (
|
||||
<span
|
||||
data-testid="remote-desktop-probe-rtt"
|
||||
className="shrink-0 rounded-md bg-emerald-500/15 px-2 py-0.5 font-mono text-[11px] font-medium text-emerald-600 dark:text-emerald-400 tabular-nums"
|
||||
>
|
||||
{probe.rttMs} ms
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-1.5 text-[11px]">
|
||||
{isRdp && probe.rdpSecurity && (
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-muted-foreground">Security</span>
|
||||
<span className="font-medium text-foreground">
|
||||
{RDP_SECURITY_LABELS[probe.rdpSecurity] ?? probe.rdpSecurity}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{!isRdp && probe.rfbVersion && (
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-muted-foreground">RFB Banner</span>
|
||||
<span className="font-mono font-medium text-foreground">{probe.rfbVersion}</span>
|
||||
</div>
|
||||
)}
|
||||
{!isRdp && probe.vncSecurityTypes && probe.vncSecurityTypes.length > 0 && (
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<span className="text-muted-foreground shrink-0">Security Types</span>
|
||||
<div className="flex flex-wrap justify-end gap-1">
|
||||
{probe.vncSecurityTypes.map((sec) => (
|
||||
<span
|
||||
key={`${sec.id}-${sec.name}`}
|
||||
className="rounded border border-border/60 bg-muted/60 px-1.5 py-0.5 text-[10px] font-medium text-foreground"
|
||||
>
|
||||
{sec.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{(probe.tlsVersion || probe.tlsCipher) && (
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-muted-foreground">TLS</span>
|
||||
<span className="font-mono text-[10px] text-foreground truncate">
|
||||
{[probe.tlsVersion, probe.tlsCipher].filter(Boolean).join(" · ")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{cert && (
|
||||
<div className="rounded-md border border-border/50 bg-muted/30 p-2 space-y-1.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-[10px] font-medium text-muted-foreground">SHA-256 Certificate</span>
|
||||
{cert.trustStatus === "trusted" ? (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-emerald-600 dark:text-emerald-400">
|
||||
<ShieldCheck size={12} /> Trusted
|
||||
</span>
|
||||
) : cert.trustStatus === "changed" ? (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-destructive">
|
||||
<ShieldAlert size={12} /> Changed
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-amber-600 dark:text-amber-400">
|
||||
<ShieldQuestion size={12} /> First Seen
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="font-mono text-[10px] leading-4 text-foreground break-all select-all">
|
||||
{cert.fingerprintSha256}
|
||||
</div>
|
||||
{(cert.subject || cert.issuer) && (
|
||||
<div className="text-[10px] text-muted-foreground truncate">
|
||||
{cert.subject || cert.issuer}
|
||||
</div>
|
||||
)}
|
||||
{(cert.trustStatus === "first-seen" || cert.trustStatus === "changed") && (
|
||||
<div className="pt-1 flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-6 px-2.5 text-[10px] gap-1"
|
||||
data-testid="remote-desktop-trust-fingerprint"
|
||||
onClick={handleTrust}
|
||||
>
|
||||
<CheckCircle2 size={11} />
|
||||
Trust Fingerprint
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export interface HostConnectionTestDialogProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
@@ -100,6 +254,16 @@ export const HostConnectionTestDialog: React.FC<HostConnectionTestDialogProps> =
|
||||
showLogs={showLogs}
|
||||
_setShowLogs={setShowLogs}
|
||||
keys={keys}
|
||||
protocolOverride={state.activeProtocol !== "ssh" ? state.activeProtocol : undefined}
|
||||
summaryContent={
|
||||
state.probeResult && state.probeResult.ok ? (
|
||||
<RemoteDesktopProbeSummaryCard
|
||||
probe={state.probeResult}
|
||||
certHost={host.hostname || state.probeResult.host}
|
||||
onTrusted={test.markProbeCertTrusted}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
authProps={{
|
||||
authMethod,
|
||||
setAuthMethod,
|
||||
|
||||
@@ -50,7 +50,7 @@ export function HostDetailsSection({
|
||||
action?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<Card className={cn("p-3 space-y-3 bg-card border-border/80 shadow-sm", className)}>
|
||||
<Card className={cn("p-3.5 space-y-2.5 bg-card border-border/60 shadow-none rounded-xl", className)}>
|
||||
<div className="flex min-h-5 items-center gap-1.5">
|
||||
<span className="flex h-5 w-4 shrink-0 items-center justify-center text-muted-foreground [&>img]:block [&>img]:h-4 [&>img]:w-4 [&>img]:object-contain [&>svg]:block [&>svg]:h-4 [&>svg]:w-4">
|
||||
{icon}
|
||||
@@ -67,11 +67,13 @@ export function HostDetailsSection({
|
||||
}
|
||||
|
||||
export function HostDetailsSettingRow({
|
||||
icon,
|
||||
label,
|
||||
hint,
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
icon?: React.ReactNode;
|
||||
label: React.ReactNode;
|
||||
hint?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
@@ -80,12 +82,17 @@ export function HostDetailsSettingRow({
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
// Fixed height so switch / select / input rows stay aligned.
|
||||
"flex h-12 items-center justify-between gap-3 rounded-lg border border-border/60 bg-secondary/40 px-3",
|
||||
// Unified flat transparent setting row across the entire host form.
|
||||
"flex h-10 items-center justify-between gap-3 bg-transparent px-1",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="flex min-h-5 min-w-0 items-center gap-1.5">
|
||||
<div className="flex min-h-5 min-w-0 items-center gap-2">
|
||||
{icon && (
|
||||
<span className="flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground [&>svg]:h-3.5 [&>svg]:w-3.5">
|
||||
{icon}
|
||||
</span>
|
||||
)}
|
||||
<span className="truncate text-sm font-medium leading-5 text-foreground">{label}</span>
|
||||
{hint && <HostDetailsHelp>{hint}</HostDetailsHelp>}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import { ChevronDown, User } from "lucide-react";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import type { Identity, SSHKey } from "../../types";
|
||||
import { Input } from "../ui/input";
|
||||
import { Popover, PopoverAnchor, PopoverContent } from "../ui/popover";
|
||||
import { ScrollArea } from "../ui/scroll-area";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||
|
||||
interface IdentitySuggestInputProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder: string;
|
||||
identities: Identity[];
|
||||
availableKeys?: SSHKey[];
|
||||
onSelectIdentity: (identity: Identity) => void;
|
||||
t: Translate;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared username input with SSH-style Keychain identity autocomplete popover.
|
||||
* Uses PopoverAnchor (never PopoverTrigger) so focus/click never races and flash-closes.
|
||||
*/
|
||||
export const IdentitySuggestInput: React.FC<IdentitySuggestInputProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
identities,
|
||||
availableKeys = [],
|
||||
onSelectIdentity,
|
||||
t,
|
||||
className,
|
||||
}) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const filteredIdentities = useMemo(() => {
|
||||
const q = (value || "").toLowerCase().trim();
|
||||
if (!q) return identities;
|
||||
return identities.filter(
|
||||
(i) =>
|
||||
i.label.toLowerCase().includes(q) ||
|
||||
i.username.toLowerCase().includes(q) ||
|
||||
(i.domain && i.domain.toLowerCase().includes(q)),
|
||||
);
|
||||
}, [identities, value]);
|
||||
|
||||
if (identities.length === 0) {
|
||||
return (
|
||||
<Input
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className={className ?? "h-10 rounded-lg"}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover
|
||||
open={open && filteredIdentities.length > 0}
|
||||
onOpenChange={setOpen}
|
||||
>
|
||||
<PopoverAnchor asChild>
|
||||
<div
|
||||
className="relative"
|
||||
data-identity-suggestions-anchor=""
|
||||
>
|
||||
<Input
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(e) => {
|
||||
const next = e.target.value;
|
||||
onChange(next);
|
||||
const q = next.toLowerCase().trim();
|
||||
const matches = q
|
||||
? identities.filter(
|
||||
(i) =>
|
||||
i.label.toLowerCase().includes(q) ||
|
||||
i.username.toLowerCase().includes(q) ||
|
||||
(i.domain && i.domain.toLowerCase().includes(q)),
|
||||
)
|
||||
: identities;
|
||||
setOpen(matches.length > 0);
|
||||
}}
|
||||
onFocus={() => {
|
||||
setOpen(filteredIdentities.length > 0);
|
||||
}}
|
||||
className={className ? `${className} pr-9` : "h-10 rounded-lg pr-9"}
|
||||
/>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("hostDetails.identity.suggestions")}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground transition-colors"
|
||||
onClick={() => {
|
||||
setOpen((prev) => {
|
||||
if (prev) return false;
|
||||
return filteredIdentities.length > 0;
|
||||
});
|
||||
}}
|
||||
>
|
||||
<ChevronDown size={16} />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t("hostDetails.identity.suggestions")}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</PopoverAnchor>
|
||||
<PopoverContent
|
||||
className="p-0 border-border/60"
|
||||
align="start"
|
||||
sideOffset={4}
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
onInteractOutside={(e) => {
|
||||
const target = e.target as Element | null;
|
||||
if (target?.closest("[data-identity-suggestions-anchor]")) {
|
||||
e.preventDefault();
|
||||
}
|
||||
}}
|
||||
style={{ width: "var(--radix-popover-trigger-width)" }}
|
||||
>
|
||||
<ScrollArea className="max-h-[280px]">
|
||||
<div className="p-1">
|
||||
{filteredIdentities.length === 0 ? (
|
||||
<div className="py-4 text-center text-sm text-muted-foreground">
|
||||
{t("common.noResultsFound")}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{filteredIdentities.map((identity) => {
|
||||
const keyLabel = identity.keyId
|
||||
? availableKeys.find((k) => k.id === identity.keyId)?.label
|
||||
: undefined;
|
||||
const methodLabel =
|
||||
identity.authMethod === "certificate"
|
||||
? t("hostDetails.credential.certificate")
|
||||
: identity.authMethod === "key"
|
||||
? t("hostDetails.credential.key")
|
||||
: t("keychain.identity.method.passwordOnly");
|
||||
const displayUser = identity.domain
|
||||
? `${identity.domain}\\${identity.username}`
|
||||
: identity.username;
|
||||
const summaryParts = [
|
||||
displayUser,
|
||||
identity.password ? "******" : undefined,
|
||||
keyLabel,
|
||||
].filter(Boolean);
|
||||
|
||||
return (
|
||||
<button
|
||||
key={identity.id}
|
||||
type="button"
|
||||
className="w-full flex items-center gap-3 px-3 py-2 rounded-md hover:bg-secondary/80 transition-colors text-left"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
onSelectIdentity(identity);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<div className="h-8 w-8 rounded-md bg-green-500/15 text-green-500 flex items-center justify-center shrink-0">
|
||||
<User size={16} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-medium truncate">
|
||||
{identity.label}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground truncate">
|
||||
{methodLabel}
|
||||
{summaryParts.length
|
||||
? ` - ${summaryParts.join(", ")}`
|
||||
: ""}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,413 @@
|
||||
import {
|
||||
ChevronDown,
|
||||
ClipboardCopy,
|
||||
Eye,
|
||||
FolderUp,
|
||||
Gauge,
|
||||
Maximize2,
|
||||
Monitor,
|
||||
MousePointer2,
|
||||
Palette,
|
||||
Scaling,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
SlidersHorizontal,
|
||||
Sparkles,
|
||||
Users,
|
||||
Volume2,
|
||||
} from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import {
|
||||
DEFAULT_RDP_CONFIG,
|
||||
DEFAULT_VNC_CONFIG,
|
||||
normalizeRdpConfig,
|
||||
normalizeVncConfig,
|
||||
} from "../../domain/remoteDesktop";
|
||||
import type {
|
||||
Host,
|
||||
RdpColorDepth,
|
||||
RdpConfig,
|
||||
RdpResolutionMode,
|
||||
RdpSecurityMode,
|
||||
VncConfig,
|
||||
VncScalingMode,
|
||||
} from "../../types";
|
||||
import { Button } from "../ui/button";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "../ui/collapsible";
|
||||
import { Input } from "../ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { HostDetailsSection, HostDetailsSettingRow } from "./HostDetailsSection";
|
||||
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||
|
||||
interface RemoteDesktopOptionsSectionProps {
|
||||
form: Host;
|
||||
setForm: React.Dispatch<React.SetStateAction<Host>>;
|
||||
t: Translate;
|
||||
}
|
||||
|
||||
export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionProps> = ({
|
||||
form,
|
||||
setForm,
|
||||
t,
|
||||
}) => {
|
||||
const [advancedOpen, setAdvancedOpen] = useState(() =>
|
||||
Boolean(
|
||||
form.rdpConfig?.loadBalanceInfo ||
|
||||
form.rdpConfig?.alternateShell ||
|
||||
form.rdpConfig?.shellWorkingDir,
|
||||
),
|
||||
);
|
||||
|
||||
if (form.protocol === "rdp") {
|
||||
const rdp = normalizeRdpConfig(form.rdpConfig);
|
||||
const updateRdp = <K extends keyof RdpConfig>(key: K, value: RdpConfig[K]) => {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
rdpConfig: {
|
||||
...(prev.rdpConfig ?? {}),
|
||||
[key]: value,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
return (
|
||||
<HostDetailsSection
|
||||
icon={<Monitor size={14} className="text-muted-foreground" />}
|
||||
title={t("hostDetails.remoteDesktop.sectionTitle")}
|
||||
>
|
||||
<HostDetailsSettingRow
|
||||
icon={<Maximize2 />}
|
||||
label={t("hostDetails.rdp.resolutionMode")}
|
||||
>
|
||||
<Select
|
||||
value={rdp.resolutionMode}
|
||||
onValueChange={(value) =>
|
||||
updateRdp("resolutionMode", value as RdpResolutionMode)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-44 text-sm">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="dynamic">{t("hostDetails.rdp.resolutionMode.dynamic")}</SelectItem>
|
||||
<SelectItem value="fit">{t("hostDetails.rdp.resolutionMode.fit")}</SelectItem>
|
||||
<SelectItem value="fixed">{t("hostDetails.rdp.resolutionMode.fixed")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
{rdp.resolutionMode === "fixed" && (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="flex items-center justify-between gap-2 bg-transparent px-1 h-10">
|
||||
<span className="text-sm font-medium text-foreground shrink-0">{t("hostDetails.rdp.width")}</span>
|
||||
<Input
|
||||
type="number"
|
||||
min={200}
|
||||
max={8192}
|
||||
value={rdp.width}
|
||||
onChange={(e) => {
|
||||
const n = Number.parseInt(e.target.value, 10);
|
||||
if (Number.isFinite(n)) updateRdp("width", n);
|
||||
}}
|
||||
className="h-8 w-20 text-sm text-center font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-2 bg-transparent px-1 h-10">
|
||||
<span className="text-sm font-medium text-foreground shrink-0">{t("hostDetails.rdp.height")}</span>
|
||||
<Input
|
||||
type="number"
|
||||
min={200}
|
||||
max={8192}
|
||||
value={rdp.height}
|
||||
onChange={(e) => {
|
||||
const n = Number.parseInt(e.target.value, 10);
|
||||
if (Number.isFinite(n)) updateRdp("height", n);
|
||||
}}
|
||||
className="h-8 w-20 text-sm text-center font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<Palette />}
|
||||
label={t("hostDetails.rdp.colorDepth")}
|
||||
>
|
||||
<Select
|
||||
value={String(rdp.colorDepth)}
|
||||
onValueChange={(value) =>
|
||||
updateRdp("colorDepth", Number(value) as RdpColorDepth)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-44 text-sm">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="32">32-bit</SelectItem>
|
||||
<SelectItem value="24">24-bit</SelectItem>
|
||||
<SelectItem value="16">16-bit</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<Volume2 />}
|
||||
label={t("hostDetails.rdp.audio")}
|
||||
hint={t("hostDetails.rdp.audioDesc")}
|
||||
>
|
||||
<Switch
|
||||
checked={rdp.audioEnabled}
|
||||
onCheckedChange={(checked) => updateRdp("audioEnabled", checked)}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<ClipboardCopy />}
|
||||
label={t("hostDetails.rdp.clipboard")}
|
||||
hint={t("hostDetails.rdp.clipboardDesc")}
|
||||
>
|
||||
<Switch
|
||||
checked={rdp.clipboardSync}
|
||||
onCheckedChange={(checked) => updateRdp("clipboardSync", checked)}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
{rdp.clipboardSync && (
|
||||
<HostDetailsSettingRow
|
||||
icon={<FolderUp />}
|
||||
label={t("hostDetails.rdp.clipboardFiles")}
|
||||
hint={t("hostDetails.rdp.clipboardFilesDesc")}
|
||||
>
|
||||
<Switch
|
||||
checked={rdp.clipboardFilesEnabled}
|
||||
onCheckedChange={(checked) => updateRdp("clipboardFilesEnabled", checked)}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
)}
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<ShieldCheck />}
|
||||
label={t("hostDetails.rdp.securityMode")}
|
||||
>
|
||||
<Select
|
||||
value={rdp.securityMode}
|
||||
onValueChange={(value) =>
|
||||
updateRdp("securityMode", value as RdpSecurityMode)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-44 text-sm">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="auto">{t("hostDetails.rdp.securityMode.auto")}</SelectItem>
|
||||
<SelectItem value="nla">{t("hostDetails.rdp.securityMode.nla")}</SelectItem>
|
||||
<SelectItem value="tls">{t("hostDetails.rdp.securityMode.tls")}</SelectItem>
|
||||
<SelectItem value="rdp">{t("hostDetails.rdp.securityMode.rdp")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<ShieldAlert />}
|
||||
label={t("hostDetails.rdp.ignoreCertErrors")}
|
||||
hint={t("hostDetails.rdp.ignoreCertErrorsDesc")}
|
||||
>
|
||||
<Switch
|
||||
checked={rdp.ignoreCertErrors}
|
||||
onCheckedChange={(checked) => updateRdp("ignoreCertErrors", checked)}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="group w-full justify-between h-8 px-2 hover:bg-accent/50"
|
||||
>
|
||||
<span className="inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
|
||||
<SlidersHorizontal size={13} />
|
||||
{t("hostDetails.rdp.advanced")}
|
||||
</span>
|
||||
<ChevronDown size={14} className="text-muted-foreground group-data-[state=open]:rotate-180 transition-transform" />
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="mt-2 space-y-2.5 rounded-lg border border-border/60 bg-secondary/25 p-2.5">
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs text-muted-foreground">
|
||||
{t("hostDetails.rdp.loadBalanceInfo")}
|
||||
</label>
|
||||
<Input
|
||||
value={form.rdpConfig?.loadBalanceInfo ?? ""}
|
||||
onChange={(e) =>
|
||||
updateRdp("loadBalanceInfo", e.target.value || undefined)
|
||||
}
|
||||
placeholder={t("hostDetails.rdp.loadBalanceInfoPlaceholder")}
|
||||
className="h-10 rounded-lg text-sm font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs text-muted-foreground">
|
||||
{t("hostDetails.rdp.alternateShell")}
|
||||
</label>
|
||||
<Input
|
||||
value={form.rdpConfig?.alternateShell ?? ""}
|
||||
onChange={(e) =>
|
||||
updateRdp("alternateShell", e.target.value || undefined)
|
||||
}
|
||||
placeholder={t("hostDetails.rdp.alternateShellPlaceholder")}
|
||||
className="h-10 rounded-lg text-sm font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs text-muted-foreground">
|
||||
{t("hostDetails.rdp.shellWorkingDir")}
|
||||
</label>
|
||||
<Input
|
||||
value={form.rdpConfig?.shellWorkingDir ?? ""}
|
||||
onChange={(e) =>
|
||||
updateRdp("shellWorkingDir", e.target.value || undefined)
|
||||
}
|
||||
placeholder={t("hostDetails.rdp.shellWorkingDirPlaceholder")}
|
||||
className="h-10 rounded-lg text-sm font-mono"
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</HostDetailsSection>
|
||||
);
|
||||
}
|
||||
|
||||
if (form.protocol === "vnc") {
|
||||
const vnc = normalizeVncConfig(form.vncConfig);
|
||||
const updateVnc = <K extends keyof VncConfig>(key: K, value: VncConfig[K]) => {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
vncConfig: {
|
||||
...(prev.vncConfig ?? {}),
|
||||
[key]: value,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
return (
|
||||
<HostDetailsSection
|
||||
icon={<Monitor size={14} className="text-muted-foreground" />}
|
||||
title={t("hostDetails.remoteDesktop.sectionTitle")}
|
||||
>
|
||||
<HostDetailsSettingRow
|
||||
icon={<Scaling />}
|
||||
label={t("hostDetails.vnc.scalingMode")}
|
||||
>
|
||||
<Select
|
||||
value={vnc.scalingMode}
|
||||
onValueChange={(value) =>
|
||||
updateVnc("scalingMode", value as VncScalingMode)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-44 text-sm">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="fit">{t("hostDetails.vnc.scalingMode.fit")}</SelectItem>
|
||||
<SelectItem value="actual">{t("hostDetails.vnc.scalingMode.actual")}</SelectItem>
|
||||
<SelectItem value="stretch">{t("hostDetails.vnc.scalingMode.stretch")}</SelectItem>
|
||||
<SelectItem value="dynamic">{t("hostDetails.vnc.scalingMode.dynamic")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<Sparkles />}
|
||||
label={t("hostDetails.vnc.quality")}
|
||||
>
|
||||
<div className="flex items-center justify-end gap-2 w-44">
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={9}
|
||||
step={1}
|
||||
value={vnc.quality ?? DEFAULT_VNC_CONFIG.quality}
|
||||
onChange={(e) => updateVnc("quality", Number(e.target.value))}
|
||||
aria-label={t("hostDetails.vnc.quality")}
|
||||
className="flex-1 min-w-0 accent-primary"
|
||||
/>
|
||||
<span className="w-9 rounded bg-background/80 border border-border/60 px-1 py-0.5 text-center font-mono text-xs text-foreground shrink-0">
|
||||
{vnc.quality}/9
|
||||
</span>
|
||||
</div>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<Gauge />}
|
||||
label={t("hostDetails.vnc.compression")}
|
||||
>
|
||||
<div className="flex items-center justify-end gap-2 w-44">
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={9}
|
||||
step={1}
|
||||
value={vnc.compressionLevel ?? DEFAULT_VNC_CONFIG.compressionLevel}
|
||||
onChange={(e) => updateVnc("compressionLevel", Number(e.target.value))}
|
||||
aria-label={t("hostDetails.vnc.compression")}
|
||||
className="flex-1 min-w-0 accent-primary"
|
||||
/>
|
||||
<span className="w-9 rounded bg-background/80 border border-border/60 px-1 py-0.5 text-center font-mono text-xs text-foreground shrink-0">
|
||||
{vnc.compressionLevel}/9
|
||||
</span>
|
||||
</div>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<Eye />}
|
||||
label={t("hostDetails.vnc.viewOnly")}
|
||||
hint={t("hostDetails.vnc.viewOnlyDesc")}
|
||||
>
|
||||
<Switch
|
||||
checked={vnc.viewOnly}
|
||||
onCheckedChange={(checked) => updateVnc("viewOnly", checked)}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<Users />}
|
||||
label={t("hostDetails.vnc.sharedSession")}
|
||||
hint={t("hostDetails.vnc.sharedSessionDesc")}
|
||||
>
|
||||
<Switch
|
||||
checked={vnc.sharedSession}
|
||||
onCheckedChange={(checked) => updateVnc("sharedSession", checked)}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<ClipboardCopy />}
|
||||
label={t("hostDetails.vnc.clipboard")}
|
||||
hint={t("hostDetails.vnc.clipboardDesc")}
|
||||
>
|
||||
<Switch
|
||||
checked={vnc.clipboardSync}
|
||||
onCheckedChange={(checked) => updateVnc("clipboardSync", checked)}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
|
||||
<HostDetailsSettingRow
|
||||
icon={<MousePointer2 />}
|
||||
label={t("hostDetails.vnc.showRemoteCursor")}
|
||||
hint={t("hostDetails.vnc.showRemoteCursorDesc")}
|
||||
>
|
||||
<Switch
|
||||
checked={vnc.showRemoteCursor}
|
||||
onCheckedChange={(checked) => updateVnc("showRemoteCursor", checked)}
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
</HostDetailsSection>
|
||||
);
|
||||
}
|
||||
|
||||
void DEFAULT_RDP_CONFIG;
|
||||
return null;
|
||||
};
|
||||
@@ -1,11 +1,26 @@
|
||||
import { Copy, FileSymlink, Files, Folder, FolderOpen, Globe2, Monitor, Pencil, Plus, Server, Settings2 } from 'lucide-react';
|
||||
import { Copy, FileSymlink, Files, Folder, FolderOpen, Globe2, Monitor, Pencil, Plus, Server, Settings2, Shield } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import {
|
||||
RdpProtocolIcon,
|
||||
SystemRdpClientIcon,
|
||||
SystemVncClientIcon,
|
||||
VncProtocolIcon,
|
||||
} from '../icons/RemoteDesktopIcons';
|
||||
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { requestOpenDualPaneSftp } from '../../application/state/sftp/sftpDualPaneOpenStore';
|
||||
import { useSettingsChromeStore } from '../../application/state/settingsChromeStore';
|
||||
import { sanitizeHost } from '../../domain/host';
|
||||
import { isPluginHostProtocol } from '../../domain/pluginConnection';
|
||||
import {
|
||||
buildHostForProtocolOverride,
|
||||
getAvailableRemoteDesktopProtocols,
|
||||
hasCompanionRdp,
|
||||
hasCompanionVnc,
|
||||
resolveHostDefaultConnectProtocol,
|
||||
shouldPromptHostProtocolOnConnect,
|
||||
type RemoteDesktopProtocol,
|
||||
} from '../../domain/remoteDesktop';
|
||||
import { canOpenDualPaneSftp } from '../../domain/sftpDualPaneOpen';
|
||||
import type { Host } from '../../types';
|
||||
import { ContextMenuContent, ContextMenuItem, ContextMenuShortcut } from '../ui/context-menu';
|
||||
@@ -14,6 +29,8 @@ import { PluginContributionIcon } from '../plugins/PluginContributionIcon';
|
||||
|
||||
export interface HostTreeHostContextMenuHandlers {
|
||||
onConnect: (host: Host) => void;
|
||||
onConnectRemoteDesktop?: (host: Host, protocol: RemoteDesktopProtocol) => void;
|
||||
onOpenSystemRemoteDesktop?: (host: Host, protocol: RemoteDesktopProtocol) => void;
|
||||
onOpenBrowser?: (host: Host) => void;
|
||||
onEditHost?: (host: Host) => void;
|
||||
onRenameHost?: (host: Host) => void;
|
||||
@@ -34,6 +51,71 @@ export const OpenDualPaneSftpMenuItem: React.FC<{ host: Host }> = ({ host }) =>
|
||||
);
|
||||
};
|
||||
|
||||
export const CompanionRemoteDesktopMenuItems: React.FC<{
|
||||
host: Host;
|
||||
onConnect?: (host: Host) => void;
|
||||
onConnectRemoteDesktop?: (host: Host, protocol: RemoteDesktopProtocol) => void;
|
||||
}> = ({ host, onConnect, onConnectRemoteDesktop }) => {
|
||||
const { t } = useI18n();
|
||||
const showRdp = Boolean(onConnectRemoteDesktop) && hasCompanionRdp(host);
|
||||
const showVnc = Boolean(onConnectRemoteDesktop) && hasCompanionVnc(host);
|
||||
const defaultProto = resolveHostDefaultConnectProtocol(host);
|
||||
const promptsOnConnect = shouldPromptHostProtocolOnConnect(host);
|
||||
const showDirectSsh =
|
||||
Boolean(onConnect) &&
|
||||
(showRdp || showVnc) &&
|
||||
(promptsOnConnect || defaultProto !== 'ssh');
|
||||
if (!showRdp && !showVnc && !showDirectSsh) return null;
|
||||
return (
|
||||
<>
|
||||
{showDirectSsh && onConnect && (
|
||||
<ContextMenuItem
|
||||
onClick={() => {
|
||||
const dispatch = buildHostForProtocolOverride(host, 'ssh', host.port || 22);
|
||||
onConnect({ ...dispatch.host, connectProtocolBehavior: 'default' });
|
||||
}}
|
||||
>
|
||||
<Shield className="mr-2 h-4 w-4 text-sky-500" /> {t('vault.hosts.connectSsh')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{showRdp && onConnectRemoteDesktop && (promptsOnConnect || defaultProto !== 'rdp') && (
|
||||
<ContextMenuItem onClick={() => onConnectRemoteDesktop(host, 'rdp')}>
|
||||
<RdpProtocolIcon size={15} className="mr-2 text-blue-500" /> {t('vault.hosts.connectRdp')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{showVnc && onConnectRemoteDesktop && (promptsOnConnect || defaultProto !== 'vnc') && (
|
||||
<ContextMenuItem onClick={() => onConnectRemoteDesktop(host, 'vnc')}>
|
||||
<VncProtocolIcon size={15} className="mr-2 text-teal-500" /> {t('vault.hosts.connectVnc')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const OpenSystemRemoteDesktopMenuItems: React.FC<{
|
||||
host: Host;
|
||||
onOpenSystemRemoteDesktop?: (host: Host, protocol: RemoteDesktopProtocol) => void;
|
||||
}> = ({ host, onOpenSystemRemoteDesktop }) => {
|
||||
const { t } = useI18n();
|
||||
if (!onOpenSystemRemoteDesktop) return null;
|
||||
const protocols = getAvailableRemoteDesktopProtocols(host);
|
||||
if (protocols.length === 0) return null;
|
||||
return (
|
||||
<>
|
||||
{protocols.includes('rdp') && (
|
||||
<ContextMenuItem onClick={() => onOpenSystemRemoteDesktop(host, 'rdp')}>
|
||||
<SystemRdpClientIcon size={15} className="mr-2 text-blue-500/85" /> {t('vault.hosts.openInSystemRdp')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{protocols.includes('vnc') && (
|
||||
<ContextMenuItem onClick={() => onOpenSystemRemoteDesktop(host, 'vnc')}>
|
||||
<SystemVncClientIcon size={15} className="mr-2 text-teal-500/85" /> {t('vault.hosts.openInSystemVnc')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const OpenHostBrowserMenuItem: React.FC<{ host: Host; onOpenBrowser?: (host: Host) => void }> = ({ host, onOpenBrowser }) => {
|
||||
const { t } = useI18n();
|
||||
if (!onOpenBrowser || (host.protocol && !['ssh', 'mosh', 'local'].includes(host.protocol))) return null;
|
||||
@@ -45,6 +127,8 @@ export const HostTreeHostContextMenuContent: React.FC<
|
||||
> = ({
|
||||
host,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onOpenSystemRemoteDesktop,
|
||||
onOpenBrowser,
|
||||
onEditHost,
|
||||
onRenameHost,
|
||||
@@ -73,7 +157,16 @@ export const HostTreeHostContextMenuContent: React.FC<
|
||||
<Monitor className="mr-2 h-4 w-4" /> {t('vault.hosts.connect')}
|
||||
</ContextMenuItem>
|
||||
<OpenDualPaneSftpMenuItem host={safeHost} />
|
||||
<CompanionRemoteDesktopMenuItems
|
||||
host={safeHost}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
/>
|
||||
<OpenHostBrowserMenuItem host={safeHost} onOpenBrowser={onOpenBrowser} />
|
||||
<OpenSystemRemoteDesktopMenuItems
|
||||
host={safeHost}
|
||||
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
|
||||
/>
|
||||
{onEditHost && (
|
||||
<ContextMenuItem onClick={() => onEditHost(host)}>
|
||||
<Settings2 className="mr-2 h-4 w-4" /> {t('terminal.layer.hostTree.editHost')}
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
import React from "react";
|
||||
|
||||
export interface RemoteDesktopIconProps extends React.SVGProps<SVGSVGElement> {
|
||||
size?: number | string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expressive RDP protocol emblem: widescreen monitor frame with subtle depth
|
||||
* fill and dual opposing remote-session arrows inspired by Remote Desktop.
|
||||
*/
|
||||
export const RdpProtocolIcon: React.FC<RemoteDesktopIconProps> = ({
|
||||
size = 16,
|
||||
className,
|
||||
...props
|
||||
}) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
aria-hidden="true"
|
||||
{...props}
|
||||
>
|
||||
<rect
|
||||
x="2.25"
|
||||
y="3.25"
|
||||
width="19.5"
|
||||
height="13.5"
|
||||
rx="2.5"
|
||||
fill="currentColor"
|
||||
fillOpacity="0.12"
|
||||
/>
|
||||
{/* Upper right-pointing arrow */}
|
||||
<path d="M8 8.25h7.5" />
|
||||
<path d="M13 5.75L15.5 8.25L13 10.75" />
|
||||
{/* Lower left-pointing arrow */}
|
||||
<path d="M16 12.25H8.5" />
|
||||
<path d="M11 9.75L8.5 12.25L11 14.75" />
|
||||
{/* Monitor stand */}
|
||||
<path d="M9.5 16.75L8.75 20.25" />
|
||||
<path d="M14.5 16.75L15.25 20.25" />
|
||||
<path d="M7.25 20.25h9.5" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
/**
|
||||
* Expressive VNC / RFB protocol emblem: layered remote framebuffer viewport
|
||||
* with dual linked displays and viewport corner reticle.
|
||||
*/
|
||||
export const VncProtocolIcon: React.FC<RemoteDesktopIconProps> = ({
|
||||
size = 16,
|
||||
className,
|
||||
...props
|
||||
}) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
aria-hidden="true"
|
||||
{...props}
|
||||
>
|
||||
{/* Back remote display window */}
|
||||
<path
|
||||
d="M7.5 6.25V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-1.25"
|
||||
opacity="0.65"
|
||||
/>
|
||||
{/* Front active RFB viewport */}
|
||||
<rect
|
||||
x="2.5"
|
||||
y="7.25"
|
||||
width="15.25"
|
||||
height="11.25"
|
||||
rx="2.25"
|
||||
fill="currentColor"
|
||||
fillOpacity="0.12"
|
||||
/>
|
||||
{/* Window titlebar bar + viewport pulse */}
|
||||
<path d="M2.75 10.75h14.75" opacity="0.55" />
|
||||
<circle cx="5.25" cy="9" r="0.6" fill="currentColor" stroke="none" />
|
||||
<circle cx="7.5" cy="9" r="0.6" fill="currentColor" stroke="none" />
|
||||
{/* Cursor / remote control triangle inside viewport */}
|
||||
<path d="M8.5 12.75L12.75 14.35L10.95 15.1L10.2 16.9L8.5 12.75Z" fill="currentColor" fillOpacity="0.28" />
|
||||
{/* Stand base */}
|
||||
<path d="M7.25 21h5.75" />
|
||||
<path d="M10.125 18.5V21" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
/**
|
||||
* Expressive JumpServer bastion emblem: faceted security shield containing a
|
||||
* bastion bridge node linking client to privileged remote target.
|
||||
*/
|
||||
export const JumpServerIcon: React.FC<RemoteDesktopIconProps> = ({
|
||||
size = 16,
|
||||
className,
|
||||
...props
|
||||
}) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
aria-hidden="true"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d="M12 2.5L4.25 5.6v5.55c0 4.95 3.3 9.2 7.75 10.6 4.45-1.4 7.75-5.65 7.75-10.6V5.6L12 2.5Z"
|
||||
fill="currentColor"
|
||||
fillOpacity="0.12"
|
||||
/>
|
||||
{/* Bastion hop arc & nodes */}
|
||||
<path d="M8 13.75c0-2.5 1.75-4.5 4-4.5s4 2 4 4.5" />
|
||||
<circle cx="8" cy="14" r="1.25" fill="currentColor" />
|
||||
<circle cx="16" cy="14" r="1.25" fill="currentColor" />
|
||||
<circle cx="12" cy="8.5" r="1.35" fill="currentColor" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
/**
|
||||
* Expressive SSH Tunnel / Bastion route glyph: encrypted arch routing traffic
|
||||
* through a secured node between two endpoints.
|
||||
*/
|
||||
export const SshTunnelIcon: React.FC<RemoteDesktopIconProps> = ({
|
||||
size = 16,
|
||||
className,
|
||||
...props
|
||||
}) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
aria-hidden="true"
|
||||
{...props}
|
||||
>
|
||||
{/* Tunnel arch */}
|
||||
<path d="M4.5 16.5V12a7.5 7.5 0 0 1 15 0v4.5" opacity="0.45" />
|
||||
<path d="M7.5 16.5V12a4.5 4.5 0 0 1 9 0v4.5" />
|
||||
{/* Endpoint nodes */}
|
||||
<circle cx="4.5" cy="17.5" r="2" fill="currentColor" fillOpacity="0.16" />
|
||||
<circle cx="19.5" cy="17.5" r="2" fill="currentColor" fillOpacity="0.16" />
|
||||
{/* Encrypted lock badge at crest */}
|
||||
<rect
|
||||
x="9.5"
|
||||
y="12.5"
|
||||
width="5"
|
||||
height="4.25"
|
||||
rx="1"
|
||||
fill="currentColor"
|
||||
fillOpacity="0.22"
|
||||
/>
|
||||
<path d="M10.75 12.5v-1a1.25 1.25 0 0 1 2.5 0v1" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
/**
|
||||
* System RDP Client icon: desktop screen with window panes and external launch arrow.
|
||||
*/
|
||||
export const SystemRdpClientIcon: React.FC<RemoteDesktopIconProps> = ({
|
||||
size = 16,
|
||||
className,
|
||||
...props
|
||||
}) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
aria-hidden="true"
|
||||
{...props}
|
||||
>
|
||||
<path d="M12.5 4H5a2.25 2.25 0 0 0-2.25 2.25v9.5A2.25 2.25 0 0 0 5 18h14a2.25 2.25 0 0 0 2.25-2.25V12" />
|
||||
<path d="M8.5 21h7" />
|
||||
<path d="M12 18v3" />
|
||||
{/* Four-pane window glyph inside left half */}
|
||||
<rect x="5.75" y="7.5" width="3" height="2.75" rx="0.5" fill="currentColor" fillOpacity="0.22" />
|
||||
<rect x="10.25" y="7.5" width="3" height="2.75" rx="0.5" fill="currentColor" fillOpacity="0.12" />
|
||||
<rect x="5.75" y="11.75" width="3" height="2.75" rx="0.5" fill="currentColor" fillOpacity="0.12" />
|
||||
<rect x="10.25" y="11.75" width="3" height="2.75" rx="0.5" fill="currentColor" fillOpacity="0.22" />
|
||||
{/* External launch arrow */}
|
||||
<path d="M16.25 3.75H20.5V8" />
|
||||
<path d="M15.25 9L20.5 3.75" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
/**
|
||||
* System VNC / macOS Screen Sharing icon: overlapping displays with external launch cue.
|
||||
*/
|
||||
export const SystemVncClientIcon: React.FC<RemoteDesktopIconProps> = ({
|
||||
size = 16,
|
||||
className,
|
||||
...props
|
||||
}) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
aria-hidden="true"
|
||||
{...props}
|
||||
>
|
||||
<rect
|
||||
x="3"
|
||||
y="8.25"
|
||||
width="13.5"
|
||||
height="10.25"
|
||||
rx="2"
|
||||
fill="currentColor"
|
||||
fillOpacity="0.14"
|
||||
/>
|
||||
<path d="M7.25 21h5" />
|
||||
<path d="M9.75 18.5V21" />
|
||||
<path d="M7 8.25V6a2 2 0 0 1 2-2h3.5" opacity="0.65" />
|
||||
{/* External launch arrow */}
|
||||
<path d="M16.25 3.75H20.5V8" />
|
||||
<path d="M15.25 9L20.5 3.75" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
/**
|
||||
* Rich `.rdp` file badge icon for ImportVaultDialog: folded document sheet with
|
||||
* remote-desktop dual-arrow emblem and crisp `.RDP` file extension tag.
|
||||
*/
|
||||
export const RdpFileBadgeIcon: React.FC<RemoteDesktopIconProps> = ({
|
||||
size = 48,
|
||||
className,
|
||||
...props
|
||||
}) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 48 48"
|
||||
fill="none"
|
||||
className={className}
|
||||
aria-hidden="true"
|
||||
{...props}
|
||||
>
|
||||
{/* Document sheet */}
|
||||
<path
|
||||
d="M11 6.5A3.5 3.5 0 0 1 14.5 3h13.75L37 11.75V41.5A3.5 3.5 0 0 1 33.5 45h-19A3.5 3.5 0 0 1 11 41.5v-35Z"
|
||||
fill="#3B82F6"
|
||||
fillOpacity="0.12"
|
||||
stroke="#3B82F6"
|
||||
strokeWidth="2"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
{/* Folded corner */}
|
||||
<path
|
||||
d="M28 3.25V10a2 2 0 0 0 2 2h6.75"
|
||||
fill="#3B82F6"
|
||||
fillOpacity="0.2"
|
||||
stroke="#3B82F6"
|
||||
strokeWidth="2"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
{/* Mini dual-arrow monitor inside sheet */}
|
||||
<rect
|
||||
x="16.5"
|
||||
y="14.5"
|
||||
width="15"
|
||||
height="10.5"
|
||||
rx="2"
|
||||
fill="#3B82F6"
|
||||
fillOpacity="0.16"
|
||||
stroke="#2563EB"
|
||||
strokeWidth="1.75"
|
||||
/>
|
||||
<path
|
||||
d="M20.5 18.25h7m-2-2L27.5 18.25L25.5 20.25"
|
||||
stroke="#2563EB"
|
||||
strokeWidth="1.6"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M27.5 21.5h-7m2-2L20.5 21.5L22.5 23.5"
|
||||
stroke="#2563EB"
|
||||
strokeWidth="1.6"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M21.5 27.5h5"
|
||||
stroke="#2563EB"
|
||||
strokeWidth="1.75"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
{/* .RDP extension pill */}
|
||||
<rect x="7" y="30.5" width="34" height="11.5" rx="3.5" fill="#2563EB" />
|
||||
<text
|
||||
x="24"
|
||||
y="38.75"
|
||||
textAnchor="middle"
|
||||
fill="#FFFFFF"
|
||||
fontSize="8.5"
|
||||
fontWeight="700"
|
||||
fontFamily="ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"
|
||||
letterSpacing="0.5"
|
||||
>
|
||||
.RDP
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
@@ -97,6 +97,15 @@ export const IdentityPanel: React.FC<IdentityPanelProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{t('keychain.identity.domain')}</Label>
|
||||
<Input
|
||||
value={draftIdentity.domain || ''}
|
||||
onChange={e => setDraftIdentity({ ...draftIdentity, domain: e.target.value })}
|
||||
placeholder={t('keychain.identity.domainPlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{t('terminal.auth.passwordLabel')}</Label>
|
||||
<div className="relative">
|
||||
|
||||
@@ -6,13 +6,19 @@ import {
|
||||
} from "lucide-react";
|
||||
import React from "react";
|
||||
import type { HostProtocol } from "../types";
|
||||
import { RdpProtocolIcon, VncProtocolIcon } from "./icons/RemoteDesktopIcons";
|
||||
|
||||
export type ProtocolVisualKey = Extract<HostProtocol, "ssh" | "mosh" | "et" | "telnet">;
|
||||
export type ProtocolVisualKey = Extract<
|
||||
HostProtocol,
|
||||
"ssh" | "mosh" | "et" | "telnet" | "rdp" | "vnc"
|
||||
>;
|
||||
|
||||
export interface ProtocolVisualStyle {
|
||||
icon: React.ReactNode;
|
||||
idle: string;
|
||||
selected: string;
|
||||
badge: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export const PROTOCOL_OPTION_CARD_BASE_CLASS =
|
||||
@@ -44,24 +50,64 @@ export const PROTOCOL_VISUAL_STYLES: Record<ProtocolVisualKey, ProtocolVisualSty
|
||||
icon: <Shield size={18} />,
|
||||
idle: "bg-sky-500/10 text-sky-500",
|
||||
selected: "bg-sky-500 text-white shadow-sm",
|
||||
badge: "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20",
|
||||
label: "SSH",
|
||||
},
|
||||
mosh: {
|
||||
icon: <Radio size={18} />,
|
||||
idle: "bg-violet-500/10 text-violet-500",
|
||||
selected: "bg-violet-500 text-white shadow-sm",
|
||||
badge: "bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20",
|
||||
label: "Mosh",
|
||||
},
|
||||
et: {
|
||||
icon: <Link2 size={18} />,
|
||||
idle: "bg-emerald-500/10 text-emerald-500",
|
||||
selected: "bg-emerald-500 text-white shadow-sm",
|
||||
badge: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20",
|
||||
label: "ET",
|
||||
},
|
||||
telnet: {
|
||||
icon: <TerminalIcon size={18} />,
|
||||
idle: "bg-amber-500/10 text-amber-500",
|
||||
selected: "bg-amber-500 text-white shadow-sm",
|
||||
badge: "bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20",
|
||||
label: "Telnet",
|
||||
},
|
||||
rdp: {
|
||||
icon: <RdpProtocolIcon size={18} />,
|
||||
idle: "bg-blue-500/12 text-blue-500 dark:text-blue-400",
|
||||
selected: "bg-blue-500 text-white shadow-sm",
|
||||
badge: "bg-blue-500/12 text-blue-600 dark:text-blue-400 border-blue-500/25",
|
||||
label: "RDP",
|
||||
},
|
||||
vnc: {
|
||||
icon: <VncProtocolIcon size={18} />,
|
||||
idle: "bg-teal-500/12 text-teal-500 dark:text-teal-400",
|
||||
selected: "bg-teal-500 text-white shadow-sm",
|
||||
badge: "bg-teal-500/12 text-teal-600 dark:text-teal-400 border-teal-500/25",
|
||||
label: "VNC",
|
||||
},
|
||||
};
|
||||
|
||||
export function renderProtocolMiniIcon(
|
||||
protocol: Extract<ProtocolVisualKey, "rdp" | "vnc">,
|
||||
size = 11,
|
||||
className?: string,
|
||||
): React.ReactNode {
|
||||
return protocol === "rdp"
|
||||
? <RdpProtocolIcon size={size} className={className} />
|
||||
: <VncProtocolIcon size={size} className={className} />;
|
||||
}
|
||||
|
||||
export function getProtocolVisualStyle(protocol: ProtocolVisualKey): ProtocolVisualStyle {
|
||||
return PROTOCOL_VISUAL_STYLES[protocol];
|
||||
}
|
||||
|
||||
export function getProtocolBadgeClass(protocol: ProtocolVisualKey): string {
|
||||
return PROTOCOL_VISUAL_STYLES[protocol].badge;
|
||||
}
|
||||
|
||||
export function getProtocolBadgeLabel(protocol: ProtocolVisualKey): string {
|
||||
return PROTOCOL_VISUAL_STYLES[protocol].label;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,243 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
Building2,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Eye,
|
||||
EyeOff,
|
||||
KeyRound,
|
||||
Lock,
|
||||
Unplug,
|
||||
User,
|
||||
} from 'lucide-react';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import type { RemoteDesktopProtocol } from '../../domain/remoteDesktop';
|
||||
import { splitWindowsUserDomain } from '../../domain/remoteDesktop';
|
||||
import { cn } from '../../lib/utils';
|
||||
import { RdpProtocolIcon, VncProtocolIcon } from '../icons/RemoteDesktopIcons';
|
||||
import { getProtocolBadgeClass } from '../protocolVisuals';
|
||||
import { Button } from '../ui/button';
|
||||
import { Input } from '../ui/input';
|
||||
import { Label } from '../ui/label';
|
||||
import { tr } from './remoteDesktopHelpers';
|
||||
|
||||
export interface RemoteDesktopAuthDialogProps {
|
||||
protocol: RemoteDesktopProtocol;
|
||||
hostLabel: string;
|
||||
hostname: string;
|
||||
port: number;
|
||||
initialUsername: string;
|
||||
initialDomain: string;
|
||||
errorMessage?: string | null;
|
||||
onSubmit: (credentials: { username: string; password: string; domain: string }) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export const RemoteDesktopAuthDialog: React.FC<RemoteDesktopAuthDialogProps> = ({
|
||||
protocol,
|
||||
hostLabel,
|
||||
hostname,
|
||||
port,
|
||||
initialUsername,
|
||||
initialDomain,
|
||||
errorMessage,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const isRdp = protocol === 'rdp';
|
||||
const [username, setUsername] = useState(initialUsername);
|
||||
const [domain, setDomain] = useState(initialDomain);
|
||||
const [password, setPassword] = useState('');
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showVncUsername, setShowVncUsername] = useState(Boolean(initialUsername));
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (isRdp) {
|
||||
const split = splitWindowsUserDomain(username, domain);
|
||||
onSubmit({
|
||||
username: split.username,
|
||||
domain: split.domain,
|
||||
password,
|
||||
});
|
||||
return;
|
||||
}
|
||||
onSubmit({
|
||||
username: showVncUsername ? username.trim() : '',
|
||||
domain: '',
|
||||
password,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="absolute inset-0 z-40 flex items-center justify-center bg-background/80 p-4 backdrop-blur-sm"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={tr(t, 'remoteDesktop.auth.title', 'Authentication Required')}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onCancel();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="w-full max-w-sm rounded-xl border border-border/80 bg-card text-card-foreground shadow-2xl animate-in fade-in-0 zoom-in-95 duration-200"
|
||||
>
|
||||
<div className="flex items-start gap-3 border-b border-border/60 px-5 py-4">
|
||||
<div
|
||||
className={cn(
|
||||
'relative mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl',
|
||||
isRdp ? 'bg-blue-500/12 text-blue-500' : 'bg-teal-500/12 text-teal-500',
|
||||
)}
|
||||
>
|
||||
{isRdp ? <RdpProtocolIcon size={20} /> : <VncProtocolIcon size={20} />}
|
||||
<span className="absolute -bottom-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full border border-card bg-primary text-primary-foreground shadow-xs">
|
||||
<KeyRound size={9} />
|
||||
</span>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<h3 className="text-sm font-semibold leading-5">
|
||||
{isRdp
|
||||
? tr(t, 'remoteDesktop.auth.rdpTitle', 'RDP Credentials')
|
||||
: tr(t, 'remoteDesktop.auth.vncTitle', 'VNC Password')}
|
||||
</h3>
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex items-center rounded-md border px-1.5 py-0 text-[10px] font-semibold uppercase leading-4',
|
||||
getProtocolBadgeClass(protocol),
|
||||
)}
|
||||
>
|
||||
{protocol}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-0.5 truncate font-mono text-[11px] text-muted-foreground" title={`${hostLabel} (${hostname}:${port})`}>
|
||||
{hostLabel} · {hostname}:{port}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 px-5 py-4">
|
||||
{errorMessage && (
|
||||
<div className="flex items-center gap-2.5 rounded-xl border border-destructive/25 bg-destructive/8 px-3 py-2.5 text-xs">
|
||||
<div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-destructive/15 text-destructive">
|
||||
<Unplug size={11} />
|
||||
</div>
|
||||
<div className="min-w-0 leading-4 text-destructive">
|
||||
{errorMessage}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isRdp ? (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="rd-auth-username" className="inline-flex items-center gap-1.5 text-xs">
|
||||
<User size={12} className="text-muted-foreground" />
|
||||
{tr(t, 'remoteDesktop.auth.username', 'Username')}
|
||||
</Label>
|
||||
<Input
|
||||
id="rd-auth-username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="Administrator"
|
||||
autoFocus={!initialUsername}
|
||||
autoComplete="username"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="rd-auth-domain" className="inline-flex items-center gap-1.5 text-xs">
|
||||
<Building2 size={12} className="text-muted-foreground" />
|
||||
{tr(t, 'remoteDesktop.auth.domain', 'Domain (optional)')}
|
||||
</Label>
|
||||
<Input
|
||||
id="rd-auth-domain"
|
||||
value={domain}
|
||||
onChange={(e) => setDomain(e.target.value)}
|
||||
placeholder="CORP"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground"
|
||||
onClick={() => setShowVncUsername((v) => !v)}
|
||||
>
|
||||
{showVncUsername ? <ChevronDown size={13} /> : <ChevronRight size={13} />}
|
||||
<User size={12} />
|
||||
<span>{tr(t, 'remoteDesktop.auth.vncUsernameToggle', 'Username (for macOS Screen Sharing / VeNCrypt)')}</span>
|
||||
</button>
|
||||
{showVncUsername && (
|
||||
<div className="mt-2 space-y-1.5">
|
||||
<Input
|
||||
id="rd-auth-vnc-username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder={tr(t, 'remoteDesktop.auth.username', 'Username')}
|
||||
autoComplete="username"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="rd-auth-password" className="inline-flex items-center gap-1.5 text-xs">
|
||||
<Lock size={12} className="text-muted-foreground" />
|
||||
{tr(t, 'remoteDesktop.auth.password', 'Password')}
|
||||
</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="rd-auth-password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoFocus={!isRdp || Boolean(initialUsername)}
|
||||
autoComplete="current-password"
|
||||
className={cn('pr-9', errorMessage && 'border-destructive/50')}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
tabIndex={-1}
|
||||
aria-label={showPassword ? 'Hide password' : 'Show password'}
|
||||
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setShowPassword((prev) => !prev)}
|
||||
>
|
||||
{showPassword ? <EyeOff size={14} /> : <Eye size={14} />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5 rounded-lg bg-secondary/45 px-2.5 py-2 text-[11px] text-muted-foreground">
|
||||
<Lock size={11} className="shrink-0 text-emerald-500" />
|
||||
<span>
|
||||
{tr(
|
||||
t,
|
||||
'remoteDesktop.auth.sessionOnlyHint',
|
||||
'Credentials are used only for this session and are not saved to disk.',
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-2 border-t border-border/60 px-5 py-3">
|
||||
<Button type="button" variant="ghost" size="sm" onClick={onCancel}>
|
||||
{tr(t, 'common.cancel', 'Cancel')}
|
||||
</Button>
|
||||
<Button type="submit" size="sm" className="gap-1.5" disabled={isRdp && !username.trim()}>
|
||||
<KeyRound size={13} />
|
||||
<span>{tr(t, 'remoteDesktop.auth.connect', 'Connect')}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,273 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
AlertTriangle,
|
||||
Calendar,
|
||||
Check,
|
||||
Copy,
|
||||
Fingerprint,
|
||||
Globe,
|
||||
Server,
|
||||
Shield,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
} from 'lucide-react';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { cn } from '../../lib/utils';
|
||||
import { RdpProtocolIcon, VncProtocolIcon } from '../icons/RemoteDesktopIcons';
|
||||
import { getProtocolBadgeClass } from '../protocolVisuals';
|
||||
import { Button } from '../ui/button';
|
||||
import {
|
||||
tr,
|
||||
type RemoteDesktopCertDecisionValue,
|
||||
type RemoteDesktopCertVerifyEvent,
|
||||
} from './remoteDesktopHelpers';
|
||||
|
||||
export interface RemoteDesktopCertDialogProps {
|
||||
event: RemoteDesktopCertVerifyEvent;
|
||||
previousFingerprint: string | null;
|
||||
onDecision: (decision: RemoteDesktopCertDecisionValue) => void;
|
||||
}
|
||||
|
||||
export const RemoteDesktopCertDialog: React.FC<RemoteDesktopCertDialogProps> = ({
|
||||
event,
|
||||
previousFingerprint,
|
||||
onDecision,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const isChanged = Boolean(previousFingerprint);
|
||||
const isRdp = event.protocol === 'rdp';
|
||||
const protocolLabel = event.protocol.toUpperCase();
|
||||
|
||||
const handleCopyFingerprint = () => {
|
||||
void navigator.clipboard?.writeText(event.fingerprintSha256).then(() => {
|
||||
setCopied(true);
|
||||
window.setTimeout(() => setCopied(false), 1800);
|
||||
}).catch(() => {});
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="absolute inset-0 z-40 flex items-center justify-center bg-background/80 p-4 backdrop-blur-sm"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={tr(t, 'remoteDesktop.cert.title', 'Verify TLS Certificate')}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onDecision('reject');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="w-full max-w-lg rounded-xl border border-border/80 bg-card text-card-foreground shadow-2xl animate-in fade-in-0 zoom-in-95 duration-200">
|
||||
{/* Header with protocol badge & endpoint */}
|
||||
<div className="flex items-center justify-between gap-3 border-b border-border/60 px-5 py-3.5">
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
<div
|
||||
className={cn(
|
||||
'flex h-8 w-8 shrink-0 items-center justify-center rounded-lg',
|
||||
isRdp ? 'bg-blue-500/12 text-blue-500' : 'bg-teal-500/12 text-teal-500',
|
||||
)}
|
||||
>
|
||||
{isRdp ? <RdpProtocolIcon size={17} /> : <VncProtocolIcon size={17} />}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="truncate text-sm font-semibold">{event.host}</span>
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex items-center rounded-md border px-1.5 py-0 text-[10px] font-semibold uppercase leading-4 shrink-0',
|
||||
getProtocolBadgeClass(event.protocol),
|
||||
)}
|
||||
>
|
||||
{protocolLabel}
|
||||
</span>
|
||||
</div>
|
||||
<div className="truncate font-mono text-[11px] text-muted-foreground">
|
||||
{event.host}:{event.port}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
'flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ring-2',
|
||||
isChanged
|
||||
? 'bg-destructive/15 text-destructive ring-destructive/20'
|
||||
: 'bg-amber-500/15 text-amber-500 ring-amber-500/20',
|
||||
)}
|
||||
>
|
||||
{isChanged ? <ShieldAlert size={16} /> : <Fingerprint size={16} />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 px-5 py-4 text-xs">
|
||||
{/* Status callout banner (matching TerminalHostKeyVerification aesthetic) */}
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-xl border px-3.5 py-3',
|
||||
isChanged
|
||||
? 'border-destructive/30 bg-destructive/8'
|
||||
: 'border-amber-500/25 bg-amber-500/8',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start gap-2.5">
|
||||
<div
|
||||
className={cn(
|
||||
'mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg',
|
||||
isChanged
|
||||
? 'bg-destructive/15 text-destructive'
|
||||
: 'bg-amber-500/15 text-amber-500',
|
||||
)}
|
||||
>
|
||||
{isChanged ? <AlertTriangle size={15} /> : <ShieldCheck size={15} />}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<h3
|
||||
className={cn(
|
||||
'text-sm font-semibold leading-5',
|
||||
isChanged ? 'text-destructive' : 'text-amber-600 dark:text-amber-400',
|
||||
)}
|
||||
>
|
||||
{isChanged
|
||||
? tr(t, 'remoteDesktop.cert.changedTitle', 'Certificate Fingerprint Changed')
|
||||
: tr(t, 'remoteDesktop.cert.unknownTitle', 'Verify Remote Desktop Certificate')}
|
||||
</h3>
|
||||
<p className="text-xs leading-5 text-muted-foreground">
|
||||
{isChanged
|
||||
? tr(
|
||||
t,
|
||||
'remoteDesktop.cert.changedWarning',
|
||||
'The TLS certificate presented by {{host}}:{{port}} does not match the previously trusted fingerprint. This could indicate a server renewal or a man-in-the-middle attack.',
|
||||
{ host: event.host, port: event.port },
|
||||
)
|
||||
: tr(
|
||||
t,
|
||||
'remoteDesktop.cert.firstSeenHint',
|
||||
'First time connecting to {{protocol}} server {{host}}:{{port}}. Verify the SHA-256 certificate fingerprint before sending credentials.',
|
||||
{ protocol: protocolLabel, host: event.host, port: event.port },
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isChanged && previousFingerprint && (
|
||||
<div className="rounded-lg border border-destructive/35 bg-destructive/10 p-3">
|
||||
<div className="flex items-center gap-1.5 text-[11px] font-medium text-destructive">
|
||||
<AlertTriangle size={13} />
|
||||
<span>{tr(t, 'remoteDesktop.cert.previousFingerprint', 'Previously Trusted SHA-256')}</span>
|
||||
</div>
|
||||
<code className="mt-1.5 block break-all font-mono text-[11px] leading-5 text-destructive/90 select-all">
|
||||
{previousFingerprint}
|
||||
</code>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Presented SHA-256 fingerprint */}
|
||||
<div className="rounded-lg border border-border/70 bg-secondary/45 p-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground">
|
||||
<Fingerprint size={13} className="text-primary" />
|
||||
<span>{tr(t, 'remoteDesktop.cert.fingerprint', 'Presented SHA-256 Fingerprint')}</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 gap-1 px-2 text-[10px] text-muted-foreground hover:text-foreground"
|
||||
onClick={handleCopyFingerprint}
|
||||
>
|
||||
{copied ? <Check size={11} className="text-emerald-500" /> : <Copy size={11} />}
|
||||
<span>{copied ? tr(t, 'common.copied', 'Copied') : tr(t, 'common.copy', 'Copy')}</span>
|
||||
</Button>
|
||||
</div>
|
||||
<code className="mt-1.5 block break-all font-mono text-[11px] leading-5 text-foreground select-all">
|
||||
{event.fingerprintSha256}
|
||||
</code>
|
||||
</div>
|
||||
|
||||
{/* Certificate details */}
|
||||
{(event.subject || event.issuer || event.validFrom || event.validTo || event.subjectAltName) && (
|
||||
<div className="grid grid-cols-[112px_1fr] gap-x-3 gap-y-2 rounded-lg border border-border/60 bg-background/60 p-3 text-[11px]">
|
||||
{event.subject && (
|
||||
<>
|
||||
<span className="inline-flex items-center gap-1.5 text-muted-foreground">
|
||||
<Server size={11} className="shrink-0" />
|
||||
{tr(t, 'remoteDesktop.cert.subject', 'Subject')}
|
||||
</span>
|
||||
<span className="truncate font-mono text-foreground" title={event.subject}>{event.subject}</span>
|
||||
</>
|
||||
)}
|
||||
{event.issuer && (
|
||||
<>
|
||||
<span className="inline-flex items-center gap-1.5 text-muted-foreground">
|
||||
<Shield size={11} className="shrink-0" />
|
||||
{tr(t, 'remoteDesktop.cert.issuer', 'Issuer')}
|
||||
</span>
|
||||
<span className="truncate font-mono text-foreground" title={event.issuer}>{event.issuer}</span>
|
||||
</>
|
||||
)}
|
||||
{(event.validFrom || event.validTo) && (
|
||||
<>
|
||||
<span className="inline-flex items-center gap-1.5 text-muted-foreground">
|
||||
<Calendar size={11} className="shrink-0" />
|
||||
{tr(t, 'remoteDesktop.cert.validity', 'Valid')}
|
||||
</span>
|
||||
<span className="truncate text-foreground">
|
||||
{event.validFrom || '?'} — {event.validTo || '?'}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{event.subjectAltName && (
|
||||
<>
|
||||
<span className="inline-flex items-center gap-1.5 text-muted-foreground">
|
||||
<Globe size={11} className="shrink-0" />
|
||||
{tr(t, 'remoteDesktop.cert.san', 'Alt Names')}
|
||||
</span>
|
||||
<span className="truncate font-mono text-foreground" title={event.subjectAltName}>
|
||||
{event.subjectAltName}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-end gap-2 border-t border-border/60 px-5 py-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onDecision('reject')}
|
||||
>
|
||||
{tr(t, 'remoteDesktop.cert.reject', 'Reject')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onDecision('accept-once')}
|
||||
>
|
||||
{tr(t, 'remoteDesktop.cert.acceptOnce', 'Accept Once')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={isChanged ? 'destructive' : 'default'}
|
||||
size="sm"
|
||||
className="gap-1.5"
|
||||
onClick={() => onDecision('accept-always')}
|
||||
>
|
||||
<ShieldCheck size={13} />
|
||||
<span>
|
||||
{isChanged
|
||||
? tr(t, 'remoteDesktop.cert.replaceTrust', 'Update & Trust Always')
|
||||
: tr(t, 'remoteDesktop.cert.trustAlways', 'Trust Always')}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,312 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { X } from 'lucide-react';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
|
||||
export interface RemoteDesktopSnipRect {
|
||||
/** Normalized permille coordinates (0..1000) of the canvas framebuffer. */
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
/** Approximate natural framebuffer pixel dimensions for user display. */
|
||||
pixelWidth: number;
|
||||
pixelHeight: number;
|
||||
}
|
||||
|
||||
export interface SnipClientRect {
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface ComputedSnipSelection {
|
||||
/** Visual selection box relative to the overlay element (in CSS pixels). */
|
||||
displayRect: { left: number; top: number; width: number; height: number };
|
||||
/** Normalized 0..1000 crop rect relative to the live canvas framebuffer. */
|
||||
normalizedRect: RemoteDesktopSnipRect;
|
||||
}
|
||||
|
||||
export const MIN_SNIP_DRAG_PX = 8;
|
||||
|
||||
/**
|
||||
* Pure geometry helper mapping viewport drag points onto the live `<canvas>`
|
||||
* rect (handling letterboxed `fit` / `actual` / `stretch` modes) and producing
|
||||
* both overlay-relative display coordinates and 0..1000 normalized permille
|
||||
* crop coordinates.
|
||||
*/
|
||||
export function computeSnipSelectionRect(
|
||||
startClient: { x: number; y: number },
|
||||
currentClient: { x: number; y: number },
|
||||
overlayRect: SnipClientRect,
|
||||
canvasRect: SnipClientRect,
|
||||
naturalWidth: number,
|
||||
naturalHeight: number,
|
||||
): ComputedSnipSelection | null {
|
||||
if (
|
||||
canvasRect.width <= 0 || canvasRect.height <= 0
|
||||
|| naturalWidth <= 0 || naturalHeight <= 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const clampX = (v: number) => Math.max(canvasRect.left, Math.min(canvasRect.left + canvasRect.width, v));
|
||||
const clampY = (v: number) => Math.max(canvasRect.top, Math.min(canvasRect.top + canvasRect.height, v));
|
||||
|
||||
const x1 = clampX(startClient.x);
|
||||
const y1 = clampY(startClient.y);
|
||||
const x2 = clampX(currentClient.x);
|
||||
const y2 = clampY(currentClient.y);
|
||||
|
||||
const leftClient = Math.min(x1, x2);
|
||||
const topClient = Math.min(y1, y2);
|
||||
const cssWidth = Math.abs(x2 - x1);
|
||||
const cssHeight = Math.abs(y2 - y1);
|
||||
|
||||
if (cssWidth < MIN_SNIP_DRAG_PX || cssHeight < MIN_SNIP_DRAG_PX) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const relX = (leftClient - canvasRect.left) / canvasRect.width;
|
||||
const relY = (topClient - canvasRect.top) / canvasRect.height;
|
||||
const relW = cssWidth / canvasRect.width;
|
||||
const relH = cssHeight / canvasRect.height;
|
||||
|
||||
const normX = Math.max(0, Math.min(999, Math.round(relX * 1000)));
|
||||
const normY = Math.max(0, Math.min(999, Math.round(relY * 1000)));
|
||||
const normW = Math.max(1, Math.min(1000 - normX, Math.round(relW * 1000)));
|
||||
const normH = Math.max(1, Math.min(1000 - normY, Math.round(relH * 1000)));
|
||||
|
||||
const pixelWidth = Math.max(1, Math.round((normW / 1000) * naturalWidth));
|
||||
const pixelHeight = Math.max(1, Math.round((normH / 1000) * naturalHeight));
|
||||
|
||||
return {
|
||||
displayRect: {
|
||||
left: leftClient - overlayRect.left,
|
||||
top: topClient - overlayRect.top,
|
||||
width: cssWidth,
|
||||
height: cssHeight,
|
||||
},
|
||||
normalizedRect: {
|
||||
x: normX,
|
||||
y: normY,
|
||||
width: normW,
|
||||
height: normH,
|
||||
pixelWidth,
|
||||
pixelHeight,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export interface RemoteDesktopSnipOverlayProps {
|
||||
/** Whether snipping mode is active. */
|
||||
open: boolean;
|
||||
/** Natural framebuffer width in pixels (used for live `W x H px` badge). */
|
||||
naturalWidth: number;
|
||||
/** Natural framebuffer height in pixels (used for live `W x H px` badge). */
|
||||
naturalHeight: number;
|
||||
/** Optional getter for the live `<canvas>` bounding rect in viewport coordinates. */
|
||||
getCanvasRect?: () => DOMRect | null;
|
||||
/** Fired on pointer release with a valid normalized `0..1000` crop rect. */
|
||||
onSelect: (rect: RemoteDesktopSnipRect) => void;
|
||||
/** Fired on Esc, right-click, or clicking the cancel button. */
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export const RemoteDesktopSnipOverlay: React.FC<RemoteDesktopSnipOverlayProps> = ({
|
||||
open,
|
||||
naturalWidth,
|
||||
naturalHeight,
|
||||
getCanvasRect,
|
||||
onSelect,
|
||||
onCancel,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const overlayRef = useRef<HTMLDivElement>(null);
|
||||
const dragStartRef = useRef<{
|
||||
x: number;
|
||||
y: number;
|
||||
pointerId: number;
|
||||
overlayRect: SnipClientRect;
|
||||
canvasRect: SnipClientRect;
|
||||
} | null>(null);
|
||||
const pendingDragPointRef = useRef<{ x: number; y: number } | null>(null);
|
||||
const dragRafRef = useRef<number | null>(null);
|
||||
const [selection, setSelection] = useState<ComputedSnipSelection | null>(null);
|
||||
|
||||
const cancelPendingDragRaf = useCallback(() => {
|
||||
if (dragRafRef.current !== null) {
|
||||
window.cancelAnimationFrame(dragRafRef.current);
|
||||
dragRafRef.current = null;
|
||||
}
|
||||
pendingDragPointRef.current = null;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
cancelPendingDragRaf();
|
||||
dragStartRef.current = null;
|
||||
setSelection(null);
|
||||
return;
|
||||
}
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
cancelPendingDragRaf();
|
||||
dragStartRef.current = null;
|
||||
setSelection(null);
|
||||
onCancel();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', handleKeyDown, true);
|
||||
return () => {
|
||||
cancelPendingDragRaf();
|
||||
window.removeEventListener('keydown', handleKeyDown, true);
|
||||
};
|
||||
}, [cancelPendingDragRaf, open, onCancel]);
|
||||
|
||||
const handlePointerDown = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (event.button !== 0) return;
|
||||
if ((event.target as HTMLElement | null)?.closest('[data-snip-control="true"]')) {
|
||||
return;
|
||||
}
|
||||
const overlayEl = overlayRef.current;
|
||||
if (!overlayEl) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const overlayRect = overlayEl.getBoundingClientRect();
|
||||
const canvasRect = getCanvasRect?.() ?? overlayRect;
|
||||
dragStartRef.current = {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
pointerId: event.pointerId,
|
||||
overlayRect,
|
||||
canvasRect,
|
||||
};
|
||||
setSelection(null);
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
}, [getCanvasRect]);
|
||||
|
||||
const handlePointerMove = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
|
||||
const start = dragStartRef.current;
|
||||
if (!start || start.pointerId !== event.pointerId) return;
|
||||
event.preventDefault();
|
||||
pendingDragPointRef.current = { x: event.clientX, y: event.clientY };
|
||||
if (dragRafRef.current === null) {
|
||||
dragRafRef.current = window.requestAnimationFrame(() => {
|
||||
dragRafRef.current = null;
|
||||
const activeStart = dragStartRef.current;
|
||||
const currentPoint = pendingDragPointRef.current;
|
||||
pendingDragPointRef.current = null;
|
||||
if (!activeStart || !currentPoint) return;
|
||||
setSelection(
|
||||
computeSnipSelectionRect(
|
||||
activeStart,
|
||||
currentPoint,
|
||||
activeStart.overlayRect,
|
||||
activeStart.canvasRect,
|
||||
naturalWidth,
|
||||
naturalHeight,
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
}, [naturalHeight, naturalWidth]);
|
||||
|
||||
const finishDrag = useCallback((event: React.PointerEvent<HTMLDivElement>, commit: boolean) => {
|
||||
const start = dragStartRef.current;
|
||||
if (!start || start.pointerId !== event.pointerId) return;
|
||||
cancelPendingDragRaf();
|
||||
dragStartRef.current = null;
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
|
||||
event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
}
|
||||
const finalSelection = commit
|
||||
? computeSnipSelectionRect(
|
||||
start,
|
||||
{ x: event.clientX, y: event.clientY },
|
||||
start.overlayRect,
|
||||
start.canvasRect,
|
||||
naturalWidth,
|
||||
naturalHeight,
|
||||
)
|
||||
: null;
|
||||
setSelection(null);
|
||||
if (commit && finalSelection) {
|
||||
onSelect(finalSelection.normalizedRect);
|
||||
}
|
||||
}, [cancelPendingDragRaf, naturalHeight, naturalWidth, onSelect]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={overlayRef}
|
||||
role="region"
|
||||
aria-label={t('ai.vision.snip.ariaLabel')}
|
||||
data-testid="remote-desktop-snip-overlay"
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={(e) => finishDrag(e, true)}
|
||||
onPointerCancel={(e) => finishDrag(e, false)}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
dragStartRef.current = null;
|
||||
setSelection(null);
|
||||
onCancel();
|
||||
}}
|
||||
className="absolute inset-0 z-40 overflow-hidden cursor-crosshair select-none touch-none"
|
||||
>
|
||||
{/* Dim backdrop when no selection box is active yet */}
|
||||
{!selection && (
|
||||
<div className="pointer-events-none absolute inset-0 bg-black/45" />
|
||||
)}
|
||||
|
||||
{/* Bright cutout selection rectangle with surrounding dimmed mask */}
|
||||
{selection && (
|
||||
<div
|
||||
data-testid="remote-desktop-snip-selection"
|
||||
className="pointer-events-none absolute border border-primary/95 ring-1 ring-white/40"
|
||||
style={{
|
||||
left: selection.displayRect.left,
|
||||
top: selection.displayRect.top,
|
||||
width: selection.displayRect.width,
|
||||
height: selection.displayRect.height,
|
||||
boxShadow: '0 0 0 9999px rgba(0, 0, 0, 0.50)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
data-testid="remote-desktop-snip-dimensions"
|
||||
className="absolute left-0 -top-7 whitespace-nowrap rounded bg-zinc-950/90 px-1.5 py-0.5 font-mono text-[11px] font-medium text-white shadow-md ring-1 ring-white/15"
|
||||
style={selection.displayRect.top < 32 ? { top: 6, left: 6 } : undefined}
|
||||
>
|
||||
{selection.normalizedRect.pixelWidth} × {selection.normalizedRect.pixelHeight} px
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Top instruction bar + cancel button */}
|
||||
<div
|
||||
data-snip-control="true"
|
||||
className="absolute left-1/2 top-3 z-10 flex -translate-x-1/2 items-center gap-2 rounded-full border border-white/15 bg-zinc-950/85 px-3 py-1.5 text-[12px] text-white/90 shadow-lg backdrop-blur-sm"
|
||||
>
|
||||
<span>{t('ai.vision.snip.hint')}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onCancel();
|
||||
}}
|
||||
aria-label={t('ai.vision.snip.cancel')}
|
||||
className="inline-flex h-5 w-5 items-center justify-center rounded-full text-white/70 transition-colors hover:bg-white/15 hover:text-white cursor-pointer"
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default React.memo(RemoteDesktopSnipOverlay);
|
||||
@@ -0,0 +1,127 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { I18nProvider } from '../../application/i18n/I18nProvider';
|
||||
import { TooltipProvider } from '../ui/tooltip';
|
||||
import { RemoteDesktopToolbar, type RemoteDesktopToolbarProps } from './RemoteDesktopToolbar';
|
||||
|
||||
function renderToolbar(overrides: Partial<RemoteDesktopToolbarProps> = {}): string {
|
||||
const baseProps: RemoteDesktopToolbarProps = {
|
||||
protocol: 'rdp',
|
||||
hostLabel: 'prod-win-01',
|
||||
status: 'connected',
|
||||
isFullscreen: false,
|
||||
keyboardGrabActive: false,
|
||||
onToggleKeyboardGrab: () => {},
|
||||
onSendSpecialKey: () => {},
|
||||
onTypeClipboard: () => {},
|
||||
displayMode: 'dynamic',
|
||||
onChangeDisplayMode: () => {},
|
||||
clipboardSyncEnabled: true,
|
||||
onToggleClipboardSync: () => {},
|
||||
quality: 'auto',
|
||||
onChangeQuality: () => {},
|
||||
viewOnly: false,
|
||||
onToggleViewOnly: () => {},
|
||||
onScreenshotCopy: () => {},
|
||||
onScreenshotSave: () => {},
|
||||
onToggleFullscreen: () => {},
|
||||
onReconnect: () => {},
|
||||
onDisconnect: () => {},
|
||||
...overrides,
|
||||
};
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<RemoteDesktopToolbar {...baseProps} />
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
test('RemoteDesktopToolbar renders SFTP button only when onOpenSftp is wired and highlights when open', () => {
|
||||
const withoutSftp = renderToolbar();
|
||||
assert.doesNotMatch(withoutSftp, /data-testid="remote-desktop-sftp-btn"/);
|
||||
|
||||
const withSftpClosed = renderToolbar({ onOpenSftp: () => {}, isSftpOpen: false });
|
||||
assert.match(withSftpClosed, /data-testid="remote-desktop-sftp-btn"/);
|
||||
assert.match(withSftpClosed, /aria-pressed="false"/);
|
||||
|
||||
const withSftpOpen = renderToolbar({ onOpenSftp: () => {}, isSftpOpen: true });
|
||||
assert.match(withSftpOpen, /aria-pressed="true"/);
|
||||
});
|
||||
|
||||
test('RemoteDesktopToolbar renders live clipboard transfer progress pills for all phases', () => {
|
||||
const staged = renderToolbar({
|
||||
clipboardTransfer: {
|
||||
id: 't1',
|
||||
direction: 'upload',
|
||||
phase: 'staged',
|
||||
fileName: 'report.pdf',
|
||||
fileCount: 2,
|
||||
transferredBytes: 0,
|
||||
totalBytes: 2048,
|
||||
percent: 0,
|
||||
message: 'Ready to paste 2 files on remote (Ctrl+V)',
|
||||
},
|
||||
});
|
||||
assert.match(staged, /data-testid="rdp-clipboard-transfer-pill"/);
|
||||
assert.match(staged, /data-transfer-phase="staged"/);
|
||||
assert.match(staged, /2 file\(s\) · Ctrl\+V/);
|
||||
|
||||
const transferring = renderToolbar({
|
||||
clipboardTransfer: {
|
||||
id: 't2',
|
||||
direction: 'download',
|
||||
phase: 'transferring',
|
||||
fileName: 'dump.log',
|
||||
fileCount: 1,
|
||||
transferredBytes: 512,
|
||||
totalBytes: 1024,
|
||||
percent: 50,
|
||||
message: 'Downloading dump.log (50%)',
|
||||
},
|
||||
});
|
||||
assert.match(transferring, /data-transfer-phase="transferring"/);
|
||||
assert.match(transferring, /dump\.log/);
|
||||
assert.match(transferring, /50%/);
|
||||
|
||||
const completed = renderToolbar({
|
||||
clipboardTransfer: {
|
||||
id: 't3',
|
||||
direction: 'upload',
|
||||
phase: 'completed',
|
||||
fileName: 'a.txt',
|
||||
fileCount: 1,
|
||||
transferredBytes: 100,
|
||||
totalBytes: 100,
|
||||
percent: 100,
|
||||
message: 'Sent a.txt',
|
||||
},
|
||||
onDismissClipboardTransfer: () => {},
|
||||
});
|
||||
assert.match(completed, /data-transfer-phase="completed"/);
|
||||
assert.match(completed, /Dismiss transfer status/);
|
||||
});
|
||||
|
||||
test('RemoteDesktopToolbar renders Ask AI split button, privacy lock badge, and recording pill (including fullscreen)', () => {
|
||||
const html = renderToolbar({
|
||||
isFullscreen: true,
|
||||
onAskAiFull: () => {},
|
||||
onAskAiRegion: () => {},
|
||||
onOpenAiChat: () => {},
|
||||
aiReadBlocked: true,
|
||||
onToggleAiReadBlocked: () => {},
|
||||
isRecording: true,
|
||||
recordingElapsedLabel: '02:14',
|
||||
onToggleRecording: () => {},
|
||||
});
|
||||
|
||||
assert.match(html, /data-testid="remote-desktop-ask-ai-btn"/);
|
||||
assert.match(html, /data-testid="remote-desktop-ask-ai-menu"/);
|
||||
assert.match(html, /AI screen reading blocked/);
|
||||
assert.match(html, /data-testid="remote-desktop-record-btn"/);
|
||||
assert.match(html, /data-recording="true"/);
|
||||
assert.match(html, /02:14/);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,932 @@
|
||||
import React, {
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import {
|
||||
captureFrameFromCanvas,
|
||||
type RemoteDesktopCaptureRequest,
|
||||
type RemoteDesktopProviderFrame,
|
||||
} from '../../infrastructure/remoteDesktop/remoteDesktopSnapshotRegistry';
|
||||
import { cn } from '../../lib/utils';
|
||||
import {
|
||||
domCodeToQemuKeycode,
|
||||
domEventToVncKeysym,
|
||||
textToVncKeysymSequence,
|
||||
unicodeCharToVncKeysym,
|
||||
VNC_SPECIAL_CHORDS,
|
||||
type RemoteDesktopSpecialKeyId,
|
||||
} from './vncKeymap';
|
||||
import {
|
||||
isRemoteDesktopGrabReleaseChord,
|
||||
type RemoteDesktopCanvasHandle,
|
||||
type RemoteDesktopDisplayMode,
|
||||
} from './remoteDesktopHelpers';
|
||||
|
||||
// VNC Binary WebSocket Opcodes (must match electron/bridges/remoteDesktopBridge.cjs)
|
||||
const S2C = {
|
||||
READY: 0x01,
|
||||
RAW_RGBA: 0x02,
|
||||
COPY_RECT: 0x03,
|
||||
JPEG: 0x04,
|
||||
CURSOR: 0x05,
|
||||
DESKTOP_SIZE: 0x06,
|
||||
CLIPBOARD: 0x07,
|
||||
BELL: 0x08,
|
||||
DESKTOP_NAME: 0x09,
|
||||
ERROR: 0x0a,
|
||||
FRAME_SYNC: 0x0b,
|
||||
} as const;
|
||||
|
||||
const C2S = {
|
||||
POINTER: 0x10,
|
||||
KEY: 0x11,
|
||||
QEMU_KEY: 0x12,
|
||||
RESIZE: 0x13,
|
||||
CLIPBOARD: 0x14,
|
||||
REFRESH: 0x15,
|
||||
PAUSE: 0x16,
|
||||
} as const;
|
||||
|
||||
export interface VncCanvasViewProps {
|
||||
wsUrl: string;
|
||||
isVisible: boolean;
|
||||
displayMode: RemoteDesktopDisplayMode;
|
||||
viewOnly: boolean;
|
||||
clipboardSyncEnabled: boolean;
|
||||
showRemoteCursor: boolean;
|
||||
keyboardGrabActive: boolean;
|
||||
onRequestReleaseGrab: () => void;
|
||||
onConnected: (info: {
|
||||
width: number;
|
||||
height: number;
|
||||
name?: string;
|
||||
securityName?: string;
|
||||
encrypted?: boolean;
|
||||
}) => void;
|
||||
onDesktopResize: (size: { width: number; height: number }) => void;
|
||||
onDesktopName?: (name: string) => void;
|
||||
onFpsChange?: (fps: number) => void;
|
||||
onError: (error: { code?: string; message: string; isAuthError?: boolean }) => void;
|
||||
onDisconnected: (reason?: string) => void;
|
||||
}
|
||||
|
||||
const textDecoder = new TextDecoder();
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
function buildPointerFrame(x: number, y: number, buttons: number): Uint8Array {
|
||||
const buf = new Uint8Array(6);
|
||||
const view = new DataView(buf.buffer);
|
||||
buf[0] = C2S.POINTER;
|
||||
view.setUint16(1, Math.max(0, Math.min(65535, Math.round(x))), false);
|
||||
view.setUint16(3, Math.max(0, Math.min(65535, Math.round(y))), false);
|
||||
buf[5] = buttons & 0xff;
|
||||
return buf;
|
||||
}
|
||||
|
||||
function buildKeyFrame(keysym: number, down: boolean): Uint8Array {
|
||||
const buf = new Uint8Array(6);
|
||||
const view = new DataView(buf.buffer);
|
||||
buf[0] = C2S.KEY;
|
||||
view.setUint32(1, keysym >>> 0, false);
|
||||
buf[5] = down ? 1 : 0;
|
||||
return buf;
|
||||
}
|
||||
|
||||
function buildQemuKeyFrame(keysym: number, keycode: number, down: boolean): Uint8Array {
|
||||
const buf = new Uint8Array(10);
|
||||
const view = new DataView(buf.buffer);
|
||||
buf[0] = C2S.QEMU_KEY;
|
||||
view.setUint32(1, keysym >>> 0, false);
|
||||
view.setUint32(5, keycode >>> 0, false);
|
||||
buf[9] = down ? 1 : 0;
|
||||
return buf;
|
||||
}
|
||||
|
||||
function buildResizeFrame(width: number, height: number): Uint8Array {
|
||||
const buf = new Uint8Array(5);
|
||||
const view = new DataView(buf.buffer);
|
||||
buf[0] = C2S.RESIZE;
|
||||
view.setUint16(1, Math.max(1, Math.min(8192, Math.round(width))), false);
|
||||
view.setUint16(3, Math.max(1, Math.min(8192, Math.round(height))), false);
|
||||
return buf;
|
||||
}
|
||||
|
||||
function buildClipboardFrame(text: string): Uint8Array {
|
||||
const bytes = textEncoder.encode(text);
|
||||
const buf = new Uint8Array(1 + bytes.byteLength);
|
||||
buf[0] = C2S.CLIPBOARD;
|
||||
buf.set(bytes, 1);
|
||||
return buf;
|
||||
}
|
||||
|
||||
function buildPauseFrame(paused: boolean): Uint8Array {
|
||||
return new Uint8Array([C2S.PAUSE, paused ? 1 : 0]);
|
||||
}
|
||||
|
||||
function buildRefreshFrame(incremental: boolean): Uint8Array {
|
||||
return new Uint8Array([C2S.REFRESH, incremental ? 1 : 0]);
|
||||
}
|
||||
|
||||
export const VncCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, VncCanvasViewProps>(
|
||||
function VncCanvasView(
|
||||
{
|
||||
wsUrl,
|
||||
isVisible,
|
||||
displayMode,
|
||||
viewOnly,
|
||||
clipboardSyncEnabled,
|
||||
showRemoteCursor,
|
||||
keyboardGrabActive,
|
||||
onRequestReleaseGrab,
|
||||
onConnected,
|
||||
onDesktopResize,
|
||||
onDesktopName,
|
||||
onFpsChange,
|
||||
onError,
|
||||
onDisconnected,
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
const ctxRef = useRef<CanvasRenderingContext2D | null>(null);
|
||||
const cursorCanvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
const lastCursorCacheRef = useRef<{ key: string; css: string } | null>(null);
|
||||
const cachedCanvasRectRef = useRef<DOMRect | null>(null);
|
||||
const pendingPointerRef = useRef<{ x: number; y: number } | null>(null);
|
||||
const pointerRafRef = useRef<number | null>(null);
|
||||
const lastSentPointerRef = useRef<{ x: number; y: number; buttons: number } | null>(null);
|
||||
const imeInputRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const supportsRef = useRef<{ extendedDesktopSize?: boolean; qemuExtendedKeyEvent?: boolean }>({});
|
||||
const pressedKeysRef = useRef<Map<string, { keysym: number; keycode: number | null }>>(new Map());
|
||||
const buttonsMaskRef = useRef(0);
|
||||
const lastPointerPosRef = useRef({ x: 0, y: 0 });
|
||||
const lastRemoteClipboardRef = useRef('');
|
||||
const lastAltRightUpRef = useRef(0);
|
||||
const paintChainRef = useRef<Promise<void>>(Promise.resolve());
|
||||
const frameCountRef = useRef(0);
|
||||
const lastReportedFpsRef = useRef<number | null>(null);
|
||||
const [remoteSize, setRemoteSize] = useState<{ width: number; height: number }>({ width: 1280, height: 800 });
|
||||
const [cursorCss, setCursorCss] = useState<string>('default');
|
||||
|
||||
const getCanvasContext = useCallback((): CanvasRenderingContext2D | null => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) {
|
||||
ctxRef.current = null;
|
||||
return null;
|
||||
}
|
||||
if (!ctxRef.current || ctxRef.current.canvas !== canvas) {
|
||||
ctxRef.current = canvas.getContext('2d', { alpha: false }) ?? canvas.getContext('2d');
|
||||
}
|
||||
return ctxRef.current;
|
||||
}, []);
|
||||
|
||||
// Keep latest callbacks in refs so WS effect never tears down on re-renders.
|
||||
const callbacksRef = useRef({
|
||||
onConnected,
|
||||
onDesktopResize,
|
||||
onDesktopName,
|
||||
onFpsChange,
|
||||
onError,
|
||||
onDisconnected,
|
||||
onRequestReleaseGrab,
|
||||
});
|
||||
callbacksRef.current = {
|
||||
onConnected,
|
||||
onDesktopResize,
|
||||
onDesktopName,
|
||||
onFpsChange,
|
||||
onError,
|
||||
onDisconnected,
|
||||
onRequestReleaseGrab,
|
||||
};
|
||||
|
||||
const propsRef = useRef({ viewOnly, clipboardSyncEnabled, showRemoteCursor, isVisible, keyboardGrabActive });
|
||||
propsRef.current = { viewOnly, clipboardSyncEnabled, showRemoteCursor, isVisible, keyboardGrabActive };
|
||||
|
||||
const sendBinary = useCallback((frame: Uint8Array) => {
|
||||
const ws = wsRef.current;
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(frame);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const sendKeyRaw = useCallback(
|
||||
(keysym: number, keycode: number | null, down: boolean) => {
|
||||
if (propsRef.current.viewOnly) return;
|
||||
if (supportsRef.current.qemuExtendedKeyEvent && keycode !== null) {
|
||||
sendBinary(buildQemuKeyFrame(keysym, keycode, down));
|
||||
} else {
|
||||
sendBinary(buildKeyFrame(keysym, down));
|
||||
}
|
||||
},
|
||||
[sendBinary],
|
||||
);
|
||||
|
||||
const releaseAllInputs = useCallback(() => {
|
||||
for (const entry of pressedKeysRef.current.values()) {
|
||||
sendKeyRaw(entry.keysym, entry.keycode, false);
|
||||
}
|
||||
pressedKeysRef.current.clear();
|
||||
if (buttonsMaskRef.current !== 0) {
|
||||
buttonsMaskRef.current = 0;
|
||||
const { x, y } = lastPointerPosRef.current;
|
||||
sendBinary(buildPointerFrame(x, y, 0));
|
||||
}
|
||||
}, [sendBinary, sendKeyRaw]);
|
||||
|
||||
const sendSpecialKey = useCallback(
|
||||
(id: RemoteDesktopSpecialKeyId) => {
|
||||
if (propsRef.current.viewOnly) return;
|
||||
const chord = VNC_SPECIAL_CHORDS[id];
|
||||
if (!chord || chord.length === 0) return;
|
||||
for (const sym of chord) {
|
||||
sendBinary(buildKeyFrame(sym, true));
|
||||
}
|
||||
for (let i = chord.length - 1; i >= 0; i -= 1) {
|
||||
sendBinary(buildKeyFrame(chord[i], false));
|
||||
}
|
||||
},
|
||||
[sendBinary],
|
||||
);
|
||||
|
||||
const typeText = useCallback(
|
||||
(text: string) => {
|
||||
if (propsRef.current.viewOnly || !text) return;
|
||||
const keysyms = textToVncKeysymSequence(text);
|
||||
for (const sym of keysyms) {
|
||||
sendBinary(buildKeyFrame(sym, true));
|
||||
sendBinary(buildKeyFrame(sym, false));
|
||||
}
|
||||
},
|
||||
[sendBinary],
|
||||
);
|
||||
|
||||
const captureScreenshot = useCallback(async (): Promise<Blob | null> => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas || canvas.width === 0 || canvas.height === 0) return null;
|
||||
return new Promise((resolve) => {
|
||||
canvas.toBlob((blob) => resolve(blob), 'image/png');
|
||||
});
|
||||
}, []);
|
||||
|
||||
const captureFrame = useCallback(
|
||||
(
|
||||
options?: RemoteDesktopCaptureRequest & {
|
||||
maxWidth?: number;
|
||||
protocol?: 'vnc' | 'rdp';
|
||||
hostLabel?: string;
|
||||
hostname?: string;
|
||||
includePreview?: boolean;
|
||||
},
|
||||
): RemoteDesktopProviderFrame | null => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas || canvas.width === 0 || canvas.height === 0) return null;
|
||||
return captureFrameFromCanvas(canvas, {
|
||||
...options,
|
||||
protocol: 'vnc',
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const getCanvasRect = useCallback((): DOMRect | null => {
|
||||
return canvasRef.current?.getBoundingClientRect() ?? null;
|
||||
}, []);
|
||||
|
||||
const getCaptureStream = useCallback((fps: number): MediaStream | null => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas || canvas.width === 0 || canvas.height === 0) return null;
|
||||
if (typeof canvas.captureStream !== 'function') return null;
|
||||
try {
|
||||
return canvas.captureStream(fps);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const requestRefresh = useCallback(() => {
|
||||
sendBinary(buildRefreshFrame(false));
|
||||
}, [sendBinary]);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
sendSpecialKey,
|
||||
typeText,
|
||||
releaseAllInputs,
|
||||
captureScreenshot,
|
||||
captureFrame,
|
||||
getCanvasRect,
|
||||
getCaptureStream,
|
||||
requestRefresh,
|
||||
}),
|
||||
[
|
||||
captureFrame,
|
||||
captureScreenshot,
|
||||
getCanvasRect,
|
||||
getCaptureStream,
|
||||
releaseAllInputs,
|
||||
requestRefresh,
|
||||
sendSpecialKey,
|
||||
typeText,
|
||||
],
|
||||
);
|
||||
|
||||
// FPS telemetry ticker (skips hidden tabs and deduplicates unchanged values)
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => {
|
||||
const frames = frameCountRef.current;
|
||||
frameCountRef.current = 0;
|
||||
if (!propsRef.current.isVisible) return;
|
||||
if (lastReportedFpsRef.current === frames) return;
|
||||
lastReportedFpsRef.current = frames;
|
||||
callbacksRef.current.onFpsChange?.(frames);
|
||||
}, 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
// Pause / resume server updates when tab visibility toggles
|
||||
useEffect(() => {
|
||||
sendBinary(buildPauseFrame(!isVisible));
|
||||
if (!isVisible) {
|
||||
releaseAllInputs();
|
||||
}
|
||||
}, [isVisible, releaseAllInputs, sendBinary]);
|
||||
|
||||
// Resize canvas helper preserving previous contents
|
||||
const resizeBackingCanvas = useCallback((width: number, height: number) => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
if (canvas.width === width && canvas.height === height) return;
|
||||
canvas.width = Math.max(1, width);
|
||||
canvas.height = Math.max(1, height);
|
||||
setRemoteSize({ width: canvas.width, height: canvas.height });
|
||||
callbacksRef.current.onDesktopResize({ width: canvas.width, height: canvas.height });
|
||||
}, []);
|
||||
|
||||
// Main WebSocket connection lifecycle
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
let reportedError = false;
|
||||
const ws = new WebSocket(wsUrl);
|
||||
ws.binaryType = 'arraybuffer';
|
||||
wsRef.current = ws;
|
||||
|
||||
const enqueuePaint = (fn: () => void | Promise<void>) => {
|
||||
paintChainRef.current = paintChainRef.current
|
||||
.then(() => {
|
||||
if (disposed) return;
|
||||
return fn();
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
if (disposed || !(event.data instanceof ArrayBuffer)) return;
|
||||
const bytes = new Uint8Array(event.data);
|
||||
if (bytes.byteLength < 1) return;
|
||||
const view = new DataView(event.data);
|
||||
const opcode = bytes[0];
|
||||
|
||||
switch (opcode) {
|
||||
case S2C.READY: {
|
||||
try {
|
||||
const info = JSON.parse(textDecoder.decode(bytes.subarray(1))) as {
|
||||
width?: number;
|
||||
height?: number;
|
||||
name?: string;
|
||||
securityName?: string;
|
||||
supports?: { extendedDesktopSize?: boolean; qemuExtendedKeyEvent?: boolean };
|
||||
};
|
||||
supportsRef.current = info.supports ?? {};
|
||||
const w = Math.max(1, Number(info.width) || 1280);
|
||||
const h = Math.max(1, Number(info.height) || 800);
|
||||
resizeBackingCanvas(w, h);
|
||||
const secName = info.securityName || '';
|
||||
const encrypted = /tls|x509|vencrypt|ra2|ard/i.test(secName);
|
||||
callbacksRef.current.onConnected({
|
||||
width: w,
|
||||
height: h,
|
||||
name: info.name,
|
||||
securityName: secName,
|
||||
encrypted,
|
||||
});
|
||||
if (!propsRef.current.isVisible) {
|
||||
ws.send(buildPauseFrame(true));
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed READY
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case S2C.RAW_RGBA: {
|
||||
if (bytes.byteLength < 9) break;
|
||||
const x = view.getUint16(1, false);
|
||||
const y = view.getUint16(3, false);
|
||||
const w = view.getUint16(5, false);
|
||||
const h = view.getUint16(7, false);
|
||||
const expectedLen = w * h * 4;
|
||||
if (w === 0 || h === 0 || bytes.byteLength < 9 + expectedLen) break;
|
||||
// Zero-copy view over the owned WebSocket ArrayBuffer
|
||||
const pixelView = new Uint8ClampedArray(event.data, 9, expectedLen);
|
||||
enqueuePaint(() => {
|
||||
const ctx = getCanvasContext();
|
||||
if (!ctx) return;
|
||||
const imgData = new ImageData(pixelView, w, h);
|
||||
ctx.putImageData(imgData, x, y);
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case S2C.COPY_RECT: {
|
||||
if (bytes.byteLength < 13) break;
|
||||
const x = view.getUint16(1, false);
|
||||
const y = view.getUint16(3, false);
|
||||
const w = view.getUint16(5, false);
|
||||
const h = view.getUint16(7, false);
|
||||
const srcX = view.getUint16(9, false);
|
||||
const srcY = view.getUint16(11, false);
|
||||
if (w === 0 || h === 0) break;
|
||||
enqueuePaint(() => {
|
||||
const canvas = canvasRef.current;
|
||||
const ctx = getCanvasContext();
|
||||
if (!canvas || !ctx) return;
|
||||
ctx.drawImage(canvas, srcX, srcY, w, h, x, y, w, h);
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case S2C.JPEG: {
|
||||
if (bytes.byteLength < 9) break;
|
||||
const x = view.getUint16(1, false);
|
||||
const y = view.getUint16(3, false);
|
||||
const w = view.getUint16(5, false);
|
||||
const h = view.getUint16(7, false);
|
||||
if (w === 0 || h === 0) break;
|
||||
const jpegBlob = new Blob([bytes.subarray(9)], { type: 'image/jpeg' });
|
||||
const bitmapPromise = createImageBitmap(jpegBlob).catch(() => null);
|
||||
enqueuePaint(async () => {
|
||||
const bitmap = await bitmapPromise;
|
||||
if (!bitmap) return;
|
||||
try {
|
||||
if (disposed) return;
|
||||
const ctx = getCanvasContext();
|
||||
if (!ctx) return;
|
||||
ctx.drawImage(bitmap, x, y, w, h);
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case S2C.CURSOR: {
|
||||
if (bytes.byteLength < 9) break;
|
||||
const hotX = view.getUint16(1, false);
|
||||
const hotY = view.getUint16(3, false);
|
||||
const w = view.getUint16(5, false);
|
||||
const h = view.getUint16(7, false);
|
||||
if (!propsRef.current.showRemoteCursor) {
|
||||
setCursorCss((prev) => (prev === 'default' ? prev : 'default'));
|
||||
break;
|
||||
}
|
||||
if (w === 0 || h === 0) {
|
||||
setCursorCss((prev) => (prev === 'none' ? prev : 'none'));
|
||||
break;
|
||||
}
|
||||
const expectedLen = w * h * 4;
|
||||
if (bytes.byteLength < 9 + expectedLen) break;
|
||||
// Fast FNV-1a fingerprint avoids re-encoding identical remote cursor bitmaps
|
||||
let hash = 0x811c9dc5;
|
||||
for (let i = 9; i < 9 + expectedLen; i += 4) {
|
||||
hash ^= bytes[i] ^ (bytes[i + 1] << 8) ^ (bytes[i + 2] << 16) ^ (bytes[i + 3] << 24);
|
||||
hash = Math.imul(hash, 0x01000193);
|
||||
}
|
||||
const cursorKey = `${w}x${h}:${hotX},${hotY}:${hash >>> 0}`;
|
||||
if (lastCursorCacheRef.current?.key === cursorKey) {
|
||||
const cachedCss = lastCursorCacheRef.current.css;
|
||||
setCursorCss((prev) => (prev === cachedCss ? prev : cachedCss));
|
||||
break;
|
||||
}
|
||||
const offscreen = cursorCanvasRef.current ?? document.createElement('canvas');
|
||||
cursorCanvasRef.current = offscreen;
|
||||
if (offscreen.width !== w) offscreen.width = w;
|
||||
if (offscreen.height !== h) offscreen.height = h;
|
||||
const offCtx = offscreen.getContext('2d');
|
||||
if (offCtx) {
|
||||
const imgData = new ImageData(new Uint8ClampedArray(event.data, 9, expectedLen), w, h);
|
||||
offCtx.putImageData(imgData, 0, 0);
|
||||
const url = offscreen.toDataURL('image/png');
|
||||
const css = `url("${url}") ${hotX} ${hotY}, auto`;
|
||||
lastCursorCacheRef.current = { key: cursorKey, css };
|
||||
setCursorCss((prev) => (prev === css ? prev : css));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case S2C.DESKTOP_SIZE: {
|
||||
if (bytes.byteLength < 5) break;
|
||||
const w = view.getUint16(1, false);
|
||||
const h = view.getUint16(3, false);
|
||||
if (w > 0 && h > 0) {
|
||||
enqueuePaint(() => {
|
||||
resizeBackingCanvas(w, h);
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case S2C.CLIPBOARD: {
|
||||
if (!propsRef.current.clipboardSyncEnabled) break;
|
||||
const text = textDecoder.decode(bytes.subarray(1));
|
||||
lastRemoteClipboardRef.current = text;
|
||||
void navigator.clipboard?.writeText(text).catch(() => {});
|
||||
break;
|
||||
}
|
||||
|
||||
case S2C.DESKTOP_NAME: {
|
||||
const name = textDecoder.decode(bytes.subarray(1));
|
||||
callbacksRef.current.onDesktopName?.(name);
|
||||
break;
|
||||
}
|
||||
|
||||
case S2C.ERROR: {
|
||||
try {
|
||||
const err = JSON.parse(textDecoder.decode(bytes.subarray(1))) as {
|
||||
code?: string;
|
||||
message?: string;
|
||||
};
|
||||
const msg = err.message || 'VNC session error';
|
||||
const isAuthError = /auth|password|credential|denied|rejected|security/i.test(
|
||||
`${err.code || ''} ${msg}`,
|
||||
);
|
||||
reportedError = true;
|
||||
callbacksRef.current.onError({ code: err.code, message: msg, isAuthError });
|
||||
} catch {
|
||||
reportedError = true;
|
||||
callbacksRef.current.onError({ message: 'VNC protocol error' });
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case S2C.FRAME_SYNC: {
|
||||
frameCountRef.current += 1;
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
if (disposed || reportedError) return;
|
||||
reportedError = true;
|
||||
callbacksRef.current.onError({ message: 'VNC WebSocket connection failed' });
|
||||
};
|
||||
|
||||
ws.onclose = (ev) => {
|
||||
if (disposed) return;
|
||||
wsRef.current = null;
|
||||
callbacksRef.current.onDisconnected(ev.reason || undefined);
|
||||
};
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
wsRef.current = null;
|
||||
try {
|
||||
ws.close();
|
||||
} catch { /* ignore */ }
|
||||
};
|
||||
}, [getCanvasContext, resizeBackingCanvas, wsUrl]);
|
||||
|
||||
// Keep cached canvas DOMRect in sync so high-frequency pointer moves avoid forced layout reads
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
const container = containerRef.current;
|
||||
const refreshRect = () => {
|
||||
cachedCanvasRectRef.current = canvasRef.current?.getBoundingClientRect() ?? null;
|
||||
};
|
||||
refreshRect();
|
||||
const observer = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(refreshRect) : null;
|
||||
if (observer && canvas) observer.observe(canvas);
|
||||
if (observer && container) observer.observe(container);
|
||||
window.addEventListener('resize', refreshRect, { passive: true });
|
||||
container?.addEventListener('scroll', refreshRect, { passive: true });
|
||||
return () => {
|
||||
observer?.disconnect();
|
||||
window.removeEventListener('resize', refreshRect);
|
||||
container?.removeEventListener('scroll', refreshRect);
|
||||
if (pointerRafRef.current !== null) {
|
||||
window.cancelAnimationFrame(pointerRafRef.current);
|
||||
pointerRafRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [displayMode, isVisible, remoteSize.height, remoteSize.width]);
|
||||
|
||||
// Debounced dynamic resize when container size changes
|
||||
useEffect(() => {
|
||||
if (displayMode !== 'dynamic') return undefined;
|
||||
const container = containerRef.current;
|
||||
if (!container || typeof ResizeObserver === 'undefined') return undefined;
|
||||
let timerId: number | null = null;
|
||||
|
||||
const scheduleResize = () => {
|
||||
if (timerId !== null) window.clearTimeout(timerId);
|
||||
timerId = window.setTimeout(() => {
|
||||
timerId = null;
|
||||
if (!propsRef.current.isVisible) return;
|
||||
if (!supportsRef.current.extendedDesktopSize) return;
|
||||
const rect = container.getBoundingClientRect();
|
||||
const targetW = Math.max(320, Math.floor(rect.width));
|
||||
const targetH = Math.max(240, Math.floor(rect.height));
|
||||
if (Math.abs(targetW - remoteSize.width) > 8 || Math.abs(targetH - remoteSize.height) > 8) {
|
||||
sendBinary(buildResizeFrame(targetW, targetH));
|
||||
}
|
||||
}, 250);
|
||||
};
|
||||
|
||||
const observer = new ResizeObserver(scheduleResize);
|
||||
observer.observe(container);
|
||||
scheduleResize();
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
if (timerId !== null) window.clearTimeout(timerId);
|
||||
};
|
||||
}, [displayMode, remoteSize.height, remoteSize.width, sendBinary]);
|
||||
|
||||
// Sync local clipboard to VNC server on focus when enabled
|
||||
const syncLocalClipboardToServer = useCallback(() => {
|
||||
if (!propsRef.current.clipboardSyncEnabled || propsRef.current.viewOnly) return;
|
||||
void navigator.clipboard
|
||||
?.readText()
|
||||
.then((text) => {
|
||||
if (text && text !== lastRemoteClipboardRef.current) {
|
||||
lastRemoteClipboardRef.current = text;
|
||||
sendBinary(buildClipboardFrame(text));
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [sendBinary]);
|
||||
|
||||
const mapPointerCoords = useCallback((clientX: number, clientY: number, forceMeasure = false) => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return { x: 0, y: 0 };
|
||||
let rect = forceMeasure ? null : cachedCanvasRectRef.current;
|
||||
if (!rect || rect.width <= 0 || rect.height <= 0) {
|
||||
rect = canvas.getBoundingClientRect();
|
||||
cachedCanvasRectRef.current = rect;
|
||||
}
|
||||
if (rect.width <= 0 || rect.height <= 0) return { x: 0, y: 0 };
|
||||
const x = Math.max(0, Math.min(canvas.width - 1, Math.round(((clientX - rect.left) / rect.width) * canvas.width)));
|
||||
const y = Math.max(0, Math.min(canvas.height - 1, Math.round(((clientY - rect.top) / rect.height) * canvas.height)));
|
||||
return { x, y };
|
||||
}, []);
|
||||
|
||||
const flushPendingPointerMove = useCallback(() => {
|
||||
if (pointerRafRef.current !== null) {
|
||||
window.cancelAnimationFrame(pointerRafRef.current);
|
||||
pointerRafRef.current = null;
|
||||
}
|
||||
const pending = pendingPointerRef.current;
|
||||
if (!pending) return;
|
||||
pendingPointerRef.current = null;
|
||||
const buttons = buttonsMaskRef.current;
|
||||
const lastSent = lastSentPointerRef.current;
|
||||
if (lastSent && lastSent.x === pending.x && lastSent.y === pending.y && lastSent.buttons === buttons) {
|
||||
return;
|
||||
}
|
||||
lastSentPointerRef.current = { x: pending.x, y: pending.y, buttons };
|
||||
sendBinary(buildPointerFrame(pending.x, pending.y, buttons));
|
||||
}, [sendBinary]);
|
||||
|
||||
const updateButtonBit = (button: number, down: boolean) => {
|
||||
let bit = 0;
|
||||
if (button === 0) bit = 1;
|
||||
else if (button === 1) bit = 2;
|
||||
else if (button === 2) bit = 4;
|
||||
if (!bit) return;
|
||||
if (down) buttonsMaskRef.current |= bit;
|
||||
else buttonsMaskRef.current &= ~bit;
|
||||
};
|
||||
|
||||
const handleMouseMove = useCallback(
|
||||
(e: React.MouseEvent<HTMLCanvasElement>) => {
|
||||
if (propsRef.current.viewOnly) return;
|
||||
const pos = mapPointerCoords(e.clientX, e.clientY);
|
||||
lastPointerPosRef.current = pos;
|
||||
pendingPointerRef.current = pos;
|
||||
if (pointerRafRef.current === null) {
|
||||
pointerRafRef.current = window.requestAnimationFrame(flushPendingPointerMove);
|
||||
}
|
||||
},
|
||||
[flushPendingPointerMove, mapPointerCoords],
|
||||
);
|
||||
|
||||
const handleMouseDown = useCallback(
|
||||
(e: React.MouseEvent<HTMLCanvasElement>) => {
|
||||
imeInputRef.current?.focus({ preventScroll: true });
|
||||
if (propsRef.current.viewOnly) return;
|
||||
e.preventDefault();
|
||||
if (pointerRafRef.current !== null) {
|
||||
window.cancelAnimationFrame(pointerRafRef.current);
|
||||
pointerRafRef.current = null;
|
||||
}
|
||||
pendingPointerRef.current = null;
|
||||
const pos = mapPointerCoords(e.clientX, e.clientY, true);
|
||||
lastPointerPosRef.current = pos;
|
||||
updateButtonBit(e.button, true);
|
||||
lastSentPointerRef.current = { x: pos.x, y: pos.y, buttons: buttonsMaskRef.current };
|
||||
sendBinary(buildPointerFrame(pos.x, pos.y, buttonsMaskRef.current));
|
||||
},
|
||||
[mapPointerCoords, sendBinary],
|
||||
);
|
||||
|
||||
const handleMouseUp = useCallback(
|
||||
(e: React.MouseEvent<HTMLCanvasElement>) => {
|
||||
if (propsRef.current.viewOnly) return;
|
||||
e.preventDefault();
|
||||
if (pointerRafRef.current !== null) {
|
||||
window.cancelAnimationFrame(pointerRafRef.current);
|
||||
pointerRafRef.current = null;
|
||||
}
|
||||
pendingPointerRef.current = null;
|
||||
const pos = mapPointerCoords(e.clientX, e.clientY);
|
||||
lastPointerPosRef.current = pos;
|
||||
updateButtonBit(e.button, false);
|
||||
lastSentPointerRef.current = { x: pos.x, y: pos.y, buttons: buttonsMaskRef.current };
|
||||
sendBinary(buildPointerFrame(pos.x, pos.y, buttonsMaskRef.current));
|
||||
},
|
||||
[mapPointerCoords, sendBinary],
|
||||
);
|
||||
|
||||
const handleWheel = useCallback(
|
||||
(e: React.WheelEvent<HTMLCanvasElement>) => {
|
||||
if (propsRef.current.viewOnly) return;
|
||||
e.preventDefault();
|
||||
flushPendingPointerMove();
|
||||
const pos = mapPointerCoords(e.clientX, e.clientY);
|
||||
lastPointerPosRef.current = pos;
|
||||
let wheelBit = 0;
|
||||
if (Math.abs(e.deltaY) >= Math.abs(e.deltaX)) {
|
||||
wheelBit = e.deltaY < 0 ? 8 : e.deltaY > 0 ? 16 : 0;
|
||||
} else {
|
||||
wheelBit = e.deltaX < 0 ? 32 : e.deltaX > 0 ? 64 : 0;
|
||||
}
|
||||
if (wheelBit === 0) return;
|
||||
sendBinary(buildPointerFrame(pos.x, pos.y, buttonsMaskRef.current | wheelBit));
|
||||
sendBinary(buildPointerFrame(pos.x, pos.y, buttonsMaskRef.current));
|
||||
},
|
||||
[flushPendingPointerMove, mapPointerCoords, sendBinary],
|
||||
);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (propsRef.current.keyboardGrabActive && isRemoteDesktopGrabReleaseChord(e.nativeEvent)) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
releaseAllInputs();
|
||||
callbacksRef.current.onRequestReleaseGrab();
|
||||
return;
|
||||
}
|
||||
if (propsRef.current.viewOnly) return;
|
||||
if (e.nativeEvent.isComposing || e.key === 'Process') return;
|
||||
|
||||
// When keyboard grab is inactive, let standard app shortcuts (Cmd/Ctrl+W/T/K/1-9, etc.) pass through.
|
||||
if (!propsRef.current.keyboardGrabActive && (e.metaKey || (e.ctrlKey && e.shiftKey))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const keysym = domEventToVncKeysym(e.nativeEvent);
|
||||
if (keysym === null) return;
|
||||
e.preventDefault();
|
||||
if (propsRef.current.keyboardGrabActive) {
|
||||
e.stopPropagation();
|
||||
}
|
||||
const keycode = domCodeToQemuKeycode(e.code);
|
||||
pressedKeysRef.current.set(e.code || e.key, { keysym, keycode });
|
||||
sendKeyRaw(keysym, keycode, true);
|
||||
},
|
||||
[releaseAllInputs, sendKeyRaw],
|
||||
);
|
||||
|
||||
const handleKeyUp = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
// Double-tap Right Alt / Option releases Keyboard Grab
|
||||
if (propsRef.current.keyboardGrabActive && e.code === 'AltRight') {
|
||||
const now = Date.now();
|
||||
if (now - lastAltRightUpRef.current < 350) {
|
||||
lastAltRightUpRef.current = 0;
|
||||
releaseAllInputs();
|
||||
callbacksRef.current.onRequestReleaseGrab();
|
||||
return;
|
||||
}
|
||||
lastAltRightUpRef.current = now;
|
||||
}
|
||||
if (propsRef.current.viewOnly) return;
|
||||
const trackedKey = e.code || e.key;
|
||||
const tracked = pressedKeysRef.current.get(trackedKey);
|
||||
if (tracked) {
|
||||
pressedKeysRef.current.delete(trackedKey);
|
||||
e.preventDefault();
|
||||
sendKeyRaw(tracked.keysym, tracked.keycode, false);
|
||||
return;
|
||||
}
|
||||
const keysym = domEventToVncKeysym(e.nativeEvent);
|
||||
if (keysym === null) return;
|
||||
e.preventDefault();
|
||||
sendKeyRaw(keysym, domCodeToQemuKeycode(e.code), false);
|
||||
},
|
||||
[releaseAllInputs, sendKeyRaw],
|
||||
);
|
||||
|
||||
const handleCompositionEnd = useCallback(
|
||||
(e: React.CompositionEvent<HTMLTextAreaElement>) => {
|
||||
if (propsRef.current.viewOnly) return;
|
||||
const committed = e.data;
|
||||
if (committed) {
|
||||
for (const ch of committed) {
|
||||
const sym = unicodeCharToVncKeysym(ch);
|
||||
if (sym !== null) {
|
||||
sendBinary(buildKeyFrame(sym, true));
|
||||
sendBinary(buildKeyFrame(sym, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (imeInputRef.current) {
|
||||
imeInputRef.current.value = '';
|
||||
}
|
||||
},
|
||||
[sendBinary],
|
||||
);
|
||||
|
||||
const canvasStyle: React.CSSProperties = (() => {
|
||||
const base: React.CSSProperties = {
|
||||
cursor: showRemoteCursor ? cursorCss : 'default',
|
||||
imageRendering: displayMode === 'actual' ? 'pixelated' : 'auto',
|
||||
};
|
||||
if (displayMode === 'stretch') {
|
||||
return { ...base, width: '100%', height: '100%' };
|
||||
}
|
||||
if (displayMode === 'actual') {
|
||||
return { ...base, width: `${remoteSize.width}px`, height: `${remoteSize.height}px` };
|
||||
}
|
||||
// fit or dynamic
|
||||
return {
|
||||
...base,
|
||||
maxWidth: '100%',
|
||||
maxHeight: '100%',
|
||||
width: 'auto',
|
||||
height: 'auto',
|
||||
objectFit: 'contain',
|
||||
};
|
||||
})();
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn(
|
||||
'relative flex h-full w-full flex-1 items-center justify-center bg-black outline-none',
|
||||
displayMode === 'actual' ? 'overflow-auto' : 'overflow-hidden',
|
||||
)}
|
||||
onMouseDown={() => imeInputRef.current?.focus({ preventScroll: true })}
|
||||
>
|
||||
<textarea
|
||||
ref={imeInputRef}
|
||||
aria-label="VNC keyboard input"
|
||||
className="pointer-events-none fixed left-0 top-0 h-px w-px opacity-0"
|
||||
autoCapitalize="off"
|
||||
autoComplete="off"
|
||||
autoCorrect="off"
|
||||
spellCheck={false}
|
||||
onFocus={syncLocalClipboardToServer}
|
||||
onBlur={releaseAllInputs}
|
||||
onKeyDown={handleKeyDown}
|
||||
onKeyUp={handleKeyUp}
|
||||
onCompositionEnd={handleCompositionEnd}
|
||||
onInput={(e) => {
|
||||
// Clear non-IME characters so the hidden textarea stays empty
|
||||
const target = e.currentTarget;
|
||||
if (target.value) target.value = '';
|
||||
}}
|
||||
/>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={canvasStyle}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseDown={handleMouseDown}
|
||||
onMouseUp={handleMouseUp}
|
||||
onWheel={handleWheel}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
));
|
||||
@@ -0,0 +1,211 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
clearAllKnownRemoteDesktopCerts,
|
||||
getKnownRemoteDesktopCert,
|
||||
getKnownRemoteDesktopFingerprints,
|
||||
getRemoteDesktopCertKey,
|
||||
listKnownRemoteDesktopCerts,
|
||||
normalizeCertFingerprint,
|
||||
parseRemoteDesktopCertKey,
|
||||
readKnownRemoteDesktopCerts,
|
||||
removeKnownRemoteDesktopCert,
|
||||
removeKnownRemoteDesktopCertByKey,
|
||||
subscribeKnownRemoteDesktopCerts,
|
||||
trustKnownRemoteDesktopCert,
|
||||
verifyKnownRemoteDesktopCert,
|
||||
} from './knownRemoteDesktopCerts';
|
||||
import { STORAGE_KEY_KNOWN_REMOTE_DESKTOP_CERTS } from '../../infrastructure/config/storageKeys';
|
||||
|
||||
const memoryStorage = new Map<string, string>();
|
||||
|
||||
const mockLocalStorage = {
|
||||
getItem: (key: string) => memoryStorage.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => {
|
||||
memoryStorage.set(key, value);
|
||||
},
|
||||
removeItem: (key: string) => {
|
||||
memoryStorage.delete(key);
|
||||
},
|
||||
clear: () => {
|
||||
memoryStorage.clear();
|
||||
},
|
||||
};
|
||||
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
value: mockLocalStorage,
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
test('normalizeCertFingerprint normalizes into uppercase colon-separated hex', () => {
|
||||
assert.equal(normalizeCertFingerprint('sha256:aa:bb:cc:dd'), 'AA:BB:CC:DD');
|
||||
assert.equal(normalizeCertFingerprint('aabbccdd'), 'AA:BB:CC:DD');
|
||||
assert.equal(normalizeCertFingerprint(' SHA-256:01 23 ab cd '), '01:23:AB:CD');
|
||||
assert.equal(normalizeCertFingerprint(''), '');
|
||||
});
|
||||
|
||||
test('getRemoteDesktopCertKey builds normalized protocol:host:port keys', () => {
|
||||
assert.equal(getRemoteDesktopCertKey('rdp', ' WIN-HOST.Local ', 3389), 'rdp:win-host.local:3389');
|
||||
assert.equal(getRemoteDesktopCertKey('vnc', '192.168.1.10', 5901), 'vnc:192.168.1.10:5901');
|
||||
});
|
||||
|
||||
test('parseRemoteDesktopCertKey handles IPv4, hostnames, IPv6, and rejects malformed keys', () => {
|
||||
assert.deepEqual(parseRemoteDesktopCertKey('rdp:192.168.1.10:3389'), {
|
||||
protocol: 'rdp',
|
||||
host: '192.168.1.10',
|
||||
port: 3389,
|
||||
});
|
||||
assert.deepEqual(parseRemoteDesktopCertKey('vnc:desktop.example.com:5901'), {
|
||||
protocol: 'vnc',
|
||||
host: 'desktop.example.com',
|
||||
port: 5901,
|
||||
});
|
||||
assert.deepEqual(parseRemoteDesktopCertKey('rdp:::1:3389'), {
|
||||
protocol: 'rdp',
|
||||
host: '::1',
|
||||
port: 3389,
|
||||
});
|
||||
assert.deepEqual(parseRemoteDesktopCertKey('rdp:[fe80::1]:3389'), {
|
||||
protocol: 'rdp',
|
||||
host: '[fe80::1]',
|
||||
port: 3389,
|
||||
});
|
||||
assert.equal(parseRemoteDesktopCertKey('ssh:host:22'), null);
|
||||
assert.equal(parseRemoteDesktopCertKey('rdp::3389'), null);
|
||||
assert.equal(parseRemoteDesktopCertKey('rdp:host:0'), null);
|
||||
assert.equal(parseRemoteDesktopCertKey('rdp:host:99999'), null);
|
||||
assert.equal(parseRemoteDesktopCertKey('rdp:host:notaport'), null);
|
||||
assert.equal(parseRemoteDesktopCertKey('invalid'), null);
|
||||
});
|
||||
|
||||
test('TOFU store tracks first-seen, trusted, changed, validity dates, and removal via localStorage', () => {
|
||||
memoryStorage.clear();
|
||||
|
||||
assert.deepEqual(
|
||||
verifyKnownRemoteDesktopCert('rdp', 'server.example', 3389, 'aa:bb:cc:dd'),
|
||||
{ status: 'first-seen', previousFingerprint: null },
|
||||
);
|
||||
|
||||
const saved = trustKnownRemoteDesktopCert(
|
||||
'rdp',
|
||||
'server.example',
|
||||
3389,
|
||||
{
|
||||
fingerprintSha256: 'aabbccdd',
|
||||
subject: 'CN=server.example',
|
||||
issuer: 'CN=Self',
|
||||
validFrom: '2025-01-01T00:00:00Z',
|
||||
validTo: '2028-01-01T00:00:00Z',
|
||||
},
|
||||
1000,
|
||||
);
|
||||
assert.equal(saved?.fingerprintSha256, 'AA:BB:CC:DD');
|
||||
assert.equal(saved?.validFrom, '2025-01-01T00:00:00Z');
|
||||
assert.equal(saved?.validTo, '2028-01-01T00:00:00Z');
|
||||
assert.equal(memoryStorage.has(STORAGE_KEY_KNOWN_REMOTE_DESKTOP_CERTS), true);
|
||||
|
||||
assert.deepEqual(
|
||||
verifyKnownRemoteDesktopCert('rdp', 'SERVER.EXAMPLE', 3389, 'AA:BB:CC:DD'),
|
||||
{ status: 'trusted', previousFingerprint: 'AA:BB:CC:DD' },
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
getKnownRemoteDesktopFingerprints('rdp', 'server.example', 3389),
|
||||
['AA:BB:CC:DD'],
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
verifyKnownRemoteDesktopCert('rdp', 'server.example', 3389, '11:22:33:44'),
|
||||
{ status: 'changed', previousFingerprint: 'AA:BB:CC:DD' },
|
||||
);
|
||||
|
||||
const updated = trustKnownRemoteDesktopCert(
|
||||
'rdp',
|
||||
'server.example',
|
||||
3389,
|
||||
{ fingerprintSha256: '11:22:33:44' },
|
||||
2000,
|
||||
);
|
||||
assert.equal(updated?.trustedAt, 2000);
|
||||
assert.equal(updated?.validTo, undefined);
|
||||
assert.equal(getKnownRemoteDesktopCert('rdp', 'server.example', 3389)?.fingerprintSha256, '11:22:33:44');
|
||||
|
||||
assert.equal(getKnownRemoteDesktopCert('vnc', 'server.example', 3389), null);
|
||||
assert.equal(getKnownRemoteDesktopCert('rdp', 'server.example', 33890), null);
|
||||
|
||||
assert.equal(removeKnownRemoteDesktopCert('rdp', 'server.example', 3389), true);
|
||||
assert.deepEqual(readKnownRemoteDesktopCerts(), {});
|
||||
});
|
||||
|
||||
test('listKnownRemoteDesktopCerts, removeKnownRemoteDesktopCertByKey, and clearAllKnownRemoteDesktopCerts', () => {
|
||||
memoryStorage.clear();
|
||||
|
||||
trustKnownRemoteDesktopCert('rdp', '::1', 3389, { fingerprintSha256: 'aa:bb' }, 100);
|
||||
trustKnownRemoteDesktopCert('vnc', '10.0.0.5', 5900, { fingerprintSha256: 'cc:dd' }, 200);
|
||||
|
||||
const listed = listKnownRemoteDesktopCerts();
|
||||
assert.equal(listed.length, 2);
|
||||
assert.equal(listed[0].key, 'vnc:10.0.0.5:5900');
|
||||
assert.equal(listed[0].protocol, 'vnc');
|
||||
assert.equal(listed[0].host, '10.0.0.5');
|
||||
assert.equal(listed[0].port, 5900);
|
||||
assert.equal(listed[1].key, 'rdp:::1:3389');
|
||||
assert.equal(listed[1].host, '::1');
|
||||
|
||||
assert.equal(removeKnownRemoteDesktopCertByKey('rdp:::1:3389'), true);
|
||||
assert.equal(removeKnownRemoteDesktopCertByKey('rdp:::1:3389'), false);
|
||||
assert.equal(listKnownRemoteDesktopCerts().length, 1);
|
||||
|
||||
assert.equal(clearAllKnownRemoteDesktopCerts(), 1);
|
||||
assert.equal(clearAllKnownRemoteDesktopCerts(), 0);
|
||||
assert.deepEqual(listKnownRemoteDesktopCerts(), []);
|
||||
});
|
||||
|
||||
test('subscribeKnownRemoteDesktopCerts notifies on both same-window writes and cross-window storage events', () => {
|
||||
memoryStorage.clear();
|
||||
const target = new EventTarget();
|
||||
const prevAdd = globalThis.addEventListener;
|
||||
const prevRemove = globalThis.removeEventListener;
|
||||
const prevDispatch = globalThis.dispatchEvent;
|
||||
|
||||
Object.defineProperty(globalThis, 'addEventListener', {
|
||||
value: target.addEventListener.bind(target),
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(globalThis, 'removeEventListener', {
|
||||
value: target.removeEventListener.bind(target),
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(globalThis, 'dispatchEvent', {
|
||||
value: target.dispatchEvent.bind(target),
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
try {
|
||||
let calls = 0;
|
||||
const unsubscribe = subscribeKnownRemoteDesktopCerts(() => {
|
||||
calls += 1;
|
||||
});
|
||||
|
||||
trustKnownRemoteDesktopCert('rdp', 'win.local', 3389, { fingerprintSha256: 'aa:bb' }, 500);
|
||||
assert.equal(calls, 1);
|
||||
|
||||
const crossWindowEvent = new Event('storage');
|
||||
Object.defineProperty(crossWindowEvent, 'key', { value: STORAGE_KEY_KNOWN_REMOTE_DESKTOP_CERTS });
|
||||
target.dispatchEvent(crossWindowEvent);
|
||||
assert.equal(calls, 2);
|
||||
|
||||
const unrelatedEvent = new Event('storage');
|
||||
Object.defineProperty(unrelatedEvent, 'key', { value: 'other_key' });
|
||||
target.dispatchEvent(unrelatedEvent);
|
||||
assert.equal(calls, 2);
|
||||
|
||||
unsubscribe();
|
||||
clearAllKnownRemoteDesktopCerts();
|
||||
assert.equal(calls, 2);
|
||||
} finally {
|
||||
Object.defineProperty(globalThis, 'addEventListener', { value: prevAdd, configurable: true });
|
||||
Object.defineProperty(globalThis, 'removeEventListener', { value: prevRemove, configurable: true });
|
||||
Object.defineProperty(globalThis, 'dispatchEvent', { value: prevDispatch, configurable: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,307 @@
|
||||
import { STORAGE_KEY_KNOWN_REMOTE_DESKTOP_CERTS } from '../../infrastructure/config/storageKeys';
|
||||
import type { RemoteDesktopProtocol } from '../../domain/remoteDesktop';
|
||||
|
||||
// Mirrors LOCAL_STORAGE_ADAPTER_CHANGED_EVENT from infrastructure/persistence/localStorageAdapter.ts
|
||||
// without violating the component -> infrastructure/persistence lint boundary.
|
||||
const LOCAL_STORAGE_CHANGED_EVENT = 'netcatty:local-storage-adapter-changed';
|
||||
|
||||
function dispatchKnownCertsChanged(): void {
|
||||
try {
|
||||
const target = globalThis as typeof globalThis & {
|
||||
dispatchEvent?: (event: Event) => boolean;
|
||||
CustomEvent?: typeof CustomEvent;
|
||||
};
|
||||
if (typeof target.dispatchEvent !== 'function' || typeof target.CustomEvent !== 'function') {
|
||||
return;
|
||||
}
|
||||
target.dispatchEvent(
|
||||
new target.CustomEvent<{ key: string }>(LOCAL_STORAGE_CHANGED_EVENT, {
|
||||
detail: { key: STORAGE_KEY_KNOWN_REMOTE_DESKTOP_CERTS },
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
// Ignore environments without CustomEvent/dispatchEvent support
|
||||
}
|
||||
}
|
||||
|
||||
function readRawStorage(key: string): unknown {
|
||||
if (typeof globalThis === 'undefined' || !('localStorage' in globalThis)) return null;
|
||||
try {
|
||||
const raw = globalThis.localStorage.getItem(key);
|
||||
return raw ? JSON.parse(raw) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeRawStorage(key: string, value: unknown): void {
|
||||
if (typeof globalThis === 'undefined' || !('localStorage' in globalThis)) return;
|
||||
try {
|
||||
globalThis.localStorage.setItem(key, JSON.stringify(value));
|
||||
dispatchKnownCertsChanged();
|
||||
} catch {
|
||||
// Ignore quota / private mode storage errors
|
||||
}
|
||||
}
|
||||
|
||||
export interface KnownRemoteDesktopCertRecord {
|
||||
fingerprintSha256: string;
|
||||
subject?: string;
|
||||
issuer?: string;
|
||||
validFrom?: string;
|
||||
validTo?: string;
|
||||
trustedAt: number;
|
||||
lastSeenAt: number;
|
||||
}
|
||||
|
||||
export interface KnownRemoteDesktopCertEntry extends KnownRemoteDesktopCertRecord {
|
||||
key: string;
|
||||
protocol: RemoteDesktopProtocol;
|
||||
host: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
export type RemoteDesktopCertMap = Record<string, KnownRemoteDesktopCertRecord>;
|
||||
|
||||
export type RemoteDesktopCertVerificationResult =
|
||||
| { status: 'trusted'; previousFingerprint: string }
|
||||
| { status: 'first-seen'; previousFingerprint: null }
|
||||
| { status: 'changed'; previousFingerprint: string };
|
||||
|
||||
/**
|
||||
* Normalize a SHA-256 certificate fingerprint into canonical uppercase
|
||||
* colon-separated hex (e.g. `AA:BB:CC:...`) so comparisons are format-invariant.
|
||||
*/
|
||||
export function normalizeCertFingerprint(fingerprint: string): string {
|
||||
const cleaned = fingerprint
|
||||
.trim()
|
||||
.replace(/^sha-?256:/i, '')
|
||||
.replace(/[^0-9a-fA-F]/g, '')
|
||||
.toUpperCase();
|
||||
if (!cleaned) return '';
|
||||
if (cleaned.length % 2 === 0) {
|
||||
const pairs: string[] = [];
|
||||
for (let i = 0; i < cleaned.length; i += 2) {
|
||||
pairs.push(cleaned.slice(i, i + 2));
|
||||
}
|
||||
return pairs.join(':');
|
||||
}
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
export function getRemoteDesktopCertKey(
|
||||
protocol: RemoteDesktopProtocol,
|
||||
host: string,
|
||||
port: number,
|
||||
): string {
|
||||
const normalizedHost = host.trim().toLowerCase();
|
||||
const normalizedPort = Number.isInteger(port) && port > 0 ? port : (protocol === 'rdp' ? 3389 : 5900);
|
||||
return `${protocol}:${normalizedHost}:${normalizedPort}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a `protocol:host:port` key into structured fields safely, preserving
|
||||
* colons inside IPv6 literals (e.g. `rdp:::1:3389` or `rdp:[fe80::1]:3389`).
|
||||
*/
|
||||
export function parseRemoteDesktopCertKey(
|
||||
key: string,
|
||||
): { protocol: RemoteDesktopProtocol; host: string; port: number } | null {
|
||||
if (typeof key !== 'string') return null;
|
||||
const firstColon = key.indexOf(':');
|
||||
const lastColon = key.lastIndexOf(':');
|
||||
if (firstColon <= 0 || lastColon <= firstColon + 1 || lastColon >= key.length - 1) {
|
||||
return null;
|
||||
}
|
||||
const rawProtocol = key.slice(0, firstColon).toLowerCase();
|
||||
if (rawProtocol !== 'rdp' && rawProtocol !== 'vnc') {
|
||||
return null;
|
||||
}
|
||||
const host = key.slice(firstColon + 1, lastColon).trim();
|
||||
if (!host) return null;
|
||||
const portStr = key.slice(lastColon + 1);
|
||||
if (!/^\d{1,5}$/.test(portStr)) return null;
|
||||
const port = Number(portStr);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
|
||||
return {
|
||||
protocol: rawProtocol,
|
||||
host,
|
||||
port,
|
||||
};
|
||||
}
|
||||
|
||||
export function readKnownRemoteDesktopCerts(): RemoteDesktopCertMap {
|
||||
const raw = readRawStorage(STORAGE_KEY_KNOWN_REMOTE_DESKTOP_CERTS);
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
return {};
|
||||
}
|
||||
const result: RemoteDesktopCertMap = {};
|
||||
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) continue;
|
||||
const rec = value as Record<string, unknown>;
|
||||
if (typeof rec.fingerprintSha256 !== 'string') continue;
|
||||
const normalizedFp = normalizeCertFingerprint(rec.fingerprintSha256);
|
||||
if (!normalizedFp) continue;
|
||||
result[key] = {
|
||||
fingerprintSha256: normalizedFp,
|
||||
...(typeof rec.subject === 'string' && rec.subject ? { subject: rec.subject } : {}),
|
||||
...(typeof rec.issuer === 'string' && rec.issuer ? { issuer: rec.issuer } : {}),
|
||||
...(typeof rec.validFrom === 'string' && rec.validFrom ? { validFrom: rec.validFrom } : {}),
|
||||
...(typeof rec.validTo === 'string' && rec.validTo ? { validTo: rec.validTo } : {}),
|
||||
trustedAt: typeof rec.trustedAt === 'number' && Number.isFinite(rec.trustedAt) ? rec.trustedAt : 0,
|
||||
lastSeenAt: typeof rec.lastSeenAt === 'number' && Number.isFinite(rec.lastSeenAt) ? rec.lastSeenAt : 0,
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function writeKnownRemoteDesktopCerts(map: RemoteDesktopCertMap): void {
|
||||
writeRawStorage(STORAGE_KEY_KNOWN_REMOTE_DESKTOP_CERTS, map);
|
||||
}
|
||||
|
||||
export function listKnownRemoteDesktopCerts(): KnownRemoteDesktopCertEntry[] {
|
||||
const all = readKnownRemoteDesktopCerts();
|
||||
const entries: KnownRemoteDesktopCertEntry[] = [];
|
||||
for (const [key, record] of Object.entries(all)) {
|
||||
const parsed = parseRemoteDesktopCertKey(key);
|
||||
if (!parsed) continue;
|
||||
entries.push({
|
||||
key,
|
||||
protocol: parsed.protocol,
|
||||
host: parsed.host,
|
||||
port: parsed.port,
|
||||
...record,
|
||||
});
|
||||
}
|
||||
entries.sort((a, b) => (b.trustedAt - a.trustedAt) || a.host.localeCompare(b.host));
|
||||
return entries;
|
||||
}
|
||||
|
||||
export function getKnownRemoteDesktopCert(
|
||||
protocol: RemoteDesktopProtocol,
|
||||
host: string,
|
||||
port: number,
|
||||
): KnownRemoteDesktopCertRecord | null {
|
||||
const key = getRemoteDesktopCertKey(protocol, host, port);
|
||||
const all = readKnownRemoteDesktopCerts();
|
||||
return all[key] ?? null;
|
||||
}
|
||||
|
||||
export function getKnownRemoteDesktopFingerprints(
|
||||
protocol: RemoteDesktopProtocol,
|
||||
host: string,
|
||||
port: number,
|
||||
): string[] {
|
||||
const existing = getKnownRemoteDesktopCert(protocol, host, port);
|
||||
return existing ? [existing.fingerprintSha256] : [];
|
||||
}
|
||||
|
||||
export function verifyKnownRemoteDesktopCert(
|
||||
protocol: RemoteDesktopProtocol,
|
||||
host: string,
|
||||
port: number,
|
||||
fingerprintSha256: string,
|
||||
): RemoteDesktopCertVerificationResult {
|
||||
const normalizedIncoming = normalizeCertFingerprint(fingerprintSha256);
|
||||
const existing = getKnownRemoteDesktopCert(protocol, host, port);
|
||||
if (!existing) {
|
||||
return { status: 'first-seen', previousFingerprint: null };
|
||||
}
|
||||
if (normalizedIncoming && existing.fingerprintSha256 === normalizedIncoming) {
|
||||
return { status: 'trusted', previousFingerprint: existing.fingerprintSha256 };
|
||||
}
|
||||
return { status: 'changed', previousFingerprint: existing.fingerprintSha256 };
|
||||
}
|
||||
|
||||
export function trustKnownRemoteDesktopCert(
|
||||
protocol: RemoteDesktopProtocol,
|
||||
host: string,
|
||||
port: number,
|
||||
info: {
|
||||
fingerprintSha256: string;
|
||||
subject?: string;
|
||||
issuer?: string;
|
||||
validFrom?: string;
|
||||
validTo?: string;
|
||||
},
|
||||
now = Date.now(),
|
||||
): KnownRemoteDesktopCertRecord | null {
|
||||
const normalizedFp = normalizeCertFingerprint(info.fingerprintSha256);
|
||||
if (!normalizedFp) return null;
|
||||
const key = getRemoteDesktopCertKey(protocol, host, port);
|
||||
const all = readKnownRemoteDesktopCerts();
|
||||
const prev = all[key];
|
||||
const sameFingerprint = Boolean(prev && prev.fingerprintSha256 === normalizedFp);
|
||||
const subject = info.subject || (sameFingerprint ? prev?.subject : undefined);
|
||||
const issuer = info.issuer || (sameFingerprint ? prev?.issuer : undefined);
|
||||
const validFrom = info.validFrom || (sameFingerprint ? prev?.validFrom : undefined);
|
||||
const validTo = info.validTo || (sameFingerprint ? prev?.validTo : undefined);
|
||||
const record: KnownRemoteDesktopCertRecord = {
|
||||
fingerprintSha256: normalizedFp,
|
||||
...(subject ? { subject } : {}),
|
||||
...(issuer ? { issuer } : {}),
|
||||
...(validFrom ? { validFrom } : {}),
|
||||
...(validTo ? { validTo } : {}),
|
||||
trustedAt: sameFingerprint && prev ? prev.trustedAt : now,
|
||||
lastSeenAt: now,
|
||||
};
|
||||
all[key] = record;
|
||||
writeKnownRemoteDesktopCerts(all);
|
||||
return record;
|
||||
}
|
||||
|
||||
export function removeKnownRemoteDesktopCert(
|
||||
protocol: RemoteDesktopProtocol,
|
||||
host: string,
|
||||
port: number,
|
||||
): boolean {
|
||||
const key = getRemoteDesktopCertKey(protocol, host, port);
|
||||
return removeKnownRemoteDesktopCertByKey(key);
|
||||
}
|
||||
|
||||
export function removeKnownRemoteDesktopCertByKey(key: string): boolean {
|
||||
const all = readKnownRemoteDesktopCerts();
|
||||
if (!(key in all)) return false;
|
||||
delete all[key];
|
||||
writeKnownRemoteDesktopCerts(all);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function clearAllKnownRemoteDesktopCerts(): number {
|
||||
const all = readKnownRemoteDesktopCerts();
|
||||
const count = Object.keys(all).length;
|
||||
if (count === 0) return 0;
|
||||
writeKnownRemoteDesktopCerts({});
|
||||
return count;
|
||||
}
|
||||
|
||||
export function subscribeKnownRemoteDesktopCerts(listener: () => void): () => void {
|
||||
const target = globalThis as typeof globalThis & {
|
||||
addEventListener?: (type: string, listener: EventListener) => void;
|
||||
removeEventListener?: (type: string, listener: EventListener) => void;
|
||||
};
|
||||
if (typeof target.addEventListener !== 'function' || typeof target.removeEventListener !== 'function') {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
const handleStorage: EventListener = (event) => {
|
||||
const storageEvent = event as StorageEvent;
|
||||
if (storageEvent.key === STORAGE_KEY_KNOWN_REMOTE_DESKTOP_CERTS || storageEvent.key === null) {
|
||||
listener();
|
||||
}
|
||||
};
|
||||
|
||||
const handleAdapterChanged: EventListener = (event) => {
|
||||
const detail = (event as CustomEvent<{ key?: string }>).detail;
|
||||
if (!detail?.key || detail.key === STORAGE_KEY_KNOWN_REMOTE_DESKTOP_CERTS) {
|
||||
listener();
|
||||
}
|
||||
};
|
||||
|
||||
target.addEventListener('storage', handleStorage);
|
||||
target.addEventListener(LOCAL_STORAGE_CHANGED_EVENT, handleAdapterChanged);
|
||||
|
||||
return () => {
|
||||
target.removeEventListener?.('storage', handleStorage);
|
||||
target.removeEventListener?.(LOCAL_STORAGE_CHANGED_EVENT, handleAdapterChanged);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
/**
|
||||
* Web Audio RDPSND playback driver using static `'self'` AudioWorklet
|
||||
* (`/audio/rdp-pcm-worklet.js`, NEVER `blob:`).
|
||||
*
|
||||
* Consumes IronRDP WASM `audio_playback` callback payloads:
|
||||
* - `{ type: 'wave'; sampleRate: number; channels: number; data: Uint8Array }`
|
||||
* - `{ type: 'volume'; left: number; right: number }` (0..1 log-scale)
|
||||
* - `{ type: 'close' }`
|
||||
*/
|
||||
|
||||
export type RdpAudioMessage =
|
||||
| { type: 'wave'; sampleRate: number; channels: number; data: Uint8Array }
|
||||
| { type: 'volume'; left: number; right: number }
|
||||
| { type: 'close' };
|
||||
|
||||
function resolveWorkletUrl(): string {
|
||||
// Always resolve against static 'self' origin so CSP script-src 'self' is satisfied.
|
||||
if (typeof window !== 'undefined' && window.location) {
|
||||
try {
|
||||
return new URL('/audio/rdp-pcm-worklet.js', window.location.origin).href;
|
||||
} catch {
|
||||
return './audio/rdp-pcm-worklet.js';
|
||||
}
|
||||
}
|
||||
return '/audio/rdp-pcm-worklet.js';
|
||||
}
|
||||
|
||||
export class RdpAudioPlayer {
|
||||
private context: AudioContext | null = null;
|
||||
private workletNode: AudioWorkletNode | null = null;
|
||||
private captureDest: MediaStreamAudioDestinationNode | null = null;
|
||||
private initPromise: Promise<void> | null = null;
|
||||
private currentSampleRate = 0;
|
||||
private userVolume = 1.0;
|
||||
private serverVolume = 1.0;
|
||||
private muted = false;
|
||||
private disposed = false;
|
||||
private pendingChunks: Array<{ data: Uint8Array; channels: number }> = [];
|
||||
|
||||
constructor(options?: { muted?: boolean; volume?: number }) {
|
||||
if (typeof options?.muted === 'boolean') {
|
||||
this.muted = options.muted;
|
||||
}
|
||||
if (typeof options?.volume === 'number' && Number.isFinite(options.volume)) {
|
||||
this.userVolume = Math.max(0, Math.min(1, options.volume));
|
||||
}
|
||||
}
|
||||
|
||||
private getEffectiveGain(): number {
|
||||
if (this.muted) return 0;
|
||||
return Math.max(0, Math.min(1, this.userVolume * this.serverVolume));
|
||||
}
|
||||
|
||||
private syncGain(): void {
|
||||
if (!this.workletNode) return;
|
||||
this.workletNode.port.postMessage({
|
||||
type: 'volume',
|
||||
volume: this.getEffectiveGain(),
|
||||
muted: this.muted,
|
||||
});
|
||||
}
|
||||
|
||||
private async ensureInitialized(sampleRate: number): Promise<void> {
|
||||
if (this.disposed) return;
|
||||
const targetRate = Number.isFinite(sampleRate) && sampleRate >= 8000 && sampleRate <= 192000
|
||||
? Math.round(sampleRate)
|
||||
: 48000;
|
||||
|
||||
if (this.context && this.workletNode && this.currentSampleRate === targetRate) {
|
||||
if (this.context.state === 'suspended') {
|
||||
await this.context.resume().catch(() => {});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.initPromise && this.currentSampleRate === targetRate) {
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
// Tear down any previous AudioContext if sample rate changed.
|
||||
this.teardownContext();
|
||||
this.currentSampleRate = targetRate;
|
||||
|
||||
this.initPromise = (async () => {
|
||||
if (typeof AudioContext === 'undefined') return;
|
||||
let ctx: AudioContext;
|
||||
try {
|
||||
ctx = new AudioContext({ sampleRate: targetRate, latencyHint: 'interactive' });
|
||||
} catch {
|
||||
ctx = new AudioContext({ latencyHint: 'interactive' });
|
||||
}
|
||||
if (this.disposed) {
|
||||
await ctx.close().catch(() => {});
|
||||
return;
|
||||
}
|
||||
this.context = ctx;
|
||||
try {
|
||||
await ctx.audioWorklet.addModule(resolveWorkletUrl());
|
||||
} catch (err) {
|
||||
console.warn('[RdpAudioPlayer] Failed to load rdp-pcm-worklet.js:', err);
|
||||
this.teardownContext();
|
||||
return;
|
||||
}
|
||||
if (this.disposed || this.context !== ctx) {
|
||||
await ctx.close().catch(() => {});
|
||||
return;
|
||||
}
|
||||
const node = new AudioWorkletNode(ctx, 'rdp-pcm-worklet', {
|
||||
numberOfInputs: 0,
|
||||
numberOfOutputs: 1,
|
||||
outputChannelCount: [2],
|
||||
processorOptions: {
|
||||
bufferFrames: Math.max(8192, targetRate),
|
||||
},
|
||||
});
|
||||
node.connect(ctx.destination);
|
||||
if (typeof ctx.createMediaStreamDestination === 'function') {
|
||||
try {
|
||||
const captureDest = ctx.createMediaStreamDestination();
|
||||
node.connect(captureDest);
|
||||
this.captureDest = captureDest;
|
||||
} catch {
|
||||
this.captureDest = null;
|
||||
}
|
||||
}
|
||||
this.workletNode = node;
|
||||
this.syncGain();
|
||||
if (ctx.state === 'suspended') {
|
||||
await ctx.resume().catch(() => {});
|
||||
}
|
||||
// Drain buffered chunks that arrived during async worklet startup.
|
||||
const queued = this.pendingChunks.splice(0);
|
||||
for (const item of queued) {
|
||||
this.postPcm(item.data, item.channels);
|
||||
}
|
||||
})();
|
||||
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
private postPcm(data: Uint8Array, channels: number): void {
|
||||
if (!this.workletNode || this.disposed) return;
|
||||
// Copy into a dedicated ArrayBuffer so transfer does not detach WASM linear memory.
|
||||
const copy = new Uint8Array(data.byteLength);
|
||||
copy.set(data);
|
||||
this.workletNode.port.postMessage(
|
||||
{
|
||||
type: 'pcm',
|
||||
channels: channels === 1 ? 1 : 2,
|
||||
buffer: copy.buffer,
|
||||
},
|
||||
[copy.buffer],
|
||||
);
|
||||
}
|
||||
|
||||
public handleMessage(msg: RdpAudioMessage): void {
|
||||
if (this.disposed || !msg) return;
|
||||
switch (msg.type) {
|
||||
case 'wave': {
|
||||
if (!msg.data || msg.data.byteLength === 0) return;
|
||||
const channels = msg.channels === 1 ? 1 : 2;
|
||||
if (this.workletNode && this.currentSampleRate === Math.round(msg.sampleRate || 48000)) {
|
||||
if (this.context?.state === 'suspended') {
|
||||
void this.context.resume().catch(() => {});
|
||||
}
|
||||
this.postPcm(msg.data, channels);
|
||||
} else {
|
||||
// Bound queued startup chunks so memory never grows unbounded.
|
||||
if (this.pendingChunks.length < 32) {
|
||||
const copy = new Uint8Array(msg.data.byteLength);
|
||||
copy.set(msg.data);
|
||||
this.pendingChunks.push({ data: copy, channels });
|
||||
}
|
||||
void this.ensureInitialized(msg.sampleRate || 48000);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'volume': {
|
||||
const left = typeof msg.left === 'number' && Number.isFinite(msg.left) ? msg.left : 1;
|
||||
const right = typeof msg.right === 'number' && Number.isFinite(msg.right) ? msg.right : 1;
|
||||
const avg = Math.max(0, Math.min(1, (left + right) * 0.5));
|
||||
// Convert 0..1 log-scale server volume into linear gain smoothly.
|
||||
this.serverVolume = avg <= 0.001 ? 0 : Math.pow(avg, 2);
|
||||
this.syncGain();
|
||||
break;
|
||||
}
|
||||
case 'close': {
|
||||
this.flush();
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public setMuted(muted: boolean): void {
|
||||
this.muted = muted;
|
||||
this.syncGain();
|
||||
}
|
||||
|
||||
public isMuted(): boolean {
|
||||
return this.muted;
|
||||
}
|
||||
|
||||
public setVolume(volume: number): void {
|
||||
if (!Number.isFinite(volume)) return;
|
||||
this.userVolume = Math.max(0, Math.min(1, volume));
|
||||
this.syncGain();
|
||||
}
|
||||
|
||||
public getVolume(): number {
|
||||
return this.userVolume;
|
||||
}
|
||||
|
||||
public resume(): void {
|
||||
if (this.context && this.context.state === 'suspended') {
|
||||
void this.context.resume().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
public flush(): void {
|
||||
this.pendingChunks.length = 0;
|
||||
this.workletNode?.port.postMessage({ type: 'flush' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a live `MediaStream` tapping the RDPSND worklet output for session
|
||||
* recording without disrupting speaker playback. Returns `null` when audio
|
||||
* playback has not initialized or `createMediaStreamDestination` is unavailable.
|
||||
*/
|
||||
public getCaptureAudioStream(): MediaStream | null {
|
||||
if (this.disposed) return null;
|
||||
if (!this.captureDest && this.context && this.workletNode && typeof this.context.createMediaStreamDestination === 'function') {
|
||||
try {
|
||||
const dest = this.context.createMediaStreamDestination();
|
||||
this.workletNode.connect(dest);
|
||||
this.captureDest = dest;
|
||||
} catch {
|
||||
this.captureDest = null;
|
||||
}
|
||||
}
|
||||
return this.captureDest?.stream ?? null;
|
||||
}
|
||||
|
||||
private teardownContext(): void {
|
||||
this.pendingChunks.length = 0;
|
||||
const node = this.workletNode;
|
||||
const ctx = this.context;
|
||||
this.workletNode = null;
|
||||
this.captureDest = null;
|
||||
this.context = null;
|
||||
this.initPromise = null;
|
||||
this.currentSampleRate = 0;
|
||||
try {
|
||||
node?.port.postMessage({ type: 'reset' });
|
||||
node?.disconnect();
|
||||
} catch { /* ignore */ }
|
||||
if (ctx) {
|
||||
void ctx.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
this.teardownContext();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
domCodeToRdpScancode,
|
||||
isExtendedRdpScancode,
|
||||
RDP_SCANCODE,
|
||||
RDP_SPECIAL_CHORDS,
|
||||
} from './rdpScancodeMap';
|
||||
|
||||
test('rdpScancodeMap maps standard alphanumeric, modifier, and function keys', () => {
|
||||
assert.equal(domCodeToRdpScancode('Escape'), 0x0001);
|
||||
assert.equal(domCodeToRdpScancode('KeyA'), 0x001e);
|
||||
assert.equal(domCodeToRdpScancode('Enter'), 0x001c);
|
||||
assert.equal(domCodeToRdpScancode('ShiftLeft'), 0x002a);
|
||||
assert.equal(domCodeToRdpScancode('ControlLeft'), 0x001d);
|
||||
assert.equal(domCodeToRdpScancode('F1'), 0x003b);
|
||||
assert.equal(domCodeToRdpScancode('F12'), 0x0058);
|
||||
assert.equal(isExtendedRdpScancode(RDP_SCANCODE.KeyA), false);
|
||||
});
|
||||
|
||||
test('rdpScancodeMap encodes extended keys with 0xE0 prefix', () => {
|
||||
assert.equal(domCodeToRdpScancode('ArrowUp'), 0xe048);
|
||||
assert.equal(domCodeToRdpScancode('ArrowDown'), 0xe050);
|
||||
assert.equal(domCodeToRdpScancode('ArrowLeft'), 0xe04b);
|
||||
assert.equal(domCodeToRdpScancode('ArrowRight'), 0xe04d);
|
||||
assert.equal(domCodeToRdpScancode('Delete'), 0xe053);
|
||||
assert.equal(domCodeToRdpScancode('ControlRight'), 0xe01d);
|
||||
assert.equal(domCodeToRdpScancode('AltRight'), 0xe038);
|
||||
assert.equal(domCodeToRdpScancode('MetaLeft'), 0xe05b);
|
||||
assert.equal(domCodeToRdpScancode('NumpadEnter'), 0xe01c);
|
||||
assert.equal(isExtendedRdpScancode(RDP_SCANCODE.Delete), true);
|
||||
assert.equal(domCodeToRdpScancode('NonExistentCode'), null);
|
||||
});
|
||||
|
||||
test('rdpScancodeMap defines Ctrl+Alt+Del and other special chords', () => {
|
||||
assert.deepEqual(RDP_SPECIAL_CHORDS['ctrl-alt-del'], [
|
||||
RDP_SCANCODE.ControlLeft,
|
||||
RDP_SCANCODE.AltLeft,
|
||||
RDP_SCANCODE.Delete,
|
||||
]);
|
||||
assert.deepEqual(RDP_SPECIAL_CHORDS['alt-f4'], [
|
||||
RDP_SCANCODE.AltLeft,
|
||||
RDP_SCANCODE.F4,
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
import type { RemoteDesktopSpecialKeyId } from './vncKeymap';
|
||||
|
||||
/**
|
||||
* DOM `KeyboardEvent.code` -> PS/2 Set 1 scancode mapper for IronRDP WASM
|
||||
* `DeviceEvent.keyPressed(scancode)` / `DeviceEvent.keyReleased(scancode)`.
|
||||
*
|
||||
* IronRDP `Scancode::from_u16(scancode)` interprets the low byte as the Set 1
|
||||
* make code (`0x00..0x7F`) and treats high byte `0xE0` (`0xE000 | code`) as an
|
||||
* extended key (`KBDFLAGS_EXTENDED`).
|
||||
*/
|
||||
|
||||
export const RDP_SCANCODE = {
|
||||
Escape: 0x0001,
|
||||
Digit1: 0x0002,
|
||||
Digit2: 0x0003,
|
||||
Digit3: 0x0004,
|
||||
Digit4: 0x0005,
|
||||
Digit5: 0x0006,
|
||||
Digit6: 0x0007,
|
||||
Digit7: 0x0008,
|
||||
Digit8: 0x0009,
|
||||
Digit9: 0x000a,
|
||||
Digit0: 0x000b,
|
||||
Minus: 0x000c,
|
||||
Equal: 0x000d,
|
||||
Backspace: 0x000e,
|
||||
Tab: 0x000f,
|
||||
KeyQ: 0x0010,
|
||||
KeyW: 0x0011,
|
||||
KeyE: 0x0012,
|
||||
KeyR: 0x0013,
|
||||
KeyT: 0x0014,
|
||||
KeyY: 0x0015,
|
||||
KeyU: 0x0016,
|
||||
KeyI: 0x0017,
|
||||
KeyO: 0x0018,
|
||||
KeyP: 0x0019,
|
||||
BracketLeft: 0x001a,
|
||||
BracketRight: 0x001b,
|
||||
Enter: 0x001c,
|
||||
ControlLeft: 0x001d,
|
||||
KeyA: 0x001e,
|
||||
KeyS: 0x001f,
|
||||
KeyD: 0x0020,
|
||||
KeyF: 0x0021,
|
||||
KeyG: 0x0022,
|
||||
KeyH: 0x0023,
|
||||
KeyJ: 0x0024,
|
||||
KeyK: 0x0025,
|
||||
KeyL: 0x0026,
|
||||
Semicolon: 0x0027,
|
||||
Quote: 0x0028,
|
||||
Backquote: 0x0029,
|
||||
ShiftLeft: 0x002a,
|
||||
Backslash: 0x002b,
|
||||
KeyZ: 0x002c,
|
||||
KeyX: 0x002d,
|
||||
KeyC: 0x002e,
|
||||
KeyV: 0x002f,
|
||||
KeyB: 0x0030,
|
||||
KeyN: 0x0031,
|
||||
KeyM: 0x0032,
|
||||
Comma: 0x0033,
|
||||
Period: 0x0034,
|
||||
Slash: 0x0035,
|
||||
ShiftRight: 0x0036,
|
||||
NumpadMultiply: 0x0037,
|
||||
AltLeft: 0x0038,
|
||||
Space: 0x0039,
|
||||
CapsLock: 0x003a,
|
||||
F1: 0x003b,
|
||||
F2: 0x003c,
|
||||
F3: 0x003d,
|
||||
F4: 0x003e,
|
||||
F5: 0x003f,
|
||||
F6: 0x0040,
|
||||
F7: 0x0041,
|
||||
F8: 0x0042,
|
||||
F9: 0x0043,
|
||||
F10: 0x0044,
|
||||
NumLock: 0x0045,
|
||||
ScrollLock: 0x0046,
|
||||
Numpad7: 0x0047,
|
||||
Numpad8: 0x0048,
|
||||
Numpad9: 0x0049,
|
||||
NumpadSubtract: 0x004a,
|
||||
Numpad4: 0x004b,
|
||||
Numpad5: 0x004c,
|
||||
Numpad6: 0x004d,
|
||||
NumpadAdd: 0x004e,
|
||||
Numpad1: 0x004f,
|
||||
Numpad2: 0x0050,
|
||||
Numpad3: 0x0051,
|
||||
Numpad0: 0x0052,
|
||||
NumpadDecimal: 0x0053,
|
||||
IntlBackslash: 0x0056,
|
||||
F11: 0x0057,
|
||||
F12: 0x0058,
|
||||
NumpadEqual: 0x0059,
|
||||
F13: 0x0064,
|
||||
F14: 0x0065,
|
||||
F15: 0x0066,
|
||||
F16: 0x0067,
|
||||
F17: 0x0068,
|
||||
F18: 0x0069,
|
||||
F19: 0x006a,
|
||||
F20: 0x006b,
|
||||
F21: 0x006c,
|
||||
F22: 0x006d,
|
||||
F23: 0x006e,
|
||||
KanaMode: 0x0070,
|
||||
IntlRo: 0x0073,
|
||||
F24: 0x0076,
|
||||
Convert: 0x0079,
|
||||
NonConvert: 0x007b,
|
||||
IntlYen: 0x007d,
|
||||
NumpadComma: 0x007e,
|
||||
// Extended Set 1 scancodes (0xE0 prefix)
|
||||
NumpadEnter: 0xe01c,
|
||||
ControlRight: 0xe01d,
|
||||
NumpadDivide: 0xe035,
|
||||
PrintScreen: 0xe037,
|
||||
AltRight: 0xe038,
|
||||
Pause: 0xe11d,
|
||||
Home: 0xe047,
|
||||
ArrowUp: 0xe048,
|
||||
PageUp: 0xe049,
|
||||
ArrowLeft: 0xe04b,
|
||||
ArrowRight: 0xe04d,
|
||||
End: 0xe04f,
|
||||
ArrowDown: 0xe050,
|
||||
PageDown: 0xe051,
|
||||
Insert: 0xe052,
|
||||
Delete: 0xe053,
|
||||
MetaLeft: 0xe05b,
|
||||
OSLeft: 0xe05b,
|
||||
MetaRight: 0xe05c,
|
||||
OSRight: 0xe05c,
|
||||
ContextMenu: 0xe05d,
|
||||
Power: 0xe05e,
|
||||
Sleep: 0xe05f,
|
||||
WakeUp: 0xe063,
|
||||
AudioVolumeMute: 0xe020,
|
||||
AudioVolumeDown: 0xe02e,
|
||||
AudioVolumeUp: 0xe030,
|
||||
MediaTrackPrevious: 0xe010,
|
||||
MediaTrackNext: 0xe019,
|
||||
MediaPlayPause: 0xe022,
|
||||
MediaStop: 0xe024,
|
||||
BrowserSearch: 0xe065,
|
||||
BrowserFavorites: 0xe066,
|
||||
BrowserRefresh: 0xe067,
|
||||
BrowserStop: 0xe068,
|
||||
BrowserForward: 0xe069,
|
||||
BrowserBack: 0xe06a,
|
||||
BrowserHome: 0xe032,
|
||||
} as const;
|
||||
|
||||
const CODE_MAP: Readonly<Record<string, number>> = RDP_SCANCODE;
|
||||
|
||||
/**
|
||||
* Convert a DOM `KeyboardEvent.code` into a PS/2 Set 1 scancode suitable for
|
||||
* IronRDP `DeviceEvent.keyPressed` / `DeviceEvent.keyReleased`.
|
||||
*/
|
||||
export function domCodeToRdpScancode(code: string | undefined): number | null {
|
||||
if (!code) return null;
|
||||
return CODE_MAP[code] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the scancode carries the PS/2 Set 1 extended (`0xE0`) flag.
|
||||
*/
|
||||
export function isExtendedRdpScancode(scancode: number): boolean {
|
||||
return (scancode & 0xff00) === 0xe000;
|
||||
}
|
||||
|
||||
export const RDP_SPECIAL_CHORDS: Record<RemoteDesktopSpecialKeyId, readonly number[]> = {
|
||||
'ctrl-alt-del': [RDP_SCANCODE.ControlLeft, RDP_SCANCODE.AltLeft, RDP_SCANCODE.Delete],
|
||||
win: [RDP_SCANCODE.MetaLeft],
|
||||
'alt-tab': [RDP_SCANCODE.AltLeft, RDP_SCANCODE.Tab],
|
||||
'alt-f4': [RDP_SCANCODE.AltLeft, RDP_SCANCODE.F4],
|
||||
'ctrl-shift-esc': [RDP_SCANCODE.ControlLeft, RDP_SCANCODE.ShiftLeft, RDP_SCANCODE.Escape],
|
||||
'cmd-space': [RDP_SCANCODE.MetaLeft, RDP_SCANCODE.Space],
|
||||
'ctrl-alt-f1': [RDP_SCANCODE.ControlLeft, RDP_SCANCODE.AltLeft, RDP_SCANCODE.F1],
|
||||
'ctrl-alt-f2': [RDP_SCANCODE.ControlLeft, RDP_SCANCODE.AltLeft, RDP_SCANCODE.F2],
|
||||
'ctrl-alt-f3': [RDP_SCANCODE.ControlLeft, RDP_SCANCODE.AltLeft, RDP_SCANCODE.F3],
|
||||
'ctrl-alt-f4': [RDP_SCANCODE.ControlLeft, RDP_SCANCODE.AltLeft, RDP_SCANCODE.F4],
|
||||
'ctrl-alt-f5': [RDP_SCANCODE.ControlLeft, RDP_SCANCODE.AltLeft, RDP_SCANCODE.F5],
|
||||
'ctrl-alt-f6': [RDP_SCANCODE.ControlLeft, RDP_SCANCODE.AltLeft, RDP_SCANCODE.F6],
|
||||
'ctrl-alt-f7': [RDP_SCANCODE.ControlLeft, RDP_SCANCODE.AltLeft, RDP_SCANCODE.F7],
|
||||
};
|
||||
@@ -0,0 +1,157 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
handleTerminalDataCaptureImpl,
|
||||
stampRemoteDesktopSessionEndTimes,
|
||||
} from '../../application/app/AppHandlers';
|
||||
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
|
||||
import type { ConnectionLog } from '../../domain/models';
|
||||
import type { Host, TerminalSession } from '../../types';
|
||||
import {
|
||||
canOpenCompanionRemoteDesktopSftp,
|
||||
computeClipboardUploadProgress,
|
||||
formatRecordingDuration,
|
||||
formatTransferBytes,
|
||||
} from './remoteDesktopHelpers';
|
||||
|
||||
test('formatTransferBytes formats zero, bytes, KB, MB, and GB cleanly', () => {
|
||||
assert.equal(formatTransferBytes(0), '0 B');
|
||||
assert.equal(formatTransferBytes(-42), '0 B');
|
||||
assert.equal(formatTransferBytes(Number.NaN), '0 B');
|
||||
assert.equal(formatTransferBytes(512), '512 B');
|
||||
assert.equal(formatTransferBytes(1024), '1 KB');
|
||||
assert.equal(formatTransferBytes(1536), '1.5 KB');
|
||||
assert.equal(formatTransferBytes(1024 * 1024 * 2.5), '2.5 MB');
|
||||
assert.equal(formatTransferBytes(1024 * 1024 * 1024 * 1.25), '1.25 GB');
|
||||
});
|
||||
|
||||
test('computeClipboardUploadProgress aggregates multi-file high-water offsets without NaN', () => {
|
||||
const files = [{ size: 1000 }, { size: 3000 }];
|
||||
const hw = new Map<number, number>([
|
||||
[0, 1000],
|
||||
[1, 1000],
|
||||
]);
|
||||
assert.deepEqual(computeClipboardUploadProgress(files, hw), {
|
||||
transferredBytes: 2000,
|
||||
totalBytes: 4000,
|
||||
percent: 50,
|
||||
});
|
||||
|
||||
// Clamps over-reported offsets to individual file size
|
||||
hw.set(0, 9999);
|
||||
hw.set(1, 3000);
|
||||
assert.deepEqual(computeClipboardUploadProgress(files, hw), {
|
||||
transferredBytes: 4000,
|
||||
totalBytes: 4000,
|
||||
percent: 100,
|
||||
});
|
||||
|
||||
// 0-byte file completes cleanly without NaN
|
||||
assert.deepEqual(computeClipboardUploadProgress([{ size: 0 }], new Map()), {
|
||||
transferredBytes: 0,
|
||||
totalBytes: 0,
|
||||
percent: 0,
|
||||
});
|
||||
assert.deepEqual(computeClipboardUploadProgress([{ size: 0 }], new Map([[0, 0]])), {
|
||||
transferredBytes: 0,
|
||||
totalBytes: 0,
|
||||
percent: 100,
|
||||
});
|
||||
});
|
||||
|
||||
test('canOpenCompanionRemoteDesktopSftp gates SSH/Mosh/ET companions vs standalone, telnet, and plugin hosts', () => {
|
||||
const host = (protocol?: Host['protocol']): Pick<Host, 'protocol'> => ({ protocol });
|
||||
|
||||
assert.equal(canOpenCompanionRemoteDesktopSftp({ remoteDesktopCompanion: true }, host(undefined)), true);
|
||||
assert.equal(canOpenCompanionRemoteDesktopSftp({ remoteDesktopCompanion: true }, host('ssh')), true);
|
||||
assert.equal(canOpenCompanionRemoteDesktopSftp({ remoteDesktopCompanion: true }, host('mosh')), true);
|
||||
assert.equal(canOpenCompanionRemoteDesktopSftp({ remoteDesktopCompanion: true }, host('et')), true);
|
||||
|
||||
assert.equal(canOpenCompanionRemoteDesktopSftp({ remoteDesktopCompanion: false }, host('ssh')), false);
|
||||
assert.equal(canOpenCompanionRemoteDesktopSftp({}, host('rdp')), false);
|
||||
assert.equal(canOpenCompanionRemoteDesktopSftp({}, host('vnc')), false);
|
||||
assert.equal(canOpenCompanionRemoteDesktopSftp({ remoteDesktopCompanion: true }, host('telnet')), false);
|
||||
assert.equal(
|
||||
canOpenCompanionRemoteDesktopSftp({ remoteDesktopCompanion: true }, host('plugin:acme:proto' as Host['protocol'])),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('formatRecordingDuration renders MM:SS and HH:MM:SS', () => {
|
||||
assert.equal(formatRecordingDuration(0), '00:00');
|
||||
assert.equal(formatRecordingDuration(-100), '00:00');
|
||||
assert.equal(formatRecordingDuration(65_000), '01:05');
|
||||
assert.equal(formatRecordingDuration(3_723_000), '1:02:03');
|
||||
});
|
||||
|
||||
test('stampRemoteDesktopSessionEndTimes and handleTerminalDataCaptureImpl stamp endTime on RDP/VNC close', async () => {
|
||||
const updates: Array<{ id: string; patch: Partial<ConnectionLog> }> = [];
|
||||
const logs: ConnectionLog[] = [
|
||||
{
|
||||
id: 'log-rdp',
|
||||
sessionId: 'sess-rdp',
|
||||
hostId: 'h1',
|
||||
hostLabel: 'Win RDP',
|
||||
hostname: '10.0.0.10',
|
||||
username: 'admin',
|
||||
protocol: 'rdp',
|
||||
startTime: 1000,
|
||||
localUsername: 'u',
|
||||
localHostname: 'l',
|
||||
saved: false,
|
||||
},
|
||||
{
|
||||
id: 'log-ssh',
|
||||
sessionId: 'sess-ssh',
|
||||
hostId: 'h2',
|
||||
hostLabel: 'Linux SSH',
|
||||
hostname: '10.0.0.11',
|
||||
username: 'root',
|
||||
protocol: 'ssh',
|
||||
startTime: 1000,
|
||||
localUsername: 'u',
|
||||
localHostname: 'l',
|
||||
saved: false,
|
||||
},
|
||||
];
|
||||
const sessions = [
|
||||
{ id: 'sess-rdp', protocol: 'rdp', hostname: '10.0.0.10' },
|
||||
{ id: 'sess-ssh', protocol: 'ssh', hostname: '10.0.0.11' },
|
||||
] as unknown as TerminalSession[];
|
||||
|
||||
const stamped = stampRemoteDesktopSessionEndTimes(
|
||||
() => ({
|
||||
sessions,
|
||||
connectionLogs: logs,
|
||||
updateConnectionLog: (id: string, patch: Partial<ConnectionLog>) => {
|
||||
updates.push({ id, patch });
|
||||
},
|
||||
}),
|
||||
['sess-rdp', 'sess-ssh'],
|
||||
);
|
||||
|
||||
assert.equal(stamped, 1);
|
||||
assert.equal(updates.length, 1);
|
||||
assert.equal(updates[0].id, 'log-rdp');
|
||||
assert.ok(typeof updates[0].patch.endTime === 'number' && updates[0].patch.endTime > 0);
|
||||
assert.equal('terminalData' in updates[0].patch, false);
|
||||
|
||||
updates.length = 0;
|
||||
await handleTerminalDataCaptureImpl(
|
||||
() => ({
|
||||
IS_DEV: false,
|
||||
sessions,
|
||||
connectionLogs: logs,
|
||||
selectConnectionLogForTerminalDataCapture,
|
||||
updateConnectionLog: (id: string, patch: Partial<ConnectionLog>) => {
|
||||
updates.push({ id, patch });
|
||||
},
|
||||
}),
|
||||
'sess-rdp',
|
||||
'',
|
||||
);
|
||||
assert.equal(updates.length, 1);
|
||||
assert.equal(updates[0].id, 'log-rdp');
|
||||
assert.ok(typeof updates[0].patch.endTime === 'number' && updates[0].patch.endTime > 0);
|
||||
assert.equal('terminalData' in updates[0].patch, false);
|
||||
});
|
||||
@@ -0,0 +1,464 @@
|
||||
import type { Host, Identity, KnownHost, SSHKey } from '../../types';
|
||||
import {
|
||||
resolveRemoteDesktopConnectionSpec,
|
||||
type RemoteDesktopConnectionSpec,
|
||||
type RemoteDesktopProtocol,
|
||||
} from '../../domain/remoteDesktop';
|
||||
import { generateRdpFileContent } from '../../domain/rdpFileParser';
|
||||
import { sanitizeCredentialValue } from '../../domain/credentials';
|
||||
import { resolveBridgeSshAgentAuth, resolveHostAuth } from '../../domain/sshAuth';
|
||||
import { connectionTotpFields } from '../../domain/totpConfig';
|
||||
import { hasUsableProxyConfig, resolveProxyConfigAuth } from '../../domain/proxyProfiles';
|
||||
import {
|
||||
getRemoteDesktopBridge,
|
||||
type RemoteDesktopBridgeApi,
|
||||
type RemoteDesktopCertDecisionValue,
|
||||
type RemoteDesktopCertVerifyEvent,
|
||||
type RemoteDesktopOpenSystemClientOptions,
|
||||
type RemoteDesktopStartOptions,
|
||||
} from '../../application/state/useSessionState';
|
||||
import { isPluginHostProtocol } from '../../domain/pluginConnection';
|
||||
import type {
|
||||
RemoteDesktopCaptureRequest,
|
||||
RemoteDesktopProviderFrame,
|
||||
} from '../../infrastructure/remoteDesktop/remoteDesktopSnapshotRegistry';
|
||||
import { getKnownRemoteDesktopFingerprints } from './knownRemoteDesktopCerts';
|
||||
import type { RemoteDesktopSpecialKeyId } from './vncKeymap';
|
||||
|
||||
export {
|
||||
getRemoteDesktopBridge,
|
||||
type RemoteDesktopBridgeApi,
|
||||
type RemoteDesktopCertDecisionValue,
|
||||
type RemoteDesktopCertVerifyEvent,
|
||||
type RemoteDesktopOpenSystemClientOptions,
|
||||
type RemoteDesktopStartOptions,
|
||||
};
|
||||
|
||||
export type RemoteDesktopDisplayMode = 'dynamic' | 'fit' | 'actual' | 'stretch';
|
||||
export type RemoteDesktopQualityPreset = 'auto' | 'high' | 'medium' | 'low' | 'lossless';
|
||||
|
||||
export interface RemoteDesktopClipboardFileOffer {
|
||||
index: number;
|
||||
name: string;
|
||||
size: number;
|
||||
isDirectory?: boolean;
|
||||
}
|
||||
|
||||
export interface RemoteDesktopClipboardTransferState {
|
||||
id: string;
|
||||
direction: 'upload' | 'download';
|
||||
phase: 'staged' | 'transferring' | 'completed' | 'error';
|
||||
fileName: string;
|
||||
fileCount: number;
|
||||
transferredBytes: number;
|
||||
totalBytes: number;
|
||||
percent: number;
|
||||
message: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface RemoteDesktopCanvasHandle {
|
||||
sendSpecialKey: (id: RemoteDesktopSpecialKeyId) => void;
|
||||
typeText: (text: string) => void;
|
||||
releaseAllInputs: () => void;
|
||||
captureScreenshot: () => Promise<Blob | null>;
|
||||
captureFrame?: (
|
||||
options?: RemoteDesktopCaptureRequest & {
|
||||
maxWidth?: number;
|
||||
protocol?: 'vnc' | 'rdp';
|
||||
hostLabel?: string;
|
||||
hostname?: string;
|
||||
includePreview?: boolean;
|
||||
},
|
||||
) => Promise<RemoteDesktopProviderFrame | null> | RemoteDesktopProviderFrame | null;
|
||||
getCanvasRect?: () => DOMRect | null;
|
||||
getCaptureStream?: (fps: number, includeAudio?: boolean) => MediaStream | null;
|
||||
requestRefresh?: () => void;
|
||||
downloadRemoteClipboardFile?: (fileIndex: number) => Promise<void>;
|
||||
uploadLocalClipboardFiles?: (files: FileList | File[]) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a byte count into a compact human-readable label (e.g. `1.4 MB`).
|
||||
*/
|
||||
export function formatTransferBytes(bytes: number): string {
|
||||
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
|
||||
if (bytes < 1024) return `${Math.round(bytes)} B`;
|
||||
const units = ['KB', 'MB', 'GB', 'TB'] as const;
|
||||
let value = bytes / 1024;
|
||||
let unitIndex = 0;
|
||||
while (value >= 1024 && unitIndex < units.length - 1) {
|
||||
value /= 1024;
|
||||
unitIndex += 1;
|
||||
}
|
||||
const decimals = value >= 100 ? 0 : value >= 10 ? 1 : 2;
|
||||
return `${Number(value.toFixed(decimals))} ${units[unitIndex]}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute aggregate CLIPRDR upload progress across staged files using per-file
|
||||
* high-water offsets without producing NaN on 0-byte files.
|
||||
*/
|
||||
export function computeClipboardUploadProgress(
|
||||
files: ReadonlyArray<{ size: number }>,
|
||||
highWaterByIndex: ReadonlyMap<number, number>,
|
||||
): { transferredBytes: number; totalBytes: number; percent: number } {
|
||||
let totalBytes = 0;
|
||||
let transferredBytes = 0;
|
||||
for (let i = 0; i < files.length; i += 1) {
|
||||
const fileSize = Math.max(0, Number(files[i]?.size) || 0);
|
||||
totalBytes += fileSize;
|
||||
const hw = highWaterByIndex.get(i) ?? 0;
|
||||
transferredBytes += Math.max(0, Math.min(fileSize, Number(hw) || 0));
|
||||
}
|
||||
if (totalBytes <= 0) {
|
||||
return {
|
||||
transferredBytes: 0,
|
||||
totalBytes: 0,
|
||||
percent: files.length > 0 && highWaterByIndex.size >= files.length ? 100 : 0,
|
||||
};
|
||||
}
|
||||
const percent = Math.max(0, Math.min(100, Math.round((transferredBytes / totalBytes) * 100)));
|
||||
return { transferredBytes, totalBytes, percent };
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when a remote desktop tab belongs to an SSH/Mosh/ET companion
|
||||
* host that supports opening the SFTP side panel.
|
||||
*/
|
||||
export function canOpenCompanionRemoteDesktopSftp(
|
||||
session: { remoteDesktopCompanion?: boolean },
|
||||
host: Pick<Host, 'protocol'>,
|
||||
): boolean {
|
||||
return Boolean(
|
||||
session.remoteDesktopCompanion
|
||||
&& (!host.protocol || host.protocol === 'ssh' || host.protocol === 'mosh' || host.protocol === 'et')
|
||||
&& !isPluginHostProtocol(host.protocol),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format an elapsed recording duration in milliseconds as `MM:SS` (or `HH:MM:SS`).
|
||||
*/
|
||||
export function formatRecordingDuration(durationMs: number): string {
|
||||
const totalSeconds = Math.max(0, Math.floor((Number.isFinite(durationMs) ? durationMs : 0) / 1000));
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return hours > 0 ? `${hours}:${pad(minutes)}:${pad(seconds)}` : `${pad(minutes)}:${pad(seconds)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a key via Netcatty's `useI18n` `t(key, values)` function,
|
||||
* falling back to `fallback` when the locale dictionary lacks that key.
|
||||
*/
|
||||
export function tr(
|
||||
t: (key: string, values?: Record<string, string | number | boolean | null | undefined>) => string,
|
||||
key: string,
|
||||
fallback: string,
|
||||
values?: Record<string, string | number | boolean | null | undefined>,
|
||||
): string {
|
||||
const translated = t(key, values);
|
||||
if (translated === key) {
|
||||
if (!values) return fallback;
|
||||
return fallback
|
||||
.replace(/\{\{(\w+)\}\}/g, (match, k) => (values[k] == null ? match : String(values[k])))
|
||||
.replace(/\{(\w+)\}/g, (_match, k) => (values[k] == null ? '' : String(values[k])));
|
||||
}
|
||||
return translated;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the user presses `Ctrl+Alt+Shift` (either side) as the emergency
|
||||
* Keyboard Grab release chord.
|
||||
*/
|
||||
export function isRemoteDesktopGrabReleaseChord(
|
||||
event: Pick<KeyboardEvent, 'ctrlKey' | 'altKey' | 'shiftKey' | 'metaKey' | 'code' | 'key'>,
|
||||
): boolean {
|
||||
if (event.metaKey) return false;
|
||||
if (!event.ctrlKey || !event.altKey || !event.shiftKey) return false;
|
||||
return (
|
||||
event.code === 'ShiftLeft'
|
||||
|| event.code === 'ShiftRight'
|
||||
|| event.code === 'ControlLeft'
|
||||
|| event.code === 'ControlRight'
|
||||
|| event.code === 'AltLeft'
|
||||
|| event.code === 'AltRight'
|
||||
|| event.key === 'Shift'
|
||||
|| event.key === 'Control'
|
||||
|| event.key === 'Alt'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the event target is currently inside a remote desktop pane
|
||||
* with active Keyboard Grab (`data-remote-desktop-capture="true"`).
|
||||
*/
|
||||
export function isTargetInsideRemoteDesktopCapture(
|
||||
target: EventTarget | null,
|
||||
composedPath?: () => EventTarget[],
|
||||
): boolean {
|
||||
const matches = (node: unknown): boolean => {
|
||||
const el = node as { closest?: (sel: string) => unknown } | null;
|
||||
return typeof el?.closest === 'function'
|
||||
&& Boolean(el.closest('[data-remote-desktop-capture="true"]'));
|
||||
};
|
||||
if (matches(target)) return true;
|
||||
if (typeof composedPath === 'function') {
|
||||
return composedPath().some(matches);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function toBridgeProxy(
|
||||
host: Host,
|
||||
identities: readonly Identity[],
|
||||
): RemoteDesktopStartOptions['proxy'] | undefined {
|
||||
if (!hasUsableProxyConfig(host.proxyConfig)) return undefined;
|
||||
const resolved = resolveProxyConfigAuth(host.proxyConfig, [...identities]);
|
||||
if (!resolved) return undefined;
|
||||
return {
|
||||
type: resolved.type,
|
||||
host: resolved.host,
|
||||
port: resolved.port,
|
||||
username: resolved.username,
|
||||
password: resolved.password,
|
||||
command: resolved.command,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildSshJumpHostConfigs(
|
||||
chainHosts: readonly Host[] | undefined,
|
||||
keys: readonly SSHKey[],
|
||||
identities: readonly Identity[],
|
||||
): Array<Record<string, unknown>> {
|
||||
if (!chainHosts?.length) return [];
|
||||
return chainHosts.map((jumpHost) => {
|
||||
const jumpAuth = resolveHostAuth({
|
||||
host: jumpHost,
|
||||
keys: [...keys],
|
||||
identities: [...identities],
|
||||
});
|
||||
const jumpKey = jumpAuth.key;
|
||||
const jumpPassword = sanitizeCredentialValue(jumpAuth.password);
|
||||
const jumpPrivateKey = sanitizeCredentialValue(jumpKey?.privateKey);
|
||||
const jumpPassphrase = sanitizeCredentialValue(jumpAuth.passphrase || jumpKey?.passphrase);
|
||||
const jumpAgentAuth = resolveBridgeSshAgentAuth(jumpHost, jumpKey, jumpAuth.authMethod);
|
||||
const jumpReferenceKeyPath = jumpAuth.authMethod === 'password'
|
||||
? undefined
|
||||
: jumpKey?.source === 'reference'
|
||||
? jumpKey.filePath
|
||||
: undefined;
|
||||
const jumpIdentityFilePaths = jumpAuth.authMethod === 'password'
|
||||
? undefined
|
||||
: jumpReferenceKeyPath
|
||||
? [jumpReferenceKeyPath]
|
||||
: !jumpAuth.keyId
|
||||
? jumpHost.identityFilePaths
|
||||
: undefined;
|
||||
return {
|
||||
hostname: jumpHost.hostname,
|
||||
hostId: jumpHost.id,
|
||||
port: jumpHost.port || 22,
|
||||
username: jumpAuth.username || 'root',
|
||||
authMethod: jumpAuth.authMethod,
|
||||
requiresMfa: Boolean(jumpHost.requiresMfa),
|
||||
password: jumpPassword,
|
||||
...connectionTotpFields(jumpHost),
|
||||
privateKey: jumpPrivateKey,
|
||||
certificate: jumpKey?.certificate,
|
||||
passphrase: jumpPassphrase,
|
||||
keyId: jumpAuth.keyId,
|
||||
identityId: jumpHost.identityId,
|
||||
label: jumpHost.label,
|
||||
proxy: toBridgeProxy(jumpHost, identities),
|
||||
identityFilePaths: jumpIdentityFilePaths,
|
||||
...jumpAgentAuth,
|
||||
legacyAlgorithms: jumpHost.legacyAlgorithms,
|
||||
skipEcdsaHostKey: jumpHost.skipEcdsaHostKey,
|
||||
algorithmOverrides: jumpHost.algorithms,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function buildCompanionSshTunnelConfig(
|
||||
host: Host,
|
||||
chainHosts: readonly Host[] | undefined,
|
||||
keys: readonly SSHKey[],
|
||||
identities: readonly Identity[],
|
||||
knownHosts?: readonly KnownHost[],
|
||||
): Record<string, unknown> {
|
||||
const sshAuth = resolveHostAuth({
|
||||
host,
|
||||
keys: [...keys],
|
||||
identities: [...identities],
|
||||
});
|
||||
const sshKey = sshAuth.key;
|
||||
const sshPassword = sanitizeCredentialValue(sshAuth.password);
|
||||
const sshPrivateKey = sanitizeCredentialValue(sshKey?.privateKey);
|
||||
const sshPassphrase = sanitizeCredentialValue(sshAuth.passphrase || sshKey?.passphrase);
|
||||
const sshAgentAuth = resolveBridgeSshAgentAuth(host, sshKey, sshAuth.authMethod);
|
||||
const referenceKeyPath = sshAuth.authMethod === 'password'
|
||||
? undefined
|
||||
: sshKey?.source === 'reference'
|
||||
? sshKey.filePath
|
||||
: undefined;
|
||||
const identityFilePaths = sshAuth.authMethod === 'password'
|
||||
? undefined
|
||||
: referenceKeyPath
|
||||
? [referenceKeyPath]
|
||||
: !sshAuth.keyId
|
||||
? host.identityFilePaths
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
hostname: host.hostname,
|
||||
port: host.port || 22,
|
||||
username: sshAuth.username || 'root',
|
||||
authMethod: sshAuth.authMethod,
|
||||
password: sshPassword,
|
||||
privateKey: sshPrivateKey,
|
||||
passphrase: sshPassphrase,
|
||||
certificate: sshKey?.certificate,
|
||||
keyId: sshAuth.keyId,
|
||||
identityId: host.identityId,
|
||||
hostId: host.id,
|
||||
label: host.label || host.hostname,
|
||||
proxy: toBridgeProxy(host, identities),
|
||||
jumpHosts: buildSshJumpHostConfigs(chainHosts, keys, identities),
|
||||
identityFilePaths,
|
||||
...sshAgentAuth,
|
||||
...connectionTotpFields(host),
|
||||
legacyAlgorithms: host.legacyAlgorithms,
|
||||
skipEcdsaHostKey: host.skipEcdsaHostKey,
|
||||
algorithmOverrides: host.algorithms,
|
||||
knownHosts: knownHosts ? (knownHosts as unknown as Array<Record<string, unknown>>) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildRemoteDesktopStartPayload(args: {
|
||||
sessionId: string;
|
||||
host: Host;
|
||||
spec: RemoteDesktopConnectionSpec;
|
||||
credentials: { username: string; password: string; domain: string };
|
||||
chainHosts?: readonly Host[];
|
||||
keys: readonly SSHKey[];
|
||||
identities: readonly Identity[];
|
||||
knownHosts?: readonly KnownHost[];
|
||||
quality?: RemoteDesktopQualityPreset;
|
||||
viewOnly?: boolean;
|
||||
securityMode?: RemoteDesktopStartOptions['securityMode'];
|
||||
ignoreCertErrors?: boolean;
|
||||
}): RemoteDesktopStartOptions {
|
||||
const {
|
||||
sessionId,
|
||||
host,
|
||||
spec,
|
||||
credentials,
|
||||
chainHosts,
|
||||
keys,
|
||||
identities,
|
||||
knownHosts,
|
||||
quality,
|
||||
viewOnly,
|
||||
securityMode,
|
||||
ignoreCertErrors,
|
||||
} = args;
|
||||
|
||||
const knownCertFingerprints = getKnownRemoteDesktopFingerprints(
|
||||
spec.protocol,
|
||||
spec.hostHostname,
|
||||
spec.port,
|
||||
);
|
||||
const jumpHosts = buildSshJumpHostConfigs(chainHosts, keys, identities);
|
||||
const proxy = toBridgeProxy(host, identities);
|
||||
|
||||
return {
|
||||
sessionId,
|
||||
protocol: spec.protocol,
|
||||
hostname: spec.hostname,
|
||||
port: spec.port,
|
||||
username: credentials.username || undefined,
|
||||
password: credentials.password || undefined,
|
||||
domain: credentials.domain || undefined,
|
||||
hostId: host.id,
|
||||
label: spec.label,
|
||||
shared: spec.vncConfig?.sharedSession ?? true,
|
||||
readOnly: viewOnly ?? spec.vncConfig?.viewOnly ?? false,
|
||||
viewOnly: viewOnly ?? spec.vncConfig?.viewOnly ?? false,
|
||||
quality: quality ?? 'auto',
|
||||
securityMode: securityMode ?? spec.rdpConfig?.securityMode ?? 'auto',
|
||||
ignoreCertErrors: ignoreCertErrors ?? spec.rdpConfig?.ignoreCertErrors ?? false,
|
||||
knownCertFingerprints,
|
||||
expectedCertFingerprint: knownCertFingerprints[0],
|
||||
proxy,
|
||||
jumpHosts: jumpHosts.length > 0 ? jumpHosts : undefined,
|
||||
tunnelViaHostSsh: spec.tunnelViaHostSsh,
|
||||
tunnelTargetHost: spec.tunnelViaHostSsh ? spec.tunnelTargetHost : undefined,
|
||||
sshTunnelConfig: spec.tunnelViaHostSsh
|
||||
? buildCompanionSshTunnelConfig(host, chainHosts, keys, identities, knownHosts)
|
||||
: undefined,
|
||||
knownHosts: knownHosts ? (knownHosts as unknown as Array<Record<string, unknown>>) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildSystemRemoteDesktopPayload(args: {
|
||||
host: Host;
|
||||
protocol: RemoteDesktopProtocol;
|
||||
chainHosts?: readonly Host[];
|
||||
keys: readonly SSHKey[];
|
||||
identities: readonly Identity[];
|
||||
knownHosts?: readonly KnownHost[];
|
||||
rawRdpContent?: string;
|
||||
}): RemoteDesktopOpenSystemClientOptions {
|
||||
const { host, protocol, chainHosts, keys, identities, knownHosts, rawRdpContent } = args;
|
||||
const spec = resolveRemoteDesktopConnectionSpec(host, protocol, identities);
|
||||
const jumpHosts = buildSshJumpHostConfigs(chainHosts, keys, identities);
|
||||
const proxy = toBridgeProxy(host, identities);
|
||||
|
||||
const rdpContent = protocol === 'rdp'
|
||||
? (rawRdpContent?.trim() || generateRdpFileContent({
|
||||
hostname: spec.hostname,
|
||||
port: spec.port,
|
||||
username: spec.username || undefined,
|
||||
domain: spec.domain || undefined,
|
||||
width: spec.rdpConfig?.width,
|
||||
height: spec.rdpConfig?.height,
|
||||
colorDepth: spec.rdpConfig?.colorDepth,
|
||||
resolutionMode: spec.rdpConfig?.resolutionMode,
|
||||
audioEnabled: spec.rdpConfig?.audioEnabled,
|
||||
clipboardSync: spec.rdpConfig?.clipboardSync,
|
||||
securityMode: spec.rdpConfig?.securityMode,
|
||||
ignoreCertErrors: spec.rdpConfig?.ignoreCertErrors,
|
||||
loadBalanceInfo: spec.rdpConfig?.loadBalanceInfo,
|
||||
alternateShell: spec.rdpConfig?.alternateShell,
|
||||
shellWorkingDir: spec.rdpConfig?.shellWorkingDir,
|
||||
remoteApplicationMode: spec.rdpConfig?.remoteApplicationMode,
|
||||
remoteApplicationProgram: spec.rdpConfig?.remoteApplicationProgram,
|
||||
}))
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
protocol,
|
||||
hostname: spec.hostname,
|
||||
port: spec.port,
|
||||
username: spec.username || undefined,
|
||||
domain: spec.domain || undefined,
|
||||
label: spec.label,
|
||||
rdpContent,
|
||||
loadBalanceInfo: spec.rdpConfig?.loadBalanceInfo,
|
||||
alternateShell: spec.rdpConfig?.alternateShell,
|
||||
shellWorkingDir: spec.rdpConfig?.shellWorkingDir,
|
||||
audioEnabled: spec.rdpConfig?.audioEnabled,
|
||||
clipboardSync: protocol === 'rdp' ? spec.rdpConfig?.clipboardSync : spec.vncConfig?.clipboardSync,
|
||||
proxy,
|
||||
jumpHosts: jumpHosts.length > 0 ? jumpHosts : undefined,
|
||||
tunnelViaHostSsh: spec.tunnelViaHostSsh,
|
||||
tunnelTargetHost: spec.tunnelViaHostSsh ? spec.tunnelTargetHost : undefined,
|
||||
sshTunnelConfig: spec.tunnelViaHostSsh
|
||||
? buildCompanionSshTunnelConfig(host, chainHosts, keys, identities, knownHosts)
|
||||
: undefined,
|
||||
knownHosts: knownHosts ? (knownHosts as unknown as Array<Record<string, unknown>>) : undefined,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
resolveTerminalPopupHost,
|
||||
resolveTerminalPopupRemoteDesktopProtocol,
|
||||
} from '../TerminalPopupPage';
|
||||
import { resolveRemoteDesktopConnectionSpec } from '../../domain/remoteDesktop';
|
||||
import { isAutoReconnectableSshHost } from '../../application/state/terminalAutoReconnect';
|
||||
import type { Host } from '../../domain/models';
|
||||
import type { TerminalPopupPayload } from '../../domain/systemManager/types';
|
||||
|
||||
test('companion RDP pop-out preserves underlying SSH host and tunnelViaHostSsh', () => {
|
||||
const sshHost: Host = {
|
||||
id: 'ssh-host-1',
|
||||
label: 'Prod Bastion',
|
||||
hostname: '10.0.0.5',
|
||||
port: 2222,
|
||||
username: 'ubuntu',
|
||||
identityId: 'id-ssh-1',
|
||||
protocol: 'ssh',
|
||||
tags: [],
|
||||
os: 'linux',
|
||||
rdpConfig: {
|
||||
enabled: true,
|
||||
port: 3390,
|
||||
tunnelViaHostSsh: true,
|
||||
tunnelTargetHost: '127.0.0.1',
|
||||
username: 'Administrator',
|
||||
},
|
||||
};
|
||||
|
||||
const payload: TerminalPopupPayload = {
|
||||
title: 'Prod Bastion (RDP)',
|
||||
parentSessionId: 'sess-1',
|
||||
startupCommand: '',
|
||||
sourceSession: {
|
||||
id: 'sess-1',
|
||||
hostId: sshHost.id,
|
||||
hostLabel: 'Prod Bastion (RDP)',
|
||||
hostname: sshHost.hostname,
|
||||
username: 'Administrator',
|
||||
status: 'connected',
|
||||
protocol: 'rdp',
|
||||
port: 3390,
|
||||
remoteDesktopCompanion: true,
|
||||
rdpConfig: sshHost.rdpConfig,
|
||||
},
|
||||
};
|
||||
|
||||
const popupHost = resolveTerminalPopupHost(payload, [sshHost]);
|
||||
const remoteProtocol = resolveTerminalPopupRemoteDesktopProtocol(payload, popupHost);
|
||||
|
||||
assert.equal(remoteProtocol, 'rdp');
|
||||
assert.equal(popupHost.protocol, 'ssh');
|
||||
assert.equal(popupHost.port, 2222);
|
||||
assert.equal(popupHost.username, 'ubuntu');
|
||||
assert.equal(popupHost.identityId, 'id-ssh-1');
|
||||
|
||||
const spec = resolveRemoteDesktopConnectionSpec(popupHost, 'rdp');
|
||||
assert.equal(spec.isCompanion, true);
|
||||
assert.equal(spec.tunnelViaHostSsh, true);
|
||||
assert.equal(spec.port, 3390);
|
||||
assert.equal(spec.hostname, '127.0.0.1');
|
||||
assert.equal(spec.hostHostname, '10.0.0.5');
|
||||
assert.equal(spec.username, 'Administrator');
|
||||
});
|
||||
|
||||
test('companion VNC pop-out preserves underlying SSH host and tunnelViaHostSsh', () => {
|
||||
const sshHost: Host = {
|
||||
id: 'ssh-host-2',
|
||||
label: 'Linux Workstation',
|
||||
hostname: '192.168.10.20',
|
||||
port: 22,
|
||||
username: 'alice',
|
||||
protocol: 'ssh',
|
||||
tags: [],
|
||||
os: 'linux',
|
||||
vncConfig: {
|
||||
enabled: true,
|
||||
port: 5901,
|
||||
tunnelViaHostSsh: true,
|
||||
},
|
||||
};
|
||||
|
||||
const payload: TerminalPopupPayload = {
|
||||
title: 'Linux Workstation (VNC)',
|
||||
parentSessionId: 'sess-2',
|
||||
startupCommand: '',
|
||||
sourceSession: {
|
||||
id: 'sess-2',
|
||||
hostId: sshHost.id,
|
||||
hostLabel: 'Linux Workstation (VNC)',
|
||||
hostname: sshHost.hostname,
|
||||
username: '',
|
||||
status: 'connected',
|
||||
protocol: 'vnc',
|
||||
port: 5901,
|
||||
remoteDesktopCompanion: true,
|
||||
vncConfig: sshHost.vncConfig,
|
||||
},
|
||||
};
|
||||
|
||||
const popupHost = resolveTerminalPopupHost(payload, [sshHost]);
|
||||
const remoteProtocol = resolveTerminalPopupRemoteDesktopProtocol(payload, popupHost);
|
||||
|
||||
assert.equal(remoteProtocol, 'vnc');
|
||||
assert.equal(popupHost.protocol, 'ssh');
|
||||
assert.equal(popupHost.port, 22);
|
||||
assert.equal(popupHost.username, 'alice');
|
||||
|
||||
const spec = resolveRemoteDesktopConnectionSpec(popupHost, 'vnc');
|
||||
assert.equal(spec.isCompanion, true);
|
||||
assert.equal(spec.tunnelViaHostSsh, true);
|
||||
assert.equal(spec.port, 5901);
|
||||
assert.equal(spec.hostname, '127.0.0.1');
|
||||
assert.equal(spec.hostHostname, '192.168.10.20');
|
||||
});
|
||||
|
||||
test('standalone RDP pop-out resolves direct RDP host without companion SSH tunneling', () => {
|
||||
const rdpHost: Host = {
|
||||
id: 'rdp-host-1',
|
||||
label: 'Windows Server',
|
||||
hostname: '10.1.2.3',
|
||||
port: 3389,
|
||||
username: 'admin',
|
||||
protocol: 'rdp',
|
||||
tags: [],
|
||||
os: 'windows',
|
||||
rdpConfig: {
|
||||
port: 3389,
|
||||
domain: 'CORP',
|
||||
},
|
||||
};
|
||||
|
||||
const payload: TerminalPopupPayload = {
|
||||
title: 'Windows Server',
|
||||
parentSessionId: 'sess-3',
|
||||
startupCommand: '',
|
||||
sourceSession: {
|
||||
id: 'sess-3',
|
||||
hostId: rdpHost.id,
|
||||
hostLabel: 'Windows Server',
|
||||
hostname: rdpHost.hostname,
|
||||
username: 'admin',
|
||||
status: 'connected',
|
||||
protocol: 'rdp',
|
||||
port: 3389,
|
||||
rdpConfig: rdpHost.rdpConfig,
|
||||
},
|
||||
};
|
||||
|
||||
const popupHost = resolveTerminalPopupHost(payload, [rdpHost]);
|
||||
const remoteProtocol = resolveTerminalPopupRemoteDesktopProtocol(payload, popupHost);
|
||||
|
||||
assert.equal(remoteProtocol, 'rdp');
|
||||
assert.equal(popupHost.protocol, 'rdp');
|
||||
assert.equal(popupHost.port, 3389);
|
||||
|
||||
const spec = resolveRemoteDesktopConnectionSpec(popupHost, 'rdp');
|
||||
assert.equal(spec.isCompanion, false);
|
||||
assert.equal(spec.tunnelViaHostSsh, false);
|
||||
assert.equal(spec.domain, 'CORP');
|
||||
});
|
||||
|
||||
test('isAutoReconnectableSshHost excludes vnc and rdp hosts cleanly', () => {
|
||||
assert.equal(isAutoReconnectableSshHost({ protocol: 'rdp', hostname: '10.0.0.1' }), false);
|
||||
assert.equal(isAutoReconnectableSshHost({ protocol: 'vnc', hostname: '10.0.0.1' }), false);
|
||||
assert.equal(isAutoReconnectableSshHost({ protocol: 'ssh', hostname: '10.0.0.1' }), true);
|
||||
});
|
||||
@@ -0,0 +1,398 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React, { useRef } from 'react';
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { I18nProvider } from '../../application/i18n/I18nProvider';
|
||||
import {
|
||||
publishConnectionLogsSnapshot,
|
||||
registerConnectionLogsActions,
|
||||
} from '../../application/state/connectionLogsStore';
|
||||
import type { ConnectionLog } from '../../domain/models';
|
||||
import {
|
||||
STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import type { RemoteDesktopCanvasHandle } from './remoteDesktopHelpers';
|
||||
import {
|
||||
pickRemoteDesktopRecordingMimeType,
|
||||
readRemoteDesktopRecordingSettings,
|
||||
resolveRecordingVideoBitsPerSecond,
|
||||
useRemoteDesktopRecorder,
|
||||
type RemoteDesktopRecordingsApi,
|
||||
type UseRemoteDesktopRecorderResult,
|
||||
} from './useRemoteDesktopRecorder';
|
||||
|
||||
function installDomEnv() {
|
||||
const dom = new JSDOM('', { url: 'http://localhost' });
|
||||
const keys = ['window', 'document', 'localStorage', 'CustomEvent', 'IS_REACT_ACT_ENVIRONMENT', 'MediaRecorder'] as const;
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>(
|
||||
keys.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
|
||||
);
|
||||
Object.defineProperties(globalThis, {
|
||||
window: { value: dom.window, configurable: true },
|
||||
document: { value: dom.window.document, configurable: true },
|
||||
localStorage: { value: dom.window.localStorage, configurable: true },
|
||||
CustomEvent: { value: dom.window.CustomEvent, configurable: true },
|
||||
IS_REACT_ACT_ENVIRONMENT: { value: true, configurable: true },
|
||||
});
|
||||
return {
|
||||
dom,
|
||||
restore: () => {
|
||||
dom.window.close();
|
||||
for (const key of keys) {
|
||||
const desc = previous.get(key);
|
||||
if (desc) Object.defineProperty(globalThis, key, desc);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
class FakeMediaRecorder {
|
||||
static supportedMimes = new Set<string>(['video/webm;codecs=vp9,opus', 'video/webm;codecs=vp9', 'video/webm']);
|
||||
static instances: FakeMediaRecorder[] = [];
|
||||
static isTypeSupported(mime: string): boolean {
|
||||
return FakeMediaRecorder.supportedMimes.has(mime);
|
||||
}
|
||||
|
||||
public state: 'inactive' | 'recording' | 'paused' = 'inactive';
|
||||
public mimeType: string;
|
||||
public videoBitsPerSecond: number | undefined;
|
||||
public timeslice: number | undefined;
|
||||
public ondataavailable: ((ev: { data: Blob }) => void) | null = null;
|
||||
public onerror: ((ev: Event) => void) | null = null;
|
||||
private listeners = new Map<string, Set<() => void>>();
|
||||
|
||||
constructor(public stream: MediaStream, options?: MediaRecorderOptions) {
|
||||
this.mimeType = options?.mimeType || 'video/webm';
|
||||
this.videoBitsPerSecond = options?.videoBitsPerSecond;
|
||||
FakeMediaRecorder.instances.push(this);
|
||||
}
|
||||
|
||||
addEventListener(type: string, cb: () => void) {
|
||||
let set = this.listeners.get(type);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
this.listeners.set(type, set);
|
||||
}
|
||||
set.add(cb);
|
||||
}
|
||||
|
||||
start(timeslice?: number) {
|
||||
this.state = 'recording';
|
||||
this.timeslice = timeslice;
|
||||
}
|
||||
|
||||
emitChunk(bytes: Uint8Array) {
|
||||
const copy = new Uint8Array(bytes.byteLength);
|
||||
copy.set(bytes);
|
||||
const blob = new Blob([copy.buffer], { type: this.mimeType });
|
||||
this.ondataavailable?.({ data: blob });
|
||||
}
|
||||
|
||||
requestData() {
|
||||
this.emitChunk(new Uint8Array([1, 2, 3, 4]));
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (this.state === 'inactive') return;
|
||||
this.state = 'inactive';
|
||||
const set = this.listeners.get('stop');
|
||||
if (set) {
|
||||
for (const cb of [...set]) cb();
|
||||
set.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function createFakeStream(includeAudio: boolean) {
|
||||
let stoppedTracks = 0;
|
||||
const makeTrack = (kind: 'video' | 'audio') => ({
|
||||
kind,
|
||||
stop: () => { stoppedTracks += 1; },
|
||||
});
|
||||
const videoTracks = [makeTrack('video')];
|
||||
const audioTracks = includeAudio ? [makeTrack('audio')] : [];
|
||||
const stream = {
|
||||
getVideoTracks: () => videoTracks,
|
||||
getAudioTracks: () => audioTracks,
|
||||
getTracks: () => [...videoTracks, ...audioTracks],
|
||||
} as unknown as MediaStream;
|
||||
return { stream, getStoppedTracks: () => stoppedTracks };
|
||||
}
|
||||
|
||||
function createFakeBridge(overrides?: Partial<RemoteDesktopRecordingsApi>) {
|
||||
const calls = {
|
||||
begin: [] as Array<{ mimeType?: string; hostLabel?: string; protocol: 'rdp' | 'vnc' }>,
|
||||
append: [] as Array<{ recordingId: string; chunkLen: number }>,
|
||||
finish: [] as Array<{
|
||||
recordingId: string;
|
||||
durationMs: number;
|
||||
hasAudio?: boolean;
|
||||
maxBytes?: number;
|
||||
retentionDays?: number;
|
||||
protectedIds?: string[];
|
||||
}>,
|
||||
abort: [] as Array<{ recordingId: string }>,
|
||||
};
|
||||
|
||||
const bridge: RemoteDesktopRecordingsApi = {
|
||||
begin: async (opts) => {
|
||||
calls.begin.push(opts);
|
||||
return { recordingId: 'rec-test-1' };
|
||||
},
|
||||
append: async (opts) => {
|
||||
calls.append.push({ recordingId: opts.recordingId, chunkLen: opts.chunk.byteLength });
|
||||
return { bytesWritten: opts.chunk.byteLength };
|
||||
},
|
||||
finish: async (opts) => {
|
||||
calls.finish.push(opts);
|
||||
return {
|
||||
recordingId: opts.recordingId,
|
||||
bytes: calls.append.reduce((sum, item) => sum + item.chunkLen, 0),
|
||||
durationMs: opts.durationMs,
|
||||
playbackUrl: `netcatty-media://recording/${opts.recordingId}`,
|
||||
};
|
||||
},
|
||||
abort: async (opts) => {
|
||||
calls.abort.push(opts);
|
||||
return { ok: true };
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
|
||||
return { bridge, calls };
|
||||
}
|
||||
|
||||
test('resolveRecordingVideoBitsPerSecond scales bitrate for 5/10/15 FPS', () => {
|
||||
assert.equal(resolveRecordingVideoBitsPerSecond(5), 1_000_000);
|
||||
assert.equal(resolveRecordingVideoBitsPerSecond(10), 1_800_000);
|
||||
assert.equal(resolveRecordingVideoBitsPerSecond(15), 2_500_000);
|
||||
});
|
||||
|
||||
test('pickRemoteDesktopRecordingMimeType selects preferred WebM codecs with audio fallback', () => {
|
||||
assert.equal(
|
||||
pickRemoteDesktopRecordingMimeType(true, (m) => m === 'video/webm;codecs=vp8,opus' || m === 'video/webm'),
|
||||
'video/webm;codecs=vp8,opus',
|
||||
);
|
||||
assert.equal(
|
||||
pickRemoteDesktopRecordingMimeType(false, (m) => m === 'video/webm;codecs=vp9'),
|
||||
'video/webm;codecs=vp9',
|
||||
);
|
||||
assert.equal(pickRemoteDesktopRecordingMimeType(true, () => false), '');
|
||||
});
|
||||
|
||||
test('readRemoteDesktopRecordingSettings reads defaults and persisted overrides', () => {
|
||||
const env = installDomEnv();
|
||||
try {
|
||||
assert.deepEqual(readRemoteDesktopRecordingSettings(), {
|
||||
autoRecord: false,
|
||||
fps: 10,
|
||||
includeAudio: true,
|
||||
maxMb: 1024,
|
||||
retentionDays: 30,
|
||||
});
|
||||
|
||||
globalThis.localStorage.setItem(STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD, 'true');
|
||||
globalThis.localStorage.setItem(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS, '15');
|
||||
globalThis.localStorage.setItem(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO, 'false');
|
||||
globalThis.localStorage.setItem(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB, '512');
|
||||
globalThis.localStorage.setItem(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS, '7');
|
||||
|
||||
assert.deepEqual(readRemoteDesktopRecordingSettings(), {
|
||||
autoRecord: true,
|
||||
fps: 15,
|
||||
includeAudio: false,
|
||||
maxMb: 512,
|
||||
retentionDays: 7,
|
||||
});
|
||||
} finally {
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('useRemoteDesktopRecorder streams chunks, finishes with protectedIds, and updates ConnectionLog', async () => {
|
||||
const env = installDomEnv();
|
||||
FakeMediaRecorder.instances = [];
|
||||
Object.defineProperty(globalThis, 'MediaRecorder', { value: FakeMediaRecorder, configurable: true });
|
||||
|
||||
const logUpdates: Array<{ id: string; updates: Partial<ConnectionLog> }> = [];
|
||||
publishConnectionLogsSnapshot({
|
||||
connectionLogs: [
|
||||
{
|
||||
id: 'log-saved-other',
|
||||
sessionId: 'sess-old',
|
||||
hostId: 'h0',
|
||||
hostLabel: 'Old RDP',
|
||||
hostname: '10.0.0.1',
|
||||
username: 'admin',
|
||||
protocol: 'rdp',
|
||||
startTime: 1000,
|
||||
endTime: 2000,
|
||||
localUsername: 'u',
|
||||
localHostname: 'l',
|
||||
saved: true,
|
||||
recordingId: 'rec-protected-99',
|
||||
},
|
||||
{
|
||||
id: 'log-active-rdp',
|
||||
sessionId: 'sess-rdp-1',
|
||||
hostId: 'h1',
|
||||
hostLabel: 'Win Server',
|
||||
hostname: '10.0.0.2',
|
||||
username: 'Administrator',
|
||||
protocol: 'rdp',
|
||||
startTime: 5000,
|
||||
localUsername: 'u',
|
||||
localHostname: 'l',
|
||||
saved: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
registerConnectionLogsActions({
|
||||
updateConnectionLog: (id, updates) => { logUpdates.push({ id, updates }); },
|
||||
toggleConnectionLogSaved: () => {},
|
||||
deleteConnectionLog: () => {},
|
||||
clearUnsavedConnectionLogs: () => {},
|
||||
});
|
||||
|
||||
const { bridge, calls } = createFakeBridge();
|
||||
const fakeStream = createFakeStream(true);
|
||||
let recorderApi!: UseRemoteDesktopRecorderResult;
|
||||
let root: ReactTestRenderer | undefined;
|
||||
|
||||
function Harness({ status }: { status: 'connecting' | 'connected' | 'disconnected' }) {
|
||||
const canvasRef = useRef<RemoteDesktopCanvasHandle | null>({
|
||||
sendSpecialKey: () => {},
|
||||
typeText: () => {},
|
||||
releaseAllInputs: () => {},
|
||||
captureScreenshot: async () => null,
|
||||
getCaptureStream: () => fakeStream.stream,
|
||||
});
|
||||
recorderApi = useRemoteDesktopRecorder({
|
||||
sessionId: 'sess-rdp-1',
|
||||
protocol: 'rdp',
|
||||
hostLabel: 'Win Server',
|
||||
status,
|
||||
audioEnabled: true,
|
||||
canvasHandleRef: canvasRef,
|
||||
recordingsBridgeOverride: bridge,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root = create(
|
||||
React.createElement(I18nProvider, {
|
||||
locale: 'en',
|
||||
children: React.createElement(Harness, { status: 'connected' }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
assert.equal(recorderApi.isRecording, false);
|
||||
assert.equal(recorderApi.isSupported, true);
|
||||
|
||||
await act(async () => {
|
||||
const started = await recorderApi.startRecording({ silent: true });
|
||||
assert.equal(started, true);
|
||||
});
|
||||
|
||||
assert.equal(recorderApi.isRecording, true);
|
||||
assert.equal(calls.begin.length, 1);
|
||||
assert.equal(calls.begin[0].protocol, 'rdp');
|
||||
assert.equal(FakeMediaRecorder.instances.length, 1);
|
||||
assert.equal(FakeMediaRecorder.instances[0].timeslice, 2000);
|
||||
assert.equal(FakeMediaRecorder.instances[0].videoBitsPerSecond, 1_800_000);
|
||||
|
||||
await act(async () => {
|
||||
FakeMediaRecorder.instances[0].emitChunk(new Uint8Array([10, 20, 30, 40, 50]));
|
||||
await recorderApi.stopRecording({ silent: true });
|
||||
});
|
||||
|
||||
assert.equal(recorderApi.isRecording, false);
|
||||
assert.equal(fakeStream.getStoppedTracks(), 2);
|
||||
assert.equal(calls.append.length, 2); // 5B + 4B from requestData
|
||||
assert.equal(calls.finish.length, 1);
|
||||
assert.deepEqual(calls.finish[0].protectedIds, ['rec-protected-99']);
|
||||
assert.equal(calls.finish[0].hasAudio, true);
|
||||
assert.equal(calls.finish[0].maxBytes, 1024 * 1024 * 1024);
|
||||
assert.equal(calls.finish[0].retentionDays, 30);
|
||||
|
||||
assert.equal(logUpdates.length, 1);
|
||||
assert.equal(logUpdates[0].id, 'log-active-rdp');
|
||||
assert.equal(logUpdates[0].updates.recordingId, 'rec-test-1');
|
||||
assert.equal(logUpdates[0].updates.recordingHasAudio, true);
|
||||
assert.equal(logUpdates[0].updates.recordingBytes, 9);
|
||||
} finally {
|
||||
await act(async () => { root?.unmount(); });
|
||||
registerConnectionLogsActions(null);
|
||||
publishConnectionLogsSnapshot({ connectionLogs: [] });
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('useRemoteDesktopRecorder aborts cleanly when chunk append fails', async () => {
|
||||
const env = installDomEnv();
|
||||
FakeMediaRecorder.instances = [];
|
||||
Object.defineProperty(globalThis, 'MediaRecorder', { value: FakeMediaRecorder, configurable: true });
|
||||
|
||||
const { bridge, calls } = createFakeBridge({
|
||||
append: async () => {
|
||||
throw new Error('ENOSPC: disk full');
|
||||
},
|
||||
});
|
||||
const fakeStream = createFakeStream(false);
|
||||
let recorderApi!: UseRemoteDesktopRecorderResult;
|
||||
let root: ReactTestRenderer | undefined;
|
||||
|
||||
function Harness() {
|
||||
const canvasRef = useRef<RemoteDesktopCanvasHandle | null>({
|
||||
sendSpecialKey: () => {},
|
||||
typeText: () => {},
|
||||
releaseAllInputs: () => {},
|
||||
captureScreenshot: async () => null,
|
||||
getCaptureStream: () => fakeStream.stream,
|
||||
});
|
||||
recorderApi = useRemoteDesktopRecorder({
|
||||
sessionId: 'sess-vnc-1',
|
||||
protocol: 'vnc',
|
||||
hostLabel: 'Ubuntu VNC',
|
||||
status: 'connected',
|
||||
audioEnabled: false,
|
||||
canvasHandleRef: canvasRef,
|
||||
recordingsBridgeOverride: bridge,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root = create(
|
||||
React.createElement(I18nProvider, {
|
||||
locale: 'en',
|
||||
children: React.createElement(Harness),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await recorderApi.startRecording({ silent: true });
|
||||
FakeMediaRecorder.instances[0].emitChunk(new Uint8Array([1, 2, 3]));
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
});
|
||||
|
||||
assert.equal(recorderApi.isRecording, false);
|
||||
assert.equal(calls.finish.length, 0);
|
||||
assert.equal(calls.abort.length, 1);
|
||||
assert.equal(calls.abort[0].recordingId, 'rec-test-1');
|
||||
} finally {
|
||||
await act(async () => { root?.unmount(); });
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,595 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import {
|
||||
getConnectionLogsActions,
|
||||
getConnectionLogsSnapshot,
|
||||
} from '../../application/state/connectionLogsStore';
|
||||
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
|
||||
import type { RemoteDesktopProtocol } from '../../domain/remoteDesktop';
|
||||
import {
|
||||
STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import { toast } from '../ui/toast';
|
||||
import {
|
||||
formatRecordingDuration,
|
||||
tr,
|
||||
type RemoteDesktopCanvasHandle,
|
||||
} from './remoteDesktopHelpers';
|
||||
|
||||
// Mirrors LOCAL_STORAGE_ADAPTER_CHANGED_EVENT from infrastructure/persistence/localStorageAdapter.ts
|
||||
// without violating the component -> infrastructure/persistence lint boundary.
|
||||
const LOCAL_STORAGE_CHANGED_EVENT = 'netcatty:local-storage-adapter-changed';
|
||||
|
||||
export interface RemoteDesktopRecordingsApi {
|
||||
begin(options: {
|
||||
mimeType?: string;
|
||||
hostLabel?: string;
|
||||
protocol: 'rdp' | 'vnc';
|
||||
}): Promise<{ recordingId: string }>;
|
||||
append(options: {
|
||||
recordingId: string;
|
||||
chunk: Uint8Array;
|
||||
}): Promise<{ bytesWritten: number }>;
|
||||
finish(options: {
|
||||
recordingId: string;
|
||||
durationMs: number;
|
||||
hasAudio?: boolean;
|
||||
maxBytes?: number;
|
||||
retentionDays?: number;
|
||||
protectedIds?: string[];
|
||||
}): Promise<{
|
||||
recordingId: string;
|
||||
bytes: number;
|
||||
durationMs: number;
|
||||
playbackUrl: string;
|
||||
}>;
|
||||
abort(options: { recordingId: string }): Promise<{ ok: boolean }>;
|
||||
}
|
||||
|
||||
function readStorageString(key: string): string | null {
|
||||
if (typeof globalThis === 'undefined' || !('localStorage' in globalThis)) return null;
|
||||
try {
|
||||
return globalThis.localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getWindowRecordingsBridge(): RemoteDesktopRecordingsApi | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
const win = window as Window & {
|
||||
netcatty?: { remoteDesktopRecordings?: RemoteDesktopRecordingsApi };
|
||||
};
|
||||
return win.netcatty?.remoteDesktopRecordings ?? null;
|
||||
}
|
||||
|
||||
export interface RemoteDesktopRecordingSettings {
|
||||
autoRecord: boolean;
|
||||
fps: 5 | 10 | 15;
|
||||
includeAudio: boolean;
|
||||
maxMb: number;
|
||||
retentionDays: number;
|
||||
}
|
||||
|
||||
const DEFAULT_RECORDING_SETTINGS: RemoteDesktopRecordingSettings = {
|
||||
autoRecord: false,
|
||||
fps: 10,
|
||||
includeAudio: true,
|
||||
maxMb: 1024,
|
||||
retentionDays: 30,
|
||||
};
|
||||
|
||||
const RECORDING_SETTING_KEYS = new Set<string>([
|
||||
STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS,
|
||||
]);
|
||||
|
||||
export function resolveRecordingVideoBitsPerSecond(fps: number): number {
|
||||
if (fps <= 5) return 1_000_000;
|
||||
if (fps <= 10) return 1_800_000;
|
||||
return 2_500_000;
|
||||
}
|
||||
|
||||
export function pickRemoteDesktopRecordingMimeType(
|
||||
includeAudio: boolean,
|
||||
isTypeSupported?: (mimeType: string) => boolean,
|
||||
): string {
|
||||
const check = isTypeSupported ?? (
|
||||
typeof MediaRecorder !== 'undefined' && typeof MediaRecorder.isTypeSupported === 'function'
|
||||
? (mime: string) => MediaRecorder.isTypeSupported(mime)
|
||||
: () => false
|
||||
);
|
||||
const candidates = includeAudio
|
||||
? [
|
||||
'video/webm;codecs=vp9,opus',
|
||||
'video/webm;codecs=vp8,opus',
|
||||
'video/webm;codecs=vp9',
|
||||
'video/webm;codecs=vp8',
|
||||
'video/webm',
|
||||
]
|
||||
: [
|
||||
'video/webm;codecs=vp9',
|
||||
'video/webm;codecs=vp8',
|
||||
'video/webm',
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
if (check(candidate)) return candidate;
|
||||
} catch {
|
||||
// ignore unsupported check errors
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export function readRemoteDesktopRecordingSettings(): RemoteDesktopRecordingSettings {
|
||||
const rawAuto = readStorageString(STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD);
|
||||
const rawFpsStr = readStorageString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS);
|
||||
const rawAudio = readStorageString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO);
|
||||
const rawMaxMbStr = readStorageString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB);
|
||||
const rawRetentionStr = readStorageString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS);
|
||||
|
||||
const rawFps = rawFpsStr === null || rawFpsStr.trim() === '' ? Number.NaN : Number(rawFpsStr);
|
||||
const rawMaxMb = rawMaxMbStr === null || rawMaxMbStr.trim() === '' ? Number.NaN : Number(rawMaxMbStr);
|
||||
const rawRetention = rawRetentionStr === null || rawRetentionStr.trim() === ''
|
||||
? Number.NaN
|
||||
: Number(rawRetentionStr);
|
||||
|
||||
const fps: 5 | 10 | 15 = rawFps === 5 ? 5 : rawFps === 15 ? 15 : DEFAULT_RECORDING_SETTINGS.fps;
|
||||
const maxMb = Number.isFinite(rawMaxMb) && rawMaxMb > 0 ? Math.round(rawMaxMb) : DEFAULT_RECORDING_SETTINGS.maxMb;
|
||||
const retentionDays = Number.isFinite(rawRetention) && rawRetention >= 0
|
||||
? Math.round(rawRetention)
|
||||
: DEFAULT_RECORDING_SETTINGS.retentionDays;
|
||||
|
||||
return {
|
||||
autoRecord: rawAuto === null ? DEFAULT_RECORDING_SETTINGS.autoRecord : rawAuto === 'true',
|
||||
fps,
|
||||
includeAudio: rawAudio === null ? DEFAULT_RECORDING_SETTINGS.includeAudio : rawAudio === 'true',
|
||||
maxMb,
|
||||
retentionDays,
|
||||
};
|
||||
}
|
||||
|
||||
function collectProtectedRecordingIds(): string[] {
|
||||
const { connectionLogs } = getConnectionLogsSnapshot();
|
||||
const ids: string[] = [];
|
||||
for (const log of connectionLogs) {
|
||||
if (log.saved && log.recordingId) {
|
||||
ids.push(log.recordingId);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function updateMatchingConnectionLogRecording(
|
||||
sessionId: string,
|
||||
updates: {
|
||||
recordingId: string;
|
||||
recordingMimeType: string;
|
||||
recordingDurationMs: number;
|
||||
recordingBytes: number;
|
||||
recordingHasAudio: boolean;
|
||||
endTime?: number;
|
||||
},
|
||||
): void {
|
||||
const { connectionLogs } = getConnectionLogsSnapshot();
|
||||
const actions = getConnectionLogsActions();
|
||||
if (!actions?.updateConnectionLog) return;
|
||||
const matchingLog = selectConnectionLogForTerminalDataCapture(
|
||||
[...connectionLogs],
|
||||
{ sessionId },
|
||||
);
|
||||
if (!matchingLog) return;
|
||||
actions.updateConnectionLog(matchingLog.id, updates);
|
||||
}
|
||||
|
||||
export interface UseRemoteDesktopRecorderOptions {
|
||||
sessionId: string;
|
||||
protocol: RemoteDesktopProtocol;
|
||||
hostLabel: string;
|
||||
status: 'connecting' | 'connected' | 'disconnected';
|
||||
audioEnabled: boolean;
|
||||
canvasHandleRef: React.RefObject<RemoteDesktopCanvasHandle | null>;
|
||||
recordingsBridgeOverride?: RemoteDesktopRecordingsApi | null;
|
||||
}
|
||||
|
||||
export interface UseRemoteDesktopRecorderResult {
|
||||
isRecording: boolean;
|
||||
isStopping: boolean;
|
||||
isSupported: boolean;
|
||||
elapsedMs: number;
|
||||
formattedElapsed: string;
|
||||
startRecording: (options?: { silent?: boolean }) => Promise<boolean>;
|
||||
stopRecording: (options?: { stampEndTime?: boolean; silent?: boolean }) => Promise<void>;
|
||||
toggleRecording: () => Promise<void>;
|
||||
}
|
||||
|
||||
interface ActiveRecordingRun {
|
||||
recordingId: string;
|
||||
mimeType: string;
|
||||
hasAudio: boolean;
|
||||
startedAt: number;
|
||||
recorder: MediaRecorder;
|
||||
stream: MediaStream;
|
||||
appendChain: Promise<void>;
|
||||
appendError: Error | null;
|
||||
bytesQueued: number;
|
||||
stopPromise: Promise<void> | null;
|
||||
aborted: boolean;
|
||||
settings: RemoteDesktopRecordingSettings;
|
||||
}
|
||||
|
||||
const CHUNK_TIMESLICE_MS = 2000;
|
||||
const STOP_WAIT_TIMEOUT_MS = 5000;
|
||||
|
||||
export function useRemoteDesktopRecorder({
|
||||
sessionId,
|
||||
protocol,
|
||||
hostLabel,
|
||||
status,
|
||||
audioEnabled,
|
||||
canvasHandleRef,
|
||||
recordingsBridgeOverride,
|
||||
}: UseRemoteDesktopRecorderOptions): UseRemoteDesktopRecorderResult {
|
||||
const { t } = useI18n();
|
||||
const [settings, setSettings] = useState<RemoteDesktopRecordingSettings>(readRemoteDesktopRecordingSettings);
|
||||
const [isRecording, setIsRecording] = useState(false);
|
||||
const [isStopping, setIsStopping] = useState(false);
|
||||
const [elapsedMs, setElapsedMs] = useState(0);
|
||||
|
||||
const activeRunRef = useRef<ActiveRecordingRun | null>(null);
|
||||
const autoRecordedForConnectionRef = useRef(false);
|
||||
const mountedRef = useRef(true);
|
||||
const latestMetaRef = useRef({ sessionId, protocol, hostLabel, status, audioEnabled, settings });
|
||||
latestMetaRef.current = { sessionId, protocol, hostLabel, status, audioEnabled, settings };
|
||||
|
||||
const getBridge = useCallback((): RemoteDesktopRecordingsApi | null => {
|
||||
if (recordingsBridgeOverride !== undefined) return recordingsBridgeOverride;
|
||||
return getWindowRecordingsBridge();
|
||||
}, [recordingsBridgeOverride]);
|
||||
|
||||
const isSupported = typeof MediaRecorder !== 'undefined' && Boolean(getBridge());
|
||||
|
||||
// Stay in sync with Settings > System recording preferences
|
||||
useEffect(() => {
|
||||
const refresh = () => setSettings(readRemoteDesktopRecordingSettings());
|
||||
const onAdapterChanged = (event: Event) => {
|
||||
const detail = (event as CustomEvent<{ key?: string | null }>).detail;
|
||||
if (!detail?.key || RECORDING_SETTING_KEYS.has(detail.key)) {
|
||||
refresh();
|
||||
}
|
||||
};
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
if (event.key === null || RECORDING_SETTING_KEYS.has(event.key)) {
|
||||
refresh();
|
||||
}
|
||||
};
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener(LOCAL_STORAGE_CHANGED_EVENT, onAdapterChanged);
|
||||
window.addEventListener('storage', onStorage);
|
||||
}
|
||||
return () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.removeEventListener(LOCAL_STORAGE_CHANGED_EVENT, onAdapterChanged);
|
||||
window.removeEventListener('storage', onStorage);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Elapsed timer while recording (1s granularity avoids redundant React re-renders)
|
||||
useEffect(() => {
|
||||
if (!isRecording) {
|
||||
setElapsedMs(0);
|
||||
return undefined;
|
||||
}
|
||||
const timer = window.setInterval(() => {
|
||||
const run = activeRunRef.current;
|
||||
if (run) {
|
||||
const nextMs = Math.max(0, Date.now() - run.startedAt);
|
||||
setElapsedMs((prev) =>
|
||||
Math.floor(prev / 1000) === Math.floor(nextMs / 1000) ? prev : nextMs,
|
||||
);
|
||||
}
|
||||
}, 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [isRecording]);
|
||||
|
||||
const stopStreamTracks = (stream: MediaStream) => {
|
||||
try {
|
||||
for (const track of stream.getTracks()) {
|
||||
track.stop();
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
const stopRecording = useCallback(
|
||||
async (options?: { stampEndTime?: boolean; silent?: boolean }): Promise<void> => {
|
||||
const run = activeRunRef.current;
|
||||
if (!run) return;
|
||||
if (run.stopPromise) {
|
||||
return run.stopPromise;
|
||||
}
|
||||
|
||||
const bridge = getBridge();
|
||||
const finalize = async () => {
|
||||
if (mountedRef.current) setIsStopping(true);
|
||||
try {
|
||||
if (run.recorder.state !== 'inactive') {
|
||||
await new Promise<void>((resolve) => {
|
||||
let settled = false;
|
||||
const done = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
window.clearTimeout(timeoutId);
|
||||
resolve();
|
||||
};
|
||||
const timeoutId = window.setTimeout(done, STOP_WAIT_TIMEOUT_MS);
|
||||
run.recorder.addEventListener('stop', done, { once: true });
|
||||
run.recorder.addEventListener('error', done, { once: true });
|
||||
try {
|
||||
if (typeof run.recorder.requestData === 'function' && run.recorder.state === 'recording') {
|
||||
run.recorder.requestData();
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
try {
|
||||
run.recorder.stop();
|
||||
} catch {
|
||||
done();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
stopStreamTracks(run.stream);
|
||||
await run.appendChain.catch(() => {});
|
||||
|
||||
const durationMs = Math.max(1, Date.now() - run.startedAt);
|
||||
if (!bridge) return;
|
||||
|
||||
if (run.aborted || run.appendError || run.bytesQueued <= 0) {
|
||||
await bridge.abort({ recordingId: run.recordingId }).catch(() => {});
|
||||
if (run.appendError && !options?.silent) {
|
||||
toast.error(tr(t, 'remoteDesktop.recording.failed', 'Session recording failed'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const finished = await bridge.finish({
|
||||
recordingId: run.recordingId,
|
||||
durationMs,
|
||||
hasAudio: run.hasAudio,
|
||||
maxBytes: run.settings.maxMb * 1024 * 1024,
|
||||
retentionDays: run.settings.retentionDays,
|
||||
protectedIds: collectProtectedRecordingIds(),
|
||||
});
|
||||
updateMatchingConnectionLogRecording(latestMetaRef.current.sessionId, {
|
||||
recordingId: finished.recordingId,
|
||||
recordingMimeType: run.mimeType || 'video/webm',
|
||||
recordingDurationMs: finished.durationMs ?? durationMs,
|
||||
recordingBytes: finished.bytes,
|
||||
recordingHasAudio: run.hasAudio,
|
||||
...(options?.stampEndTime ? { endTime: Date.now() } : {}),
|
||||
});
|
||||
if (!options?.silent) {
|
||||
toast.success(
|
||||
tr(t, 'remoteDesktop.recording.saved', 'Session recording saved to Connection Logs'),
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
await bridge.abort({ recordingId: run.recordingId }).catch(() => {});
|
||||
if (!options?.silent) {
|
||||
toast.error(tr(t, 'remoteDesktop.recording.failed', 'Session recording failed'));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (activeRunRef.current === run) {
|
||||
activeRunRef.current = null;
|
||||
}
|
||||
if (mountedRef.current) {
|
||||
setIsRecording(false);
|
||||
setIsStopping(false);
|
||||
setElapsedMs(0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
run.stopPromise = finalize();
|
||||
return run.stopPromise;
|
||||
},
|
||||
[getBridge, t],
|
||||
);
|
||||
|
||||
const startRecording = useCallback(
|
||||
async (options?: { silent?: boolean }): Promise<boolean> => {
|
||||
if (activeRunRef.current) return false;
|
||||
const meta = latestMetaRef.current;
|
||||
if (meta.status !== 'connected') return false;
|
||||
|
||||
const bridge = getBridge();
|
||||
if (typeof MediaRecorder === 'undefined' || !bridge) {
|
||||
if (!options?.silent) {
|
||||
toast.error(
|
||||
tr(
|
||||
t,
|
||||
'remoteDesktop.recording.unsupported',
|
||||
'Session recording is not supported in this environment',
|
||||
),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const wantAudio = meta.protocol === 'rdp' && meta.audioEnabled && meta.settings.includeAudio;
|
||||
const stream = canvasHandleRef.current?.getCaptureStream?.(meta.settings.fps, wantAudio) ?? null;
|
||||
if (!stream || stream.getVideoTracks().length === 0) {
|
||||
if (!options?.silent) {
|
||||
toast.error(
|
||||
tr(
|
||||
t,
|
||||
'remoteDesktop.recording.unsupported',
|
||||
'Session recording is not supported in this environment',
|
||||
),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const hasAudio = stream.getAudioTracks().length > 0;
|
||||
const mimeType = pickRemoteDesktopRecordingMimeType(hasAudio);
|
||||
const videoBitsPerSecond = resolveRecordingVideoBitsPerSecond(meta.settings.fps);
|
||||
|
||||
let recordingId: string;
|
||||
try {
|
||||
const begun = await bridge.begin({
|
||||
mimeType: mimeType || 'video/webm',
|
||||
hostLabel: meta.hostLabel,
|
||||
protocol: meta.protocol,
|
||||
});
|
||||
recordingId = begun.recordingId;
|
||||
} catch {
|
||||
stopStreamTracks(stream);
|
||||
if (!options?.silent) {
|
||||
toast.error(tr(t, 'remoteDesktop.recording.failed', 'Session recording failed'));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
let recorder: MediaRecorder;
|
||||
try {
|
||||
const recorderOptions: MediaRecorderOptions = { videoBitsPerSecond };
|
||||
if (mimeType) recorderOptions.mimeType = mimeType;
|
||||
recorder = new MediaRecorder(stream, recorderOptions);
|
||||
} catch {
|
||||
stopStreamTracks(stream);
|
||||
await bridge.abort({ recordingId }).catch(() => {});
|
||||
if (!options?.silent) {
|
||||
toast.error(tr(t, 'remoteDesktop.recording.failed', 'Session recording failed'));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const run: ActiveRecordingRun = {
|
||||
recordingId,
|
||||
mimeType: recorder.mimeType || mimeType || 'video/webm',
|
||||
hasAudio,
|
||||
startedAt: Date.now(),
|
||||
recorder,
|
||||
stream,
|
||||
appendChain: Promise.resolve(),
|
||||
appendError: null,
|
||||
bytesQueued: 0,
|
||||
stopPromise: null,
|
||||
aborted: false,
|
||||
settings: meta.settings,
|
||||
};
|
||||
activeRunRef.current = run;
|
||||
|
||||
recorder.ondataavailable = (ev: BlobEvent) => {
|
||||
if (!ev.data || ev.data.size <= 0 || run.aborted) return;
|
||||
const blob = ev.data;
|
||||
run.bytesQueued += blob.size;
|
||||
run.appendChain = run.appendChain.then(async () => {
|
||||
if (run.aborted) return;
|
||||
try {
|
||||
const buffer = await blob.arrayBuffer();
|
||||
if (run.aborted) return;
|
||||
await bridge.append({
|
||||
recordingId: run.recordingId,
|
||||
chunk: new Uint8Array(buffer),
|
||||
});
|
||||
} catch (err) {
|
||||
run.appendError = err instanceof Error ? err : new Error(String(err));
|
||||
run.aborted = true;
|
||||
void stopRecording({ silent: false });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
recorder.onerror = () => {
|
||||
if (!run.appendError) {
|
||||
run.appendError = new Error('MediaRecorder error');
|
||||
}
|
||||
run.aborted = true;
|
||||
void stopRecording({ silent: false });
|
||||
};
|
||||
|
||||
try {
|
||||
recorder.start(CHUNK_TIMESLICE_MS);
|
||||
} catch {
|
||||
activeRunRef.current = null;
|
||||
stopStreamTracks(stream);
|
||||
await bridge.abort({ recordingId }).catch(() => {});
|
||||
if (!options?.silent) {
|
||||
toast.error(tr(t, 'remoteDesktop.recording.failed', 'Session recording failed'));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (mountedRef.current) {
|
||||
setIsRecording(true);
|
||||
setElapsedMs(0);
|
||||
}
|
||||
if (!options?.silent) {
|
||||
toast.info(tr(t, 'remoteDesktop.recording.started', 'Session recording started'));
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[canvasHandleRef, getBridge, stopRecording, t],
|
||||
);
|
||||
|
||||
const toggleRecording = useCallback(async () => {
|
||||
if (activeRunRef.current) {
|
||||
await stopRecording();
|
||||
} else {
|
||||
await startRecording();
|
||||
}
|
||||
}, [startRecording, stopRecording]);
|
||||
|
||||
// Auto-record once per connection when enabled in settings
|
||||
useEffect(() => {
|
||||
if (status === 'connected') {
|
||||
if (settings.autoRecord && !autoRecordedForConnectionRef.current && !activeRunRef.current) {
|
||||
autoRecordedForConnectionRef.current = true;
|
||||
void startRecording({ silent: false });
|
||||
}
|
||||
return;
|
||||
}
|
||||
autoRecordedForConnectionRef.current = false;
|
||||
if (activeRunRef.current) {
|
||||
void stopRecording({ stampEndTime: false });
|
||||
}
|
||||
}, [settings.autoRecord, startRecording, status, stopRecording]);
|
||||
|
||||
// Clean flush/stop on unmount
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
if (activeRunRef.current) {
|
||||
void stopRecording({ stampEndTime: true, silent: true });
|
||||
}
|
||||
};
|
||||
}, [stopRecording]);
|
||||
|
||||
return {
|
||||
isRecording,
|
||||
isStopping,
|
||||
isSupported,
|
||||
elapsedMs,
|
||||
formattedElapsed: formatRecordingDuration(elapsedMs),
|
||||
startRecording,
|
||||
stopRecording,
|
||||
toggleRecording,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
domCodeToQemuKeycode,
|
||||
domEventToVncKeysym,
|
||||
textToVncKeysymSequence,
|
||||
unicodeCharToVncKeysym,
|
||||
VNC_SPECIAL_CHORDS,
|
||||
X11_KEYSYM,
|
||||
} from './vncKeymap';
|
||||
|
||||
test('vncKeymap maps modifiers, navigation, function keys, and numpad keys', () => {
|
||||
assert.equal(domEventToVncKeysym({ key: 'Control', code: 'ControlLeft' }), X11_KEYSYM.Control_L);
|
||||
assert.equal(domEventToVncKeysym({ key: 'Control', code: 'ControlRight' }), X11_KEYSYM.Control_R);
|
||||
assert.equal(domEventToVncKeysym({ key: 'Alt', code: 'AltRight' }), X11_KEYSYM.Alt_R);
|
||||
assert.equal(domEventToVncKeysym({ key: 'Meta', code: 'MetaLeft' }), X11_KEYSYM.Super_L);
|
||||
assert.equal(domEventToVncKeysym({ key: 'ArrowUp', code: 'ArrowUp' }), X11_KEYSYM.Up);
|
||||
assert.equal(domEventToVncKeysym({ key: 'Delete', code: 'Delete' }), X11_KEYSYM.Delete);
|
||||
assert.equal(domEventToVncKeysym({ key: 'F12', code: 'F12' }), X11_KEYSYM.F12);
|
||||
assert.equal(domEventToVncKeysym({ key: 'Enter', code: 'NumpadEnter' }), X11_KEYSYM.KP_Enter);
|
||||
});
|
||||
|
||||
test('vncKeymap maps printable ASCII, Latin-1, and Unicode characters with 0x01000000 bit', () => {
|
||||
assert.equal(domEventToVncKeysym({ key: 'a', code: 'KeyA' }), 0x61);
|
||||
assert.equal(domEventToVncKeysym({ key: 'A', code: 'KeyA' }), 0x41);
|
||||
assert.equal(domEventToVncKeysym({ key: 'é' }), 0xe9);
|
||||
assert.equal(unicodeCharToVncKeysym('中'), 0x01000000 | 0x4e2d);
|
||||
assert.equal(domEventToVncKeysym({ key: 'Process' }), null);
|
||||
assert.equal(domEventToVncKeysym({ key: 'Dead' }), null);
|
||||
});
|
||||
|
||||
test('vncKeymap maps DOM codes to QEMU extended XT scancodes', () => {
|
||||
assert.equal(domCodeToQemuKeycode('KeyA'), 0x1e);
|
||||
assert.equal(domCodeToQemuKeycode('ControlLeft'), 0x1d);
|
||||
assert.equal(domCodeToQemuKeycode('ControlRight'), 0x80 | 0x1d);
|
||||
assert.equal(domCodeToQemuKeycode('ArrowUp'), 0x80 | 0x48);
|
||||
assert.equal(domCodeToQemuKeycode('Delete'), 0x80 | 0x53);
|
||||
assert.equal(domCodeToQemuKeycode('MetaLeft'), 0x80 | 0x5b);
|
||||
assert.equal(domCodeToQemuKeycode('UnknownKey'), null);
|
||||
});
|
||||
|
||||
test('vncKeymap converts clipboard strings into X11 keysym sequences', () => {
|
||||
assert.deepEqual(textToVncKeysymSequence('Hi!\r\n\t中'), [
|
||||
0x48,
|
||||
0x69,
|
||||
0x21,
|
||||
X11_KEYSYM.Return,
|
||||
X11_KEYSYM.Tab,
|
||||
0x01000000 | 0x4e2d,
|
||||
]);
|
||||
assert.deepEqual(VNC_SPECIAL_CHORDS['ctrl-alt-del'], [
|
||||
X11_KEYSYM.Control_L,
|
||||
X11_KEYSYM.Alt_L,
|
||||
X11_KEYSYM.Delete,
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,408 @@
|
||||
/**
|
||||
* DOM KeyboardEvent -> X11 Keysym & QEMU Extended Key Event (XT scancode) mapper
|
||||
* for VNC / RFB sessions.
|
||||
*
|
||||
* Keysym references: X11 keysymdef.h & RFC 6143 (RFB Protocol).
|
||||
* QEMU XT keycode references: QEMU RFB Extended Key Event spec (normal Set 1
|
||||
* scancode 0x01..0x7F; extended 0xE0xx keys encoded as `0x80 | lowByte`).
|
||||
*/
|
||||
|
||||
export const X11_KEYSYM = {
|
||||
BackSpace: 0xff08,
|
||||
Tab: 0xff09,
|
||||
Return: 0xff0d,
|
||||
Pause: 0xff13,
|
||||
Scroll_Lock: 0xff14,
|
||||
Escape: 0xff1b,
|
||||
Home: 0xff50,
|
||||
Left: 0xff51,
|
||||
Up: 0xff52,
|
||||
Right: 0xff53,
|
||||
Down: 0xff54,
|
||||
Page_Up: 0xff55,
|
||||
Page_Down: 0xff56,
|
||||
End: 0xff57,
|
||||
Print: 0xff61,
|
||||
Insert: 0xff63,
|
||||
Menu: 0xff67,
|
||||
Num_Lock: 0xff7f,
|
||||
KP_Enter: 0xff8d,
|
||||
KP_Multiply: 0xffaa,
|
||||
KP_Add: 0xffab,
|
||||
KP_Subtract: 0xffad,
|
||||
KP_Decimal: 0xffae,
|
||||
KP_Divide: 0xffaf,
|
||||
KP_0: 0xffb0,
|
||||
KP_1: 0xffb1,
|
||||
KP_2: 0xffb2,
|
||||
KP_3: 0xffb3,
|
||||
KP_4: 0xffb4,
|
||||
KP_5: 0xffb5,
|
||||
KP_6: 0xffb6,
|
||||
KP_7: 0xffb7,
|
||||
KP_8: 0xffb8,
|
||||
KP_9: 0xffb9,
|
||||
F1: 0xffbe,
|
||||
F2: 0xffbf,
|
||||
F3: 0xffc0,
|
||||
F4: 0xffc1,
|
||||
F5: 0xffc2,
|
||||
F6: 0xffc3,
|
||||
F7: 0xffc4,
|
||||
F8: 0xffc5,
|
||||
F9: 0xffc6,
|
||||
F10: 0xffc7,
|
||||
F11: 0xffc8,
|
||||
F12: 0xffc9,
|
||||
Shift_L: 0xffe1,
|
||||
Shift_R: 0xffe2,
|
||||
Control_L: 0xffe3,
|
||||
Control_R: 0xffe4,
|
||||
Caps_Lock: 0xffe5,
|
||||
Meta_L: 0xffe7,
|
||||
Meta_R: 0xffe8,
|
||||
Alt_L: 0xffe9,
|
||||
Alt_R: 0xffea,
|
||||
Super_L: 0xffeb,
|
||||
Super_R: 0xffec,
|
||||
Delete: 0xffff,
|
||||
Space: 0x0020,
|
||||
} as const;
|
||||
|
||||
const DOM_CODE_TO_SPECIAL_KEYSYM: Record<string, number> = {
|
||||
Backspace: X11_KEYSYM.BackSpace,
|
||||
Tab: X11_KEYSYM.Tab,
|
||||
Enter: X11_KEYSYM.Return,
|
||||
Escape: X11_KEYSYM.Escape,
|
||||
Pause: X11_KEYSYM.Pause,
|
||||
ScrollLock: X11_KEYSYM.Scroll_Lock,
|
||||
PrintScreen: X11_KEYSYM.Print,
|
||||
Insert: X11_KEYSYM.Insert,
|
||||
Delete: X11_KEYSYM.Delete,
|
||||
Home: X11_KEYSYM.Home,
|
||||
End: X11_KEYSYM.End,
|
||||
PageUp: X11_KEYSYM.Page_Up,
|
||||
PageDown: X11_KEYSYM.Page_Down,
|
||||
ArrowLeft: X11_KEYSYM.Left,
|
||||
ArrowUp: X11_KEYSYM.Up,
|
||||
ArrowRight: X11_KEYSYM.Right,
|
||||
ArrowDown: X11_KEYSYM.Down,
|
||||
ContextMenu: X11_KEYSYM.Menu,
|
||||
NumLock: X11_KEYSYM.Num_Lock,
|
||||
CapsLock: X11_KEYSYM.Caps_Lock,
|
||||
ShiftLeft: X11_KEYSYM.Shift_L,
|
||||
ShiftRight: X11_KEYSYM.Shift_R,
|
||||
ControlLeft: X11_KEYSYM.Control_L,
|
||||
ControlRight: X11_KEYSYM.Control_R,
|
||||
AltLeft: X11_KEYSYM.Alt_L,
|
||||
AltRight: X11_KEYSYM.Alt_R,
|
||||
MetaLeft: X11_KEYSYM.Super_L,
|
||||
MetaRight: X11_KEYSYM.Super_R,
|
||||
OSLeft: X11_KEYSYM.Super_L,
|
||||
OSRight: X11_KEYSYM.Super_R,
|
||||
NumpadEnter: X11_KEYSYM.KP_Enter,
|
||||
NumpadAdd: X11_KEYSYM.KP_Add,
|
||||
NumpadSubtract: X11_KEYSYM.KP_Subtract,
|
||||
NumpadMultiply: X11_KEYSYM.KP_Multiply,
|
||||
NumpadDivide: X11_KEYSYM.KP_Divide,
|
||||
NumpadDecimal: X11_KEYSYM.KP_Decimal,
|
||||
Numpad0: X11_KEYSYM.KP_0,
|
||||
Numpad1: X11_KEYSYM.KP_1,
|
||||
Numpad2: X11_KEYSYM.KP_2,
|
||||
Numpad3: X11_KEYSYM.KP_3,
|
||||
Numpad4: X11_KEYSYM.KP_4,
|
||||
Numpad5: X11_KEYSYM.KP_5,
|
||||
Numpad6: X11_KEYSYM.KP_6,
|
||||
Numpad7: X11_KEYSYM.KP_7,
|
||||
Numpad8: X11_KEYSYM.KP_8,
|
||||
Numpad9: X11_KEYSYM.KP_9,
|
||||
F1: X11_KEYSYM.F1,
|
||||
F2: X11_KEYSYM.F2,
|
||||
F3: X11_KEYSYM.F3,
|
||||
F4: X11_KEYSYM.F4,
|
||||
F5: X11_KEYSYM.F5,
|
||||
F6: X11_KEYSYM.F6,
|
||||
F7: X11_KEYSYM.F7,
|
||||
F8: X11_KEYSYM.F8,
|
||||
F9: X11_KEYSYM.F9,
|
||||
F10: X11_KEYSYM.F10,
|
||||
F11: X11_KEYSYM.F11,
|
||||
F12: X11_KEYSYM.F12,
|
||||
};
|
||||
|
||||
const DOM_KEY_TO_KEYSYM: Record<string, number> = {
|
||||
Backspace: X11_KEYSYM.BackSpace,
|
||||
Tab: X11_KEYSYM.Tab,
|
||||
Enter: X11_KEYSYM.Return,
|
||||
Escape: X11_KEYSYM.Escape,
|
||||
Pause: X11_KEYSYM.Pause,
|
||||
ScrollLock: X11_KEYSYM.Scroll_Lock,
|
||||
PrintScreen: X11_KEYSYM.Print,
|
||||
Insert: X11_KEYSYM.Insert,
|
||||
Delete: X11_KEYSYM.Delete,
|
||||
Home: X11_KEYSYM.Home,
|
||||
End: X11_KEYSYM.End,
|
||||
PageUp: X11_KEYSYM.Page_Up,
|
||||
PageDown: X11_KEYSYM.Page_Down,
|
||||
ArrowLeft: X11_KEYSYM.Left,
|
||||
ArrowUp: X11_KEYSYM.Up,
|
||||
ArrowRight: X11_KEYSYM.Right,
|
||||
ArrowDown: X11_KEYSYM.Down,
|
||||
ContextMenu: X11_KEYSYM.Menu,
|
||||
NumLock: X11_KEYSYM.Num_Lock,
|
||||
CapsLock: X11_KEYSYM.Caps_Lock,
|
||||
Shift: X11_KEYSYM.Shift_L,
|
||||
Control: X11_KEYSYM.Control_L,
|
||||
Alt: X11_KEYSYM.Alt_L,
|
||||
AltGraph: 0xfe03, // ISO_Level3_Shift
|
||||
Meta: X11_KEYSYM.Super_L,
|
||||
OS: X11_KEYSYM.Super_L,
|
||||
F1: X11_KEYSYM.F1,
|
||||
F2: X11_KEYSYM.F2,
|
||||
F3: X11_KEYSYM.F3,
|
||||
F4: X11_KEYSYM.F4,
|
||||
F5: X11_KEYSYM.F5,
|
||||
F6: X11_KEYSYM.F6,
|
||||
F7: X11_KEYSYM.F7,
|
||||
F8: X11_KEYSYM.F8,
|
||||
F9: X11_KEYSYM.F9,
|
||||
F10: X11_KEYSYM.F10,
|
||||
F11: X11_KEYSYM.F11,
|
||||
F12: X11_KEYSYM.F12,
|
||||
};
|
||||
|
||||
/**
|
||||
* QEMU RFB Extended Key Event XT scancode table.
|
||||
* Standard Set 1 scancodes are `0x01..0x7F`; extended `0xE0` keys are encoded
|
||||
* as `0x80 | lowByte` (QEMU RFB extension specification).
|
||||
*/
|
||||
const DOM_CODE_TO_QEMU_KEYCODE: Record<string, number> = {
|
||||
Escape: 0x01,
|
||||
Digit1: 0x02,
|
||||
Digit2: 0x03,
|
||||
Digit3: 0x04,
|
||||
Digit4: 0x05,
|
||||
Digit5: 0x06,
|
||||
Digit6: 0x07,
|
||||
Digit7: 0x08,
|
||||
Digit8: 0x09,
|
||||
Digit9: 0x0a,
|
||||
Digit0: 0x0b,
|
||||
Minus: 0x0c,
|
||||
Equal: 0x0d,
|
||||
Backspace: 0x0e,
|
||||
Tab: 0x0f,
|
||||
KeyQ: 0x10,
|
||||
KeyW: 0x11,
|
||||
KeyE: 0x12,
|
||||
KeyR: 0x13,
|
||||
KeyT: 0x14,
|
||||
KeyY: 0x15,
|
||||
KeyU: 0x16,
|
||||
KeyI: 0x17,
|
||||
KeyO: 0x18,
|
||||
KeyP: 0x19,
|
||||
BracketLeft: 0x1a,
|
||||
BracketRight: 0x1b,
|
||||
Enter: 0x1c,
|
||||
ControlLeft: 0x1d,
|
||||
KeyA: 0x1e,
|
||||
KeyS: 0x1f,
|
||||
KeyD: 0x20,
|
||||
KeyF: 0x21,
|
||||
KeyG: 0x22,
|
||||
KeyH: 0x23,
|
||||
KeyJ: 0x24,
|
||||
KeyK: 0x25,
|
||||
KeyL: 0x26,
|
||||
Semicolon: 0x27,
|
||||
Quote: 0x28,
|
||||
Backquote: 0x29,
|
||||
ShiftLeft: 0x2a,
|
||||
Backslash: 0x2b,
|
||||
KeyZ: 0x2c,
|
||||
KeyX: 0x2d,
|
||||
KeyC: 0x2e,
|
||||
KeyV: 0x2f,
|
||||
KeyB: 0x30,
|
||||
KeyN: 0x31,
|
||||
KeyM: 0x32,
|
||||
Comma: 0x33,
|
||||
Period: 0x34,
|
||||
Slash: 0x35,
|
||||
ShiftRight: 0x36,
|
||||
NumpadMultiply: 0x37,
|
||||
AltLeft: 0x38,
|
||||
Space: 0x39,
|
||||
CapsLock: 0x3a,
|
||||
F1: 0x3b,
|
||||
F2: 0x3c,
|
||||
F3: 0x3d,
|
||||
F4: 0x3e,
|
||||
F5: 0x3f,
|
||||
F6: 0x40,
|
||||
F7: 0x41,
|
||||
F8: 0x42,
|
||||
F9: 0x43,
|
||||
F10: 0x44,
|
||||
NumLock: 0x45,
|
||||
ScrollLock: 0x46,
|
||||
Numpad7: 0x47,
|
||||
Numpad8: 0x48,
|
||||
Numpad9: 0x49,
|
||||
NumpadSubtract: 0x4a,
|
||||
Numpad4: 0x4b,
|
||||
Numpad5: 0x4c,
|
||||
Numpad6: 0x4d,
|
||||
NumpadAdd: 0x4e,
|
||||
Numpad1: 0x4f,
|
||||
Numpad2: 0x50,
|
||||
Numpad3: 0x51,
|
||||
Numpad0: 0x52,
|
||||
NumpadDecimal: 0x53,
|
||||
IntlBackslash: 0x56,
|
||||
F11: 0x57,
|
||||
F12: 0x58,
|
||||
// Extended keys (0x80 | Set1 code)
|
||||
NumpadEnter: 0x80 | 0x1c,
|
||||
ControlRight: 0x80 | 0x1d,
|
||||
NumpadDivide: 0x80 | 0x35,
|
||||
PrintScreen: 0x80 | 0x37,
|
||||
AltRight: 0x80 | 0x38,
|
||||
Home: 0x80 | 0x47,
|
||||
ArrowUp: 0x80 | 0x48,
|
||||
PageUp: 0x80 | 0x49,
|
||||
ArrowLeft: 0x80 | 0x4b,
|
||||
ArrowRight: 0x80 | 0x4d,
|
||||
End: 0x80 | 0x4f,
|
||||
ArrowDown: 0x80 | 0x50,
|
||||
PageDown: 0x80 | 0x51,
|
||||
Insert: 0x80 | 0x52,
|
||||
Delete: 0x80 | 0x53,
|
||||
MetaLeft: 0x80 | 0x5b,
|
||||
OSLeft: 0x80 | 0x5b,
|
||||
MetaRight: 0x80 | 0x5c,
|
||||
OSRight: 0x80 | 0x5c,
|
||||
ContextMenu: 0x80 | 0x5d,
|
||||
};
|
||||
|
||||
export interface VncKeyboardEventLike {
|
||||
key: string;
|
||||
code?: string;
|
||||
location?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a single Unicode character (or codepoint) into an X11 Keysym.
|
||||
* Printable ASCII (0x20..0x7E) and Latin-1 (0xA0..0xFF) map directly;
|
||||
* higher Unicode codepoints use `0x01000000 | codepoint`.
|
||||
*/
|
||||
export function unicodeCharToVncKeysym(char: string): number | null {
|
||||
if (!char) return null;
|
||||
const codePoint = char.codePointAt(0);
|
||||
if (codePoint === undefined) return null;
|
||||
if (char === '\n' || char === '\r') return X11_KEYSYM.Return;
|
||||
if (char === '\t') return X11_KEYSYM.Tab;
|
||||
if (codePoint >= 0x20 && codePoint <= 0x7e) return codePoint;
|
||||
if (codePoint >= 0xa0 && codePoint <= 0xff) return codePoint;
|
||||
if (codePoint > 0xff && codePoint <= 0x10ffff) {
|
||||
return (0x01000000 | codePoint) >>> 0;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a DOM KeyboardEvent to an X11 Keysym.
|
||||
* Returns `null` for dead/unidentified/IME-process keys.
|
||||
*/
|
||||
export function domEventToVncKeysym(event: VncKeyboardEventLike): number | null {
|
||||
const { key, code, location } = event;
|
||||
if (!key || key === 'Unidentified' || key === 'Process' || key === 'Dead') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Distinguish left/right modifiers & numpad keys via code first
|
||||
if (code && code in DOM_CODE_TO_SPECIAL_KEYSYM) {
|
||||
// Only use Numpad* keysyms when key isn't a nav key from NumLock-off
|
||||
if (!code.startsWith('Numpad') || key.length === 1 || key === 'Enter') {
|
||||
return DOM_CODE_TO_SPECIAL_KEYSYM[code];
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for right-side modifiers when code is omitted
|
||||
if (location === 2) {
|
||||
if (key === 'Shift') return X11_KEYSYM.Shift_R;
|
||||
if (key === 'Control') return X11_KEYSYM.Control_R;
|
||||
if (key === 'Alt') return X11_KEYSYM.Alt_R;
|
||||
if (key === 'Meta' || key === 'OS') return X11_KEYSYM.Super_R;
|
||||
}
|
||||
|
||||
if (key in DOM_KEY_TO_KEYSYM) {
|
||||
return DOM_KEY_TO_KEYSYM[key];
|
||||
}
|
||||
|
||||
// Single printable character (including surrogate pairs)
|
||||
const chars = Array.from(key);
|
||||
if (chars.length === 1) {
|
||||
return unicodeCharToVncKeysym(chars[0]);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map DOM `KeyboardEvent.code` to a QEMU RFB Extended Key Event XT scancode.
|
||||
*/
|
||||
export function domCodeToQemuKeycode(code: string | undefined): number | null {
|
||||
if (!code) return null;
|
||||
return DOM_CODE_TO_QEMU_KEYCODE[code] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an arbitrary text string (e.g. clipboard contents) into a sequence of
|
||||
* X11 keysyms for "Type Clipboard as Keystrokes".
|
||||
* Normalizes CRLF -> CR (Return) and skips non-printable control characters.
|
||||
*/
|
||||
export function textToVncKeysymSequence(text: string): number[] {
|
||||
if (!text) return [];
|
||||
const normalized = text.replace(/\r\n/g, '\n');
|
||||
const keysyms: number[] = [];
|
||||
for (const ch of normalized) {
|
||||
const sym = unicodeCharToVncKeysym(ch);
|
||||
if (sym !== null) {
|
||||
keysyms.push(sym);
|
||||
}
|
||||
}
|
||||
return keysyms;
|
||||
}
|
||||
|
||||
export type RemoteDesktopSpecialKeyId =
|
||||
| 'ctrl-alt-del'
|
||||
| 'win'
|
||||
| 'alt-tab'
|
||||
| 'alt-f4'
|
||||
| 'ctrl-shift-esc'
|
||||
| 'cmd-space'
|
||||
| 'ctrl-alt-f1'
|
||||
| 'ctrl-alt-f2'
|
||||
| 'ctrl-alt-f3'
|
||||
| 'ctrl-alt-f4'
|
||||
| 'ctrl-alt-f5'
|
||||
| 'ctrl-alt-f6'
|
||||
| 'ctrl-alt-f7';
|
||||
|
||||
export const VNC_SPECIAL_CHORDS: Record<RemoteDesktopSpecialKeyId, readonly number[]> = {
|
||||
'ctrl-alt-del': [X11_KEYSYM.Control_L, X11_KEYSYM.Alt_L, X11_KEYSYM.Delete],
|
||||
win: [X11_KEYSYM.Super_L],
|
||||
'alt-tab': [X11_KEYSYM.Alt_L, X11_KEYSYM.Tab],
|
||||
'alt-f4': [X11_KEYSYM.Alt_L, X11_KEYSYM.F4],
|
||||
'ctrl-shift-esc': [X11_KEYSYM.Control_L, X11_KEYSYM.Shift_L, X11_KEYSYM.Escape],
|
||||
'cmd-space': [X11_KEYSYM.Super_L, X11_KEYSYM.Space],
|
||||
'ctrl-alt-f1': [X11_KEYSYM.Control_L, X11_KEYSYM.Alt_L, X11_KEYSYM.F1],
|
||||
'ctrl-alt-f2': [X11_KEYSYM.Control_L, X11_KEYSYM.Alt_L, X11_KEYSYM.F2],
|
||||
'ctrl-alt-f3': [X11_KEYSYM.Control_L, X11_KEYSYM.Alt_L, X11_KEYSYM.F3],
|
||||
'ctrl-alt-f4': [X11_KEYSYM.Control_L, X11_KEYSYM.Alt_L, X11_KEYSYM.F4],
|
||||
'ctrl-alt-f5': [X11_KEYSYM.Control_L, X11_KEYSYM.Alt_L, X11_KEYSYM.F5],
|
||||
'ctrl-alt-f6': [X11_KEYSYM.Control_L, X11_KEYSYM.Alt_L, X11_KEYSYM.F6],
|
||||
'ctrl-alt-f7': [X11_KEYSYM.Control_L, X11_KEYSYM.Alt_L, X11_KEYSYM.F7],
|
||||
};
|
||||
@@ -1,13 +1,38 @@
|
||||
/**
|
||||
* Settings System Tab - System information, temp file management, session logs, and global hotkey
|
||||
*/
|
||||
import { ChevronDown, ChevronRight, Download, ExternalLink, FolderOpen, RefreshCw, RotateCcw, Trash2 } from "lucide-react";
|
||||
import { Check, ChevronDown, ChevronRight, Download, ExternalLink, FolderOpen, RefreshCw, RotateCcw, Trash2 } from "lucide-react";
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
JumpServerIcon,
|
||||
RdpProtocolIcon,
|
||||
SystemRdpClientIcon,
|
||||
} from "../../icons/RemoteDesktopIcons";
|
||||
import { useI18n } from "../../../application/i18n/I18nProvider";
|
||||
import type { AppLockSystemUnlockStatus } from "../../../application/state/useAppLockState";
|
||||
import type { AppLockSettings, AppLockSettingsChangeError, AppLockTimeoutMinutes } from "../../../domain/appLock";
|
||||
import { getCredentialProtectionAvailability } from "../../../infrastructure/services/credentialProtection";
|
||||
import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge";
|
||||
import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter";
|
||||
import {
|
||||
STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB,
|
||||
STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS,
|
||||
} from "../../../infrastructure/config/storageKeys";
|
||||
import {
|
||||
DEFAULT_REMOTE_DESKTOP_AUTO_RECORD,
|
||||
DEFAULT_REMOTE_DESKTOP_RECORDING_FPS,
|
||||
DEFAULT_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO,
|
||||
DEFAULT_REMOTE_DESKTOP_RECORDING_MAX_MB,
|
||||
DEFAULT_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS,
|
||||
normalizeRemoteDesktopRecordingFps,
|
||||
normalizeRemoteDesktopRecordingMaxMb,
|
||||
normalizeRemoteDesktopRecordingRetentionDays,
|
||||
type RemoteDesktopRecordingFps,
|
||||
} from "../../../application/state/settingsStorageSync";
|
||||
import { VaultDeleteConfirmDialog } from "../../vault/VaultDeleteConfirmDialog";
|
||||
import type { UpdateState } from '../../../application/state/useUpdateCheck';
|
||||
import { SessionLogFormat, keyEventToString } from "../../../domain/models";
|
||||
import type { HttpNetworkProxyMode, HttpNetworkProxySettings } from "../../../domain/httpNetworkProxy";
|
||||
@@ -104,12 +129,24 @@ interface SettingsSystemTabProps {
|
||||
setSessionLogsFormat: (format: SessionLogFormat) => void;
|
||||
sessionLogsTimestampsEnabled: boolean;
|
||||
setSessionLogsTimestampsEnabled: (enabled: boolean) => void;
|
||||
remoteDesktopAutoRecord?: boolean;
|
||||
setRemoteDesktopAutoRecord?: (enabled: boolean) => void;
|
||||
remoteDesktopRecordingFps?: RemoteDesktopRecordingFps;
|
||||
setRemoteDesktopRecordingFps?: (fps: RemoteDesktopRecordingFps) => void;
|
||||
remoteDesktopRecordingIncludeAudio?: boolean;
|
||||
setRemoteDesktopRecordingIncludeAudio?: (enabled: boolean) => void;
|
||||
remoteDesktopRecordingMaxMb?: number;
|
||||
setRemoteDesktopRecordingMaxMb?: (maxMb: number) => void;
|
||||
remoteDesktopRecordingRetentionDays?: number;
|
||||
setRemoteDesktopRecordingRetentionDays?: (days: number) => void;
|
||||
sshDebugLogsEnabled: boolean;
|
||||
setSshDebugLogsEnabled: (enabled: boolean) => void;
|
||||
sshDeepLinkEnabled: boolean;
|
||||
setSshDeepLinkEnabled: (enabled: boolean) => void;
|
||||
jmsDeepLinkEnabled: boolean;
|
||||
setJmsDeepLinkEnabled: (enabled: boolean) => void;
|
||||
jumpServerRdpLaunchMode?: 'builtin' | 'system';
|
||||
setJumpServerRdpLaunchMode?: (mode: 'builtin' | 'system') => void;
|
||||
explorerContextMenuEnabled: boolean;
|
||||
setExplorerContextMenuEnabled: (enabled: boolean) => void;
|
||||
explorerContextMenuSupported: boolean;
|
||||
@@ -158,12 +195,24 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
|
||||
setSessionLogsFormat,
|
||||
sessionLogsTimestampsEnabled,
|
||||
setSessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord: remoteDesktopAutoRecordProp,
|
||||
setRemoteDesktopAutoRecord: setRemoteDesktopAutoRecordProp,
|
||||
remoteDesktopRecordingFps: remoteDesktopRecordingFpsProp,
|
||||
setRemoteDesktopRecordingFps: setRemoteDesktopRecordingFpsProp,
|
||||
remoteDesktopRecordingIncludeAudio: remoteDesktopRecordingIncludeAudioProp,
|
||||
setRemoteDesktopRecordingIncludeAudio: setRemoteDesktopRecordingIncludeAudioProp,
|
||||
remoteDesktopRecordingMaxMb: remoteDesktopRecordingMaxMbProp,
|
||||
setRemoteDesktopRecordingMaxMb: setRemoteDesktopRecordingMaxMbProp,
|
||||
remoteDesktopRecordingRetentionDays: remoteDesktopRecordingRetentionDaysProp,
|
||||
setRemoteDesktopRecordingRetentionDays: setRemoteDesktopRecordingRetentionDaysProp,
|
||||
sshDebugLogsEnabled,
|
||||
setSshDebugLogsEnabled,
|
||||
sshDeepLinkEnabled,
|
||||
setSshDeepLinkEnabled,
|
||||
jmsDeepLinkEnabled,
|
||||
setJmsDeepLinkEnabled,
|
||||
jumpServerRdpLaunchMode = 'builtin',
|
||||
setJumpServerRdpLaunchMode,
|
||||
explorerContextMenuEnabled,
|
||||
setExplorerContextMenuEnabled,
|
||||
explorerContextMenuSupported,
|
||||
@@ -220,6 +269,143 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
|
||||
const [isClearingSessionLogs, setIsClearingSessionLogs] = useState(false);
|
||||
const [sessionLogsClearResult, setSessionLogsClearResult] = useState<{ deletedCount: number; failedCount: number } | null>(null);
|
||||
|
||||
// Local fallback state for Remote Desktop Recordings settings so the card stays
|
||||
// functional whether or not the parent container passes these props explicitly.
|
||||
const [localRdAutoRecord, setLocalRdAutoRecord] = useState<boolean>(() => {
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD);
|
||||
return stored ?? DEFAULT_REMOTE_DESKTOP_AUTO_RECORD;
|
||||
});
|
||||
const [localRdFps, setLocalRdFps] = useState<RemoteDesktopRecordingFps>(() => {
|
||||
const stored = localStorageAdapter.readString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS);
|
||||
return stored === null
|
||||
? DEFAULT_REMOTE_DESKTOP_RECORDING_FPS
|
||||
: normalizeRemoteDesktopRecordingFps(stored);
|
||||
});
|
||||
const [localRdIncludeAudio, setLocalRdIncludeAudio] = useState<boolean>(() => {
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO);
|
||||
return stored ?? DEFAULT_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO;
|
||||
});
|
||||
const [localRdMaxMb, setLocalRdMaxMb] = useState<number>(() => {
|
||||
const stored = localStorageAdapter.readString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB);
|
||||
return stored === null
|
||||
? DEFAULT_REMOTE_DESKTOP_RECORDING_MAX_MB
|
||||
: normalizeRemoteDesktopRecordingMaxMb(stored);
|
||||
});
|
||||
const [localRdRetentionDays, setLocalRdRetentionDays] = useState<number>(() => {
|
||||
const stored = localStorageAdapter.readString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS);
|
||||
return stored === null
|
||||
? DEFAULT_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS
|
||||
: normalizeRemoteDesktopRecordingRetentionDays(stored);
|
||||
});
|
||||
|
||||
const remoteDesktopAutoRecord = remoteDesktopAutoRecordProp ?? localRdAutoRecord;
|
||||
const remoteDesktopRecordingFps = remoteDesktopRecordingFpsProp ?? localRdFps;
|
||||
const remoteDesktopRecordingIncludeAudio = remoteDesktopRecordingIncludeAudioProp ?? localRdIncludeAudio;
|
||||
const remoteDesktopRecordingMaxMb = remoteDesktopRecordingMaxMbProp ?? localRdMaxMb;
|
||||
const remoteDesktopRecordingRetentionDays = remoteDesktopRecordingRetentionDaysProp ?? localRdRetentionDays;
|
||||
|
||||
const handleSetRemoteDesktopAutoRecord = useCallback((enabled: boolean) => {
|
||||
if (setRemoteDesktopAutoRecordProp) {
|
||||
setRemoteDesktopAutoRecordProp(enabled);
|
||||
return;
|
||||
}
|
||||
setLocalRdAutoRecord(enabled);
|
||||
localStorageAdapter.writeBoolean(STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD, enabled);
|
||||
netcattyBridge.get()?.notifySettingsChanged?.({ key: STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD, value: enabled });
|
||||
}, [setRemoteDesktopAutoRecordProp]);
|
||||
|
||||
const handleSetRemoteDesktopRecordingFps = useCallback((fps: RemoteDesktopRecordingFps) => {
|
||||
const normalized = normalizeRemoteDesktopRecordingFps(fps);
|
||||
if (setRemoteDesktopRecordingFpsProp) {
|
||||
setRemoteDesktopRecordingFpsProp(normalized);
|
||||
return;
|
||||
}
|
||||
setLocalRdFps(normalized);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS, String(normalized));
|
||||
netcattyBridge.get()?.notifySettingsChanged?.({ key: STORAGE_KEY_REMOTE_DESKTOP_RECORDING_FPS, value: normalized });
|
||||
}, [setRemoteDesktopRecordingFpsProp]);
|
||||
|
||||
const handleSetRemoteDesktopRecordingIncludeAudio = useCallback((enabled: boolean) => {
|
||||
if (setRemoteDesktopRecordingIncludeAudioProp) {
|
||||
setRemoteDesktopRecordingIncludeAudioProp(enabled);
|
||||
return;
|
||||
}
|
||||
setLocalRdIncludeAudio(enabled);
|
||||
localStorageAdapter.writeBoolean(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO, enabled);
|
||||
netcattyBridge.get()?.notifySettingsChanged?.({ key: STORAGE_KEY_REMOTE_DESKTOP_RECORDING_INCLUDE_AUDIO, value: enabled });
|
||||
}, [setRemoteDesktopRecordingIncludeAudioProp]);
|
||||
|
||||
const handleSetRemoteDesktopRecordingMaxMb = useCallback((maxMb: number) => {
|
||||
const normalized = normalizeRemoteDesktopRecordingMaxMb(maxMb);
|
||||
if (setRemoteDesktopRecordingMaxMbProp) {
|
||||
setRemoteDesktopRecordingMaxMbProp(normalized);
|
||||
return;
|
||||
}
|
||||
setLocalRdMaxMb(normalized);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB, String(normalized));
|
||||
netcattyBridge.get()?.notifySettingsChanged?.({ key: STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB, value: normalized });
|
||||
}, [setRemoteDesktopRecordingMaxMbProp]);
|
||||
|
||||
const handleSetRemoteDesktopRecordingRetentionDays = useCallback((days: number) => {
|
||||
const normalized = normalizeRemoteDesktopRecordingRetentionDays(days);
|
||||
if (setRemoteDesktopRecordingRetentionDaysProp) {
|
||||
setRemoteDesktopRecordingRetentionDaysProp(normalized);
|
||||
return;
|
||||
}
|
||||
setLocalRdRetentionDays(normalized);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS, String(normalized));
|
||||
netcattyBridge.get()?.notifySettingsChanged?.({ key: STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS, value: normalized });
|
||||
}, [setRemoteDesktopRecordingRetentionDaysProp]);
|
||||
|
||||
const [recordingStats, setRecordingStats] = useState<{ count: number; totalBytes: number; dirPath: string } | null>(null);
|
||||
const [isLoadingRecordingStats, setIsLoadingRecordingStats] = useState(false);
|
||||
const [isClearingRecordings, setIsClearingRecordings] = useState(false);
|
||||
const [clearRecordingsConfirmOpen, setClearRecordingsConfirmOpen] = useState(false);
|
||||
const [recordingsClearDeletedCount, setRecordingsClearDeletedCount] = useState<number | null>(null);
|
||||
|
||||
const loadRecordingStats = useCallback(async () => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.remoteDesktopRecordings?.getStats) return;
|
||||
setIsLoadingRecordingStats(true);
|
||||
try {
|
||||
const stats = await bridge.remoteDesktopRecordings.getStats();
|
||||
setRecordingStats(stats);
|
||||
} catch (err) {
|
||||
console.error("[SettingsSystemTab] Failed to get recording stats:", err);
|
||||
} finally {
|
||||
setIsLoadingRecordingStats(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadRecordingStats();
|
||||
}, [loadRecordingStats]);
|
||||
|
||||
const handleOpenRecordingsFolder = useCallback(async () => {
|
||||
try {
|
||||
await netcattyBridge.get()?.remoteDesktopRecordings?.openFolder?.();
|
||||
} catch (err) {
|
||||
console.error("[SettingsSystemTab] Failed to open recordings folder:", err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleConfirmClearAllRecordings = useCallback(async () => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.remoteDesktopRecordings?.clearAll) return;
|
||||
setIsClearingRecordings(true);
|
||||
setRecordingsClearDeletedCount(null);
|
||||
try {
|
||||
const res = await bridge.remoteDesktopRecordings.clearAll({});
|
||||
setRecordingsClearDeletedCount(res?.deleted ?? 0);
|
||||
setClearRecordingsConfirmOpen(false);
|
||||
await loadRecordingStats();
|
||||
} catch (err) {
|
||||
console.error("[SettingsSystemTab] Failed to clear recordings:", err);
|
||||
} finally {
|
||||
setIsClearingRecordings(false);
|
||||
}
|
||||
}, [loadRecordingStats]);
|
||||
|
||||
const [appVersion, setAppVersion] = useState('');
|
||||
|
||||
// Load app version on mount
|
||||
@@ -1187,6 +1373,162 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
|
||||
{t("settings.sessionLogs.hint")}
|
||||
</SettingHint>
|
||||
|
||||
<SectionHeader title={t("settings.remoteDesktopRecordings.title")} />
|
||||
<SettingCard className="space-y-4 py-4">
|
||||
<SettingRow
|
||||
anchorId="system-remote-desktop-recordings-auto"
|
||||
label={t("settings.remoteDesktopRecordings.autoRecord")}
|
||||
description={t("settings.remoteDesktopRecordings.autoRecordDesc")}
|
||||
>
|
||||
<Toggle
|
||||
checked={remoteDesktopAutoRecord}
|
||||
onChange={handleSetRemoteDesktopAutoRecord}
|
||||
ariaLabel={t("settings.remoteDesktopRecordings.autoRecord")}
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="system-remote-desktop-recordings-fps"
|
||||
label={t("settings.remoteDesktopRecordings.fps")}
|
||||
description={t("settings.remoteDesktopRecordings.fpsDesc")}
|
||||
>
|
||||
<Select
|
||||
value={String(remoteDesktopRecordingFps)}
|
||||
options={[
|
||||
{ value: "5", label: t("settings.remoteDesktopRecordings.fpsOption", { fps: 5 }) },
|
||||
{ value: "10", label: t("settings.remoteDesktopRecordings.fpsOption", { fps: 10 }) },
|
||||
{ value: "15", label: t("settings.remoteDesktopRecordings.fpsOption", { fps: 15 }) },
|
||||
]}
|
||||
onChange={(val) => handleSetRemoteDesktopRecordingFps(Number(val) as RemoteDesktopRecordingFps)}
|
||||
className="w-36"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="system-remote-desktop-recordings-audio"
|
||||
label={t("settings.remoteDesktopRecordings.includeAudio")}
|
||||
description={t("settings.remoteDesktopRecordings.includeAudioDesc")}
|
||||
>
|
||||
<Toggle
|
||||
checked={remoteDesktopRecordingIncludeAudio}
|
||||
onChange={handleSetRemoteDesktopRecordingIncludeAudio}
|
||||
ariaLabel={t("settings.remoteDesktopRecordings.includeAudio")}
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="system-remote-desktop-recordings-max-mb"
|
||||
label={t("settings.remoteDesktopRecordings.maxStorage")}
|
||||
description={t("settings.remoteDesktopRecordings.maxStorageDesc")}
|
||||
>
|
||||
<Select
|
||||
value={String(remoteDesktopRecordingMaxMb)}
|
||||
options={[
|
||||
{ value: "256", label: "256 MB" },
|
||||
{ value: "512", label: "512 MB" },
|
||||
{ value: "1024", label: "1 GB" },
|
||||
{ value: "2048", label: "2 GB" },
|
||||
{ value: "5120", label: "5 GB" },
|
||||
]}
|
||||
onChange={(val) => handleSetRemoteDesktopRecordingMaxMb(Number(val))}
|
||||
className="w-36"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="system-remote-desktop-recordings-retention"
|
||||
label={t("settings.remoteDesktopRecordings.retentionDays")}
|
||||
description={t("settings.remoteDesktopRecordings.retentionDaysDesc")}
|
||||
>
|
||||
<Select
|
||||
value={String(remoteDesktopRecordingRetentionDays)}
|
||||
options={[
|
||||
{ value: "7", label: t("settings.remoteDesktopRecordings.retentionDaysOption", { days: 7 }) },
|
||||
{ value: "14", label: t("settings.remoteDesktopRecordings.retentionDaysOption", { days: 14 }) },
|
||||
{ value: "30", label: t("settings.remoteDesktopRecordings.retentionDaysOption", { days: 30 }) },
|
||||
{ value: "90", label: t("settings.remoteDesktopRecordings.retentionDaysOption", { days: 90 }) },
|
||||
{ value: "0", label: t("settings.remoteDesktopRecordings.retentionUnlimited") },
|
||||
]}
|
||||
onChange={(val) => handleSetRemoteDesktopRecordingRetentionDays(Number(val))}
|
||||
className="w-36"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<div className="space-y-2 pt-3 border-t border-border/60">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium">{t("settings.remoteDesktopRecordings.storageUsage")}</p>
|
||||
<p className="text-xs text-muted-foreground tabular-nums">
|
||||
{recordingStats
|
||||
? t("settings.remoteDesktopRecordings.storageUsageSummary", {
|
||||
count: recordingStats.count,
|
||||
size: formatBytes(recordingStats.totalBytes),
|
||||
})
|
||||
: t("settings.remoteDesktopRecordings.storageUsageLoading")}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2 shrink-0">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => void loadRecordingStats()}
|
||||
disabled={isLoadingRecordingStats}
|
||||
className="h-8 w-8"
|
||||
>
|
||||
<RefreshCw size={14} className={cn(isLoadingRecordingStats && "animate-spin")} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t("settings.remoteDesktopRecordings.refresh")}</TooltipContent>
|
||||
</Tooltip>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => void handleOpenRecordingsFolder()}
|
||||
className="gap-1.5"
|
||||
>
|
||||
<FolderOpen size={14} />
|
||||
{t("settings.remoteDesktopRecordings.openFolder")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setClearRecordingsConfirmOpen(true)}
|
||||
disabled={isClearingRecordings || (recordingStats?.count ?? 0) === 0}
|
||||
className="gap-1.5 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
{isClearingRecordings
|
||||
? t("settings.system.clearing")
|
||||
: t("settings.remoteDesktopRecordings.clearAll")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{recordingsClearDeletedCount !== null && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("settings.remoteDesktopRecordings.clearResult", { count: recordingsClearDeletedCount })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</SettingCard>
|
||||
|
||||
<SettingHint>
|
||||
{t("settings.remoteDesktopRecordings.hint")}
|
||||
</SettingHint>
|
||||
|
||||
<VaultDeleteConfirmDialog
|
||||
open={clearRecordingsConfirmOpen}
|
||||
title={t("settings.remoteDesktopRecordings.clearAllConfirmTitle")}
|
||||
description={t("settings.remoteDesktopRecordings.clearAllConfirmDesc", {
|
||||
count: recordingStats?.count ?? 0,
|
||||
})}
|
||||
confirmLabel={t("settings.remoteDesktopRecordings.clearAll")}
|
||||
disabled={isClearingRecordings}
|
||||
onOpenChange={setClearRecordingsConfirmOpen}
|
||||
onConfirm={() => void handleConfirmClearAllRecordings()}
|
||||
/>
|
||||
|
||||
<SectionHeader title={t('settings.sshDeepLink.title')} />
|
||||
<SettingCard>
|
||||
<SettingRow
|
||||
@@ -1203,9 +1545,14 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
|
||||
</SettingCard>
|
||||
|
||||
<SectionHeader title={t('settings.jmsDeepLink.title')} />
|
||||
<SettingCard>
|
||||
<SettingCard divided>
|
||||
<SettingRow
|
||||
anchorId="system-jms-deep-link"
|
||||
leading={
|
||||
<div className="flex h-9 w-9 items-center justify-center rounded-xl bg-emerald-500/12 text-emerald-600 dark:text-emerald-400 border border-emerald-500/20">
|
||||
<JumpServerIcon size={18} />
|
||||
</div>
|
||||
}
|
||||
label={t('settings.jmsDeepLink.enable')}
|
||||
description={t('settings.jmsDeepLink.enableDesc')}
|
||||
>
|
||||
@@ -1215,6 +1562,85 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
|
||||
ariaLabel={t('settings.jmsDeepLink.enable')}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingsAnchor anchorId="system-jms-rdp-launch-mode" className="py-3.5 space-y-3">
|
||||
<div>
|
||||
<div className="text-sm font-medium">{t('settings.jmsDeepLink.rdpLaunchMode')}</div>
|
||||
<div className="text-xs text-muted-foreground mt-0.5">
|
||||
{t('settings.jmsDeepLink.rdpLaunchModeDesc')}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
role="radiogroup"
|
||||
aria-label={t('settings.jmsDeepLink.rdpLaunchMode')}
|
||||
className="grid grid-cols-1 gap-2.5 sm:grid-cols-2"
|
||||
>
|
||||
{(
|
||||
[
|
||||
{
|
||||
value: 'builtin' as const,
|
||||
label: t('settings.jmsDeepLink.rdpLaunchMode.builtin'),
|
||||
hint: 'IronRDP tab inside Netcatty',
|
||||
icon: <RdpProtocolIcon size={18} />,
|
||||
activeTint: 'bg-blue-500 text-white shadow-sm',
|
||||
idleTint: 'bg-blue-500/12 text-blue-600 dark:text-blue-400',
|
||||
},
|
||||
{
|
||||
value: 'system' as const,
|
||||
label: t('settings.jmsDeepLink.rdpLaunchMode.system'),
|
||||
hint: isMac ? 'Windows App / Microsoft Remote Desktop' : 'mstsc.exe / OS default handler',
|
||||
icon: <SystemRdpClientIcon size={18} />,
|
||||
activeTint: 'bg-sky-500 text-white shadow-sm',
|
||||
idleTint: 'bg-sky-500/12 text-sky-600 dark:text-sky-400',
|
||||
},
|
||||
] as const
|
||||
).map((option) => {
|
||||
const selected = jumpServerRdpLaunchMode === option.value;
|
||||
return (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={selected}
|
||||
data-jms-rdp-mode={option.value}
|
||||
onClick={() => setJumpServerRdpLaunchMode?.(option.value)}
|
||||
className={cn(
|
||||
'group relative flex items-center gap-3 rounded-xl border p-3 text-left transition-all',
|
||||
selected
|
||||
? 'border-primary/70 bg-primary/8 ring-1 ring-primary/25 shadow-sm'
|
||||
: 'border-border/60 bg-background/60 hover:border-border hover:bg-secondary/50',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'flex h-9 w-9 shrink-0 items-center justify-center rounded-lg transition-colors',
|
||||
selected ? option.activeTint : option.idleTint,
|
||||
)}
|
||||
>
|
||||
{option.icon}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-medium text-foreground">
|
||||
{option.label}
|
||||
</span>
|
||||
<span className="block truncate text-[11px] text-muted-foreground">
|
||||
{option.hint}
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'flex h-4 w-4 shrink-0 items-center justify-center rounded-full border transition-colors',
|
||||
selected
|
||||
? 'border-primary bg-primary text-primary-foreground'
|
||||
: 'border-border/80 bg-transparent text-transparent',
|
||||
)}
|
||||
>
|
||||
<Check size={10} strokeWidth={3} />
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</SettingsAnchor>
|
||||
</SettingCard>
|
||||
|
||||
{explorerContextMenuSupported ? (
|
||||
|
||||
@@ -55,12 +55,35 @@ export interface TerminalConnectionDialogProps {
|
||||
onContinue: () => void;
|
||||
onAddAndContinue: () => void;
|
||||
};
|
||||
/** Optional protocol override when testing companion RDP/VNC on an SSH host. */
|
||||
protocolOverride?: 'ssh' | 'rdp' | 'vnc';
|
||||
/** Optional structured summary block shown when status === 'connected'. */
|
||||
summaryContent?: React.ReactNode;
|
||||
// Progress props
|
||||
progressProps: Omit<TerminalConnectionProgressProps, 'status' | 'error' | 'showLogs' | 'showEnterReconnectHint'>;
|
||||
}
|
||||
|
||||
// Helper to get protocol display info
|
||||
const getProtocolInfo = (host: Host): { i18nKey: string; showPort: boolean; port: number } => {
|
||||
const getProtocolInfo = (
|
||||
host: Host,
|
||||
protocolOverride?: 'ssh' | 'rdp' | 'vnc',
|
||||
): { i18nKey: string; fallbackLabel?: string; showPort: boolean; port: number } => {
|
||||
if (protocolOverride === 'rdp') {
|
||||
return {
|
||||
i18nKey: '',
|
||||
fallbackLabel: 'RDP',
|
||||
showPort: true,
|
||||
port: host.rdpConfig?.port || (host.protocol === 'rdp' ? host.port : undefined) || 3389,
|
||||
};
|
||||
}
|
||||
if (protocolOverride === 'vnc') {
|
||||
return {
|
||||
i18nKey: '',
|
||||
fallbackLabel: 'VNC',
|
||||
showPort: true,
|
||||
port: host.vncConfig?.port || (host.protocol === 'vnc' ? host.port : undefined) || 5900,
|
||||
};
|
||||
}
|
||||
// Check moshEnabled first since mosh uses protocol: "ssh" with moshEnabled: true
|
||||
if (host.moshEnabled) {
|
||||
return { i18nKey: 'terminal.connection.protocol.mosh', showPort: true, port: host.port || 22 };
|
||||
@@ -83,6 +106,10 @@ const getProtocolInfo = (host: Host): { i18nKey: string; showPort: boolean; port
|
||||
case 'telnet':
|
||||
// Telnet uses telnetPort, not port (which is SSH port)
|
||||
return { i18nKey: 'terminal.connection.protocol.telnet', showPort: true, port: resolveTelnetPort(host) };
|
||||
case 'rdp':
|
||||
return { i18nKey: '', fallbackLabel: 'RDP', showPort: true, port: host.rdpConfig?.port || host.port || 3389 };
|
||||
case 'vnc':
|
||||
return { i18nKey: '', fallbackLabel: 'VNC', showPort: true, port: host.vncConfig?.port || host.port || 5900 };
|
||||
case 'mosh':
|
||||
return { i18nKey: 'terminal.connection.protocol.mosh', showPort: true, port: host.port || 22 };
|
||||
case 'serial':
|
||||
@@ -110,6 +137,8 @@ export const TerminalConnectionDialog: React.FC<TerminalConnectionDialogProps> =
|
||||
showEnterReconnectHint,
|
||||
isFocusedPane,
|
||||
hostKeyVerification,
|
||||
protocolOverride,
|
||||
summaryContent,
|
||||
progressProps,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
@@ -118,7 +147,8 @@ export const TerminalConnectionDialog: React.FC<TerminalConnectionDialogProps> =
|
||||
const isRestoredDisconnected = status === 'disconnected' && restoreState === 'restored-disconnected';
|
||||
const isConnecting = status === 'connecting';
|
||||
const canDismissDisconnected = status === 'disconnected' && !needsAuth && !!onDismissDisconnected;
|
||||
const protocolInfo = getProtocolInfo(host);
|
||||
const protocolInfo = getProtocolInfo(host, protocolOverride);
|
||||
const protocolLabel = protocolInfo.i18nKey ? t(protocolInfo.i18nKey) : (protocolInfo.fallbackLabel ?? '');
|
||||
const isVerifyingHostKey = Boolean(hostKeyVerification);
|
||||
const isHostKeyChanged = hostKeyVerification?.hostKeyInfo.status === 'changed';
|
||||
const shouldCompleteProgress = hasError || (!isConnecting && !needsAuth);
|
||||
@@ -304,7 +334,7 @@ export const TerminalConnectionDialog: React.FC<TerminalConnectionDialogProps> =
|
||||
className="text-[10px] font-mono truncate"
|
||||
style={{ color: 'color-mix(in srgb, var(--terminal-ui-fg, var(--foreground)) 58%, transparent)' }}
|
||||
>
|
||||
{t(protocolInfo.i18nKey)} {protocolInfo.showPort ? formatHostPort(host.hostname, protocolInfo.port) : host.hostname}
|
||||
{protocolLabel} {protocolInfo.showPort ? formatHostPort(host.hostname, protocolInfo.port) : host.hostname}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
@@ -314,7 +344,7 @@ export const TerminalConnectionDialog: React.FC<TerminalConnectionDialogProps> =
|
||||
className="text-[10px] font-mono truncate"
|
||||
style={{ color: 'color-mix(in srgb, var(--terminal-ui-fg, var(--foreground)) 58%, transparent)' }}
|
||||
>
|
||||
{t(protocolInfo.i18nKey)} {protocolInfo.showPort ? formatHostPort(host.hostname, protocolInfo.port) : host.hostname}
|
||||
{protocolLabel} {protocolInfo.showPort ? formatHostPort(host.hostname, protocolInfo.port) : host.hostname}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
@@ -444,6 +474,7 @@ export const TerminalConnectionDialog: React.FC<TerminalConnectionDialogProps> =
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{status === 'connected' && summaryContent}
|
||||
<TerminalConnectionProgress
|
||||
status={status}
|
||||
error={error}
|
||||
|
||||
@@ -124,6 +124,8 @@ interface TerminalHostTreeSidebarProps {
|
||||
resolvedPreviewTheme: TerminalTheme;
|
||||
activeHostId?: string | null;
|
||||
onConnect: (host: Host) => void;
|
||||
onConnectRemoteDesktop?: (host: Host, protocol: 'vnc' | 'rdp') => void;
|
||||
onOpenSystemRemoteDesktop?: (host: Host, protocol: 'vnc' | 'rdp') => void;
|
||||
onNewHost?: (defaultGroup?: string) => void;
|
||||
onEditHost?: (host: Host) => void;
|
||||
onCreateLocalTerminal?: () => void;
|
||||
@@ -325,6 +327,8 @@ type HostTreeFlatRowProps = {
|
||||
isInlineEditing: boolean;
|
||||
inlineEditInitialName?: string;
|
||||
onConnect: (host: Host) => void;
|
||||
onConnectRemoteDesktop?: (host: Host, protocol: 'vnc' | 'rdp') => void;
|
||||
onOpenSystemRemoteDesktop?: (host: Host, protocol: 'vnc' | 'rdp') => void;
|
||||
onNewHost?: (defaultGroup?: string) => void;
|
||||
onEditHost?: (host: Host) => void;
|
||||
onTogglePath: (path: string) => void;
|
||||
@@ -347,6 +351,8 @@ const HostTreeFlatRowItem = memo<HostTreeFlatRowProps>(({
|
||||
isInlineEditing,
|
||||
inlineEditInitialName,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onOpenSystemRemoteDesktop,
|
||||
onNewHost,
|
||||
onEditHost,
|
||||
onTogglePath,
|
||||
@@ -480,6 +486,8 @@ const HostTreeFlatRowItem = memo<HostTreeFlatRowProps>(({
|
||||
<HostTreeHostContextMenuContent
|
||||
host={row.host}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
|
||||
onEditHost={onEditHost}
|
||||
onRenameHost={menuActions.onRenameHost}
|
||||
onDuplicateHost={menuActions.onDuplicateHost}
|
||||
@@ -648,6 +656,8 @@ const HostTreeFlatRowItem = memo<HostTreeFlatRowProps>(({
|
||||
if (prev.onDropToRow !== next.onDropToRow) return false;
|
||||
if (prev.onTogglePath !== next.onTogglePath) return false;
|
||||
if (prev.onConnect !== next.onConnect) return false;
|
||||
if (prev.onConnectRemoteDesktop !== next.onConnectRemoteDesktop) return false;
|
||||
if (prev.onOpenSystemRemoteDesktop !== next.onOpenSystemRemoteDesktop) return false;
|
||||
if (prev.activeHostId === next.activeHostId) return true;
|
||||
if (prev.row.kind === 'host') {
|
||||
return prev.row.host.id !== prev.activeHostId && prev.row.host.id !== next.activeHostId;
|
||||
@@ -668,6 +678,8 @@ const TerminalHostTreeSidebarInner: React.FC<TerminalHostTreeSidebarProps> = ({
|
||||
resolvedPreviewTheme,
|
||||
activeHostId,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onOpenSystemRemoteDesktop,
|
||||
onNewHost,
|
||||
onEditHost,
|
||||
onCreateLocalTerminal,
|
||||
@@ -941,6 +953,8 @@ const TerminalHostTreeSidebarInner: React.FC<TerminalHostTreeSidebarProps> = ({
|
||||
: undefined
|
||||
}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
|
||||
onNewHost={onNewHost}
|
||||
onEditHost={onEditHost}
|
||||
onTogglePath={togglePath}
|
||||
@@ -966,6 +980,8 @@ const TerminalHostTreeSidebarInner: React.FC<TerminalHostTreeSidebarProps> = ({
|
||||
isRowDragOver,
|
||||
menuActions,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onOpenSystemRemoteDesktop,
|
||||
onNewHost,
|
||||
onEditHost,
|
||||
treeExpandAll,
|
||||
|
||||
@@ -65,6 +65,7 @@ import { usePluginTerminalSidebar } from '../../application/state/usePluginTermi
|
||||
import { PluginTerminalSidebarPageHost } from '../plugins/PluginTerminalSidebar';
|
||||
import { PluginContributionIcon } from '../plugins/PluginContributionIcon';
|
||||
import { getPaneMagnificationShortcutLabel, resolveMagnifiedChromeBorderWidth } from '../../domain/paneMagnification';
|
||||
import { isRemoteDesktopProtocol } from '../../domain/remoteDesktop';
|
||||
|
||||
const MemoizedSidePanelMountedContent = memo(
|
||||
SidePanelMountedContent,
|
||||
@@ -674,17 +675,17 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
|
||||
magnifiedPane,
|
||||
} = ctx;
|
||||
|
||||
// Live theme for chrome when panel is open and not follow-app — stable memo
|
||||
// Live theme & focused session metadata when panel is open — stable memo
|
||||
// no longer receives focus-driven resolvedPreviewTheme via ctx.
|
||||
const subscribeLiveTheme = isSidePanelOpenForCurrentTab && !followAppTerminalTheme;
|
||||
const subscribeLivePanel = isSidePanelOpenForCurrentTab;
|
||||
const liveSnapshot = useSyncExternalStore(
|
||||
(listener) => subscribeSidePanelLiveSnapshot(subscribeLiveTheme, listener),
|
||||
() => getSidePanelLiveSnapshot(subscribeLiveTheme),
|
||||
() => getSidePanelLiveSnapshot(subscribeLiveTheme),
|
||||
(listener) => subscribeSidePanelLiveSnapshot(subscribeLivePanel, listener),
|
||||
() => getSidePanelLiveSnapshot(subscribeLivePanel),
|
||||
() => getSidePanelLiveSnapshot(subscribeLivePanel),
|
||||
);
|
||||
const resolvedPreviewTheme = followAppTerminalTheme
|
||||
? null
|
||||
: (subscribeLiveTheme
|
||||
: (subscribeLivePanel
|
||||
? (liveSnapshot.resolvedPreviewTheme ?? ctxResolvedPreviewTheme)
|
||||
: ctxResolvedPreviewTheme);
|
||||
|
||||
@@ -1079,19 +1080,33 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
|
||||
setDragOverSidePanelTab(null);
|
||||
}, [dragOverSidePanelTab]);
|
||||
|
||||
const sidePanelTabItems = useMemo<SidePanelTabItem[]>(() => [
|
||||
{ id: 'sftp' as const, label: t('terminal.layer.sftp'), icon: <FolderTree size={15} />, onClick: handleToggleSftpFromBar },
|
||||
{ id: 'browser' as const, label: t('terminal.browser.title'), icon: <Globe2 size={15} />, onClick: handleOpenBrowser },
|
||||
{ id: 'scripts' as const, label: t('terminal.layer.scripts'), icon: <Play size={15} />, onClick: handleOpenScripts },
|
||||
{ id: 'history' as const, label: t('terminal.layer.history'), icon: <History size={15} />, onClick: handleOpenHistory },
|
||||
{ id: 'theme' as const, label: t('terminal.layer.theme'), icon: <Palette size={15} />, onClick: handleOpenTheme },
|
||||
{ id: 'system' as const, label: t('terminal.layer.system'), icon: <Activity size={15} />, onClick: handleOpenSystem },
|
||||
{ id: 'notes' as const, label: t('terminal.layer.notes'), icon: <NotebookText size={15} />, onClick: handleOpenNotes },
|
||||
{ id: 'ai' as const, label: t('terminal.layer.aiChat'), icon: <MessageSquare size={15} />, onClick: handleOpenAI },
|
||||
...pluginSidebar.pages.map((page) => ({ id: page.tool, label: `${page.title} · ${page.pluginName}`,
|
||||
icon: <PluginContributionIcon pluginId={page.pluginId} icon={page.icon} size={15} />,
|
||||
onClick: () => handleSwitchSidePanelTab?.(page.tool) })),
|
||||
], [
|
||||
const focusedSession = useMemo(() => {
|
||||
const sessionsList = (ctx.sessions ?? []) as Array<{ id: string; protocol?: string; remoteDesktopCompanion?: boolean }>;
|
||||
const targetId = liveSnapshot.focusedSessionId ?? activeTabId;
|
||||
return sessionsList.find((session) => session.id === targetId) ?? null;
|
||||
}, [activeTabId, ctx.sessions, liveSnapshot.focusedSessionId]);
|
||||
const isFocusedRemoteDesktop = isRemoteDesktopProtocol(focusedSession?.protocol);
|
||||
const canUseSftpOnRemoteDesktop = Boolean(focusedSession?.remoteDesktopCompanion);
|
||||
|
||||
const sidePanelTabItems = useMemo<SidePanelTabItem[]>(() => {
|
||||
const allItems: SidePanelTabItem[] = [
|
||||
{ id: 'sftp' as const, label: t('terminal.layer.sftp'), icon: <FolderTree size={15} />, onClick: handleToggleSftpFromBar },
|
||||
{ id: 'browser' as const, label: t('terminal.browser.title'), icon: <Globe2 size={15} />, onClick: handleOpenBrowser },
|
||||
{ id: 'scripts' as const, label: t('terminal.layer.scripts'), icon: <Play size={15} />, onClick: handleOpenScripts },
|
||||
{ id: 'history' as const, label: t('terminal.layer.history'), icon: <History size={15} />, onClick: handleOpenHistory },
|
||||
{ id: 'theme' as const, label: t('terminal.layer.theme'), icon: <Palette size={15} />, onClick: handleOpenTheme },
|
||||
{ id: 'system' as const, label: t('terminal.layer.system'), icon: <Activity size={15} />, onClick: handleOpenSystem },
|
||||
{ id: 'notes' as const, label: t('terminal.layer.notes'), icon: <NotebookText size={15} />, onClick: handleOpenNotes },
|
||||
{ id: 'ai' as const, label: t('terminal.layer.aiChat'), icon: <MessageSquare size={15} />, onClick: handleOpenAI },
|
||||
...pluginSidebar.pages.map((page) => ({ id: page.tool, label: `${page.title} · ${page.pluginName}`,
|
||||
icon: <PluginContributionIcon pluginId={page.pluginId} icon={page.icon} size={15} />,
|
||||
onClick: () => handleSwitchSidePanelTab?.(page.tool) })),
|
||||
];
|
||||
if (!isFocusedRemoteDesktop) return allItems;
|
||||
// Exclude terminal-only side panels on VNC/RDP tabs; keep AI, Notes, and SSH companion SFTP.
|
||||
return allItems.filter((item) => item.id === 'ai' || item.id === 'notes' || (canUseSftpOnRemoteDesktop && item.id === 'sftp'));
|
||||
}, [
|
||||
canUseSftpOnRemoteDesktop,
|
||||
handleOpenAI,
|
||||
handleOpenHistory,
|
||||
handleOpenNotes,
|
||||
@@ -1100,6 +1115,7 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
|
||||
handleOpenSystem,
|
||||
handleOpenTheme,
|
||||
handleToggleSftpFromBar,
|
||||
isFocusedRemoteDesktop,
|
||||
t,
|
||||
handleSwitchSidePanelTab,
|
||||
pluginSidebar.pages,
|
||||
|
||||
@@ -27,6 +27,19 @@ import {
|
||||
resolveTerminalHibernateEnabled,
|
||||
resolveTerminalHibernateEnabledForProtocol,
|
||||
} from '../../domain/terminalHibernate';
|
||||
import {
|
||||
hasCompanionRdp,
|
||||
hasCompanionVnc,
|
||||
isRemoteDesktopProtocol,
|
||||
type RemoteDesktopProtocol,
|
||||
} from '../../domain/remoteDesktop';
|
||||
import {
|
||||
createRemoteDesktopUploadedFile,
|
||||
subscribeAddRemoteScreenToAI,
|
||||
type RemoteDesktopScreenshotDraftPayload,
|
||||
} from '../ai/remoteDesktopAiDraft';
|
||||
import { canOpenCompanionRemoteDesktopSftp } from '../remoteDesktop/remoteDesktopHelpers';
|
||||
import { RdpProtocolIcon, VncProtocolIcon } from '../icons/RemoteDesktopIcons';
|
||||
import { KeyBinding, TerminalSettings } from '../../domain/models';
|
||||
import type { TerminalCwdChangeMeta } from '../terminal/sftpCwd';
|
||||
import { STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION } from '../../infrastructure/config/storageKeys';
|
||||
@@ -65,6 +78,9 @@ export type SidePanelTab = SidePanelTool;
|
||||
const LazyAIChatSidePanel = lazy(() =>
|
||||
import('../AIChatSidePanel').then((module) => ({ default: module.AIChatSidePanel })),
|
||||
);
|
||||
const LazyRemoteDesktopPane = lazy(() =>
|
||||
import('../remoteDesktop/RemoteDesktopPane').then((module) => ({ default: module.RemoteDesktopPane })),
|
||||
);
|
||||
|
||||
if (typeof requestIdleCallback === 'function') {
|
||||
requestIdleCallback(() => {
|
||||
@@ -138,6 +154,62 @@ export type PendingTerminalSelectionForAI = {
|
||||
text: string;
|
||||
};
|
||||
|
||||
type RemoteDesktopAskAiHandler = (
|
||||
sessionId: string,
|
||||
payload: RemoteDesktopScreenshotDraftPayload | null,
|
||||
) => void;
|
||||
|
||||
const EMPTY_SIDE_PANEL_OPEN_TABS: ReadonlyMap<string, SidePanelTab> = new Map();
|
||||
let remoteDesktopSidePanelOpenTabs: ReadonlyMap<string, SidePanelTab> = EMPTY_SIDE_PANEL_OPEN_TABS;
|
||||
let remoteDesktopAskAiHandler: RemoteDesktopAskAiHandler | null = null;
|
||||
const remoteDesktopLayerBridgeListeners = new Set<() => void>();
|
||||
const pendingRemoteScreenDraftQueue: RemoteDesktopScreenshotDraftPayload[] = [];
|
||||
|
||||
export function publishRemoteDesktopLayerBridge(state: {
|
||||
sidePanelOpenTabs: ReadonlyMap<string, SidePanelTab>;
|
||||
onAddRemoteScreenToAI: RemoteDesktopAskAiHandler | null;
|
||||
}): void {
|
||||
const tabsChanged = remoteDesktopSidePanelOpenTabs !== state.sidePanelOpenTabs;
|
||||
const handlerChanged = remoteDesktopAskAiHandler !== state.onAddRemoteScreenToAI;
|
||||
if (!tabsChanged && !handlerChanged) return;
|
||||
remoteDesktopSidePanelOpenTabs = state.sidePanelOpenTabs;
|
||||
remoteDesktopAskAiHandler = state.onAddRemoteScreenToAI;
|
||||
for (const listener of remoteDesktopLayerBridgeListeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
export function enqueuePendingRemoteScreenForAI(
|
||||
payload: RemoteDesktopScreenshotDraftPayload,
|
||||
): void {
|
||||
pendingRemoteScreenDraftQueue.push(payload);
|
||||
if (pendingRemoteScreenDraftQueue.length > 8) {
|
||||
pendingRemoteScreenDraftQueue.shift();
|
||||
}
|
||||
}
|
||||
|
||||
function subscribeRemoteDesktopLayerBridge(listener: () => void): () => void {
|
||||
remoteDesktopLayerBridgeListeners.add(listener);
|
||||
return () => {
|
||||
remoteDesktopLayerBridgeListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
function getRemoteDesktopSftpOpenForTab(tabId: string): boolean {
|
||||
return remoteDesktopSidePanelOpenTabs.get(tabId) === 'sftp';
|
||||
}
|
||||
|
||||
function getHasRemoteDesktopAskAiHandler(): boolean {
|
||||
return remoteDesktopAskAiHandler !== null;
|
||||
}
|
||||
|
||||
function invokeRemoteDesktopAskAi(
|
||||
sessionId: string,
|
||||
payload: RemoteDesktopScreenshotDraftPayload | null,
|
||||
): void {
|
||||
remoteDesktopAskAiHandler?.(sessionId, payload);
|
||||
}
|
||||
|
||||
export {
|
||||
adjustLightnessToken,
|
||||
adjustSaturationToken,
|
||||
@@ -583,6 +655,54 @@ const AIChatPanelsHostInner: React.FC<AIChatPanelsHostProps> = ({
|
||||
updateDraft,
|
||||
]);
|
||||
|
||||
// P2-AI: Attach full-screen or region-snip remote desktop screenshots to the tab's AI draft.
|
||||
useEffect(() => {
|
||||
const attachRemoteScreen = (payload: RemoteDesktopScreenshotDraftPayload): boolean => {
|
||||
const targetTabId = payload.workspaceId || payload.sessionId;
|
||||
const context = contextsByTabId.get(targetTabId) ?? contextsByTabId.get(payload.sessionId);
|
||||
if (!context) return false;
|
||||
const scopeKey = `${context.scopeType}:${context.scopeTargetId ?? ''}`;
|
||||
const isSessionView =
|
||||
panelViewByScope[scopeKey]?.mode === 'session'
|
||||
|| activeSessionIdMap[scopeKey] != null;
|
||||
if (!isSessionView) {
|
||||
showDraftView(scopeKey);
|
||||
}
|
||||
const uploaded = createRemoteDesktopUploadedFile(payload);
|
||||
updateDraft(scopeKey, defaultAgentId, (draft) => ({
|
||||
...draft,
|
||||
attachments: [...draft.attachments, uploaded],
|
||||
}));
|
||||
return true;
|
||||
};
|
||||
|
||||
// Drain any screenshot queued right before the AI panel mounted on a fresh remote desktop tab.
|
||||
if (pendingRemoteScreenDraftQueue.length > 0) {
|
||||
const remaining: RemoteDesktopScreenshotDraftPayload[] = [];
|
||||
for (const queued of pendingRemoteScreenDraftQueue) {
|
||||
if (!attachRemoteScreen(queued)) {
|
||||
remaining.push(queued);
|
||||
}
|
||||
}
|
||||
pendingRemoteScreenDraftQueue.length = 0;
|
||||
pendingRemoteScreenDraftQueue.push(...remaining);
|
||||
}
|
||||
|
||||
return subscribeAddRemoteScreenToAI((payload) => {
|
||||
if (attachRemoteScreen(payload)) {
|
||||
const idx = pendingRemoteScreenDraftQueue.indexOf(payload);
|
||||
if (idx >= 0) pendingRemoteScreenDraftQueue.splice(idx, 1);
|
||||
}
|
||||
});
|
||||
}, [
|
||||
activeSessionIdMap,
|
||||
contextsByTabId,
|
||||
defaultAgentId,
|
||||
panelViewByScope,
|
||||
showDraftView,
|
||||
updateDraft,
|
||||
]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{mountedTabIds.map((tabId) => {
|
||||
@@ -759,6 +879,12 @@ export interface TerminalLayerProps {
|
||||
) => void;
|
||||
onSplitSession?: (sessionId: string, direction: SplitDirection) => void;
|
||||
onConnectToHost: (host: Host) => string | void;
|
||||
onConnectRemoteDesktop?: (
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
options?: { splitFromSessionId?: string },
|
||||
) => string | null | void;
|
||||
onOpenSystemRemoteDesktop?: (host: Host, protocol: RemoteDesktopProtocol) => void;
|
||||
onCreateLocalTerminal?: () => void;
|
||||
// Broadcast mode
|
||||
isBroadcastEnabled?: (workspaceId: string) => boolean;
|
||||
@@ -870,6 +996,12 @@ interface TerminalPaneProps {
|
||||
onCommandSubmitted?: (command: string, hostId: string, hostLabel: string, sessionId: string) => void;
|
||||
onSetWorkspaceFocusedSession?: (workspaceId: string, sessionId: string) => void;
|
||||
onSplitSession?: (sessionId: string, direction: SplitDirection) => void;
|
||||
onConnectRemoteDesktop?: (
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
options?: { splitFromSessionId?: string },
|
||||
) => string | null | void;
|
||||
onCopySessionToNewWindow?: (sessionId: string) => void;
|
||||
isBroadcastEnabled?: (workspaceId: string) => boolean;
|
||||
isComposeSendToAll?: (workspaceId: string) => boolean;
|
||||
isGlobalBroadcastEnabled?: boolean;
|
||||
@@ -924,8 +1056,11 @@ const getPaneRenderedWorkspaceRect = (props: Pick<TerminalPaneProps, 'session' |
|
||||
if (!workspaceId) return null;
|
||||
const workspace = props.workspaceById.get(workspaceId);
|
||||
if (!workspace) return null;
|
||||
if (resolveTerminalHibernateEnabledForProtocol(props.terminalSettings, props.host.protocol)
|
||||
&& activeTabStore.getActiveTabId() !== workspaceId) {
|
||||
if (
|
||||
!isRemoteDesktopProtocol(props.session.protocol)
|
||||
&& resolveTerminalHibernateEnabledForProtocol(props.terminalSettings, props.host.protocol)
|
||||
&& activeTabStore.getActiveTabId() !== workspaceId
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (workspace.viewMode === 'focus' && workspace.focusedSessionId === props.session.id) {
|
||||
@@ -1002,6 +1137,8 @@ const terminalPanePropsAreEqual = (
|
||||
prev.onCommandSubmitted === next.onCommandSubmitted &&
|
||||
prev.onSetWorkspaceFocusedSession === next.onSetWorkspaceFocusedSession &&
|
||||
prev.onSplitSession === next.onSplitSession &&
|
||||
prev.onConnectRemoteDesktop === next.onConnectRemoteDesktop &&
|
||||
prev.onCopySessionToNewWindow === next.onCopySessionToNewWindow &&
|
||||
prev.isBroadcastEnabled === next.isBroadcastEnabled &&
|
||||
prev.isComposeSendToAll === next.isComposeSendToAll &&
|
||||
prev.isGlobalBroadcastEnabled === next.isGlobalBroadcastEnabled &&
|
||||
@@ -1295,6 +1432,8 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
onCommandSubmitted,
|
||||
onSetWorkspaceFocusedSession,
|
||||
onSplitSession,
|
||||
onConnectRemoteDesktop,
|
||||
onCopySessionToNewWindow,
|
||||
isBroadcastEnabled,
|
||||
isComposeSendToAll,
|
||||
isGlobalBroadcastEnabled,
|
||||
@@ -1352,10 +1491,12 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
setPaneVisible(session.id, isVisible);
|
||||
}, [session.id, isVisible]);
|
||||
useEffect(() => () => removePaneVisible(session.id), [session.id]);
|
||||
const isRemoteDesktop = isRemoteDesktopProtocol(session.protocol);
|
||||
const inActiveWorkspace = !!activeWorkspaceId;
|
||||
const isFocusMode = paneState.mode === 'focus';
|
||||
const isSplitViewVisible = paneState.mode === 'split';
|
||||
const hibernateHiddenTabs = resolveTerminalHibernateEnabledForProtocol(terminalSettings, host.protocol);
|
||||
const hibernateHiddenTabs = !isRemoteDesktop
|
||||
&& resolveTerminalHibernateEnabledForProtocol(terminalSettings, host.protocol);
|
||||
const layoutWorkspaceId = activeWorkspaceId ?? (!hibernateHiddenTabs ? session.workspaceId : undefined);
|
||||
const layoutWorkspace = layoutWorkspaceId ? workspaceById.get(layoutWorkspaceId) : undefined;
|
||||
const keepsWorkspacePresentation = !!layoutWorkspace;
|
||||
@@ -1632,6 +1773,43 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
onTerminalFontSizeChange?.(session.id, nextFontSize);
|
||||
}, [onTerminalFontSizeChange, session.id]);
|
||||
|
||||
const companionVnc = !isRemoteDesktop && hasCompanionVnc(host);
|
||||
const companionRdp = !isRemoteDesktop && hasCompanionRdp(host);
|
||||
const showCompanionQuickActions = Boolean(
|
||||
onConnectRemoteDesktop && (companionVnc || companionRdp) && isVisible && session.status === 'connected',
|
||||
);
|
||||
const remoteDesktopTabId = activeWorkspaceId ?? session.id;
|
||||
const subscribeRemoteDesktopBridge = useCallback(
|
||||
(listener: () => void) => (isRemoteDesktop ? subscribeRemoteDesktopLayerBridge(listener) : () => {}),
|
||||
[isRemoteDesktop],
|
||||
);
|
||||
const isRemoteDesktopSftpOpen = useSyncExternalStore(
|
||||
subscribeRemoteDesktopBridge,
|
||||
() => (isRemoteDesktop ? getRemoteDesktopSftpOpenForTab(remoteDesktopTabId) : false),
|
||||
() => false,
|
||||
);
|
||||
const hasRemoteDesktopAskAi = useSyncExternalStore(
|
||||
subscribeRemoteDesktopBridge,
|
||||
() => (isRemoteDesktop ? getHasRemoteDesktopAskAiHandler() : false),
|
||||
() => false,
|
||||
);
|
||||
const canOpenCompanionSftp = isRemoteDesktop && canOpenCompanionRemoteDesktopSftp(session, host);
|
||||
const handleOpenCompanionSftp = useCallback(() => {
|
||||
onOpenSftp(host, undefined, undefined, session.id);
|
||||
}, [host, onOpenSftp, session.id]);
|
||||
const handleRemoteDesktopAskAi = useCallback(
|
||||
(payload: RemoteDesktopScreenshotDraftPayload | null) => {
|
||||
invokeRemoteDesktopAskAi(session.id, payload);
|
||||
},
|
||||
[session.id],
|
||||
);
|
||||
const handleRemoteDesktopStatusChange = useCallback(
|
||||
(sid: string, nextStatus: 'connecting' | 'connected' | 'disconnected') => {
|
||||
onStatusChange(sid, nextStatus);
|
||||
},
|
||||
[onStatusChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={paneElementRef}
|
||||
@@ -1656,7 +1834,70 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
onClick={handlePaneClick}
|
||||
onFocusCapture={handlePaneClick}
|
||||
>
|
||||
<Terminal
|
||||
{isRemoteDesktop && isRemoteDesktopProtocol(session.protocol) ? (
|
||||
<LazyLoadBoundary name="Remote desktop" resetKey={session.id}>
|
||||
<Suspense fallback={<div className="h-full w-full bg-black" aria-hidden="true" />}>
|
||||
<LazyRemoteDesktopPane
|
||||
sessionId={session.id}
|
||||
workspaceId={session.workspaceId}
|
||||
protocol={session.protocol}
|
||||
host={host}
|
||||
chainHosts={chainHosts}
|
||||
keys={keys}
|
||||
identities={identities}
|
||||
knownHosts={knownHosts}
|
||||
isVisible={isVisible}
|
||||
isFocused={isFocusedPane}
|
||||
inWorkspace={keepsWorkspacePresentation}
|
||||
onStatusChange={handleRemoteDesktopStatusChange}
|
||||
onCloseSession={onCloseSession}
|
||||
onPopOut={onCopySessionToNewWindow}
|
||||
onOpenSftp={canOpenCompanionSftp ? handleOpenCompanionSftp : undefined}
|
||||
isSftpOpen={canOpenCompanionSftp ? isRemoteDesktopSftpOpen : false}
|
||||
onAskAi={hasRemoteDesktopAskAi ? handleRemoteDesktopAskAi : undefined}
|
||||
onTerminalDataCapture={onTerminalDataCapture}
|
||||
/>
|
||||
</Suspense>
|
||||
</LazyLoadBoundary>
|
||||
) : (
|
||||
<>
|
||||
{showCompanionQuickActions && (
|
||||
<div
|
||||
className="pointer-events-auto absolute right-2 top-1.5 z-20 flex items-center gap-1 opacity-45 transition-opacity hover:opacity-100"
|
||||
data-section="ssh-companion-desktop-actions"
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
{companionRdp && (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex h-6 items-center gap-1 rounded-md border border-blue-500/30 bg-background/90 px-1.5 text-[10px] font-semibold text-foreground shadow-sm backdrop-blur-sm transition-colors hover:bg-blue-500/15 hover:border-blue-500/50"
|
||||
title="Open RDP in split pane"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onConnectRemoteDesktop?.(host, 'rdp', { splitFromSessionId: session.id });
|
||||
}}
|
||||
>
|
||||
<RdpProtocolIcon size={12} className="text-blue-500" />
|
||||
<span>RDP</span>
|
||||
</button>
|
||||
)}
|
||||
{companionVnc && (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex h-6 items-center gap-1 rounded-md border border-teal-500/30 bg-background/90 px-1.5 text-[10px] font-semibold text-foreground shadow-sm backdrop-blur-sm transition-colors hover:bg-teal-500/15 hover:border-teal-500/50"
|
||||
title="Open VNC in split pane"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onConnectRemoteDesktop?.(host, 'vnc', { splitFromSessionId: session.id });
|
||||
}}
|
||||
>
|
||||
<VncProtocolIcon size={12} className="text-teal-500" />
|
||||
<span>VNC</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<Terminal
|
||||
host={host}
|
||||
keys={keys}
|
||||
identities={identities}
|
||||
@@ -1749,6 +1990,8 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
onDetachDragStart={inActiveWorkspace ? handleDetachDragStart : undefined}
|
||||
onDetachDragEnd={inActiveWorkspace ? handleDetachDragEnd : undefined}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}, terminalPanePropsAreEqual);
|
||||
@@ -1818,6 +2061,12 @@ interface TerminalPanesHostProps {
|
||||
onCommandSubmitted?: (command: string, hostId: string, hostLabel: string, sessionId: string) => void;
|
||||
onSetWorkspaceFocusedSession?: (workspaceId: string, sessionId: string) => void;
|
||||
onSplitSession?: (sessionId: string, direction: SplitDirection) => void;
|
||||
onConnectRemoteDesktop?: (
|
||||
host: Host,
|
||||
protocol: RemoteDesktopProtocol,
|
||||
options?: { splitFromSessionId?: string },
|
||||
) => string | null | void;
|
||||
onCopySessionToNewWindow?: (sessionId: string) => void;
|
||||
isBroadcastEnabled?: (workspaceId: string) => boolean;
|
||||
isComposeSendToAll?: (workspaceId: string) => boolean;
|
||||
isGlobalBroadcastEnabled?: boolean;
|
||||
@@ -1912,6 +2161,8 @@ const terminalPanesHostPropsAreEqual = (
|
||||
if (prev.onCommandSubmitted !== next.onCommandSubmitted) return false;
|
||||
if (prev.onSetWorkspaceFocusedSession !== next.onSetWorkspaceFocusedSession) return false;
|
||||
if (prev.onSplitSession !== next.onSplitSession) return false;
|
||||
if (prev.onConnectRemoteDesktop !== next.onConnectRemoteDesktop) return false;
|
||||
if (prev.onCopySessionToNewWindow !== next.onCopySessionToNewWindow) return false;
|
||||
if (prev.isBroadcastEnabled !== next.isBroadcastEnabled) return false;
|
||||
if (prev.isComposeSendToAll !== next.isComposeSendToAll) return false;
|
||||
if (prev.isGlobalBroadcastEnabled !== next.isGlobalBroadcastEnabled) return false;
|
||||
@@ -1945,10 +2196,12 @@ const terminalPanesHostPropsAreEqual = (
|
||||
const activeWorkspace = activeTabId ? next.workspaceById.get(activeTabId) : undefined;
|
||||
|
||||
return prev.sessions.every((session) => {
|
||||
const isLocalTerminal = next.sessionHostsMap.get(session.id)?.protocol === 'local';
|
||||
const isLocalOrRemoteDesktop =
|
||||
next.sessionHostsMap.get(session.id)?.protocol === 'local'
|
||||
|| isRemoteDesktopProtocol(session.protocol);
|
||||
const isInVisibleSplitWorkspace = activeWorkspace?.viewMode !== 'focus'
|
||||
&& session.workspaceId === activeWorkspace?.id;
|
||||
if (!isLocalTerminal && !isInVisibleSplitWorkspace) return true;
|
||||
if (!isLocalOrRemoteDesktop && !isInVisibleSplitWorkspace) return true;
|
||||
return workspaceRectsEqual(
|
||||
getPaneWorkspaceRect({ session, workspaceRectsById: prev.workspaceRectsById }),
|
||||
getPaneWorkspaceRect({ session, workspaceRectsById: next.workspaceRectsById }),
|
||||
|
||||
Loaded 100 of 232 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user