Compare commits

...
37 changed files with 3981 additions and 436 deletions

No files matched your search

+12
View File
@@ -1319,6 +1319,7 @@ export const enVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': 'Record session',
'remoteDesktop.toolbar.stopRecording': 'Stop recording',
'remoteDesktop.toolbar.savingRecording': 'Saving...',
'remoteDesktop.toolbar.recording': 'Recording',
'remoteDesktop.toolbar.askAi': 'Ask AI',
'remoteDesktop.toolbar.askAiFull': 'Capture Screen & Ask AI',
@@ -1424,7 +1425,18 @@ export const enVaultMessages: Messages = {
'logView.remoteDesktop.started': 'Started',
'logView.remoteDesktop.ended': 'Ended',
'logView.remoteDesktop.duration': 'Duration',
'logView.remoteDesktop.resolution': 'Resolution',
'logView.remoteDesktop.security': 'Security',
'logView.remoteDesktop.disconnectReason': 'Disconnect reason',
'logView.remoteDesktop.timeline': 'Session Timeline',
'logView.remoteDesktop.recordingTip': 'Click Record in the remote desktop toolbar or enable Auto-record in Settings -> System to save .webm replays here.',
'logs.recording.clipsCount': '{count} clips',
'logs.filter.all': 'All',
'logs.filter.terminal': 'Terminal',
'logs.filter.remoteDesktop': 'Remote Desktop',
'logs.filter.recorded': 'Recorded',
'logs.filter.emptyTitle': 'No matching logs',
'logs.filter.emptyDesc': 'No connection logs match the selected filter yet.',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': 'Remote Desktop Recordings',
+12
View File
@@ -1378,6 +1378,7 @@ export const esVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': 'Grabar sesión',
'remoteDesktop.toolbar.stopRecording': 'Detener grabación',
'remoteDesktop.toolbar.savingRecording': 'Guardando...',
'remoteDesktop.toolbar.recording': 'Grabando',
'remoteDesktop.toolbar.askAi': 'Preguntar a la IA',
'remoteDesktop.toolbar.askAiFull': 'Capturar pantalla y preguntar a la IA',
@@ -1424,7 +1425,18 @@ export const esVaultMessages: Messages = {
'logView.remoteDesktop.started': 'Inicio',
'logView.remoteDesktop.ended': 'Fin',
'logView.remoteDesktop.duration': 'Duración',
'logView.remoteDesktop.resolution': 'Resolución',
'logView.remoteDesktop.security': 'Seguridad',
'logView.remoteDesktop.disconnectReason': 'Motivo de desconexión',
'logView.remoteDesktop.timeline': 'Cronología de sesió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í.',
'logs.recording.clipsCount': '{count} clips',
'logs.filter.all': 'Todos',
'logs.filter.terminal': 'Terminal',
'logs.filter.remoteDesktop': 'Escritorio remoto',
'logs.filter.recorded': 'Con grabación',
'logs.filter.emptyTitle': 'Sin registros coincidentes',
'logs.filter.emptyDesc': 'Todavía no hay registros de conexión que coincidan con este filtro.',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': 'Grabaciones de escritorio remoto',
+12
View File
@@ -1394,6 +1394,7 @@ export const ruVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': 'Записать сессию',
'remoteDesktop.toolbar.stopRecording': 'Остановить запись',
'remoteDesktop.toolbar.savingRecording': 'Сохранение...',
'remoteDesktop.toolbar.recording': 'Запись',
'remoteDesktop.toolbar.askAi': 'Спросить ИИ',
'remoteDesktop.toolbar.askAiFull': 'Снять экран и спросить ИИ',
@@ -1440,7 +1441,18 @@ export const ruVaultMessages: Messages = {
'logView.remoteDesktop.started': 'Начало',
'logView.remoteDesktop.ended': 'Окончание',
'logView.remoteDesktop.duration': 'Длительность',
'logView.remoteDesktop.resolution': 'Разрешение',
'logView.remoteDesktop.security': 'Безопасность',
'logView.remoteDesktop.disconnectReason': 'Причина отключения',
'logView.remoteDesktop.timeline': 'Хронология сессии',
'logView.remoteDesktop.recordingTip': 'Нажмите «Записать сессию» на панели удалённого рабочего стола или включите автозапись в Настройки → Система, чтобы сохранять повторы .webm.',
'logs.recording.clipsCount': 'Клипов: {count}',
'logs.filter.all': 'Все',
'logs.filter.terminal': 'Терминал',
'logs.filter.remoteDesktop': 'Удалённый рабочий стол',
'logs.filter.recorded': 'С записью',
'logs.filter.emptyTitle': 'Нет подходящих журналов',
'logs.filter.emptyDesc': 'Для выбранного фильтра пока нет записей подключений.',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': 'Записи удалённого рабочего стола',
+12
View File
@@ -1283,6 +1283,7 @@ export const zhCNVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': '录制会话',
'remoteDesktop.toolbar.stopRecording': '停止录制',
'remoteDesktop.toolbar.savingRecording': '保存中...',
'remoteDesktop.toolbar.recording': '录制中',
'remoteDesktop.toolbar.askAi': '问 AI',
'remoteDesktop.toolbar.askAiFull': '截全屏问 AI',
@@ -1388,7 +1389,18 @@ export const zhCNVaultMessages: Messages = {
'logView.remoteDesktop.started': '开始时间',
'logView.remoteDesktop.ended': '结束时间',
'logView.remoteDesktop.duration': '持续时长',
'logView.remoteDesktop.resolution': '分辨率',
'logView.remoteDesktop.security': '安全协议',
'logView.remoteDesktop.disconnectReason': '断开原因',
'logView.remoteDesktop.timeline': '会话时间轴',
'logView.remoteDesktop.recordingTip': '点击远程桌面工具栏的录制按钮,或在「设置 → 系统」中开启自动录制,即可在此回放 .webm 录屏。',
'logs.recording.clipsCount': '{count} 段',
'logs.filter.all': '全部',
'logs.filter.terminal': '终端',
'logs.filter.remoteDesktop': '远程桌面',
'logs.filter.recorded': '有录屏',
'logs.filter.emptyTitle': '没有匹配的日志',
'logs.filter.emptyDesc': '当前筛选条件下暂无连接日志记录。',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': '远程桌面录屏',
+12
View File
@@ -1218,6 +1218,7 @@ export const zhTWVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': '錄製工作階段',
'remoteDesktop.toolbar.stopRecording': '停止錄製',
'remoteDesktop.toolbar.savingRecording': '儲存中...',
'remoteDesktop.toolbar.recording': '錄製中',
'remoteDesktop.toolbar.askAi': '詢問 AI',
'remoteDesktop.toolbar.askAiFull': '擷取全螢幕詢問 AI',
@@ -1388,7 +1389,18 @@ export const zhTWVaultMessages: Messages = {
'logView.remoteDesktop.started': '開始時間',
'logView.remoteDesktop.ended': '結束時間',
'logView.remoteDesktop.duration': '持續時間',
'logView.remoteDesktop.resolution': '解析度',
'logView.remoteDesktop.security': '安全協定',
'logView.remoteDesktop.disconnectReason': '斷線原因',
'logView.remoteDesktop.timeline': '工作階段時間軸',
'logView.remoteDesktop.recordingTip': '點擊遠端桌面工具列的錄製按鈕,或在「設定 → 系統」中開啟自動錄製,即可在此重播 .webm 錄影。',
'logs.recording.clipsCount': '{count} 段',
'logs.filter.all': '全部',
'logs.filter.terminal': '終端機',
'logs.filter.remoteDesktop': '遠端桌面',
'logs.filter.recorded': '含錄影',
'logs.filter.emptyTitle': '沒有符合的日誌',
'logs.filter.emptyDesc': '目前篩選條件下尚無連線日誌記錄。',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': '遠端桌面錄影',
+1 -1
View File
@@ -9,7 +9,7 @@ export type ConnectionLogsSnapshot = {
};
export type ConnectionLogsActions = {
updateConnectionLog: (id: string, updates: Partial<ConnectionLog>) => void;
updateConnectionLog: (id: string, updates: Partial<ConnectionLog>) => void | Promise<unknown>;
toggleConnectionLogSaved: (id: string) => void;
deleteConnectionLog: (id: string) => void;
clearUnsavedConnectionLogs: () => void;
@@ -0,0 +1,215 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
import type { ConnectionLog } from '../../domain/models';
import { STORAGE_KEY_CONNECTION_LOGS } from '../../infrastructure/config/storageKeys';
import {
publishConnectionLogsSnapshot,
registerConnectionLogsActions,
} from './connectionLogsStore';
import {
clearAllRemoteDesktopRecordingsAndSyncLogs,
collectProtectedRemoteDesktopMediaIds,
} from './remoteDesktopLogActions';
import { withVaultImportLock } from './vaultManagedImportLock';
function installDomEnv() {
const dom = new JSDOM('', { url: 'http://localhost' });
const heldLocks = new Set<string>();
const fakeLocks = {
request: async <T>(name: string, cb: () => Promise<T>): Promise<T> => {
if (heldLocks.has(name)) {
throw new Error(`DEADLOCK: re-entrant lock acquisition on ${name}`);
}
heldLocks.add(name);
try {
return await cb();
} finally {
heldLocks.delete(name);
}
},
};
const keys = ['window', 'document', 'localStorage', 'navigator'] 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 },
navigator: { value: { locks: fakeLocks }, configurable: true },
});
return {
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);
}
},
};
}
test('clearAllRemoteDesktopRecordingsAndSyncLogs protects saved logs and clears unsaved metadata even in detached Settings window', async () => {
const env = installDomEnv();
const savedClipId = '11111111-1111-4111-8111-111111111111';
const unsavedClipId = '22222222-2222-4222-8222-222222222222';
const unsavedThumbId = '33333333-3333-4333-8333-333333333333';
const persistedLogs: ConnectionLog[] = [
{
id: 'log-saved',
hostId: 'h1',
hostLabel: 'Saved RDP',
hostname: '10.0.0.1',
username: 'admin',
protocol: 'rdp',
startTime: 1000,
endTime: 2000,
localUsername: 'u',
localHostname: 'l',
saved: true,
recordingId: savedClipId,
recordings: [
{
id: savedClipId,
startedAt: 1000,
endedAt: 2000,
durationMs: 1000,
bytes: 500,
mimeType: 'video/webm',
hasAudio: false,
},
],
},
{
id: 'log-unsaved',
hostId: 'h2',
hostLabel: 'Unsaved RDP',
hostname: '10.0.0.2',
username: 'admin',
protocol: 'rdp',
startTime: 3000,
endTime: 4000,
localUsername: 'u',
localHostname: 'l',
saved: false,
recordingId: unsavedClipId,
recordings: [
{
id: unsavedClipId,
startedAt: 3000,
endedAt: 4000,
durationMs: 1000,
bytes: 600,
mimeType: 'video/webm',
hasAudio: false,
},
],
remoteDesktopMeta: {
resolution: { width: 1920, height: 1080 },
thumbnailId: unsavedThumbId,
},
},
];
globalThis.localStorage.setItem(STORAGE_KEY_CONNECTION_LOGS, JSON.stringify(persistedLogs));
// Simulate detached Settings window: connectionLogsStore is unmounted/empty.
publishConnectionLogsSnapshot({ connectionLogs: [] });
registerConnectionLogsActions(null);
const clearAllCalls: Array<{ protectedIds?: string[] }> = [];
(globalThis.window as unknown as Record<string, unknown>).netcatty = {
remoteDesktopRecordings: {
clearAll: async (opts: { protectedIds?: string[] }) => {
clearAllCalls.push(opts);
return { deleted: 1 };
},
},
};
try {
assert.deepEqual(collectProtectedRemoteDesktopMediaIds(), [savedClipId]);
const res = await clearAllRemoteDesktopRecordingsAndSyncLogs();
assert.equal(res.deleted, 1);
assert.equal(clearAllCalls.length, 1);
assert.deepEqual(clearAllCalls[0].protectedIds, [savedClipId]);
const after = JSON.parse(
globalThis.localStorage.getItem(STORAGE_KEY_CONNECTION_LOGS) || '[]',
) as ConnectionLog[];
assert.equal(after.length, 2);
assert.equal(after[0].recordingId, savedClipId);
assert.equal(after[0].recordings?.length, 1);
assert.equal(after[1].recordingId, undefined);
assert.equal(after[1].recordings, undefined);
assert.equal(after[1].remoteDesktopMeta?.thumbnailId, undefined);
assert.deepEqual(after[1].remoteDesktopMeta?.resolution, { width: 1920, height: 1080 });
} finally {
registerConnectionLogsActions(null);
publishConnectionLogsSnapshot({ connectionLogs: [] });
env.restore();
}
});
test('clearAllRemoteDesktopRecordingsAndSyncLogs does not deadlock when updateConnectionLog acquires connection-logs lock', async () => {
const env = installDomEnv();
const unsavedClipId = '44444444-4444-4444-8444-444444444444';
const liveLog: ConnectionLog = {
id: 'log-live-unsaved',
hostId: 'h3',
hostLabel: 'Live RDP',
hostname: '10.0.0.3',
username: 'admin',
protocol: 'rdp',
startTime: 5000,
endTime: 6000,
localUsername: 'u',
localHostname: 'l',
saved: false,
recordingId: unsavedClipId,
recordings: [
{
id: unsavedClipId,
startedAt: 5000,
endedAt: 6000,
durationMs: 1000,
bytes: 700,
mimeType: 'video/webm',
hasAudio: false,
},
],
};
let updatedCount = 0;
publishConnectionLogsSnapshot({ connectionLogs: [liveLog] });
registerConnectionLogsActions({
updateConnectionLog: async () => {
await withVaultImportLock('connection-logs', async () => {
updatedCount += 1;
});
},
toggleConnectionLogSaved: () => {},
deleteConnectionLog: () => {},
clearUnsavedConnectionLogs: () => {},
});
(globalThis.window as unknown as Record<string, unknown>).netcatty = {
remoteDesktopRecordings: {
clearAll: async () => ({ deleted: 1 }),
},
};
try {
const res = await clearAllRemoteDesktopRecordingsAndSyncLogs();
assert.equal(res.deleted, 1);
assert.equal(updatedCount, 1);
} finally {
registerConnectionLogsActions(null);
publishConnectionLogsSnapshot({ connectionLogs: [] });
env.restore();
}
});
@@ -0,0 +1,207 @@
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
import type {
ConnectionLog,
RemoteDesktopRecordingClip,
RemoteDesktopSessionEvent,
RemoteDesktopSessionMetadata,
} from '../../domain/models';
import {
buildAppendRecordingClipUpdate,
buildClearRecordingsUpdate,
getConnectionLogMediaIds,
} from '../../domain/remoteDesktopRecording';
import { STORAGE_KEY_CONNECTION_LOGS } from '../../infrastructure/config/storageKeys';
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import {
listRemoteDesktopAuditEntries,
subscribeRemoteDesktopAuditLog,
type RemoteDesktopAuditEntry,
} from '../../infrastructure/remoteDesktop/remoteDesktopAuditLog';
import {
netcattyBridge,
type RemoteDesktopRecordingsBridgeApi,
} from '../../infrastructure/services/netcattyBridge';
import {
getConnectionLogsActions,
getConnectionLogsSnapshot,
} from './connectionLogsStore';
import { withVaultImportLock } from './vaultManagedImportLock';
export type { RemoteDesktopAuditEntry };
export function getRemoteDesktopRecordingsBridge(): RemoteDesktopRecordingsBridgeApi | null {
return netcattyBridge.get()?.remoteDesktopRecordings ?? null;
}
export function registerSessionLogFinalizer(
finalize: () => void | Promise<void>,
): (() => void) | undefined {
const unsub = netcattyBridge.get()?.onFinalizeSessionLogs?.(finalize);
return typeof unsub === 'function' ? unsub : undefined;
}
export async function getSystemUserHostInfo(): Promise<{ username: string; hostname: string }> {
try {
const info = await netcattyBridge.get()?.getSystemInfo?.();
return {
username: info?.username || 'user',
hostname: info?.hostname || 'localhost',
};
} catch {
return { username: 'user', hostname: 'localhost' };
}
}
export function listRemoteDesktopSessionAuditEntries(
sessionId?: string,
): RemoteDesktopAuditEntry[] {
return listRemoteDesktopAuditEntries(sessionId);
}
export function subscribeRemoteDesktopSessionAuditLog(listener: () => void): () => void {
return subscribeRemoteDesktopAuditLog(listener);
}
function readPersistedConnectionLogs(): ConnectionLog[] {
try {
const stored = localStorageAdapter.read<ConnectionLog[]>(STORAGE_KEY_CONNECTION_LOGS);
return Array.isArray(stored) ? stored : [];
} catch {
return [];
}
}
/**
* Collect all protected media IDs (video clips + thumbnails) across bookmarked
* connection logs from BOTH the in-memory store and persisted localStorage.
* Works identically in the main window and detached Settings window.
*/
export function collectProtectedRemoteDesktopMediaIds(): string[] {
const protectedSet = new Set<string>();
const { connectionLogs } = getConnectionLogsSnapshot();
for (const log of connectionLogs) {
if (log.saved) {
for (const mediaId of getConnectionLogMediaIds(log)) {
protectedSet.add(mediaId);
}
}
}
for (const log of readPersistedConnectionLogs()) {
if (log.saved) {
for (const mediaId of getConnectionLogMediaIds(log)) {
protectedSet.add(mediaId);
}
}
}
return Array.from(protectedSet);
}
export async function appendRemoteDesktopClipToConnectionLog(
sessionId: string,
clip: RemoteDesktopRecordingClip,
options?: { stampEndTime?: boolean },
): Promise<boolean> {
const { connectionLogs } = getConnectionLogsSnapshot();
const actions = getConnectionLogsActions();
if (!actions?.updateConnectionLog) return false;
const matchingLog = selectConnectionLogForTerminalDataCapture(
[...connectionLogs],
{ sessionId },
);
if (!matchingLog) return false;
const updates = buildAppendRecordingClipUpdate(matchingLog, clip, {
stampEndTime: options?.stampEndTime ? Date.now() : undefined,
});
await Promise.resolve(actions.updateConnectionLog(matchingLog.id, updates));
return true;
}
export async function updateRemoteDesktopConnectionLogActivity(
sessionId: string,
updater: (current: {
events: RemoteDesktopSessionEvent[];
meta: RemoteDesktopSessionMetadata | undefined;
}) => {
events?: RemoteDesktopSessionEvent[];
meta?: RemoteDesktopSessionMetadata;
},
): Promise<boolean> {
const actions = getConnectionLogsActions();
if (!actions?.updateConnectionLog) return false;
const { connectionLogs } = getConnectionLogsSnapshot();
const matchingLog = selectConnectionLogForTerminalDataCapture(
[...connectionLogs],
{ sessionId },
);
if (!matchingLog) return false;
const next = updater({
events: Array.isArray(matchingLog.remoteDesktopEvents) ? matchingLog.remoteDesktopEvents : [],
meta: matchingLog.remoteDesktopMeta,
});
const patch: Partial<ConnectionLog> = {};
if (next.events) patch.remoteDesktopEvents = next.events;
if (next.meta) patch.remoteDesktopMeta = next.meta;
if (Object.keys(patch).length === 0) return false;
await Promise.resolve(actions.updateConnectionLog(matchingLog.id, patch));
return true;
}
export async function saveRemoteDesktopThumbnail(options: {
id?: string;
data: Uint8Array;
}): Promise<{ ok: boolean; id?: string; url?: string; bytes?: number } | null> {
const bridge = getRemoteDesktopRecordingsBridge();
if (!bridge?.saveThumbnail) return null;
return bridge.saveThumbnail(options);
}
/**
* Clear all unprotected remote desktop recordings on disk and atomically clear
* their references from connection logs. Safe to invoke from detached windows
* (such as Settings -> System) where `useVaultState` is not mounted.
*/
export async function clearAllRemoteDesktopRecordingsAndSyncLogs(): Promise<{ deleted: number }> {
const bridge = getRemoteDesktopRecordingsBridge();
if (!bridge?.clearAll) return { deleted: 0 };
const protectedIds = collectProtectedRemoteDesktopMediaIds();
const protectedSet = new Set(protectedIds);
const res = await bridge.clearAll({ protectedIds });
const actions = getConnectionLogsActions();
if (actions?.updateConnectionLog) {
// Call `actions.updateConnectionLog` OUTSIDE `withVaultImportLock('connection-logs')`
// because `useVaultState.commitConnectionLogs` acquires that same non-reentrant Web Lock.
const { connectionLogs } = getConnectionLogsSnapshot();
const persistedById = new Map(readPersistedConnectionLogs().map((log) => [log.id, log]));
const targets = new Map<string, ConnectionLog>();
for (const log of connectionLogs) targets.set(log.id, log);
for (const [id, log] of persistedById) {
if (!targets.has(id)) targets.set(id, log);
}
for (const log of targets.values()) {
const updates = buildClearRecordingsUpdate(log, protectedSet);
if (updates) {
await Promise.resolve(actions.updateConnectionLog(log.id, updates));
}
}
} else {
// Detached window (e.g. Settings -> System without Sync tab mounted): update
// localStorage atomically under the shared cross-window Web Lock.
await withVaultImportLock('connection-logs', async () => {
const persisted = readPersistedConnectionLogs();
let changed = false;
const nextPersisted = persisted.map((log) => {
const updates = buildClearRecordingsUpdate(log, protectedSet);
if (!updates) return log;
changed = true;
return { ...log, ...updates };
});
if (changed) {
localStorageAdapter.write(STORAGE_KEY_CONNECTION_LOGS, nextPersisted);
}
});
}
return { deleted: res?.deleted ?? 0 };
}
+24 -15
View File
@@ -12,6 +12,7 @@ import { retainLocalHostLastConnectedAt } from "../../domain/sync";
import { sanitizeGroupConfig } from "../../domain/groupConfig";
import { normalizeKnownHosts } from "../../domain/knownHosts";
import { normalizeNoteGroups, normalizeVaultNotes } from "../../domain/notes";
import { getConnectionLogMediaIds } from "../../domain/remoteDesktopRecording";
import {
applyPluginImporterDestination,
mergePluginImporterDrafts,
@@ -634,16 +635,18 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
}
const remainingRecordingIds = new Set<string>();
for (const log of next) {
if (log.recordingId) remainingRecordingIds.add(log.recordingId);
for (const mediaId of getConnectionLogMediaIds(log)) {
remainingRecordingIds.add(mediaId);
}
}
const removedRecordingIds: string[] = [];
for (const log of prev) {
if (
!nextIds.has(log.id)
&& log.recordingId
&& !remainingRecordingIds.has(log.recordingId)
) {
removedRecordingIds.push(log.recordingId);
if (!nextIds.has(log.id)) {
for (const mediaId of getConnectionLogMediaIds(log)) {
if (!remainingRecordingIds.has(mediaId)) {
removedRecordingIds.push(mediaId);
}
}
}
}
if (removedRecordingIds.length > 0) {
@@ -1586,19 +1589,25 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
// One-time startup GC to sweep orphaned / expired / over-quota remote desktop recordings
// while preserving all bookmarked/saved connection log recordings.
// CRITICAL: Must wait for `isInitialized` so `connectionLogsRef.current` has been hydrated
// from storage; running before boot hydration would pass `referencedIds: []` and wipe files!
const hasRunRecordingStartupGcRef = useRef(false);
useEffect(() => {
if (!syncConnectionLogTerminalData || hasRunRecordingStartupGcRef.current) return;
if (!isInitialized || !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 referencedSet = new Set<string>();
const protectedSet = new Set<string>();
for (const log of logs) {
for (const mediaId of getConnectionLogMediaIds(log)) {
referencedSet.add(mediaId);
if (log.saved) protectedSet.add(mediaId);
}
}
const referencedIds = Array.from(referencedSet);
const protectedIds = Array.from(protectedSet);
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);
@@ -1611,7 +1620,7 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
protectedIds,
})
.catch(() => {});
}, [syncConnectionLogTerminalData]);
}, [isInitialized, syncConnectionLogTerminalData]);
useLayoutEffect(() => {
registerConnectionLogsActions({
+60
View File
@@ -81,4 +81,64 @@ test("ConnectionLogsManager renders RDP/VNC icons and compact recording pill whe
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/);
assert.match(markup, /data-testid="logs-filter-bar"/);
assert.match(markup, /data-logs-filter="remoteDesktop"/);
assert.match(markup, /data-logs-filter="recorded"/);
});
test("ConnectionLogsManager renders multi-clip count and remote desktop resolution metadata", () => {
const logs: ConnectionLog[] = [
{
id: "log-multi-rec",
hostId: "h-1",
hostLabel: "Windows Multi",
hostname: "10.0.0.10",
username: "Administrator",
protocol: "rdp",
startTime: 1_700_000_000_000,
endTime: 1_700_000_200_000,
localUsername: "alice",
localHostname: "macbook",
saved: false,
recordings: [
{
id: "11111111-1111-4111-8111-111111111111",
startedAt: 1_700_000_010_000,
endedAt: 1_700_000_040_000,
durationMs: 30_000,
bytes: 1_048_576,
mimeType: "video/webm",
hasAudio: false,
},
{
id: "22222222-2222-4222-8222-222222222222",
startedAt: 1_700_000_060_000,
endedAt: 1_700_000_120_000,
durationMs: 60_000,
bytes: 2_097_152,
mimeType: "video/webm",
hasAudio: true,
},
],
remoteDesktopMeta: {
resolution: { width: 1920, height: 1080 },
securityLabel: "TLS / NLA",
},
},
];
const markup = renderWithI18n(
React.createElement(ConnectionLogsManager, {
logs,
hosts: [],
onToggleSaved: () => {},
onDelete: () => {},
onClearUnsaved: () => {},
onOpenLogView: () => {},
}),
);
assert.match(markup, /2 clips · 01:30 · 3 MB/);
assert.match(markup, /1920×1080/);
assert.match(markup, /TLS \/ NLA/);
});
+116 -21
View File
@@ -2,6 +2,7 @@ import {
Bookmark,
ChevronDown,
CircleUserRound,
Monitor,
Server,
Terminal,
Trash2,
@@ -11,7 +12,8 @@ import {
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 { isRdpProtocol, isRemoteDesktopProtocol, isVncProtocol } from "../domain/remoteDesktop";
import { getConnectionLogRecordingSummary } from "../domain/remoteDesktopRecording";
import { cn } from "../lib/utils";
import { ConnectionLog, Host } from "../types";
import { DistroAvatar } from "./DistroAvatar";
@@ -28,6 +30,8 @@ interface ConnectionLogsManagerProps {
onOpenLogView: (log: ConnectionLog) => void;
}
export type ConnectionLogFilter = "all" | "terminal" | "remoteDesktop" | "recorded";
export function formatRecordingDuration(durationMs?: number): string {
if (!durationMs || !Number.isFinite(durationMs) || durationMs <= 0) {
return "00:00";
@@ -110,8 +114,28 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
iconColorCustom: log.hostIconColorCustom,
});
const hasPersistedHostIcon = !isLocal && !isSerial && !isRemoteDesktop && (!!log.hostDistro || !!customHostIcon);
const recordingSizeText = formatRecordingBytes(log.recordingBytes);
const recordingDurationText = formatRecordingDuration(log.recordingDurationMs);
const recordingSummary = getConnectionLogRecordingSummary(log);
const recordingSizeText = formatRecordingBytes(recordingSummary.totalBytes);
const recordingDurationText = formatRecordingDuration(recordingSummary.totalDurationMs);
const resolutionText = log.remoteDesktopMeta?.resolution
? `${log.remoteDesktopMeta.resolution.width}\u00d7${log.remoteDesktopMeta.resolution.height}`
: "";
const subtitleParts: string[] = [];
if (isLocal) {
subtitleParts.push("local");
} else if (isSerial) {
subtitleParts.push(`serial, ${log.hostname}`);
} else if (log.username) {
subtitleParts.push(`${log.protocol}, ${log.username}`);
} else {
subtitleParts.push(`${log.protocol}, ${log.hostname}`);
}
if (isRemoteDesktop && resolutionText) {
subtitleParts.push(resolutionText);
}
if (isRemoteDesktop && log.remoteDesktopMeta?.securityLabel) {
subtitleParts.push(log.remoteDesktopMeta.securityLabel);
}
return (
<div
@@ -185,13 +209,16 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
<div className="text-sm font-medium truncate">
{isLocal ? t("logs.localTerminal") : log.hostLabel}
</div>
{log.recordingId && (
{recordingSummary.primaryClip && (
<span
data-recording-badge={log.recordingId}
data-recording-badge={recordingSummary.primaryClip.id}
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>
{recordingSummary.clipCount > 1
? `${t("logs.recording.clipsCount", { count: recordingSummary.clipCount })} · `
: ""}
{recordingDurationText}
{recordingSizeText ? ` · ${recordingSizeText}` : ""}
</span>
@@ -199,13 +226,7 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
)}
</div>
<div className="text-xs text-muted-foreground truncate">
{isLocal
? "local"
: isSerial
? `serial, ${log.hostname}`
: log.username
? `${log.protocol}, ${log.username}`
: `${log.protocol}, ${log.hostname}`}
{subtitleParts.join(" · ")}
</div>
</div>
</div>
@@ -264,20 +285,52 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
const INITIAL_RENDER_LIMIT = 30;
const LOAD_MORE_COUNT = 30;
// Track how many items to show
const [filter, setFilter] = useState<ConnectionLogFilter>("all");
const [renderLimit, setRenderLimit] = useState(INITIAL_RENDER_LIMIT);
// Sort logs by newest first
const filteredLogs = useMemo(() => {
return [...logs].sort((a, b) => b.startTime - a.startTime);
const filterCounts = useMemo(() => {
let terminal = 0;
let remoteDesktop = 0;
let recorded = 0;
for (const log of logs) {
if (isRemoteDesktopProtocol(log.protocol)) {
remoteDesktop += 1;
} else {
terminal += 1;
}
if (getConnectionLogRecordingSummary(log).clipCount > 0) {
recorded += 1;
}
}
return { all: logs.length, terminal, remoteDesktop, recorded };
}, [logs]);
const showFilterBar = logs.length > 0 && (filterCounts.remoteDesktop > 0 || filterCounts.recorded > 0);
const effectiveFilter: ConnectionLogFilter = showFilterBar ? filter : "all";
// Filter and sort logs by newest first
const filteredLogs = useMemo(() => {
const subset = effectiveFilter === "all"
? logs
: logs.filter((log) => {
if (effectiveFilter === "remoteDesktop") return isRemoteDesktopProtocol(log.protocol);
if (effectiveFilter === "terminal") return !isRemoteDesktopProtocol(log.protocol);
return getConnectionLogRecordingSummary(log).clipCount > 0;
});
return [...subset].sort((a, b) => b.startTime - a.startTime);
}, [effectiveFilter, logs]);
const displayedLogs = useMemo(() => {
return filteredLogs.slice(0, renderLimit);
}, [filteredLogs, renderLimit]);
const hasMore = filteredLogs.length > renderLimit;
const handleChangeFilter = useCallback((next: ConnectionLogFilter) => {
setFilter(next);
setRenderLimit(INITIAL_RENDER_LIMIT);
}, []);
const handleLoadMore = useCallback(() => {
setRenderLimit(prev => prev + LOAD_MORE_COUNT);
}, []);
@@ -292,7 +345,6 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
[onDelete],
);
// Rendered items
const renderedItems = useMemo(() => {
return displayedLogs.map((log) => (
<LogItem
@@ -307,9 +359,46 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
return (
<div className="h-full flex flex-col">
{/* Protocol / Recording Filter Bar */}
{showFilterBar && (
<div
data-testid="logs-filter-bar"
className="flex flex-wrap items-center gap-1.5 px-4 py-2 border-b border-border/30 bg-background shrink-0"
>
{(
[
{ id: "all" as const, label: t("logs.filter.all"), count: filterCounts.all, icon: null },
{ id: "terminal" as const, label: t("logs.filter.terminal"), count: filterCounts.terminal, icon: <Terminal size={12} /> },
{ id: "remoteDesktop" as const, label: t("logs.filter.remoteDesktop"), count: filterCounts.remoteDesktop, icon: <Monitor size={12} /> },
{ id: "recorded" as const, label: t("logs.filter.recorded"), count: filterCounts.recorded, icon: <Video size={12} /> },
]
).map((item) => {
const active = effectiveFilter === item.id;
return (
<button
key={item.id}
type="button"
data-logs-filter={item.id}
onClick={() => handleChangeFilter(item.id)}
className={cn(
"inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors cursor-pointer",
active
? "bg-primary/12 text-primary border border-primary/25"
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60 border border-transparent",
)}
>
{item.icon}
<span>{item.label}</span>
<span className="font-mono text-[10px] opacity-75 tabular-nums">{item.count}</span>
</button>
);
})}
</div>
)}
{/* Table Header */}
{displayedLogs.length > 0 && (
<div className="flex items-center gap-4 px-4 py-2 text-xs font-medium text-muted-foreground border-b border-border/30 bg-secondary/30">
<div className="flex items-center gap-4 px-4 py-2 text-xs font-medium text-muted-foreground border-b border-border/30 bg-secondary/30 shrink-0">
<div className="w-32 shrink-0 flex items-center gap-1">
{t("logs.table.date")}
<ChevronDown size={12} />
@@ -329,13 +418,19 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
{displayedLogs.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
<div className="h-16 w-16 rounded-2xl bg-secondary/80 flex items-center justify-center mb-4">
<Terminal size={32} className="opacity-60" />
{effectiveFilter === "recorded" ? (
<Video size={32} className="opacity-60" />
) : effectiveFilter === "remoteDesktop" ? (
<Monitor size={32} className="opacity-60" />
) : (
<Terminal size={32} className="opacity-60" />
)}
</div>
<h3 className="text-lg font-semibold text-foreground mb-2">
{t("logs.empty.title")}
{effectiveFilter === "all" ? t("logs.empty.title") : t("logs.filter.emptyTitle")}
</h3>
<p className="text-sm text-center max-w-sm">
{t("logs.empty.desc")}
{effectiveFilter === "all" ? t("logs.empty.desc") : t("logs.filter.emptyDesc")}
</p>
</div>
) : (
+76 -1
View File
@@ -126,10 +126,85 @@ test("LogView renders clean non-terminal metadata card for unrecorded VNC/RDP se
assert.doesNotMatch(markup, /Appearance/);
});
test("LogView memo comparator checks recordingId and recordingBytes", () => {
test("LogView memo comparator checks recordingId, recordings, remoteDesktopEvents, 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/);
assert.match(comparator, /prev\.log\.recordings === next\.log\.recordings/);
assert.match(comparator, /prev\.log\.remoteDesktopEvents === next\.log\.remoteDesktopEvents/);
});
test("LogView renders multi-clip strip and video-linked session timeline with seek chips", () => {
const log: ConnectionLog = {
id: "log-multi",
sessionId: "sess-rdp-multi",
hostId: "h-1",
hostLabel: "Windows Multi",
hostname: "10.0.0.11",
username: "Administrator",
protocol: "rdp",
startTime: 1_700_000_000_000,
endTime: 1_700_000_180_000,
localUsername: "alice",
localHostname: "macbook",
saved: true,
recordingId: "22222222-2222-4222-8222-222222222222",
recordings: [
{
id: "11111111-1111-4111-8111-111111111111",
startedAt: 1_700_000_010_000,
endedAt: 1_700_000_040_000,
durationMs: 30_000,
bytes: 1_048_576,
mimeType: "video/webm;codecs=vp9",
hasAudio: false,
width: 1920,
height: 1080,
},
{
id: "22222222-2222-4222-8222-222222222222",
startedAt: 1_700_000_060_000,
endedAt: 1_700_000_120_000,
durationMs: 60_000,
bytes: 2_097_152,
mimeType: "video/webm;codecs=vp9,opus",
hasAudio: true,
width: 1920,
height: 1080,
},
],
remoteDesktopMeta: {
resolution: { width: 1920, height: 1080 },
securityLabel: "TLS / NLA",
tunneled: true,
},
remoteDesktopEvents: [
{
id: "ev-1",
timestamp: 1_700_000_075_000,
kind: "clipboard_download",
summary: "Downloaded report.pdf",
detail: "1.2 MB",
},
],
};
const markup = renderWithI18n(
React.createElement(LogView, {
log,
defaultTerminalTheme: defaultTheme,
defaultFontSize: 13,
isVisible: true,
onClose: () => {},
onUpdateLog: () => {},
}),
);
assert.match(markup, /data-testid="log-view-clip-strip"/);
assert.match(markup, /data-testid="log-view-timeline-drawer"/);
assert.match(markup, /Downloaded report\.pdf/);
assert.match(markup, /data-seek-seconds="15"/);
assert.match(markup, /TLS \/ NLA/);
});
+669 -192
View File
File diff suppressed because it is too large. Load diff
+68 -1
View File
@@ -14,10 +14,15 @@ import { upsertKnownHost } from '../domain/knownHosts';
import { isPluginHostProtocol, sanitizePluginConnection } from '../domain/pluginConnection';
import {
isRemoteDesktopProtocol,
resolveRemoteDesktopConnectionSpec,
sanitizeRdpConfig,
sanitizeVncConfig,
type RemoteDesktopProtocol,
} from '../domain/remoteDesktop';
import { selectConnectionLogForTerminalDataCapture } from '../domain/connectionLog';
import { getConnectionLogsSnapshot } from '../application/state/connectionLogsStore';
import { getSystemUserHostInfo } from '../application/state/remoteDesktopLogActions';
import { captureClosingTerminalSessions } from '../application/state/terminalSessionCloseCapture';
import type { ResolveDefaultLocalShellContext } from '../domain/localShellHost';
import {
resolveEffectiveTerminalHost,
@@ -362,6 +367,8 @@ function TerminalPopupPageInner({
snippets,
snippetPackages,
groupConfigs,
addConnectionLog,
updateConnectionLog,
updateKnownHosts,
deleteSelectedSnippets,
} = useVaultState({ syncConnectionLogTerminalData: false });
@@ -397,6 +404,8 @@ function TerminalPopupPageInner({
}
await markAttachClosePrepared(attachSessionId, attachAuthorization);
} catch { /* The main-process close handshake owns the final fallback. */ }
} else {
captureClosingTerminalSessions([sessionId]);
}
await close();
})();
@@ -406,7 +415,7 @@ function TerminalPopupPageInner({
};
void closePromise.then(clearClosePromise, clearClosePromise);
return closePromise;
}, [attachAuthorization, attachSessionId, close, isAttachMode, markAttachClosePrepared]);
}, [attachAuthorization, attachSessionId, close, isAttachMode, markAttachClosePrepared, sessionId]);
const effectiveKnownHosts = useMemo(
() => getEffectiveKnownHosts(knownHosts) ?? [],
[knownHosts],
@@ -486,6 +495,63 @@ function TerminalPopupPageInner({
if (readyToStart) setSessionStarted(true);
}, [readyToStart]);
const ready = sessionStarted || readyToStart;
const popupRemoteDesktopLogCreatedRef = React.useRef<string | null>(null);
useEffect(() => {
if (!ready || !host || !remoteDesktopProtocol) return;
if (popupRemoteDesktopLogCreatedRef.current === sessionId) return;
popupRemoteDesktopLogCreatedRef.current = sessionId;
const existingLog = selectConnectionLogForTerminalDataCapture(
[...getConnectionLogsSnapshot().connectionLogs],
{ sessionId },
);
if (existingLog) return;
const spec = resolveRemoteDesktopConnectionSpec(host, remoteDesktopProtocol, identities);
// Create the ConnectionLog synchronously before RemoteDesktopPane connects
// so early connected/error events are never dropped, then enrich local user/host.
addConnectionLog({
sessionId,
hostId: host.id,
hostLabel: spec.isCompanion ? `${spec.label} (${remoteDesktopProtocol.toUpperCase()})` : spec.label,
hostname: spec.hostHostname,
username: spec.username,
protocol: remoteDesktopProtocol,
startTime: Date.now(),
localUsername: 'user',
localHostname: 'localhost',
saved: false,
});
let cancelled = false;
void getSystemUserHostInfo().then((info) => {
if (cancelled) return;
const log = selectConnectionLogForTerminalDataCapture(
[...getConnectionLogsSnapshot().connectionLogs],
{ sessionId },
);
if (log && (info.username !== 'user' || info.hostname !== 'localhost')) {
void updateConnectionLog(log.id, {
localUsername: info.username,
localHostname: info.hostname,
});
}
});
return () => {
cancelled = true;
};
}, [addConnectionLog, host, identities, ready, remoteDesktopProtocol, sessionId, updateConnectionLog]);
const handlePopupRemoteDesktopCloseCapture = useCallback(
async (closingSessionId: string) => {
const { connectionLogs } = getConnectionLogsSnapshot();
const matchingLog = selectConnectionLogForTerminalDataCapture([...connectionLogs], {
sessionId: closingSessionId,
});
if (matchingLog) {
await updateConnectionLog(matchingLog.id, { endTime: Date.now() });
}
},
[updateConnectionLog],
);
const startupRevealDelayMs = useMemo(() => {
// Attach mode shows the live session immediately (no startup command).
if (isAttachMode) return 0;
@@ -562,6 +628,7 @@ function TerminalPopupPageInner({
knownHosts={effectiveKnownHosts}
isVisible
isFocused
onTerminalDataCapture={handlePopupRemoteDesktopCloseCapture}
onCloseSession={() => {
void handleClose();
}}
@@ -47,7 +47,12 @@ import {
type RemoteDesktopClipboardTransferState,
type RemoteDesktopDisplayMode,
type RemoteDesktopRdpdrRequest,
type RemoteDesktopRecordingCaptureHandle,
} from './remoteDesktopHelpers';
import {
captureCanvasThumbnailJpeg,
createStableCanvasCaptureStream,
} from './remoteDesktopVideoCapture';
import type { RemoteDesktopSpecialKeyId } from './vncKeymap';
import type {
@@ -410,6 +415,12 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
return canvasRef.current?.getBoundingClientRect() ?? null;
}, []);
const captureThumbnailJpeg = useCallback(async (): Promise<Uint8Array | null> => {
const canvas = canvasRef.current;
if (!canvas) return null;
return captureCanvasThumbnailJpeg(canvas);
}, []);
const getCaptureStream = useCallback((fps: number, includeAudio?: boolean): MediaStream | null => {
const canvas = canvasRef.current;
if (!canvas || canvas.width === 0 || canvas.height === 0) return null;
@@ -431,6 +442,22 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
}
}, []);
const createRecordingCapture = useCallback(
(fps: number, includeAudio?: boolean): RemoteDesktopRecordingCaptureHandle | null => {
const canvas = canvasRef.current;
if (!canvas || canvas.width === 0 || canvas.height === 0) return null;
const audioPlayer = includeAudio ? audioPlayerRef.current : null;
const audioStream = audioPlayer?.ensureCaptureAudioStream() ?? null;
return createStableCanvasCaptureStream(canvas, fps, {
audioStream,
onReleaseAudio: audioStream && audioPlayer
? () => audioPlayer.releaseCaptureAudioStream()
: undefined,
});
},
[],
);
const emitClipboardTransfer = useCallback((transfer: RemoteDesktopClipboardTransferState | null) => {
callbacksRef.current.onClipboardTransferChange?.(transfer);
callbacksRef.current.onClipboardFileTransferStatus?.(transfer?.message ?? null);
@@ -890,9 +917,11 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
typeText,
releaseAllInputs,
captureScreenshot,
captureThumbnailJpeg,
captureFrame,
getCanvasRect,
getCaptureStream,
createRecordingCapture,
focusInput,
syncClipboardNow,
downloadRemoteClipboardFile,
@@ -907,6 +936,8 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
addSharedDrive,
captureFrame,
captureScreenshot,
captureThumbnailJpeg,
createRecordingCapture,
downloadRemoteClipboardFile,
focusInput,
getCanvasRect,
+255 -20
View File
@@ -1,9 +1,25 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { AlertCircle, Check, KeyRound, Loader2, Plug, RefreshCw, ShieldCheck, X } from 'lucide-react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { getConnectionLogsSnapshot } from '../../application/state/connectionLogsStore';
import {
registerSessionLogFinalizer,
saveRemoteDesktopThumbnail,
updateRemoteDesktopConnectionLogActivity,
} from '../../application/state/remoteDesktopLogActions';
import { useTerminalSessionCloseCapture } from '../../application/state/terminalSessionCloseCapture';
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
import type { Host, Identity, KnownHost, SSHKey, TerminalSession } from '../../types';
import type { RdpMultiMonitorMode } from '../../domain/models/connection';
import type {
RdpMultiMonitorMode,
RemoteDesktopSessionEventKind,
RemoteDesktopSessionMetadata,
} from '../../domain/models';
import {
appendRemoteDesktopSessionEvent,
getConnectionLogRecordingClips,
mergeRemoteDesktopSessionMetadata,
} from '../../domain/remoteDesktopRecording';
import {
computeMonitorLayoutEntries,
formatStandardRdpSecurityBadge,
@@ -76,6 +92,7 @@ import { RemoteDesktopCertDialog } from './RemoteDesktopCertDialog';
import {
buildRemoteDesktopStartPayload,
buildSystemRemoteDesktopPayload,
formatTransferBytes,
getRemoteDesktopBridge,
tr,
type RemoteDesktopCanvasHandle,
@@ -96,8 +113,8 @@ import { useRemoteDesktopRecorder } from './useRemoteDesktopRecorder';
import { VncCanvasView, type VncCapabilities } from './VncCanvasView';
import type { RemoteDesktopSpecialKeyId } from './vncKeymap';
const SHOW_REMOTE_DESKTOP_RECORDING_BUTTON = false;
const EMPTY_FINALIZE_LOG = () => '';
const RESIZE_EVENT_DEBOUNCE_MS = 1500;
export interface RemoteDesktopPaneProps {
sessionId: string;
@@ -197,6 +214,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const attemptNonceRef = useRef(0);
const closeCaptureNeverConnectedRef = useRef(false);
const closeCaptureDoneRef = useRef(false);
const closeCapturePromiseRef = useRef<Promise<void> | null>(null);
const spec = useMemo(
() => resolveRemoteDesktopConnectionSpec(host, protocol, identities),
@@ -309,6 +327,83 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const tunneled = Boolean(spec.tunnelViaHostSsh || (chainHosts && chainHosts.length > 0));
const effectiveLabel = desktopTitle || spec.label || spec.hostHostname;
const hasConnectedOnceRef = useRef(false);
const sessionThumbnailCapturedRef = useRef(false);
const sessionThumbnailInFlightRef = useRef(false);
const isRecordingOrStoppingRef = useRef(false);
const resizeEventTimerRef = useRef<number | null>(null);
const thumbnailTimerRef = useRef<number | null>(null);
const lastLoggedResolutionRef = useRef<string | null>(null);
const appendSessionEvent = useCallback(
(
kind: RemoteDesktopSessionEventKind,
summary: string,
options?: {
timestamp?: number;
detail?: string;
metaPatch?: Partial<RemoteDesktopSessionMetadata>;
},
) => {
const ts = options?.timestamp ?? Date.now();
void updateRemoteDesktopConnectionLogActivity(sessionId, ({ events, meta }) => ({
events: appendRemoteDesktopSessionEvent(events, {
timestamp: ts,
kind,
summary,
detail: options?.detail,
}),
meta: options?.metaPatch ? mergeRemoteDesktopSessionMetadata(meta, options.metaPatch) : undefined,
}));
},
[sessionId],
);
// Capture a compact local JPEG poster for unrecorded sessions before tearing down canvas.
const captureUnrecordedSessionThumbnail = useCallback(async () => {
if (
sessionThumbnailCapturedRef.current
|| sessionThumbnailInFlightRef.current
|| isRecordingOrStoppingRef.current
) {
return;
}
const handle = canvasHandleRef.current;
if (!handle?.captureThumbnailJpeg) return;
const { connectionLogs } = getConnectionLogsSnapshot();
const matchingLog = selectConnectionLogForTerminalDataCapture([...connectionLogs], { sessionId });
if (!matchingLog) return;
if (getConnectionLogRecordingClips(matchingLog).length > 0 || matchingLog.remoteDesktopMeta?.thumbnailId) {
sessionThumbnailCapturedRef.current = true;
return;
}
sessionThumbnailInFlightRef.current = true;
try {
const jpeg = await handle.captureThumbnailJpeg();
if (!jpeg || jpeg.byteLength === 0 || isRecordingOrStoppingRef.current) return;
const saved = await saveRemoteDesktopThumbnail({ data: jpeg });
if (saved?.ok && saved.id) {
sessionThumbnailCapturedRef.current = true;
await updateRemoteDesktopConnectionLogActivity(sessionId, ({ meta }) => ({
meta: mergeRemoteDesktopSessionMetadata(meta, { thumbnailId: saved.id }),
}));
}
} catch {
// Non-fatal: session log works fine without a thumbnail.
} finally {
sessionThumbnailInFlightRef.current = false;
}
}, [sessionId]);
const handleRecordingLifecycleEvent = useCallback(
(ev: { kind: 'recording_started' | 'recording_stopped'; timestamp: number; summary: string; detail?: string }) => {
appendSessionEvent(ev.kind, ev.summary, {
timestamp: ev.timestamp,
detail: ev.detail,
});
},
[appendSessionEvent],
);
const recorder = useRemoteDesktopRecorder({
sessionId,
@@ -317,13 +412,32 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
status,
audioEnabled: isRdp && Boolean(spec.rdpConfig?.audioEnabled),
canvasHandleRef,
onRecordingLifecycleEvent: handleRecordingLifecycleEvent,
});
isRecordingOrStoppingRef.current = recorder.isRecording || recorder.isStopping;
// Stamp ConnectionLog endTime when this remote desktop session closes via any UI/hotkey path.
// Clear debounced timers on unmount to prevent post-unmount leaks.
useEffect(() => () => {
if (resizeEventTimerRef.current !== null) {
window.clearTimeout(resizeEventTimerRef.current);
resizeEventTimerRef.current = null;
}
if (thumbnailTimerRef.current !== null) {
window.clearTimeout(thumbnailTimerRef.current);
thumbnailTimerRef.current = null;
}
}, []);
// Stamp ConnectionLog endTime when this remote desktop session closes via any UI/hotkey/quit path.
const handleCloseLogCapture = useCallback(
(closingSessionId: string, data: string) => {
if (closeCapturePromiseRef.current) return closeCapturePromiseRef.current;
closeCaptureDoneRef.current = true;
return onTerminalDataCapture?.(closingSessionId, data);
const promise = Promise.resolve(onTerminalDataCapture?.(closingSessionId, data))
.catch(() => {})
.then(() => undefined);
closeCapturePromiseRef.current = promise;
return promise;
},
[onTerminalDataCapture],
);
@@ -336,6 +450,14 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
onTerminalDataCapture: handleCloseLogCapture,
});
// Also await endTime stamping on native window close / app quit (even when unrecorded).
useEffect(() => {
if (!onTerminalDataCapture) return undefined;
return registerSessionLogFinalizer(async () => {
await handleCloseLogCapture(sessionId, '');
});
}, [handleCloseLogCapture, onTerminalDataCapture, sessionId]);
const updateStatus = useCallback(
(next: 'connecting' | 'connected' | 'disconnected') => {
setStatus(next);
@@ -389,6 +511,17 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const toastKey = `${next.id}:${next.phase}`;
if (lastToastedTransferKeyRef.current !== toastKey) {
lastToastedTransferKeyRef.current = toastKey;
const fileSummary = next.fileCount > 1
? `${next.fileName} (+${next.fileCount - 1})`
: next.fileName;
const sizeDetail = next.totalBytes > 0 ? formatTransferBytes(next.totalBytes) : undefined;
appendSessionEvent(
next.direction === 'upload' ? 'clipboard_upload' : 'clipboard_download',
next.phase === 'completed'
? `${next.direction === 'upload' ? 'Uploaded' : 'Downloaded'} ${fileSummary}`
: `${next.direction === 'upload' ? 'Upload' : 'Download'} failed: ${fileSummary}`,
{ detail: next.phase === 'error' ? (next.error || sizeDetail) : sizeDetail },
);
if (next.phase === 'completed') {
toast.success(
next.message || tr(t, 'remoteDesktop.clipboard.transferCompleted', 'Clipboard file transfer complete'),
@@ -401,7 +534,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
}
}
},
[t],
[appendSessionEvent, t],
);
useEffect(() => {
@@ -1002,6 +1135,12 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const handleDisconnect = useCallback(() => {
releaseKeyboardGrab();
if (statusRef.current === 'connected') {
void captureUnrecordedSessionThumbnail();
appendSessionEvent('disconnected', 'Session closed by user', {
metaPatch: { disconnectReason: 'Closed by user' },
});
}
const activeId = activeBackendSessionIdRef.current;
if (activeId) {
void getRemoteDesktopBridge()?.stop(activeId).catch(() => {});
@@ -1009,7 +1148,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
setWsUrl(null);
updateStatus('disconnected');
onCloseSession?.(sessionId);
}, [onCloseSession, releaseKeyboardGrab, sessionId, updateStatus]);
}, [appendSessionEvent, captureUnrecordedSessionThumbnail, onCloseSession, releaseKeyboardGrab, sessionId, updateStatus]);
const handleOpenSystemClient = useCallback(async () => {
const rdBridge = getRemoteDesktopBridge();
@@ -1065,12 +1204,13 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
try {
if (typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
appendSessionEvent('screenshot', 'Copied screenshot to clipboard');
toast.success(tr(t, 'remoteDesktop.screenshot.copied', 'Screenshot copied to clipboard'));
}
} catch {
toast.error(tr(t, 'remoteDesktop.screenshot.copyFailed', 'Failed to copy screenshot'));
}
}, [t]);
}, [appendSessionEvent, t]);
const handleScreenshotSave = useCallback(async () => {
const blob = await canvasHandleRef.current?.captureScreenshot();
@@ -1082,6 +1222,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const bytes = new Uint8Array(await blob.arrayBuffer());
const res = await rdBridge.saveClipboardFile({ action: 'oneshot', fileName, data: bytes });
if (res?.ok && !res.canceled) {
appendSessionEvent('screenshot', 'Saved PNG screenshot', { detail: fileName });
toast.success(tr(t, 'remoteDesktop.screenshot.saved', 'Screenshot saved'));
}
return;
@@ -1092,13 +1233,19 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
a.download = fileName;
a.click();
URL.revokeObjectURL(url);
}, [effectiveLabel, protocol, t]);
appendSessionEvent('screenshot', 'Saved PNG screenshot', { detail: fileName });
}, [appendSessionEvent, effectiveLabel, protocol, t]);
const handleCanvasError = useCallback(
(err: { message: string; isAuthError?: boolean }) => {
releaseKeyboardGrab();
publishRemoteDesktopNetworkStats(sessionId, null);
publishRemoteDesktopFps(sessionId, 0);
const cleanMessage = sanitizeRemoteDesktopError(err.message) || err.message;
appendSessionEvent('error', err.isAuthError ? 'Authentication failed' : 'Connection error', {
detail: cleanMessage,
metaPatch: { disconnectReason: cleanMessage },
});
if (err.isAuthError) {
setAuthErrorMessage(err.message);
setConnectionIntent('idle');
@@ -1110,7 +1257,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
setDisconnectError(err.message);
updateStatus('disconnected');
},
[releaseKeyboardGrab, sessionId, updateStatus],
[appendSessionEvent, releaseKeyboardGrab, sessionId, updateStatus],
);
const handleCanvasDisconnected = useCallback(
@@ -1118,10 +1265,15 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
releaseKeyboardGrab();
publishRemoteDesktopNetworkStats(sessionId, null);
publishRemoteDesktopFps(sessionId, 0);
const cleanReason = sanitizeRemoteDesktopError(reason || null) || undefined;
appendSessionEvent('disconnected', 'Remote desktop disconnected', {
detail: cleanReason,
metaPatch: cleanReason ? { disconnectReason: cleanReason } : undefined,
});
if (reason) setDisconnectError(reason);
updateStatus('disconnected');
},
[releaseKeyboardGrab, sessionId, updateStatus],
[appendSessionEvent, releaseKeyboardGrab, sessionId, updateStatus],
);
const handleNegotiationFallback = useCallback((nextStage: Exclude<RdpAutoFallbackStage, 'none'>) => {
@@ -1356,6 +1508,9 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
deviceId: result.added.deviceId,
name: result.added.name,
});
appendSessionEvent('shared_folder_mounted', `Mounted shared folder "${result.added.name}"`, {
detail: result.added.readOnly ? 'Read-only' : 'Read / Write',
});
toast.success(
tr(t, 'remoteDesktop.sharedFolders.mounted', 'Mounted "{name}" on remote desktop', {
name: result.added.name,
@@ -1365,7 +1520,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Failed to add shared folder');
}
}, [host.id, syncDrivesToBackend, t]);
}, [appendSessionEvent, host.id, syncDrivesToBackend, t]);
const handleAddSharedFolderClick = useCallback(() => {
void handleAddSharedFolder();
@@ -1379,6 +1534,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
void syncDrivesToBackend(next);
if (target && status === 'connected') {
canvasHandleRef.current?.removeSharedDrive?.(target.deviceId);
appendSessionEvent('shared_folder_unmounted', `Unmounted shared folder "${target.name}"`);
toast.info(
tr(t, 'remoteDesktop.sharedFolders.unmounted', 'Unmounted "{name}"', {
name: target.name,
@@ -1386,7 +1542,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
);
}
},
[host.id, sharedFolders, status, syncDrivesToBackend, t],
[appendSessionEvent, host.id, sharedFolders, status, syncDrivesToBackend, t],
);
const handleToggleSharedFolderReadOnly = useCallback(
@@ -1428,6 +1584,28 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
void handleOpenSystemClient();
}, [handleOpenSystemClient]);
const handleDesktopResize = useCallback(
(size: { width: number; height: number }) => {
setResolution(size);
if (size.width <= 0 || size.height <= 0) return;
if (resizeEventTimerRef.current !== null) {
window.clearTimeout(resizeEventTimerRef.current);
resizeEventTimerRef.current = null;
}
const key = `${size.width}x${size.height}`;
if (lastLoggedResolutionRef.current === key) return;
resizeEventTimerRef.current = window.setTimeout(() => {
resizeEventTimerRef.current = null;
if (lastLoggedResolutionRef.current === key) return;
lastLoggedResolutionRef.current = key;
appendSessionEvent('resized', `Desktop resized to ${size.width}\u00d7${size.height}`, {
metaPatch: { resolution: { width: size.width, height: size.height } },
});
}, RESIZE_EVENT_DEBOUNCE_MS);
},
[appendSessionEvent],
);
const handleVncConnected = useCallback(
(info: {
width: number;
@@ -1444,8 +1622,34 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
setSupportsXvp(Boolean(info.supportsXvp));
setStageMessage('Desktop connected');
updateStatus('connected');
const isReconnect = hasConnectedOnceRef.current;
hasConnectedOnceRef.current = true;
lastLoggedResolutionRef.current = `${info.width}x${info.height}`;
const securityLabel = info.encrypted ? 'TLS' : 'RFB';
appendSessionEvent(
isReconnect ? 'reconnected' : 'connected',
isReconnect ? 'Reconnected to VNC desktop' : 'Connected to VNC desktop',
{
detail: `${info.width}\u00d7${info.height} \u00b7 ${securityLabel}${tunneled ? ' \u00b7 SSH Tunnel' : ''}`,
metaPatch: {
resolution: { width: info.width, height: info.height },
securityLabel,
tunneled,
monitorCount: 1,
},
},
);
if (thumbnailTimerRef.current !== null) {
window.clearTimeout(thumbnailTimerRef.current);
}
thumbnailTimerRef.current = window.setTimeout(() => {
thumbnailTimerRef.current = null;
if (statusRef.current === 'connected') {
void captureUnrecordedSessionThumbnail();
}
}, 1500);
},
[updateStatus],
[appendSessionEvent, captureUnrecordedSessionThumbnail, tunneled, updateStatus],
);
const handleRdpConnected = useCallback(
@@ -1458,15 +1662,15 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
setResolution({ width: info.width, height: info.height });
setEncrypted(Boolean(info.encrypted));
setRdpSecurityInfo(info.securityInfo ?? null);
const legacyBadge = formatStandardRdpSecurityBadge(info.securityInfo);
if (autoFallbackStage === 'rdp') {
const badge = formatStandardRdpSecurityBadge(info.securityInfo);
toast.info(
badge
legacyBadge
? tr(
t,
'remoteDesktop.rdp.fallbackStandardRdpWithCipher',
'Connected using Standard RDP Security ({{cipher}}).',
{ cipher: badge },
{ cipher: legacyBadge },
)
: tr(
t,
@@ -1477,8 +1681,38 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
}
setStageMessage('Desktop connected');
updateStatus('connected');
const isReconnect = hasConnectedOnceRef.current;
hasConnectedOnceRef.current = true;
lastLoggedResolutionRef.current = `${info.width}x${info.height}`;
const securityLabel = info.encrypted
? (autoFallbackStage === 'tls' ? 'TLS' : 'TLS / NLA')
: (legacyBadge || 'Standard RDP');
const activeMonitors = Math.max(1, monitorLayout.length);
appendSessionEvent(
isReconnect ? 'reconnected' : 'connected',
isReconnect ? 'Reconnected to RDP desktop' : 'Connected to RDP desktop',
{
detail: `${info.width}\u00d7${info.height} \u00b7 ${securityLabel}${tunneled ? ' \u00b7 SSH Tunnel' : ''}`,
metaPatch: {
resolution: { width: info.width, height: info.height },
securityLabel,
tunneled,
monitorCount: activeMonitors,
},
},
);
// Capture an early lightweight poster thumbnail once desktop finishes first paint.
if (thumbnailTimerRef.current !== null) {
window.clearTimeout(thumbnailTimerRef.current);
}
thumbnailTimerRef.current = window.setTimeout(() => {
thumbnailTimerRef.current = null;
if (statusRef.current === 'connected') {
void captureUnrecordedSessionThumbnail();
}
}, 1500);
},
[autoFallbackStage, t, updateStatus],
[appendSessionEvent, autoFallbackStage, captureUnrecordedSessionThumbnail, monitorLayout.length, t, tunneled, updateStatus],
);
const handleRemoteClipboardFilesChange = useCallback(
@@ -1584,9 +1818,10 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
aiAuditCount={aiAuditCount}
onOpenAiAuditLog={onAskAi ? handleOpenAiAuditLog : undefined}
isRecording={recorder.isRecording}
isStoppingRecording={recorder.isStopping}
recordingElapsedLabel={recorder.formattedElapsed}
recordingSupported={recorder.isSupported}
onToggleRecording={SHOW_REMOTE_DESKTOP_RECORDING_BUTTON ? handleToggleRecordingClick : undefined}
onToggleRecording={handleToggleRecordingClick}
quality={quality}
onChangeQuality={handleChangeQuality}
viewOnly={viewOnly}
@@ -1661,7 +1896,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
onRequestReleaseGrab={releaseKeyboardGrab}
onConnected={handleVncConnected}
onCapabilitiesChange={handleVncCapabilitiesChange}
onDesktopResize={setResolution}
onDesktopResize={handleDesktopResize}
onDesktopName={setDesktopTitle}
onBell={handleVncBell}
onFpsChange={handleFpsChange}
@@ -1699,7 +1934,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
onFpsChange={handleFpsChange}
onRequestReleaseGrab={releaseKeyboardGrab}
onConnected={handleRdpConnected}
onDesktopResize={setResolution}
onDesktopResize={handleDesktopResize}
onRemoteClipboardFilesChange={handleRemoteClipboardFilesChange}
onClipboardFileTransferStatus={setClipboardFileTransferStatus}
onClipboardTransferChange={handleClipboardTransferChange}
@@ -24,6 +24,7 @@ import {
History,
Keyboard,
Layers,
Loader2,
Lock,
Maximize,
Maximize2,
@@ -161,6 +162,7 @@ export interface RemoteDesktopToolbarProps {
onOpenAiAuditLog?: () => void;
// Session Recording
isRecording?: boolean;
isStoppingRecording?: boolean;
recordingElapsedLabel?: string;
recordingSupported?: boolean;
onToggleRecording?: () => void;
@@ -682,6 +684,7 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
aiAuditCount = 0,
onOpenAiAuditLog,
isRecording = false,
isStoppingRecording = false,
recordingElapsedLabel = '00:00',
recordingSupported = true,
onToggleRecording,
@@ -1974,23 +1977,34 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
)}
{/* Session Recording Button / Active Pill (P2-B, visible in fullscreen too) */}
{onToggleRecording && (!narrowMode || isRecording) && (
{onToggleRecording && (!narrowMode || isRecording || isStoppingRecording) && (
<Tooltip>
<TooltipTrigger asChild>
{isRecording ? (
{isRecording || isStoppingRecording ? (
<Button
type="button"
variant="ghost"
size="sm"
data-testid="remote-desktop-record-btn"
data-recording="true"
className="h-7 shrink-0 gap-1.5 rounded-md bg-rose-500/12 px-2 text-xs font-medium text-rose-500 hover:bg-rose-500/20"
data-recording={isStoppingRecording ? 'stopping' : 'true'}
disabled={isStoppingRecording}
className="h-7 shrink-0 gap-1.5 rounded-md bg-rose-500/12 px-2 text-xs font-medium text-rose-500 hover:bg-rose-500/20 disabled:opacity-70"
onClick={onToggleRecording}
aria-label={tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')}
>
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-rose-500 animate-pulse" />
<Square size={9} className="fill-current" />
<span className="font-mono text-[11px] font-medium">{recordingElapsedLabel}</span>
{isStoppingRecording ? (
<Loader2 size={11} className="shrink-0 animate-spin" />
) : (
<>
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-rose-500 animate-pulse" />
<Square size={9} className="fill-current" />
</>
)}
<span className="font-mono text-[11px] font-medium">
{isStoppingRecording
? tr(t, 'remoteDesktop.toolbar.savingRecording', 'Saving...')
: recordingElapsedLabel}
</span>
</Button>
) : (
<Button
@@ -2010,9 +2024,11 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
)}
</TooltipTrigger>
<TooltipContent side="bottom" className="text-xs">
{isRecording
? tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')
: tr(t, 'remoteDesktop.toolbar.record', 'Record session')}
{isStoppingRecording
? tr(t, 'remoteDesktop.toolbar.savingRecording', 'Saving...')
: isRecording
? tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')
: tr(t, 'remoteDesktop.toolbar.record', 'Record session')}
</TooltipContent>
</Tooltip>
)}
@@ -2193,15 +2209,17 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
<PopoverClose asChild>
<button
type="button"
disabled={status !== 'connected' || !recordingSupported}
disabled={status !== 'connected' || !recordingSupported || isStoppingRecording}
onClick={onToggleRecording}
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-accent disabled:opacity-45"
>
<Circle size={12} className={isRecording ? 'fill-rose-500 text-rose-500' : 'text-muted-foreground'} />
<span>
{isRecording
? tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')
: tr(t, 'remoteDesktop.toolbar.record', 'Record session')}
{isStoppingRecording
? tr(t, 'remoteDesktop.toolbar.savingRecording', 'Saving...')
: isRecording
? tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')
: tr(t, 'remoteDesktop.toolbar.record', 'Record session')}
</span>
</button>
</PopoverClose>
@@ -31,7 +31,12 @@ import {
type RemoteDesktopCanvasHandle,
type RemoteDesktopDisplayMode,
type RemoteDesktopQualityPreset,
type RemoteDesktopRecordingCaptureHandle,
} from './remoteDesktopHelpers';
import {
captureCanvasThumbnailJpeg,
createStableCanvasCaptureStream,
} from './remoteDesktopVideoCapture';
// VNC Binary WebSocket Opcodes (must match electron/bridges/remoteDesktopBridge.cjs)
const S2C = {
@@ -375,6 +380,12 @@ export const VncCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Vn
return canvasRef.current?.getBoundingClientRect() ?? null;
}, []);
const captureThumbnailJpeg = useCallback(async (): Promise<Uint8Array | null> => {
const canvas = canvasRef.current;
if (!canvas) return null;
return captureCanvasThumbnailJpeg(canvas);
}, []);
const getCaptureStream = useCallback((fps: number): MediaStream | null => {
const canvas = canvasRef.current;
if (!canvas || canvas.width === 0 || canvas.height === 0) return null;
@@ -386,6 +397,15 @@ export const VncCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Vn
}
}, []);
const createRecordingCapture = useCallback(
(fps: number): RemoteDesktopRecordingCaptureHandle | null => {
const canvas = canvasRef.current;
if (!canvas || canvas.width === 0 || canvas.height === 0) return null;
return createStableCanvasCaptureStream(canvas, fps);
},
[],
);
const focusInput = useCallback(() => {
imeInputRef.current?.focus({ preventScroll: true });
}, []);
@@ -673,9 +693,11 @@ export const VncCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Vn
typeText,
releaseAllInputs,
captureScreenshot,
captureThumbnailJpeg,
captureFrame,
getCanvasRect,
getCaptureStream,
createRecordingCapture,
focusInput,
syncClipboardNow,
requestRefresh,
@@ -687,6 +709,8 @@ export const VncCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Vn
[
captureFrame,
captureScreenshot,
captureThumbnailJpeg,
createRecordingCapture,
focusInput,
getCanvasRect,
getCaptureStream,
+222 -41
View File
@@ -31,17 +31,58 @@ function normalizeSampleRate(sampleRate: number): number {
: 48000;
}
/**
* Lightweight linear resampler for 16-bit little-endian PCM when an active
* recording locked the AudioContext sample rate before the first RDPSND wave.
*/
function resamplePcm16(
data: Uint8Array,
channels: 1 | 2,
sourceRate: number,
targetRate: number,
): Uint8Array {
if (sourceRate === targetRate || sourceRate <= 0 || targetRate <= 0) {
const copy = new Uint8Array(data.byteLength);
copy.set(data);
return copy;
}
const srcView = new DataView(data.buffer, data.byteOffset, data.byteLength);
const bytesPerFrame = channels * 2;
const srcFrames = Math.floor(data.byteLength / bytesPerFrame);
if (srcFrames <= 0) return new Uint8Array(0);
const dstFrames = Math.max(1, Math.round((srcFrames * targetRate) / sourceRate));
const out = new Uint8Array(dstFrames * bytesPerFrame);
const dstView = new DataView(out.buffer);
const ratio = srcFrames / dstFrames;
for (let i = 0; i < dstFrames; i += 1) {
const srcPos = i * ratio;
const idx0 = Math.min(srcFrames - 1, Math.floor(srcPos));
const idx1 = Math.min(srcFrames - 1, idx0 + 1);
const frac = srcPos - idx0;
for (let ch = 0; ch < channels; ch += 1) {
const s0 = srcView.getInt16((idx0 * channels + ch) * 2, true);
const s1 = srcView.getInt16((idx1 * channels + ch) * 2, true);
const sample = Math.max(-32768, Math.min(32767, Math.round(s0 + (s1 - s0) * frac)));
dstView.setInt16((i * channels + ch) * 2, sample, true);
}
}
return out;
}
export class RdpAudioPlayer {
private context: AudioContext | null = null;
private workletNode: AudioWorkletNode | null = null;
private captureDest: MediaStreamAudioDestinationNode | null = null;
private keepaliveSource: ConstantSourceNode | null = null;
private keepaliveGain: GainNode | null = null;
private captureRefCount = 0;
private initPromise: Promise<void> | null = null;
private currentSampleRate = 0;
private requestedSampleRate = 0;
private userVolume = 1.0;
private serverVolume = 1.0;
private muted = false;
private disposed = false;
private pendingChunks: Array<{ data: Uint8Array; channels: number }> = [];
private pendingChunks: Array<{ data: Uint8Array; channels: number; sampleRate: number }> = [];
constructor(options?: { muted?: boolean; volume?: number }) {
if (typeof options?.muted === 'boolean') {
@@ -70,71 +111,90 @@ export class RdpAudioPlayer {
if (this.disposed) return;
const targetRate = normalizeSampleRate(sampleRate);
if (this.context && this.workletNode && this.currentSampleRate === targetRate) {
// Once the worklet is live, reuse the existing AudioContext regardless of
// hardware sample-rate differences; `postPcm` resamples when rates differ.
if (this.context && this.workletNode) {
if (this.context.state === 'suspended') {
await this.context.resume().catch(() => {});
}
return;
}
if (this.initPromise && this.currentSampleRate === targetRate) {
if (this.initPromise) {
return this.initPromise;
}
// Tear down any previous AudioContext if sample rate changed, preserving
// freshly queued chunks for the new rate when initializing from scratch.
this.teardownContext({ clearPending: this.currentSampleRate !== 0 && this.currentSampleRate !== targetRate });
this.currentSampleRate = targetRate;
// If a recording already pre-created the AudioContext + captureDest, keep
// it alive so the live MediaRecorder audio track is never severed.
const reusePreCreatedContext = Boolean(this.context && !this.workletNode && this.captureRefCount > 0);
if (!reusePreCreatedContext && this.context && this.requestedSampleRate !== 0 && this.requestedSampleRate !== targetRate) {
this.teardownContext({ clearPending: true });
}
this.requestedSampleRate = targetRate;
this.initPromise = (async () => {
const initTask = (async () => {
if (typeof AudioContext === 'undefined') return;
let ctx: AudioContext;
try {
ctx = new AudioContext({ sampleRate: targetRate, latencyHint: 'interactive' });
} catch {
ctx = new AudioContext({ latencyHint: 'interactive' });
if (reusePreCreatedContext && this.context) {
ctx = this.context;
} else {
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;
}
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);
if (this.context === ctx) {
this.pendingChunks.length = 0;
if (this.context === ctx && this.captureRefCount <= 0) {
this.teardownContext({ clearPending: true });
} else {
} else if (this.context !== ctx) {
await ctx.close().catch(() => {});
}
return;
}
if (this.disposed || this.context !== ctx) {
await ctx.close().catch(() => {});
if (this.context !== ctx) await ctx.close().catch(() => {});
return;
}
let node: AudioWorkletNode;
try {
const bufferSampleRate = normalizeSampleRate(ctx.sampleRate || targetRate);
node = new AudioWorkletNode(ctx, 'rdp-pcm-worklet', {
numberOfInputs: 0,
numberOfOutputs: 1,
outputChannelCount: [2],
processorOptions: {
bufferFrames: Math.max(8192, targetRate),
bufferFrames: Math.max(8192, bufferSampleRate),
},
});
node.connect(ctx.destination);
} catch (err) {
console.warn('[RdpAudioPlayer] Failed to create AudioWorkletNode:', err);
if (this.context === ctx) {
this.pendingChunks.length = 0;
if (this.context === ctx && this.captureRefCount <= 0) {
this.teardownContext({ clearPending: true });
} else {
} else if (this.context !== ctx) {
await ctx.close().catch(() => {});
}
return;
}
if (typeof ctx.createMediaStreamDestination === 'function') {
if (this.captureDest) {
try {
node.connect(this.captureDest);
} catch {
// ignore
}
} else if (typeof ctx.createMediaStreamDestination === 'function') {
try {
const captureDest = ctx.createMediaStreamDestination();
node.connect(captureDest);
@@ -151,25 +211,44 @@ export class RdpAudioPlayer {
// 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);
this.postPcm(item.data, item.channels, item.sampleRate);
}
})();
return this.initPromise;
this.initPromise = initTask;
try {
await initTask;
} finally {
if (this.initPromise === initTask) {
this.initPromise = null;
}
if (!this.workletNode && this.captureRefCount <= 0 && this.context) {
this.teardownContext({ clearPending: true });
}
}
}
private postPcm(data: Uint8Array, channels: number): void {
private postPcm(data: Uint8Array, channels: number, sourceSampleRate?: 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);
const ch: 1 | 2 = channels === 1 ? 1 : 2;
const ctxRate = this.context?.sampleRate || this.requestedSampleRate;
// Copy (or resample when hardware/recording AudioContext rate differs from stream)
// into a dedicated ArrayBuffer so transfer never detaches WASM linear memory.
const prepared = sourceSampleRate && ctxRate && sourceSampleRate !== ctxRate
? resamplePcm16(data, ch, sourceSampleRate, ctxRate)
: (() => {
const copy = new Uint8Array(data.byteLength);
copy.set(data);
return copy;
})();
if (prepared.byteLength === 0) return;
this.workletNode.port.postMessage(
{
type: 'pcm',
channels: channels === 1 ? 1 : 2,
buffer: copy.buffer,
channels: ch,
buffer: prepared.buffer,
},
[copy.buffer],
[prepared.buffer],
);
}
@@ -180,20 +259,17 @@ export class RdpAudioPlayer {
if (!msg.data || msg.data.byteLength === 0) return;
const channels = msg.channels === 1 ? 1 : 2;
const normalizedRate = normalizeSampleRate(msg.sampleRate || 48000);
if (this.workletNode && this.currentSampleRate === normalizedRate) {
if (this.workletNode) {
if (this.context?.state === 'suspended') {
void this.context.resume().catch(() => {});
}
this.postPcm(msg.data, channels);
this.postPcm(msg.data, channels, normalizedRate);
} else {
if (this.currentSampleRate !== 0 && this.currentSampleRate !== normalizedRate) {
this.pendingChunks.length = 0;
}
// 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 });
this.pendingChunks.push({ data: copy, channels, sampleRate: normalizedRate });
}
void this.ensureInitialized(normalizedRate);
}
@@ -247,6 +323,41 @@ export class RdpAudioPlayer {
this.workletNode?.port.postMessage({ type: 'flush' });
}
private stopCaptureKeepalive(): void {
const source = this.keepaliveSource;
const gain = this.keepaliveGain;
this.keepaliveSource = null;
this.keepaliveGain = null;
try { source?.stop(); } catch { /* ignore */ }
try { source?.disconnect(); } catch { /* ignore */ }
try { gain?.disconnect(); } catch { /* ignore */ }
}
private ensureCaptureKeepalive(ctx: AudioContext, dest: MediaStreamAudioDestinationNode): void {
if (this.keepaliveSource) return;
if (typeof ctx.createConstantSource !== 'function' || typeof ctx.createGain !== 'function') {
return;
}
let source: ConstantSourceNode | null = null;
let gain: GainNode | null = null;
try {
source = ctx.createConstantSource();
source.offset.value = 0;
gain = ctx.createGain();
gain.gain.value = 0;
source.connect(gain);
gain.connect(dest);
source.start();
this.keepaliveSource = source;
this.keepaliveGain = gain;
} catch {
try { source?.stop(); } catch { /* ignore */ }
try { source?.disconnect(); } catch { /* ignore */ }
try { gain?.disconnect(); } catch { /* ignore */ }
this.stopCaptureKeepalive();
}
}
/**
* Returns a live `MediaStream` tapping the RDPSND worklet output for session
* recording without disrupting speaker playback. Returns `null` when audio
@@ -266,10 +377,79 @@ export class RdpAudioPlayer {
return this.captureDest?.stream ?? null;
}
/**
* Acquire a live recording audio stream even if the remote desktop has not
* emitted its first audio packet yet. Pair every successful call with
* `releaseCaptureAudioStream()` so idle keepalive nodes and unused contexts
* are immediately torn down once recording stops.
*/
public ensureCaptureAudioStream(): MediaStream | null {
if (this.disposed) return null;
if (typeof AudioContext === 'undefined') return null;
let ctx = this.context;
let createdNewContext = false;
if (!ctx) {
try {
ctx = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });
} catch {
try {
ctx = new AudioContext({ latencyHint: 'interactive' });
} catch {
return null;
}
}
this.context = ctx;
this.requestedSampleRate = normalizeSampleRate(ctx.sampleRate || 48000);
createdNewContext = true;
}
if (!this.captureDest) {
if (typeof ctx.createMediaStreamDestination !== 'function') {
if (createdNewContext) this.teardownContext({ clearPending: false });
return null;
}
try {
const dest = ctx.createMediaStreamDestination();
if (this.workletNode) {
this.workletNode.connect(dest);
}
this.captureDest = dest;
} catch {
this.captureDest = null;
if (createdNewContext) this.teardownContext({ clearPending: false });
return null;
}
}
if (ctx.state === 'suspended') {
void ctx.resume().catch(() => {});
}
this.captureRefCount += 1;
this.ensureCaptureKeepalive(ctx, this.captureDest);
return this.captureDest.stream;
}
/**
* Release a capture hold acquired via `ensureCaptureAudioStream()`. Stops
* silent keepalive nodes immediately, and closes the AudioContext if no
* RDPSND playback worklet was ever needed.
*/
public releaseCaptureAudioStream(): void {
this.captureRefCount = Math.max(0, this.captureRefCount - 1);
if (this.captureRefCount > 0) return;
this.stopCaptureKeepalive();
if (!this.workletNode && !this.initPromise && this.context) {
this.teardownContext({ clearPending: false });
}
}
private teardownContext(options?: { clearPending?: boolean }): void {
if (options?.clearPending !== false) {
this.pendingChunks.length = 0;
}
this.stopCaptureKeepalive();
const node = this.workletNode;
const captureDest = this.captureDest;
const ctx = this.context;
@@ -277,7 +457,7 @@ export class RdpAudioPlayer {
this.captureDest = null;
this.context = null;
this.initPromise = null;
this.currentSampleRate = 0;
this.requestedSampleRate = 0;
try {
node?.port.postMessage({ type: 'reset' });
node?.port.close?.();
@@ -296,6 +476,7 @@ export class RdpAudioPlayer {
public dispose(): void {
if (this.disposed) return;
this.disposed = true;
this.captureRefCount = 0;
this.teardownContext({ clearPending: true });
}
}
@@ -67,11 +67,19 @@ export interface RemoteDesktopClipboardTransferState {
error?: string;
}
export interface RemoteDesktopRecordingCaptureHandle {
stream: MediaStream;
width: number;
height: number;
dispose: () => void;
}
export interface RemoteDesktopCanvasHandle {
sendSpecialKey: (id: RemoteDesktopSpecialKeyId) => void;
typeText: (text: string) => void;
releaseAllInputs: () => void;
captureScreenshot: () => Promise<Blob | null>;
captureThumbnailJpeg?: () => Promise<Uint8Array | null>;
captureFrame?: (
options?: RemoteDesktopCaptureRequest & {
maxWidth?: number;
@@ -83,6 +91,10 @@ export interface RemoteDesktopCanvasHandle {
) => Promise<RemoteDesktopProviderFrame | null> | RemoteDesktopProviderFrame | null;
getCanvasRect?: () => DOMRect | null;
getCaptureStream?: (fps: number, includeAudio?: boolean) => MediaStream | null;
createRecordingCapture?: (
fps: number,
includeAudio?: boolean,
) => RemoteDesktopRecordingCaptureHandle | null;
focusInput?: () => void;
syncClipboardNow?: () => Promise<void> | void;
requestRefresh?: () => void;
@@ -0,0 +1,29 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
computeAspectFitRect,
computeRecordingCanvasDimensions,
} from './remoteDesktopVideoCapture';
test('computeRecordingCanvasDimensions caps 4K/HiDPI canvases at even-aligned 1080p', () => {
assert.deepEqual(computeRecordingCanvasDimensions(3840, 2160), { width: 1920, height: 1080 });
assert.deepEqual(computeRecordingCanvasDimensions(1920, 1080), { width: 1920, height: 1080 });
assert.deepEqual(computeRecordingCanvasDimensions(1281, 721), { width: 1280, height: 720 });
assert.deepEqual(computeRecordingCanvasDimensions(2560, 1600), { width: 1728, height: 1080 });
});
test('computeAspectFitRect letterboxes resized source cleanly inside fixed recording canvas', () => {
assert.deepEqual(computeAspectFitRect(1920, 1080, 1920, 1080), {
dx: 0,
dy: 0,
dw: 1920,
dh: 1080,
});
// Square source inside 16:9 target -> centered horizontally
assert.deepEqual(computeAspectFitRect(1000, 1000, 1920, 1080), {
dx: 420,
dy: 0,
dw: 1080,
dh: 1080,
});
});
@@ -0,0 +1,271 @@
import type { RemoteDesktopRecordingCaptureHandle } from './remoteDesktopHelpers';
export const MAX_RECORDING_VIDEO_WIDTH = 1920;
export const MAX_RECORDING_VIDEO_HEIGHT = 1080;
export const DEFAULT_THUMBNAIL_MAX_WIDTH = 320;
export const DEFAULT_THUMBNAIL_MAX_HEIGHT = 240;
export const DEFAULT_THUMBNAIL_JPEG_QUALITY = 0.72;
/**
* Compute even-aligned output dimensions capped within `maxWidth x maxHeight`
* while preserving the source aspect ratio. Capping at 1080p avoids burning
* 4x GPU/CPU/RAM when recording HiDPI / 4K remote desktop canvases in Electron.
*/
export function computeRecordingCanvasDimensions(
sourceWidth: number,
sourceHeight: number,
maxWidth = MAX_RECORDING_VIDEO_WIDTH,
maxHeight = MAX_RECORDING_VIDEO_HEIGHT,
): { width: number; height: number } {
const safeW = Number.isFinite(sourceWidth) && sourceWidth > 0 ? Math.floor(sourceWidth) : 1280;
const safeH = Number.isFinite(sourceHeight) && sourceHeight > 0 ? Math.floor(sourceHeight) : 720;
const scale = Math.min(1, maxWidth / safeW, maxHeight / safeH);
const rawW = Math.max(2, Math.floor(safeW * scale));
const rawH = Math.max(2, Math.floor(safeH * scale));
return {
width: rawW - (rawW % 2),
height: rawH - (rawH % 2),
};
}
/**
* Compute aspect-fit destination rectangle for blitting a (potentially resized)
* source canvas onto a fixed-size recording staging canvas.
*/
export function computeAspectFitRect(
sourceWidth: number,
sourceHeight: number,
targetWidth: number,
targetHeight: number,
): { dx: number; dy: number; dw: number; dh: number } {
if (sourceWidth <= 0 || sourceHeight <= 0 || targetWidth <= 0 || targetHeight <= 0) {
return { dx: 0, dy: 0, dw: Math.max(0, targetWidth), dh: Math.max(0, targetHeight) };
}
const scale = Math.min(targetWidth / sourceWidth, targetHeight / sourceHeight);
const dw = Math.max(1, Math.round(sourceWidth * scale));
const dh = Math.max(1, Math.round(sourceHeight * scale));
const dx = Math.floor((targetWidth - dw) / 2);
const dy = Math.floor((targetHeight - dh) / 2);
return { dx, dy, dw, dh };
}
/**
* Create a resize-safe, fixed-cadence recording capture handle backed by an
* offscreen staging `<canvas>`.
*
* Why a staging canvas instead of direct `sourceCanvas.captureStream(fps)`:
* 1. Dynamic RDP resize mutates `sourceCanvas.width`/`height` mid-session,
* which can break Chromium's VP8/VP9 MediaRecorder or corrupt keyframes.
* 2. Capping to <= 1080p keeps Electron memory & encoder CPU bounded on 4K/HiDPI.
* 3. Blitting frame 0 synchronously guarantees non-empty recordings even when
* the remote desktop is completely idle/static.
* 4. `dispose()` explicitly stops intervals, stops all MediaStreamTracks,
* releases audio keepalive, and zeroes `stagingCanvas.width/height` so
* Skia/GPU backing memory is freed immediately.
*/
export function createStableCanvasCaptureStream(
sourceCanvas: HTMLCanvasElement,
fps: number,
options?: {
audioStream?: MediaStream | null;
onReleaseAudio?: () => void;
maxWidth?: number;
maxHeight?: number;
},
): RemoteDesktopRecordingCaptureHandle | null {
if (!sourceCanvas || sourceCanvas.width <= 0 || sourceCanvas.height <= 0 || typeof document === 'undefined') {
options?.onReleaseAudio?.();
return null;
}
const stagingCanvas = document.createElement('canvas');
if (typeof stagingCanvas.captureStream !== 'function') {
options?.onReleaseAudio?.();
return null;
}
const { width, height } = computeRecordingCanvasDimensions(
sourceCanvas.width,
sourceCanvas.height,
options?.maxWidth,
options?.maxHeight,
);
stagingCanvas.width = width;
stagingCanvas.height = height;
const ctx = stagingCanvas.getContext('2d', { alpha: false });
if (!ctx) {
stagingCanvas.width = 0;
stagingCanvas.height = 0;
options?.onReleaseAudio?.();
return null;
}
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'medium';
let lastSrcW = 0;
let lastSrcH = 0;
let disposed = false;
const drawCurrentFrame = () => {
if (disposed) return;
const sw = sourceCanvas.width;
const sh = sourceCanvas.height;
if (sw <= 0 || sh <= 0) return;
try {
if (sw === width && sh === height) {
ctx.drawImage(sourceCanvas, 0, 0, width, height);
lastSrcW = sw;
lastSrcH = sh;
return;
}
const { dx, dy, dw, dh } = computeAspectFitRect(sw, sh, width, height);
// Clear letterbox bars whenever source dimensions change and do not fill target completely.
if ((dx > 0 || dy > 0 || dw < width || dh < height) && (sw !== lastSrcW || sh !== lastSrcH)) {
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, width, height);
}
ctx.drawImage(sourceCanvas, 0, 0, sw, sh, dx, dy, dw, dh);
lastSrcW = sw;
lastSrcH = sh;
} catch {
// Source canvas may be mid-resize or detached; skip this tick safely.
}
};
// Paint frame 0 immediately so static desktops produce valid keyframes.
drawCurrentFrame();
const safeFps = Number.isFinite(fps) && fps > 0 ? Math.min(30, Math.max(1, fps)) : 10;
let videoStream: MediaStream;
try {
videoStream = stagingCanvas.captureStream(safeFps);
} catch {
stagingCanvas.width = 0;
stagingCanvas.height = 0;
options?.onReleaseAudio?.();
return null;
}
const clonedAudioTracks: MediaStreamTrack[] = [];
const attachedAudioTracks: MediaStreamTrack[] = [];
let outputStream: MediaStream = videoStream;
const sourceAudioTracks = options?.audioStream?.getAudioTracks?.() ?? [];
if (sourceAudioTracks.length > 0 && typeof MediaStream !== 'undefined') {
for (const track of sourceAudioTracks) {
try {
if (typeof track.clone === 'function') {
const cloned = track.clone();
clonedAudioTracks.push(cloned);
attachedAudioTracks.push(cloned);
} else {
attachedAudioTracks.push(track);
}
} catch {
// Ignore unusable audio track
}
}
if (attachedAudioTracks.length > 0) {
try {
outputStream = new MediaStream([...videoStream.getVideoTracks(), ...attachedAudioTracks]);
} catch {
for (const track of clonedAudioTracks) {
try { track.stop(); } catch { /* ignore */ }
}
clonedAudioTracks.length = 0;
outputStream = videoStream;
}
}
}
const intervalMs = Math.max(33, Math.round(1000 / safeFps));
const timerId = window.setInterval(drawCurrentFrame, intervalMs);
const dispose = () => {
if (disposed) return;
disposed = true;
window.clearInterval(timerId);
try {
// Stop only tracks owned by this capture (staging video tracks + cloned audio tracks),
// never a shared audio destination track if clone() was unavailable.
for (const track of videoStream.getTracks()) {
try { track.stop(); } catch { /* ignore */ }
}
for (const track of clonedAudioTracks) {
try { track.stop(); } catch { /* ignore */ }
}
} catch {
// ignore
}
// Immediately release Chromium/Skia GPU backing texture.
try {
stagingCanvas.width = 0;
stagingCanvas.height = 0;
} catch {
// ignore
}
try {
options?.onReleaseAudio?.();
} catch {
// ignore
}
};
return {
stream: outputStream,
width,
height,
dispose,
};
}
/**
* Capture a compact JPEG thumbnail (<= 320px wide) from a remote desktop
* canvas, freeing the temporary canvas GPU buffer immediately in `finally`.
*/
export async function captureCanvasThumbnailJpeg(
sourceCanvas: HTMLCanvasElement,
options?: { maxWidth?: number; maxHeight?: number; quality?: number },
): Promise<Uint8Array | null> {
if (!sourceCanvas || sourceCanvas.width <= 0 || sourceCanvas.height <= 0) return null;
if (typeof document === 'undefined') return null;
const maxWidth = options?.maxWidth ?? DEFAULT_THUMBNAIL_MAX_WIDTH;
const maxHeight = options?.maxHeight ?? DEFAULT_THUMBNAIL_MAX_HEIGHT;
const quality = options?.quality ?? DEFAULT_THUMBNAIL_JPEG_QUALITY;
const scale = Math.min(1, maxWidth / sourceCanvas.width, maxHeight / sourceCanvas.height);
const w = Math.max(2, Math.round(sourceCanvas.width * scale));
const h = Math.max(2, Math.round(sourceCanvas.height * scale));
const thumbCanvas = document.createElement('canvas');
thumbCanvas.width = w;
thumbCanvas.height = h;
try {
const ctx = thumbCanvas.getContext('2d', { alpha: false });
if (!ctx) return null;
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'medium';
ctx.drawImage(sourceCanvas, 0, 0, sourceCanvas.width, sourceCanvas.height, 0, 0, w, h);
const blob = await new Promise<Blob | null>((resolve) => {
try {
thumbCanvas.toBlob((result) => resolve(result), 'image/jpeg', quality);
} catch {
resolve(null);
}
});
if (!blob || blob.size === 0) return null;
const buffer = await blob.arrayBuffer();
return new Uint8Array(buffer);
} catch {
return null;
} finally {
// Free GPU texture immediately without waiting for GC.
try {
thumbCanvas.width = 0;
thumbCanvas.height = 0;
} catch {
// ignore
}
}
}
@@ -400,3 +400,135 @@ test('useRemoteDesktopRecorder aborts cleanly when chunk append fails', async ()
env.restore();
}
});
test('useRemoteDesktopRecorder preserves multiple clips, captures thumbnails, disposes capture, and flushes on app shutdown', async () => {
const env = installDomEnv();
FakeMediaRecorder.instances = [];
Object.defineProperty(globalThis, 'MediaRecorder', { value: FakeMediaRecorder, configurable: true });
const finalizers = new Set<() => void | Promise<void>>();
let finalizerUnsubscribed = false;
(globalThis.window as unknown as Record<string, unknown>).netcatty = {
onFinalizeSessionLogs: (fn: () => void | Promise<void>) => {
finalizers.add(fn);
return () => {
finalizerUnsubscribed = true;
finalizers.delete(fn);
};
},
};
let currentLog: ConnectionLog = {
id: 'log-multi-rdp',
sessionId: 'sess-multi',
hostId: 'h1',
hostLabel: 'Win Multi',
hostname: '10.0.0.9',
username: 'Administrator',
protocol: 'rdp',
startTime: 10_000,
localUsername: 'u',
localHostname: 'l',
saved: false,
};
publishConnectionLogsSnapshot({ connectionLogs: [currentLog] });
registerConnectionLogsActions({
updateConnectionLog: (_id, updates) => {
currentLog = { ...currentLog, ...updates };
publishConnectionLogsSnapshot({ connectionLogs: [currentLog] });
},
toggleConnectionLogSaved: () => {},
deleteConnectionLog: () => {},
clearUnsavedConnectionLogs: () => {},
});
let nextId = 0;
const savedThumbs: string[] = [];
const { bridge } = createFakeBridge({
begin: async () => ({ recordingId: `11111111-1111-4111-8111-11111111111${++nextId}` }),
saveThumbnail: async (opts) => {
savedThumbs.push(opts.id || '');
return { ok: true, id: opts.id, bytes: opts.data.byteLength };
},
});
let disposeCount = 0;
let recorderApi!: UseRemoteDesktopRecorderResult;
let root: ReactTestRenderer | undefined;
function Harness() {
const canvasRef = useRef<RemoteDesktopCanvasHandle | null>({
sendSpecialKey: () => {},
typeText: () => {},
releaseAllInputs: () => {},
captureScreenshot: async () => null,
captureThumbnailJpeg: async () => new Uint8Array([0xff, 0xd8, 0xff, 0xd9]),
createRecordingCapture: () => {
const fake = createFakeStream(false);
return {
stream: fake.stream,
width: 1920,
height: 1080,
dispose: () => {
disposeCount += 1;
fake.stream.getTracks().forEach((track) => track.stop());
},
};
},
});
recorderApi = useRemoteDesktopRecorder({
sessionId: 'sess-multi',
protocol: 'rdp',
hostLabel: 'Win Multi',
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),
}),
);
});
// Clip 1: manual start + stop
await act(async () => {
await recorderApi.startRecording({ silent: true });
FakeMediaRecorder.instances[0].emitChunk(new Uint8Array([1, 2, 3]));
await recorderApi.stopRecording({ silent: true });
});
assert.equal(currentLog.recordings?.length, 1);
assert.equal(currentLog.recordings?.[0].hasThumbnail, true);
assert.equal(currentLog.recordings?.[0].width, 1920);
assert.equal(savedThumbs.length, 1);
// Clip 2: start then flush via app shutdown finalizer (onFinalizeSessionLogs)
await act(async () => {
await recorderApi.startRecording({ silent: true });
FakeMediaRecorder.instances[1].emitChunk(new Uint8Array([4, 5, 6, 7]));
for (const fn of finalizers) {
await fn();
}
});
assert.equal(recorderApi.isRecording, false);
assert.equal(currentLog.recordings?.length, 2);
assert.equal(currentLog.recordings?.[0].id, '11111111-1111-4111-8111-111111111111');
assert.equal(currentLog.recordings?.[1].id, '11111111-1111-4111-8111-111111111112');
assert.ok(disposeCount >= 2, 'capture dispose() should run for every clip');
} finally {
await act(async () => { root?.unmount(); });
assert.equal(finalizerUnsubscribed, true, 'shutdown finalizer listener must unsubscribe on unmount');
registerConnectionLogsActions(null);
publishConnectionLogsSnapshot({ connectionLogs: [] });
env.restore();
}
});
@@ -1,10 +1,11 @@
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';
appendRemoteDesktopClipToConnectionLog,
collectProtectedRemoteDesktopMediaIds,
getRemoteDesktopRecordingsBridge,
registerSessionLogFinalizer,
} from '../../application/state/remoteDesktopLogActions';
import type { RemoteDesktopProtocol } from '../../domain/remoteDesktop';
import {
STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD,
@@ -16,14 +17,21 @@ import {
import { toast } from '../ui/toast';
import {
formatRecordingDuration,
formatTransferBytes,
tr,
type RemoteDesktopCanvasHandle,
type RemoteDesktopRecordingCaptureHandle,
} 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';
// Cap in-flight IPC chunk bytes in renderer RAM so stalled disk I/O never OOMs Electron.
const MAX_PENDING_IPC_BYTES = 32 * 1024 * 1024;
const CHUNK_TIMESLICE_MS = 2000;
const STOP_WAIT_TIMEOUT_MS = 5000;
export interface RemoteDesktopRecordingsApi {
begin(options: {
mimeType?: string;
@@ -48,6 +56,10 @@ export interface RemoteDesktopRecordingsApi {
playbackUrl: string;
}>;
abort(options: { recordingId: string }): Promise<{ ok: boolean }>;
saveThumbnail?(options: {
id?: string;
data: Uint8Array;
}): Promise<{ ok: boolean; id?: string; url?: string; bytes?: number }>;
}
function readStorageString(key: string): string | null {
@@ -59,14 +71,6 @@ function readStorageString(key: string): string | 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;
@@ -157,39 +161,6 @@ export function readRemoteDesktopRecordingSettings(): RemoteDesktopRecordingSett
};
}
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;
@@ -198,6 +169,12 @@ export interface UseRemoteDesktopRecorderOptions {
audioEnabled: boolean;
canvasHandleRef: React.RefObject<RemoteDesktopCanvasHandle | null>;
recordingsBridgeOverride?: RemoteDesktopRecordingsApi | null;
onRecordingLifecycleEvent?: (event: {
kind: 'recording_started' | 'recording_stopped';
timestamp: number;
summary: string;
detail?: string;
}) => void;
}
export interface UseRemoteDesktopRecorderResult {
@@ -215,19 +192,51 @@ interface ActiveRecordingRun {
recordingId: string;
mimeType: string;
hasAudio: boolean;
width?: number;
height?: number;
startedAt: number;
recorder: MediaRecorder;
stream: MediaStream;
disposeCapture: () => void;
thumbnailPromise: Promise<boolean>;
appendChain: Promise<void>;
appendError: Error | null;
bytesQueued: number;
pendingIpcBytes: number;
stopPromise: Promise<void> | null;
aborted: boolean;
settings: RemoteDesktopRecordingSettings;
}
const CHUNK_TIMESLICE_MS = 2000;
const STOP_WAIT_TIMEOUT_MS = 5000;
function acquireCanvasCapture(
handle: RemoteDesktopCanvasHandle | null,
fps: number,
wantAudio: boolean,
): RemoteDesktopRecordingCaptureHandle | null {
if (!handle) return null;
if (typeof handle.createRecordingCapture === 'function') {
return handle.createRecordingCapture(fps, wantAudio);
}
const stream = handle.getCaptureStream?.(fps, wantAudio) ?? null;
if (!stream) return null;
let disposed = false;
return {
stream,
width: 0,
height: 0,
dispose: () => {
if (disposed) return;
disposed = true;
try {
for (const track of stream.getTracks()) {
track.stop();
}
} catch {
// ignore
}
},
};
}
export function useRemoteDesktopRecorder({
sessionId,
@@ -237,6 +246,7 @@ export function useRemoteDesktopRecorder({
audioEnabled,
canvasHandleRef,
recordingsBridgeOverride,
onRecordingLifecycleEvent,
}: UseRemoteDesktopRecorderOptions): UseRemoteDesktopRecorderResult {
const { t } = useI18n();
const [settings, setSettings] = useState<RemoteDesktopRecordingSettings>(readRemoteDesktopRecordingSettings);
@@ -247,12 +257,28 @@ export function useRemoteDesktopRecorder({
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 latestMetaRef = useRef({
sessionId,
protocol,
hostLabel,
status,
audioEnabled,
settings,
onRecordingLifecycleEvent,
});
latestMetaRef.current = {
sessionId,
protocol,
hostLabel,
status,
audioEnabled,
settings,
onRecordingLifecycleEvent,
};
const getBridge = useCallback((): RemoteDesktopRecordingsApi | null => {
if (recordingsBridgeOverride !== undefined) return recordingsBridgeOverride;
return getWindowRecordingsBridge();
return getRemoteDesktopRecordingsBridge();
}, [recordingsBridgeOverride]);
const isSupported = typeof MediaRecorder !== 'undefined' && Boolean(getBridge());
@@ -301,16 +327,6 @@ export function useRemoteDesktopRecorder({
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;
@@ -359,10 +375,14 @@ export function useRemoteDesktopRecorder({
run.recorder.ondataavailable = null;
run.recorder.onerror = null;
stopStreamTracks(run.stream);
await run.appendChain.catch(() => {});
run.disposeCapture();
await Promise.all([
run.appendChain.catch(() => {}),
run.thumbnailPromise.catch(() => false),
]);
const durationMs = Math.max(1, Date.now() - run.startedAt);
const endedAt = Date.now();
const durationMs = Math.max(1, endedAt - run.startedAt);
if (!bridge) return;
if (run.aborted || run.appendError || run.bytesQueued <= 0) {
@@ -374,21 +394,36 @@ export function useRemoteDesktopRecorder({
}
try {
const hasThumbnail = await run.thumbnailPromise.catch(() => false);
const finished = await bridge.finish({
recordingId: run.recordingId,
durationMs,
hasAudio: run.hasAudio,
maxBytes: run.settings.maxMb * 1024 * 1024,
retentionDays: run.settings.retentionDays,
protectedIds: collectProtectedRecordingIds(),
protectedIds: collectProtectedRemoteDesktopMediaIds(),
});
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() } : {}),
const finalDurationMs = finished.durationMs ?? durationMs;
await appendRemoteDesktopClipToConnectionLog(
latestMetaRef.current.sessionId,
{
id: finished.recordingId,
startedAt: run.startedAt,
endedAt,
durationMs: finalDurationMs,
bytes: finished.bytes,
mimeType: run.mimeType || 'video/webm',
hasAudio: run.hasAudio,
...(hasThumbnail ? { hasThumbnail: true } : {}),
...(run.width && run.height ? { width: run.width, height: run.height } : {}),
},
{ stampEndTime: options?.stampEndTime },
);
latestMetaRef.current.onRecordingLifecycleEvent?.({
kind: 'recording_stopped',
timestamp: endedAt,
summary: 'Recording saved',
detail: `${formatRecordingDuration(finalDurationMs)} \u00b7 ${formatTransferBytes(finished.bytes)}${run.hasAudio ? ' \u00b7 Audio' : ''}`,
});
if (!options?.silent) {
toast.success(
@@ -402,6 +437,8 @@ export function useRemoteDesktopRecorder({
}
}
} finally {
// Ensure capture is always disposed even on unexpected throw.
run.disposeCapture();
if (activeRunRef.current === run) {
activeRunRef.current = null;
}
@@ -446,9 +483,9 @@ export function useRemoteDesktopRecorder({
startingRef.current = true;
try {
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 (stream) stopStreamTracks(stream);
const capture = acquireCanvasCapture(canvasHandleRef.current, meta.settings.fps, wantAudio);
if (!capture || capture.stream.getVideoTracks().length === 0) {
capture?.dispose();
if (!options?.silent) {
toast.error(
tr(
@@ -461,7 +498,7 @@ export function useRemoteDesktopRecorder({
return false;
}
const hasAudio = stream.getAudioTracks().length > 0;
const hasAudio = capture.stream.getAudioTracks().length > 0;
const mimeType = pickRemoteDesktopRecordingMimeType(hasAudio);
const videoBitsPerSecond = resolveRecordingVideoBitsPerSecond(meta.settings.fps);
@@ -474,7 +511,7 @@ export function useRemoteDesktopRecorder({
});
recordingId = begun.recordingId;
} catch {
stopStreamTracks(stream);
capture.dispose();
if (!options?.silent) {
toast.error(tr(t, 'remoteDesktop.recording.failed', 'Session recording failed'));
}
@@ -483,7 +520,7 @@ export function useRemoteDesktopRecorder({
// Guard against unmount or disconnect while awaiting bridge.begin()
if (!mountedRef.current || latestMetaRef.current.status !== 'connected') {
stopStreamTracks(stream);
capture.dispose();
await bridge.abort({ recordingId }).catch(() => {});
return false;
}
@@ -492,9 +529,9 @@ export function useRemoteDesktopRecorder({
try {
const recorderOptions: MediaRecorderOptions = { videoBitsPerSecond };
if (mimeType) recorderOptions.mimeType = mimeType;
recorder = new MediaRecorder(stream, recorderOptions);
recorder = new MediaRecorder(capture.stream, recorderOptions);
} catch {
stopStreamTracks(stream);
capture.dispose();
await bridge.abort({ recordingId }).catch(() => {});
if (!options?.silent) {
toast.error(tr(t, 'remoteDesktop.recording.failed', 'Session recording failed'));
@@ -502,16 +539,22 @@ export function useRemoteDesktopRecorder({
return false;
}
const startedAt = Date.now();
const run: ActiveRecordingRun = {
recordingId,
mimeType: recorder.mimeType || mimeType || 'video/webm',
hasAudio,
startedAt: Date.now(),
width: capture.width || undefined,
height: capture.height || undefined,
startedAt,
recorder,
stream,
stream: capture.stream,
disposeCapture: capture.dispose,
thumbnailPromise: Promise.resolve(false),
appendChain: Promise.resolve(),
appendError: null,
bytesQueued: 0,
pendingIpcBytes: 0,
stopPromise: null,
aborted: false,
settings: meta.settings,
@@ -521,10 +564,18 @@ export function useRemoteDesktopRecorder({
recorder.ondataavailable = (ev: BlobEvent) => {
if (!ev.data || ev.data.size <= 0 || run.aborted) return;
const blob = ev.data;
run.bytesQueued += blob.size;
const chunkSize = blob.size;
if (run.pendingIpcBytes + chunkSize > MAX_PENDING_IPC_BYTES) {
run.appendError = new Error('Recording write queue exceeded memory limit');
run.aborted = true;
void stopRecordingRef.current({ silent: false });
return;
}
run.bytesQueued += chunkSize;
run.pendingIpcBytes += chunkSize;
run.appendChain = run.appendChain.then(async () => {
if (run.aborted) return;
try {
if (run.aborted) return;
const buffer = await blob.arrayBuffer();
if (run.aborted) return;
await bridge.append({
@@ -535,6 +586,8 @@ export function useRemoteDesktopRecorder({
run.appendError = err instanceof Error ? err : new Error(String(err));
run.aborted = true;
void stopRecordingRef.current({ silent: false });
} finally {
run.pendingIpcBytes = Math.max(0, run.pendingIpcBytes - chunkSize);
}
});
};
@@ -553,7 +606,7 @@ export function useRemoteDesktopRecorder({
activeRunRef.current = null;
recorder.ondataavailable = null;
recorder.onerror = null;
stopStreamTracks(stream);
capture.dispose();
await bridge.abort({ recordingId }).catch(() => {});
if (!options?.silent) {
toast.error(tr(t, 'remoteDesktop.recording.failed', 'Session recording failed'));
@@ -561,6 +614,29 @@ export function useRemoteDesktopRecorder({
return false;
}
// Capture a tiny JPEG poster thumbnail only after MediaRecorder.start() succeeds
// so failed starts can never race abort() and leave an orphan thumbnail file.
run.thumbnailPromise = (async () => {
if (!bridge.saveThumbnail || !canvasHandleRef.current?.captureThumbnailJpeg) {
return false;
}
try {
const jpeg = await canvasHandleRef.current.captureThumbnailJpeg();
if (!jpeg || jpeg.byteLength === 0 || run.aborted) return false;
const res = await bridge.saveThumbnail({ id: recordingId, data: jpeg });
return Boolean(res?.ok);
} catch {
return false;
}
})();
latestMetaRef.current.onRecordingLifecycleEvent?.({
kind: 'recording_started',
timestamp: startedAt,
summary: 'Recording started',
detail: `${meta.settings.fps} FPS${hasAudio ? ' \u00b7 Audio' : ''}`,
});
if (mountedRef.current) {
setIsRecording(true);
setElapsedMs(0);
@@ -584,6 +660,16 @@ export function useRemoteDesktopRecorder({
}
}, [startRecording, stopRecording]);
// Flush active recordings gracefully before window close / app quit
// so main-process shutdown cleanupAll() never discards an in-progress .webm.part.
useEffect(() => {
return registerSessionLogFinalizer(async () => {
if (activeRunRef.current) {
await stopRecordingRef.current({ stampEndTime: true, silent: true });
}
});
}, []);
// Auto-record once per connection when enabled in settings
useEffect(() => {
if (status === 'connected') {
@@ -9,6 +9,7 @@ import {
SystemRdpClientIcon,
} from "../../icons/RemoteDesktopIcons";
import { useI18n } from "../../../application/i18n/I18nProvider";
import { clearAllRemoteDesktopRecordingsAndSyncLogs } from "../../../application/state/remoteDesktopLogActions";
import type { AppLockSystemUnlockStatus } from "../../../application/state/useAppLockState";
import type { AppLockSettings, AppLockSettingsChangeError, AppLockTimeoutMinutes } from "../../../domain/appLock";
import { getCredentialProtectionAvailability } from "../../../infrastructure/services/credentialProtection";
@@ -390,13 +391,11 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
}, []);
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);
const res = await clearAllRemoteDesktopRecordingsAndSyncLogs();
setRecordingsClearDeletedCount(res.deleted);
setClearRecordingsConfirmOpen(false);
await loadRecordingStats();
} catch (err) {
+48 -1
View File
@@ -37,6 +37,50 @@ export interface RemoteHistoryEntry {
timestamp?: number; // Only set when the history file carries one (zsh EXTENDED_HISTORY, fish `when`)
}
export interface RemoteDesktopRecordingClip {
id: string; // UUID referencing <userData>/recordings/<id>.webm
startedAt: number; // Wall-clock ms when recording started
endedAt: number; // Wall-clock ms when recording ended
durationMs: number; // Finalized clip duration in milliseconds
bytes: number; // Finalized clip file size in bytes
mimeType: string; // e.g. 'video/webm;codecs=vp9,opus'
hasAudio: boolean; // Whether an audio track was merged into the clip
hasThumbnail?: boolean; // Whether <id>.jpg exists on disk (never inline base64)
width?: number; // Recorded video frame width in pixels
height?: number; // Recorded video frame height in pixels
}
export type RemoteDesktopSessionEventKind =
| 'connected'
| 'reconnected'
| 'disconnected'
| 'resized'
| 'clipboard_upload'
| 'clipboard_download'
| 'shared_folder_mounted'
| 'shared_folder_unmounted'
| 'screenshot'
| 'recording_started'
| 'recording_stopped'
| 'error';
export interface RemoteDesktopSessionEvent {
id: string;
timestamp: number;
kind: RemoteDesktopSessionEventKind;
summary: string;
detail?: string;
}
export interface RemoteDesktopSessionMetadata {
resolution?: { width: number; height: number };
securityLabel?: string; // e.g. 'TLS / NLA', 'TLS', 'RC4-128', 'RFB'
tunneled?: boolean;
monitorCount?: number;
disconnectReason?: string;
thumbnailId?: string; // UUID referencing <userData>/recordings/<id>.jpg for unrecorded sessions
}
// Connection Log - records connection history
export interface ConnectionLog {
id: string;
@@ -61,11 +105,14 @@ export interface ConnectionLog {
terminalData?: string; // Captured terminal output data for replay
themeId?: string; // Terminal theme ID for this log view
fontSize?: number; // Terminal font size for this log view
recordingId?: string; // UUID referencing <userData>/recordings/<id>.webm (never inline bytes)
recordingId?: string; // UUID referencing <userData>/recordings/<id>.webm (legacy / latest clip mirror)
recordingMimeType?: string; // e.g. 'video/webm;codecs=vp9,opus'
recordingDurationMs?: number; // Finalized recording duration in milliseconds
recordingBytes?: number; // Finalized recording file size in bytes
recordingHasAudio?: boolean; // Whether an audio track was merged into the recording
recordings?: RemoteDesktopRecordingClip[]; // Multi-clip recordings for a single RDP/VNC session
remoteDesktopMeta?: RemoteDesktopSessionMetadata; // Structured RDP/VNC connection summary
remoteDesktopEvents?: RemoteDesktopSessionEvent[]; // Bounded chronological session activity timeline
}
// Session Logs Settings - for auto-saving terminal logs to local filesystem
+248
View File
@@ -0,0 +1,248 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import type { ConnectionLog, RemoteDesktopRecordingClip } from './models/history';
import {
MAX_REMOTE_DESKTOP_SESSION_EVENTS,
appendRemoteDesktopSessionEvent,
buildAppendRecordingClipUpdate,
buildClearRecordingsUpdate,
buildRemoveRecordingClipUpdate,
findRecordingSeekTargetForEvent,
getConnectionLogMediaIds,
getConnectionLogRecordingClips,
getConnectionLogRecordingSummary,
mergeRemoteDesktopSessionMetadata,
resolveVideoSeekSecondsForEvent,
} from './remoteDesktopRecording';
function makeBaseLog(overrides: Partial<ConnectionLog> = {}): ConnectionLog {
return {
id: 'log-1',
sessionId: 'sess-1',
hostId: 'h-1',
hostLabel: 'Win Prod',
hostname: '10.0.0.10',
username: 'Administrator',
protocol: 'rdp',
startTime: 1_700_000_000_000,
localUsername: 'alice',
localHostname: 'macbook',
saved: false,
...overrides,
};
}
test('getConnectionLogRecordingClips upgrades legacy single recordingId seamlessly', () => {
const legacy = makeBaseLog({
endTime: 1_700_000_060_000,
recordingId: '11111111-1111-4111-8111-111111111111',
recordingMimeType: 'video/webm;codecs=vp9',
recordingDurationMs: 45_000,
recordingBytes: 2_000_000,
recordingHasAudio: true,
});
const clips = getConnectionLogRecordingClips(legacy);
assert.equal(clips.length, 1);
assert.equal(clips[0].id, '11111111-1111-4111-8111-111111111111');
assert.equal(clips[0].durationMs, 45_000);
assert.equal(clips[0].bytes, 2_000_000);
assert.equal(clips[0].hasAudio, true);
assert.equal(clips[0].startedAt, 1_700_000_015_000);
assert.equal(clips[0].endedAt, 1_700_000_060_000);
});
test('multi-clip append and remove preserve earlier clips and keep legacy mirror fields accurate', () => {
const clip1: RemoteDesktopRecordingClip = {
id: '11111111-1111-4111-8111-111111111111',
startedAt: 1_700_000_010_000,
endedAt: 1_700_000_030_000,
durationMs: 20_000,
bytes: 1_000_000,
mimeType: 'video/webm;codecs=vp9',
hasAudio: false,
hasThumbnail: true,
width: 1920,
height: 1080,
};
const clip2: RemoteDesktopRecordingClip = {
id: '22222222-2222-4222-8222-222222222222',
startedAt: 1_700_000_050_000,
endedAt: 1_700_000_090_000,
durationMs: 40_000,
bytes: 2_500_000,
mimeType: 'video/webm;codecs=vp9,opus',
hasAudio: true,
hasThumbnail: true,
width: 1920,
height: 1080,
};
let log = makeBaseLog();
log = { ...log, ...buildAppendRecordingClipUpdate(log, clip1) };
assert.equal(log.recordingId, clip1.id);
assert.equal(log.recordings?.length, 1);
log = { ...log, ...buildAppendRecordingClipUpdate(log, clip2) };
assert.equal(log.recordings?.length, 2);
assert.equal(log.recordingId, clip2.id);
assert.equal(log.recordingDurationMs, 60_000);
assert.equal(log.recordingBytes, 3_500_000);
assert.equal(log.recordingHasAudio, true);
const summary = getConnectionLogRecordingSummary(log);
assert.equal(summary.clipCount, 2);
assert.equal(summary.totalDurationMs, 60_000);
assert.equal(summary.totalBytes, 3_500_000);
assert.equal(summary.hasAudio, true);
// Removing clip2 falls back to clip1
log = { ...log, ...buildRemoveRecordingClipUpdate(log, clip2.id) };
assert.equal(log.recordings?.length, 1);
assert.equal(log.recordingId, clip1.id);
assert.equal(log.recordingHasAudio, false);
// Removing clip1 clears all recording fields
log = { ...log, ...buildRemoveRecordingClipUpdate(log, clip1.id) };
assert.equal(log.recordings, undefined);
assert.equal(log.recordingId, undefined);
assert.equal(log.recordingBytes, undefined);
});
test('getConnectionLogMediaIds collects all clip IDs and session thumbnailId', () => {
const log = makeBaseLog({
recordings: [
{
id: '11111111-1111-4111-8111-111111111111',
startedAt: 1000,
endedAt: 2000,
durationMs: 1000,
bytes: 100,
mimeType: 'video/webm',
hasAudio: false,
},
{
id: '22222222-2222-4222-8222-222222222222',
startedAt: 3000,
endedAt: 4000,
durationMs: 1000,
bytes: 200,
mimeType: 'video/webm',
hasAudio: false,
},
],
remoteDesktopMeta: {
thumbnailId: '33333333-3333-4333-8333-333333333333',
},
});
assert.deepEqual(getConnectionLogMediaIds(log).sort(), [
'11111111-1111-4111-8111-111111111111',
'22222222-2222-4222-8222-222222222222',
'33333333-3333-4333-8333-333333333333',
]);
});
test('buildClearRecordingsUpdate preserves protected media and clears unprotected metadata', () => {
const protectedId = '11111111-1111-4111-8111-111111111111';
const unprotectedId = '22222222-2222-4222-8222-222222222222';
const log = makeBaseLog({
recordings: [
{
id: protectedId,
startedAt: 1000,
endedAt: 2000,
durationMs: 1000,
bytes: 100,
mimeType: 'video/webm',
hasAudio: false,
},
{
id: unprotectedId,
startedAt: 3000,
endedAt: 4000,
durationMs: 1000,
bytes: 200,
mimeType: 'video/webm',
hasAudio: false,
},
],
recordingId: unprotectedId,
remoteDesktopMeta: {
resolution: { width: 1920, height: 1080 },
thumbnailId: '33333333-3333-4333-8333-333333333333',
},
});
const updates = buildClearRecordingsUpdate(log, new Set([protectedId]));
assert.ok(updates);
assert.equal(updates.recordings?.length, 1);
assert.equal(updates.recordingId, protectedId);
assert.equal(updates.remoteDesktopMeta?.thumbnailId, undefined);
assert.deepEqual(updates.remoteDesktopMeta?.resolution, { width: 1920, height: 1080 });
});
test('appendRemoteDesktopSessionEvent enforces event cap and trims long text', () => {
let events = appendRemoteDesktopSessionEvent(undefined, {
timestamp: 1000,
kind: 'connected',
summary: ' Connected to RDP ',
});
assert.equal(events.length, 1);
assert.equal(events[0].summary, 'Connected to RDP');
for (let i = 0; i < MAX_REMOTE_DESKTOP_SESSION_EVENTS + 25; i += 1) {
events = appendRemoteDesktopSessionEvent(events, {
timestamp: 2000 + i,
kind: 'resized',
summary: `Resized #${i}`,
});
}
assert.equal(events.length, MAX_REMOTE_DESKTOP_SESSION_EVENTS);
assert.equal(events[events.length - 1].summary, `Resized #${MAX_REMOTE_DESKTOP_SESSION_EVENTS + 24}`);
});
test('resolveVideoSeekSecondsForEvent and findRecordingSeekTargetForEvent map event timestamps to clips', () => {
const clips: RemoteDesktopRecordingClip[] = [
{
id: 'clip-a',
startedAt: 10_000,
endedAt: 30_000,
durationMs: 20_000,
bytes: 100,
mimeType: 'video/webm',
hasAudio: false,
},
{
id: 'clip-b',
startedAt: 60_000,
endedAt: 120_000,
durationMs: 60_000,
bytes: 200,
mimeType: 'video/webm',
hasAudio: true,
},
];
assert.equal(resolveVideoSeekSecondsForEvent(clips[0], 15_500), 5.5);
assert.equal(resolveVideoSeekSecondsForEvent(clips[0], 45_000), null);
assert.deepEqual(findRecordingSeekTargetForEvent(clips, 75_000), {
clipId: 'clip-b',
offsetSeconds: 15,
});
assert.equal(findRecordingSeekTargetForEvent(clips, 45_000), null);
});
test('mergeRemoteDesktopSessionMetadata preserves previous fields when patching', () => {
const merged = mergeRemoteDesktopSessionMetadata(
{ resolution: { width: 1280, height: 720 }, tunneled: true },
{ securityLabel: 'TLS / NLA', monitorCount: 2 },
);
assert.deepEqual(merged, {
resolution: { width: 1280, height: 720 },
tunneled: true,
securityLabel: 'TLS / NLA',
monitorCount: 2,
});
});
+339
View File
@@ -0,0 +1,339 @@
import type {
ConnectionLog,
RemoteDesktopRecordingClip,
RemoteDesktopSessionEvent,
RemoteDesktopSessionMetadata,
} from './models/history';
export const MAX_REMOTE_DESKTOP_RECORDING_CLIPS_PER_LOG = 50;
export const MAX_REMOTE_DESKTOP_SESSION_EVENTS = 100;
export const MAX_REMOTE_DESKTOP_EVENT_SUMMARY_CHARS = 200;
export const MAX_REMOTE_DESKTOP_EVENT_DETAIL_CHARS = 240;
let nextSessionEventSeq = 0;
function trimBoundedText(value: string | undefined, maxLen: number): string | undefined {
if (typeof value !== 'string') return undefined;
const cleaned = value.trim();
if (!cleaned) return undefined;
if (cleaned.length <= maxLen) return cleaned;
return `${cleaned.slice(0, Math.max(0, maxLen - 1))}\u2026`;
}
/**
* Normalize a ConnectionLog's recordings into an ordered list of clips
* (oldest first), transparently upgrading legacy single-`recordingId` logs.
*/
export function getConnectionLogRecordingClips(
log: Pick<
ConnectionLog,
| 'recordings'
| 'recordingId'
| 'recordingMimeType'
| 'recordingDurationMs'
| 'recordingBytes'
| 'recordingHasAudio'
| 'startTime'
| 'endTime'
>,
): RemoteDesktopRecordingClip[] {
if (Array.isArray(log.recordings) && log.recordings.length > 0) {
const seen = new Set<string>();
const valid: RemoteDesktopRecordingClip[] = [];
for (const clip of log.recordings) {
if (!clip || typeof clip.id !== 'string' || !clip.id || seen.has(clip.id)) continue;
seen.add(clip.id);
valid.push(clip);
}
if (valid.length > 0) return valid;
}
if (typeof log.recordingId === 'string' && log.recordingId.length > 0) {
const durationMs = typeof log.recordingDurationMs === 'number' && Number.isFinite(log.recordingDurationMs)
? Math.max(0, log.recordingDurationMs)
: 0;
const endedAt = typeof log.endTime === 'number' && Number.isFinite(log.endTime)
? log.endTime
: log.startTime + durationMs;
const startedAt = durationMs > 0 ? Math.max(log.startTime, endedAt - durationMs) : log.startTime;
return [
{
id: log.recordingId,
startedAt,
endedAt,
durationMs,
bytes: typeof log.recordingBytes === 'number' && Number.isFinite(log.recordingBytes)
? Math.max(0, log.recordingBytes)
: 0,
mimeType: log.recordingMimeType || 'video/webm',
hasAudio: Boolean(log.recordingHasAudio),
},
];
}
return [];
}
/**
* Return all local media UUIDs referenced by a ConnectionLog (video clips +
* optional unrecorded session thumbnail). Used for cascade delete and GC.
*/
export function getConnectionLogMediaIds(
log: Pick<
ConnectionLog,
'recordings' | 'recordingId' | 'remoteDesktopMeta'
>,
): string[] {
const ids = new Set<string>();
if (Array.isArray(log.recordings)) {
for (const clip of log.recordings) {
if (clip && typeof clip.id === 'string' && clip.id.length > 0) {
ids.add(clip.id);
}
}
}
if (typeof log.recordingId === 'string' && log.recordingId.length > 0) {
ids.add(log.recordingId);
}
const thumbId = log.remoteDesktopMeta?.thumbnailId;
if (typeof thumbId === 'string' && thumbId.length > 0) {
ids.add(thumbId);
}
return Array.from(ids);
}
export interface ConnectionLogRecordingSummary {
clipCount: number;
totalDurationMs: number;
totalBytes: number;
hasAudio: boolean;
primaryClip: RemoteDesktopRecordingClip | null;
}
export function getConnectionLogRecordingSummary(
log: Pick<
ConnectionLog,
| 'recordings'
| 'recordingId'
| 'recordingMimeType'
| 'recordingDurationMs'
| 'recordingBytes'
| 'recordingHasAudio'
| 'startTime'
| 'endTime'
>,
): ConnectionLogRecordingSummary {
const clips = getConnectionLogRecordingClips(log);
if (clips.length === 0) {
return {
clipCount: 0,
totalDurationMs: 0,
totalBytes: 0,
hasAudio: false,
primaryClip: null,
};
}
let totalDurationMs = 0;
let totalBytes = 0;
let hasAudio = false;
for (const clip of clips) {
totalDurationMs += Math.max(0, Number(clip.durationMs) || 0);
totalBytes += Math.max(0, Number(clip.bytes) || 0);
if (clip.hasAudio) hasAudio = true;
}
return {
clipCount: clips.length,
totalDurationMs,
totalBytes,
hasAudio,
primaryClip: clips[clips.length - 1] ?? null,
};
}
function buildLegacyMirrorFields(clips: RemoteDesktopRecordingClip[]): Partial<ConnectionLog> {
if (clips.length === 0) {
return {
recordings: undefined,
recordingId: undefined,
recordingMimeType: undefined,
recordingDurationMs: undefined,
recordingBytes: undefined,
recordingHasAudio: undefined,
};
}
const latest = clips[clips.length - 1];
let totalDurationMs = 0;
let totalBytes = 0;
let hasAudio = false;
for (const clip of clips) {
totalDurationMs += Math.max(0, clip.durationMs);
totalBytes += Math.max(0, clip.bytes);
if (clip.hasAudio) hasAudio = true;
}
return {
recordings: clips,
recordingId: latest.id,
recordingMimeType: latest.mimeType,
recordingDurationMs: totalDurationMs,
recordingBytes: totalBytes,
recordingHasAudio: hasAudio,
};
}
/**
* Append a newly finalized recording clip to a ConnectionLog without losing
* earlier clips recorded in the same session.
*/
export function buildAppendRecordingClipUpdate(
log: ConnectionLog,
clip: RemoteDesktopRecordingClip,
options?: { stampEndTime?: number },
): Partial<ConnectionLog> {
const existing = getConnectionLogRecordingClips(log).filter((item) => item.id !== clip.id);
const nextClips = [...existing, clip].slice(-MAX_REMOTE_DESKTOP_RECORDING_CLIPS_PER_LOG);
return {
...buildLegacyMirrorFields(nextClips),
...(typeof options?.stampEndTime === 'number' ? { endTime: options.stampEndTime } : {}),
};
}
/**
* Remove a single recording clip from a ConnectionLog and keep legacy mirror
* fields consistent with any remaining clips.
*/
export function buildRemoveRecordingClipUpdate(
log: ConnectionLog,
clipId: string,
): Partial<ConnectionLog> {
const remaining = getConnectionLogRecordingClips(log).filter((clip) => clip.id !== clipId);
return buildLegacyMirrorFields(remaining);
}
/**
* Clear non-protected recording clips (and optional unrecorded thumbnail) from
* a ConnectionLog after Settings -> Clear All Recordings.
*/
export function buildClearRecordingsUpdate(
log: ConnectionLog,
protectedIds: ReadonlySet<string>,
): Partial<ConnectionLog> | null {
const existingClips = getConnectionLogRecordingClips(log);
const keptClips = existingClips.filter((clip) => protectedIds.has(clip.id));
const thumbId = log.remoteDesktopMeta?.thumbnailId;
const shouldClearThumb = Boolean(thumbId && !protectedIds.has(thumbId));
if (keptClips.length === existingClips.length && !shouldClearThumb) {
return null;
}
const updates: Partial<ConnectionLog> = {
...buildLegacyMirrorFields(keptClips),
};
if (shouldClearThumb && log.remoteDesktopMeta) {
const { thumbnailId: _removed, ...restMeta } = log.remoteDesktopMeta;
updates.remoteDesktopMeta = Object.keys(restMeta).length > 0 ? restMeta : undefined;
}
return updates;
}
/**
* Append a structured event to a ConnectionLog's bounded timeline.
*/
export function appendRemoteDesktopSessionEvent(
existing: readonly RemoteDesktopSessionEvent[] | undefined,
event: Omit<RemoteDesktopSessionEvent, 'id'> & { id?: string },
): RemoteDesktopSessionEvent[] {
const list = Array.isArray(existing) ? existing.slice() : [];
const summary = trimBoundedText(event.summary, MAX_REMOTE_DESKTOP_EVENT_SUMMARY_CHARS);
if (!summary) return list;
const detail = trimBoundedText(event.detail, MAX_REMOTE_DESKTOP_EVENT_DETAIL_CHARS);
const safeTimestamp = Number.isFinite(event.timestamp) ? event.timestamp : Date.now();
nextSessionEventSeq += 1;
const nextEvent: RemoteDesktopSessionEvent = {
id: event.id || `rdev-${safeTimestamp.toString(36)}-${nextSessionEventSeq}`,
timestamp: safeTimestamp,
kind: event.kind,
summary,
...(detail ? { detail } : {}),
};
list.push(nextEvent);
if (list.length > MAX_REMOTE_DESKTOP_SESSION_EVENTS) {
return list.slice(list.length - MAX_REMOTE_DESKTOP_SESSION_EVENTS);
}
return list;
}
export function mergeRemoteDesktopSessionMetadata(
existing: RemoteDesktopSessionMetadata | undefined,
patch: Partial<RemoteDesktopSessionMetadata>,
): RemoteDesktopSessionMetadata {
const next: RemoteDesktopSessionMetadata = { ...(existing ?? {}) };
if (patch.resolution && patch.resolution.width > 0 && patch.resolution.height > 0) {
next.resolution = {
width: Math.round(patch.resolution.width),
height: Math.round(patch.resolution.height),
};
}
if (typeof patch.securityLabel === 'string' && patch.securityLabel.trim()) {
next.securityLabel = patch.securityLabel.trim();
}
if (typeof patch.tunneled === 'boolean') {
next.tunneled = patch.tunneled;
}
if (typeof patch.monitorCount === 'number' && Number.isFinite(patch.monitorCount) && patch.monitorCount > 0) {
next.monitorCount = Math.round(patch.monitorCount);
}
if (typeof patch.disconnectReason === 'string' && patch.disconnectReason.trim()) {
next.disconnectReason = trimBoundedText(patch.disconnectReason, MAX_REMOTE_DESKTOP_EVENT_DETAIL_CHARS);
}
if (typeof patch.thumbnailId === 'string' && patch.thumbnailId.trim()) {
next.thumbnailId = patch.thumbnailId.trim();
}
return next;
}
/**
* Given a recording clip and an event timestamp, compute the video seek offset
* in seconds if the event occurred during the clip (with configurable tolerance).
*/
export function resolveVideoSeekSecondsForEvent(
clip: Pick<RemoteDesktopRecordingClip, 'startedAt' | 'endedAt' | 'durationMs'>,
eventTimestamp: number,
toleranceMs = 1000,
): number | null {
if (!Number.isFinite(eventTimestamp) || !Number.isFinite(clip.startedAt)) return null;
const effectiveDurationMs = clip.durationMs > 0
? clip.durationMs
: Math.max(0, (clip.endedAt || clip.startedAt) - clip.startedAt);
const clipEnd = Math.max(clip.endedAt || 0, clip.startedAt + effectiveDurationMs);
if (eventTimestamp < clip.startedAt - toleranceMs || eventTimestamp > clipEnd + toleranceMs) {
return null;
}
const clampedOffsetMs = Math.max(0, Math.min(effectiveDurationMs, eventTimestamp - clip.startedAt));
return clampedOffsetMs / 1000;
}
/**
* Find the recording clip and seek offset (seconds) covering a given event
* timestamp, preferring exact in-range matches over boundary tolerance matches.
*/
export function findRecordingSeekTargetForEvent(
clips: readonly RemoteDesktopRecordingClip[],
eventTimestamp: number,
): { clipId: string; offsetSeconds: number } | null {
for (const clip of clips) {
const exactOffset = resolveVideoSeekSecondsForEvent(clip, eventTimestamp, 0);
if (exactOffset !== null) {
return { clipId: clip.id, offsetSeconds: exactOffset };
}
}
for (const clip of clips) {
const tolerantOffset = resolveVideoSeekSecondsForEvent(clip, eventTimestamp, 1000);
if (tolerantOffset !== null) {
return { clipId: clip.id, offsetSeconds: tolerantOffset };
}
}
return null;
}
@@ -19,6 +19,8 @@ const { Readable } = require("node:stream");
const RECORDING_MEDIA_SCHEME = "netcatty-media";
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const STALE_PART_AGE_MS = 5 * 60 * 1000;
const MAX_THUMBNAIL_BYTES = 256 * 1024;
const WRITER_CLOSE_TIMEOUT_MS = 3000;
function isValidRecordingId(value) {
return typeof value === "string" && UUID_RE.test(value);
@@ -132,41 +134,67 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
const dir = path.resolve(getRecordingsDir());
const finalPath = path.resolve(dir, `${recordingId}.webm`);
const partPath = path.resolve(dir, `${recordingId}.webm.part`);
const thumbPath = path.resolve(dir, `${recordingId}.jpg`);
const thumbPartPath = path.resolve(dir, `${recordingId}.jpg.part`);
if (
!finalPath.startsWith(`${dir}${path.sep}`)
|| !partPath.startsWith(`${dir}${path.sep}`)
|| !thumbPath.startsWith(`${dir}${path.sep}`)
|| !thumbPartPath.startsWith(`${dir}${path.sep}`)
) {
throw new Error("Invalid recording path");
}
return { dir, finalPath, partPath };
return { dir, finalPath, partPath, thumbPath, thumbPartPath };
}
function buildPlaybackUrl(recordingId) {
return `${RECORDING_MEDIA_SCHEME}://recording/${recordingId}?token=${launchToken}`;
}
function buildThumbnailUrl(id) {
return `${RECORDING_MEDIA_SCHEME}://thumbnail/${id}?token=${launchToken}`;
}
async function closeWriterStream(writer) {
if (!writer || writer.closed) return;
if (!writer) return;
if (writer.closePromise) {
return writer.closePromise;
}
writer.closed = true;
await writer.writeChain.catch(() => {});
if (writer.stream && !writer.stream.destroyed) {
writer.closePromise = (async () => {
await writer.writeChain.catch(() => {});
const stream = writer.stream;
if (!stream || stream.destroyed || stream.writableFinished) return;
await new Promise((resolve) => {
let settled = false;
const done = () => {
if (settled) return;
settled = true;
clearTimeout(timer);
stream.removeListener("finish", done);
stream.removeListener("close", done);
stream.removeListener("error", done);
resolve();
};
writer.stream.once("finish", done);
writer.stream.once("close", done);
writer.stream.once("error", done);
const timer = setTimeout(() => {
try {
stream.destroy();
} catch {
// ignore
}
done();
}, WRITER_CLOSE_TIMEOUT_MS);
stream.once("finish", done);
stream.once("close", done);
stream.once("error", done);
try {
writer.stream.end();
stream.end();
} catch {
done();
}
});
}
})();
return writer.closePromise;
}
async function begin(payload = {}) {
@@ -308,7 +336,12 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
playbackUrl: buildPlaybackUrl(recordingId),
};
} catch (err) {
await fs.promises.unlink(writer.partPath).catch(() => {});
const { thumbPath, thumbPartPath } = resolveRecordingPaths(recordingId);
await Promise.all([
fs.promises.unlink(writer.partPath).catch(() => {}),
fs.promises.unlink(thumbPath).catch(() => {}),
fs.promises.unlink(thumbPartPath).catch(() => {}),
]);
throw err;
} finally {
activeWriters.delete(recordingId);
@@ -321,14 +354,16 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
return { ok: false };
}
const writer = activeWriters.get(recordingId);
const { partPath, thumbPath, thumbPartPath } = resolveRecordingPaths(recordingId);
if (writer) {
activeWriters.delete(recordingId);
await closeWriterStream(writer);
await fs.promises.unlink(writer.partPath).catch(() => {});
return { ok: true };
}
const { partPath } = resolveRecordingPaths(recordingId);
await fs.promises.unlink(partPath).catch(() => {});
await Promise.all([
fs.promises.unlink(partPath).catch(() => {}),
fs.promises.unlink(thumbPath).catch(() => {}),
fs.promises.unlink(thumbPartPath).catch(() => {}),
]);
return { ok: true };
}
@@ -353,6 +388,54 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
}
}
async function saveThumbnail(payload = {}) {
const { id: rawId, data } = payload || {};
const id = typeof rawId === "string" && rawId.length > 0 ? rawId : crypto.randomUUID();
if (!isValidRecordingId(id)) {
throw new Error("Invalid thumbnail id");
}
const buf = toBuffer(data);
if (!buf || buf.length === 0 || buf.length > MAX_THUMBNAIL_BYTES) {
throw new Error("Invalid or oversized thumbnail payload");
}
await ensureRecordingsDir();
const { thumbPath, thumbPartPath } = resolveRecordingPaths(id);
try {
await fs.promises.writeFile(thumbPartPath, buf, { mode: 0o600 });
await fs.promises.rename(thumbPartPath, thumbPath);
return {
ok: true,
id,
url: buildThumbnailUrl(id),
bytes: buf.length,
};
} catch (err) {
await fs.promises.unlink(thumbPartPath).catch(() => {});
throw err;
}
}
async function getThumbnailUrl(payload = {}) {
const { id } = payload || {};
if (!isValidRecordingId(id)) {
return { url: null, exists: false };
}
const { thumbPath } = resolveRecordingPaths(id);
try {
const stat = await fs.promises.stat(thumbPath);
if (!stat.isFile()) {
return { url: null, exists: false };
}
return {
url: buildThumbnailUrl(id),
exists: true,
bytes: stat.size,
};
} catch {
return { url: null, exists: false };
}
}
async function exportRecording(event, payload = {}) {
const { recordingId, defaultFileName } = payload || {};
if (!isValidRecordingId(recordingId)) {
@@ -392,9 +475,9 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
activeWriters.delete(recordingId);
await closeWriterStream(writer);
}
const { finalPath, partPath } = resolveRecordingPaths(recordingId);
const { finalPath, partPath, thumbPath, thumbPartPath } = resolveRecordingPaths(recordingId);
let removed = false;
for (const target of [finalPath, partPath]) {
for (const target of [finalPath, partPath, thumbPath, thumbPartPath]) {
try {
await fs.promises.unlink(target);
removed = true;
@@ -434,15 +517,26 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
for (const entry of entries) {
if (!entry.isFile()) continue;
const name = entry.name;
const isWebm = name.endsWith(".webm");
const isPart = name.endsWith(".webm.part");
if (!isWebm && !isPart) continue;
const id = isPart ? name.slice(0, -".webm.part".length) : name.slice(0, -".webm".length);
let id = null;
let isRecordingFile = false;
if (name.endsWith(".webm")) {
id = name.slice(0, -".webm".length);
isRecordingFile = true;
} else if (name.endsWith(".webm.part")) {
id = name.slice(0, -".webm.part".length);
isRecordingFile = true;
} else if (name.endsWith(".jpg")) {
id = name.slice(0, -".jpg".length);
} else if (name.endsWith(".jpg.part")) {
id = name.slice(0, -".jpg.part".length);
} else {
continue;
}
if (!isValidRecordingId(id)) continue;
if (activeWriters.has(id) || protectedSet.has(id)) continue;
try {
await fs.promises.unlink(path.join(dir, name));
deleted += 1;
if (isRecordingFile) deleted += 1;
} catch {
// ignore individual file delete failure
}
@@ -464,13 +558,18 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
let count = 0;
let totalBytes = 0;
for (const entry of entries) {
if (!entry.isFile() || !entry.name.endsWith(".webm")) continue;
const id = entry.name.slice(0, -".webm".length);
if (!entry.isFile()) continue;
const isWebm = entry.name.endsWith(".webm");
const isThumb = entry.name.endsWith(".jpg");
if (!isWebm && !isThumb) continue;
const id = isWebm
? entry.name.slice(0, -".webm".length)
: entry.name.slice(0, -".jpg".length);
if (!isValidRecordingId(id)) continue;
try {
const stat = await fs.promises.stat(path.join(dirPath, entry.name));
if (stat.isFile()) {
count += 1;
if (isWebm) count += 1;
totalBytes += stat.size;
}
} catch {
@@ -517,19 +616,21 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
let deleted = 0;
const files = [];
const thumbFiles = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
const name = entry.name;
const fullPath = path.join(dir, name);
if (name.endsWith(".webm.part")) {
const id = name.slice(0, -".webm.part".length);
if (name.endsWith(".webm.part") || name.endsWith(".jpg.part")) {
const suffix = name.endsWith(".webm.part") ? ".webm.part" : ".jpg.part";
const id = name.slice(0, -suffix.length);
if (!isValidRecordingId(id) || activeWriters.has(id)) continue;
try {
const stat = await fs.promises.stat(fullPath);
if (purgeAllInactiveParts || now - stat.mtimeMs >= STALE_PART_AGE_MS) {
await fs.promises.unlink(fullPath);
deleted += 1;
if (suffix === ".webm.part") deleted += 1;
}
} catch {
// ignore
@@ -537,6 +638,20 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
continue;
}
if (name.endsWith(".jpg")) {
const id = name.slice(0, -".jpg".length);
if (!isValidRecordingId(id)) continue;
let stat;
try {
stat = await fs.promises.stat(fullPath);
} catch {
continue;
}
if (!stat.isFile()) continue;
thumbFiles.push({ id, fullPath, mtimeMs: stat.mtimeMs });
continue;
}
if (!name.endsWith(".webm")) continue;
const id = name.slice(0, -".webm".length);
if (!isValidRecordingId(id)) continue;
@@ -555,6 +670,7 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
if (referencedSet && !referencedSet.has(id) && !isProtected) {
try {
await fs.promises.unlink(fullPath);
await fs.promises.unlink(path.join(dir, `${id}.jpg`)).catch(() => {});
deleted += 1;
continue;
} catch {
@@ -573,6 +689,7 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
if (stat.mtimeMs < cutoff) {
try {
await fs.promises.unlink(fullPath);
await fs.promises.unlink(path.join(dir, `${id}.jpg`)).catch(() => {});
deleted += 1;
continue;
} catch {
@@ -591,6 +708,7 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
}
// 3. Max storage quota eviction (oldest non-protected first).
const evictedIds = new Set();
if (typeof maxBytes === "number" && Number.isFinite(maxBytes) && maxBytes > 0) {
let totalBytes = files.reduce((sum, f) => sum + f.size, 0);
if (totalBytes > maxBytes) {
@@ -601,6 +719,8 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
if (totalBytes <= maxBytes) break;
try {
await fs.promises.unlink(item.fullPath);
await fs.promises.unlink(path.join(dir, `${item.id}.jpg`)).catch(() => {});
evictedIds.add(item.id);
totalBytes -= item.size;
deleted += 1;
} catch {
@@ -610,11 +730,43 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
}
}
// 4. Sweep orphaned / expired standalone thumbnails.
const survivingWebmIds = new Set(
files.filter((f) => !evictedIds.has(f.id)).map((f) => f.id),
);
for (const thumb of thumbFiles) {
if (protectedSet.has(thumb.id) || activeWriters.has(thumb.id) || survivingWebmIds.has(thumb.id)) {
continue;
}
if (referencedSet && !referencedSet.has(thumb.id)) {
await fs.promises.unlink(thumb.fullPath).catch(() => {});
continue;
}
if (
typeof retentionDays === "number"
&& Number.isFinite(retentionDays)
&& retentionDays > 0
) {
const cutoff = now - retentionDays * 24 * 60 * 60 * 1000;
if (thumb.mtimeMs < cutoff) {
await fs.promises.unlink(thumb.fullPath).catch(() => {});
}
}
}
return { deleted };
}
function toSafeWebStream(filePath, streamOpts) {
const nodeStream = fs.createReadStream(filePath, streamOpts);
// Guard against unhandled error events if the file is removed mid-playback.
nodeStream.on("error", () => {});
return Readable.toWeb(nodeStream);
}
/**
* HTTP 206 Range streaming handler for `netcatty-media://recording/<uuid>?token=<token>`.
* HTTP 206 Range streaming handler for `netcatty-media://recording/<uuid>?token=<token>`
* and `netcatty-media://thumbnail/<uuid>?token=<token>`.
* Zero-RAM streaming via `fs.createReadStream` -> Web `ReadableStream`.
*/
async function handleMediaProtocolRequest(request) {
@@ -626,7 +778,9 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
try {
const url = new URL(request.url);
if (url.protocol !== `${RECORDING_MEDIA_SCHEME}:` || url.hostname !== "recording") {
const isRecordingHost = url.hostname === "recording";
const isThumbnailHost = url.hostname === "thumbnail";
if (url.protocol !== `${RECORDING_MEDIA_SCHEME}:` || (!isRecordingHost && !isThumbnailHost)) {
return new Response("Not Found", { status: 404, headers: baseHeaders });
}
const token = url.searchParams.get("token");
@@ -638,14 +792,46 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
return new Response("Bad Request", { status: 400, headers: baseHeaders });
}
const { finalPath } = resolveRecordingPaths(recordingId);
const { finalPath, thumbPath } = resolveRecordingPaths(recordingId);
const method = (request.method || "GET").toUpperCase();
if (isThumbnailHost) {
if (method === "HEAD") {
const stat = await fs.promises.stat(thumbPath).catch(() => null);
if (!stat || !stat.isFile()) {
return new Response("Not Found", { status: 404, headers: baseHeaders });
}
return new Response(null, {
status: 200,
headers: {
"Cache-Control": "private, max-age=3600",
"Cross-Origin-Resource-Policy": "cross-origin",
"Content-Type": "image/jpeg",
"Content-Length": String(stat.size),
},
});
}
const bytes = await fs.promises.readFile(thumbPath).catch(() => null);
if (!bytes) {
return new Response("Not Found", { status: 404, headers: baseHeaders });
}
return new Response(bytes, {
status: 200,
headers: {
"Cache-Control": "private, max-age=3600",
"Cross-Origin-Resource-Policy": "cross-origin",
"Content-Type": "image/jpeg",
"Content-Length": String(bytes.byteLength),
},
});
}
const stat = await fs.promises.stat(finalPath).catch(() => null);
if (!stat || !stat.isFile()) {
return new Response("Not Found", { status: 404, headers: baseHeaders });
}
const totalSize = stat.size;
const method = (request.method || "GET").toUpperCase();
const rangeHeader = typeof request.headers?.get === "function"
? request.headers.get("range")
: request.headers?.range;
@@ -671,11 +857,10 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
if (method === "HEAD") {
return new Response(null, { status: 206, headers });
}
const nodeStream = fs.createReadStream(finalPath, {
start: parsed.start,
end: parsed.end,
});
return new Response(Readable.toWeb(nodeStream), { status: 206, headers });
return new Response(
toSafeWebStream(finalPath, { start: parsed.start, end: parsed.end }),
{ status: 206, headers },
);
}
const headers = {
@@ -686,8 +871,7 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
if (method === "HEAD") {
return new Response(null, { status: 200, headers });
}
const nodeStream = fs.createReadStream(finalPath);
return new Response(Readable.toWeb(nodeStream), { status: 200, headers });
return new Response(toSafeWebStream(finalPath), { status: 200, headers });
} catch {
return new Response("Not Found", { status: 404, headers: baseHeaders });
}
@@ -700,7 +884,12 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
writers.map(async (writer) => {
try {
await closeWriterStream(writer);
await fs.promises.unlink(writer.partPath).catch(() => {});
const { thumbPath, thumbPartPath } = resolveRecordingPaths(writer.recordingId);
await Promise.all([
fs.promises.unlink(writer.partPath).catch(() => {}),
fs.promises.unlink(thumbPath).catch(() => {}),
fs.promises.unlink(thumbPartPath).catch(() => {}),
]);
} catch {
// ignore shutdown cleanup errors
}
@@ -714,6 +903,8 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
ipcMain.handle("netcatty:remote-desktop-recording:finish", (_event, payload) => finish(payload));
ipcMain.handle("netcatty:remote-desktop-recording:abort", (_event, payload) => abort(payload));
ipcMain.handle("netcatty:remote-desktop-recording:get-playback-url", (_event, payload) => getPlaybackUrl(payload));
ipcMain.handle("netcatty:remote-desktop-recording:save-thumbnail", (_event, payload) => saveThumbnail(payload));
ipcMain.handle("netcatty:remote-desktop-recording:get-thumbnail-url", (_event, payload) => getThumbnailUrl(payload));
ipcMain.handle("netcatty:remote-desktop-recording:export", (event, payload) => exportRecording(event, payload));
ipcMain.handle("netcatty:remote-desktop-recording:delete", (_event, payload) => deleteRecording(payload));
ipcMain.handle("netcatty:remote-desktop-recording:delete-many", (_event, payload) => deleteMany(payload));
@@ -728,11 +919,14 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
launchToken,
getRecordingsDir,
buildPlaybackUrl,
buildThumbnailUrl,
begin,
append,
finish,
abort,
getPlaybackUrl,
saveThumbnail,
getThumbnailUrl,
exportRecording,
deleteRecording,
deleteMany,
@@ -309,3 +309,56 @@ test("remoteDesktopRecordingsBridge end-to-end: streaming write, duration patch,
await fs.promises.rm(tmpDir, { recursive: true, force: true });
}
});
test("remoteDesktopRecordingsBridge saves, serves, caps, and garbage-collects JPEG thumbnails", async () => {
const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "nc-rec-thumb-"));
try {
const recordingsDir = path.join(tmpDir, "recordings");
const bridge = createRemoteDesktopRecordingsBridge({
recordingsDir,
launchToken: "thumb-token-99",
});
const jpegBytes = Uint8Array.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0xff, 0xd9]);
const saved = await bridge.saveThumbnail({ data: jpegBytes });
assert.equal(saved.ok, true);
assert.equal(isValidRecordingId(saved.id), true);
assert.equal(saved.url, `netcatty-media://thumbnail/${saved.id}?token=thumb-token-99`);
// Oversized thumbnail rejected (> 256 KB)
await assert.rejects(
() => bridge.saveThumbnail({ data: new Uint8Array(300 * 1024) }),
/oversized/i,
);
const urlInfo = await bridge.getThumbnailUrl({ id: saved.id });
assert.equal(urlInfo.exists, true);
assert.equal(urlInfo.url, saved.url);
// Media protocol serves image/jpeg
const resp = await bridge.handleMediaProtocolRequest({
url: saved.url,
method: "GET",
headers: new Headers(),
});
assert.equal(resp.status, 200);
assert.equal(resp.headers.get("content-type"), "image/jpeg");
assert.deepEqual(new Uint8Array(await resp.arrayBuffer()), jpegBytes);
// Orphan GC sweeps unreferenced standalone thumbnails
await bridge.runGc({ referencedIds: [], protectedIds: [] });
assert.equal((await bridge.getThumbnailUrl({ id: saved.id })).exists, false);
// Deleting a recording cascades to its companion thumbnail
const { recordingId } = await bridge.begin({ protocol: "rdp" });
await bridge.append({ recordingId, chunk: Buffer.from([1, 2, 3, 4]) });
await bridge.saveThumbnail({ id: recordingId, data: jpegBytes });
await bridge.finish({ recordingId, durationMs: 3000 });
assert.equal((await bridge.getThumbnailUrl({ id: recordingId })).exists, true);
await bridge.deleteRecording({ recordingId });
assert.equal((await bridge.getThumbnailUrl({ id: recordingId })).exists, false);
} finally {
await fs.promises.rm(tmpDir, { recursive: true, force: true });
}
});
+1
View File
@@ -1125,6 +1125,7 @@ const { createTerminalPopupWindowApi } = require("./windowManager/terminalPopupW
const terminalPopupWindowApi = createTerminalPopupWindowApi({
get mainWindow() { return mainWindow; },
get currentTheme() { return currentTheme; },
get isQuitting() { return isQuitting; },
V8_CACHE_OPTIONS,
__dirname,
resolveFrontendBackgroundColor,
@@ -21,6 +21,7 @@ const { placeTerminalPopup } = require("./terminalPopupPlacement.cjs");
const {
attachRemoteDesktopKeyboardGrab,
} = require("./remoteDesktopKeyboardGrab.cjs");
const { finalizeSessionLogs } = require("../sessionLogShutdown.cjs");
const ATTACH_CLOSE_PREPARE_TIMEOUT_MS = 2000;
@@ -315,8 +316,27 @@ function createTerminalPopupWindowApi(ctx) {
// ignore
}
let standaloneCloseFinalized = false;
let standaloneCloseFinalizing = false;
win.on("close", (event) => {
if (!attachSessionId || isAttachPopupClosePrepared(attachAuthorization) || isHomeGone()) return;
if (!attachSessionId) {
if (ctx.isQuitting || standaloneCloseFinalized) return;
event?.preventDefault?.();
if (standaloneCloseFinalizing) return;
standaloneCloseFinalizing = true;
void finalizeSessionLogs(win.webContents, { ipcMain: electronModule.ipcMain })
.catch(() => {})
.finally(() => {
standaloneCloseFinalized = true;
try {
if (isLiveWindow(win)) win.close();
} catch {
releaseLifecycle();
}
});
return;
}
if (isAttachPopupClosePrepared(attachAuthorization) || isHomeGone()) return;
event?.preventDefault?.();
if (closePreparationRequested) return;
closePreparationRequested = true;
@@ -670,3 +670,90 @@ test("reopening a moved tab cancels stale close notifications from an earlier cr
setRestoreAttachedSessionOutput(null);
}
});
test("standalone terminal popup finalizes session logs on normal close and skips preventDefault when isQuitting", async () => {
const { EventEmitter } = require("node:events");
const ipcMain = new EventEmitter();
let isQuittingFlag = false;
const createdWindows = [];
class StandalonePopupStub {
constructor() {
createdWindows.push(this);
this.handlers = new Map();
this.closeCalls = 0;
this.destroyed = false;
this.webContents = {
id: 100 + createdWindows.length,
on() {},
send: (channel, payload) => {
if (channel === "app:finalize-session-logs") {
queueMicrotask(() => {
ipcMain.emit("app:session-logs-finalized", { sender: this.webContents }, {
requestId: payload.requestId,
success: true,
});
});
}
},
setWindowOpenHandler() {},
};
}
on(channel, handler) { this.handlers.set(channel, handler); }
isDestroyed() { return this.destroyed; }
loadURL() { return Promise.resolve(); }
setBackgroundColor() {}
close() {
this.closeCalls += 1;
const evt = { prevented: false, preventDefault() { this.prevented = true; } };
this.handlers.get("close")?.(evt);
if (!evt.prevented) {
this.destroyed = true;
this.handlers.get("closed")?.();
}
}
}
const api = createTerminalPopupWindowApi({
mainWindow: null,
currentTheme: "light",
get isQuitting() { return isQuittingFlag; },
V8_CACHE_OPTIONS: "bypassHeatCheck",
resolveFrontendBackgroundColor() { return "#fff"; },
resolveSettingsWindowBounds() { return {}; },
createExternalOnlyWindowOpenHandler() { return {}; },
applyWindowOpacityToWindow() {},
getDevRendererBaseUrl(url) { return url; },
showAndFocusWindow() {},
registerAppContentWindow() {},
unregisterAppContentWindow() {},
notifyAppContentWindowClosed() {},
});
// Case 1: Normal close prevents first close, finalizes logs, then closes cleanly.
await api.openTerminalPopupWindow(
{ BrowserWindow: StandalonePopupStub, nativeTheme: {}, shell: {}, ipcMain },
{ preload: "/tmp/preload.cjs", isDev: false, appIcon: null, isMac: false, electronDir: __dirname },
{ popupId: "standalone-normal", title: "RDP Popup" },
);
const normalWin = createdWindows[0];
const normalCloseEvent = { prevented: false, preventDefault() { this.prevented = true; } };
normalWin.handlers.get("close")?.(normalCloseEvent);
assert.equal(normalCloseEvent.prevented, true);
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(normalWin.closeCalls, 1);
assert.equal(normalWin.destroyed, true);
// Case 2: App quit (isQuitting === true) must NOT preventDefault on popup close.
isQuittingFlag = true;
await api.openTerminalPopupWindow(
{ BrowserWindow: StandalonePopupStub, nativeTheme: {}, shell: {}, ipcMain },
{ preload: "/tmp/preload.cjs", isDev: false, appIcon: null, isMac: false, electronDir: __dirname },
{ popupId: "standalone-quit", title: "RDP Popup Quit" },
);
const quitWin = createdWindows[1];
const quitCloseEvent = { prevented: false, preventDefault() { this.prevented = true; } };
quitWin.handlers.get("close")?.(quitCloseEvent);
assert.equal(quitCloseEvent.prevented, false);
});
+4
View File
@@ -2505,6 +2505,10 @@ function createPreloadApi(ctx) {
abort: (options) => ipcRenderer.invoke("netcatty:remote-desktop-recording:abort", options),
getPlaybackUrl: (options) =>
ipcRenderer.invoke("netcatty:remote-desktop-recording:get-playback-url", options),
saveThumbnail: (options) =>
ipcRenderer.invoke("netcatty:remote-desktop-recording:save-thumbnail", options),
getThumbnailUrl: (options) =>
ipcRenderer.invoke("netcatty:remote-desktop-recording:get-thumbnail-url", options),
export: (options) => ipcRenderer.invoke("netcatty:remote-desktop-recording:export", options),
delete: (options) => ipcRenderer.invoke("netcatty:remote-desktop-recording:delete", options),
deleteMany: (options) =>
+1 -1
View File
@@ -5,7 +5,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src 'self' data: blob: ws: wss: https:; img-src 'self' data: https:; media-src 'self' blob: netcatty-media:;" />
content="default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src 'self' data: blob: ws: wss: https:; img-src 'self' data: https: netcatty-media:; media-src 'self' blob: netcatty-media:;" />
<title>netcatty SSH</title>
<style>
/* Load extended Unicode ranges for terminal box drawing characters */
@@ -379,6 +379,13 @@ export interface RemoteDesktopRecordingsBridgeApi {
getPlaybackUrl(options: {
recordingId: string;
}): Promise<{ url: string | null; exists: boolean; bytes?: number }>;
saveThumbnail?(options: {
id?: string;
data: Uint8Array;
}): Promise<{ ok: boolean; id?: string; url?: string; bytes?: number }>;
getThumbnailUrl?(options: {
id: string;
}): Promise<{ url: string | null; exists: boolean; bytes?: number }>;
export(options: {
recordingId: string;
defaultFileName?: string;
@@ -0,0 +1,262 @@
"use strict";
/* global process, __dirname, console */
if (!process.versions.electron) {
require("node:test")("remote desktop recording end-to-end Electron smoke test", {
skip: "run with Electron to exercise real MediaRecorder, netcatty-media://, and video playback",
}, () => {});
} else {
const { app, BrowserWindow, ipcMain, protocol } = require("electron");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const esbuild = require("esbuild");
const {
RECORDING_MEDIA_SCHEME,
createRemoteDesktopRecordingsBridge,
} = require("../electron/bridges/remoteDesktopRecordingsBridge.cjs");
const root = path.resolve(__dirname, "..");
const userData = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-rdp-rec-smoke-"));
app.setPath("userData", userData);
app.on("window-all-closed", () => {});
protocol.registerSchemesAsPrivileged([
{
scheme: RECORDING_MEDIA_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
stream: true,
},
},
]);
let win;
const cleanup = (code) => {
try {
win?.destroy();
} catch {
// ignore
}
fs.rmSync(userData, { recursive: true, force: true });
app.exit(code);
};
let bundle;
try {
bundle = esbuild.buildSync({
stdin: {
contents: [
'export { createStableCanvasCaptureStream, captureCanvasThumbnailJpeg } from "./components/remoteDesktop/remoteDesktopVideoCapture";',
'export { pickRemoteDesktopRecordingMimeType } from "./components/remoteDesktop/useRemoteDesktopRecorder";',
].join("\n"),
loader: "ts",
resolveDir: root,
},
bundle: true,
format: "cjs",
platform: "browser",
target: "chrome130",
write: false,
define: { "import.meta.env.DEV": "false", "import.meta.env.PROD": "true", "import.meta": "{}" },
}).outputFiles[0].text;
} catch (error) {
console.error(error);
fs.rmSync(userData, { recursive: true, force: true });
process.exit(1);
}
void app.whenReady().then(async () => {
const recordingsBridge = createRemoteDesktopRecordingsBridge({
recordingsDir: path.join(userData, "recordings"),
});
recordingsBridge.registerHandlers(ipcMain);
protocol.handle(RECORDING_MEDIA_SCHEME, (request) => (
recordingsBridge.handleMediaProtocolRequest(request)
));
win = new BrowserWindow({
show: false,
width: 900,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
sandbox: false,
backgroundThrottling: false,
},
});
await win.loadURL("data:text/html,<body style='margin:0;background:%23111'><div id='root'></div></body>");
const result = await win.webContents.executeJavaScript(`(async () => {
const assert = require('node:assert/strict');
const { ipcRenderer } = require('electron');
const loaded = { exports: {} };
((module, exports) => { ${bundle} })(loaded, loaded.exports);
const {
createStableCanvasCaptureStream,
captureCanvasThumbnailJpeg,
pickRemoteDesktopRecordingMimeType,
} = loaded.exports;
const canvas = document.createElement('canvas');
canvas.width = 1280;
canvas.height = 720;
document.getElementById('root').appendChild(canvas);
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#1e3a8a';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#ffffff';
ctx.fillRect(100, 100, 200, 120);
// 1. Capture JPEG thumbnail
const jpegBytes = await captureCanvasThumbnailJpeg(canvas);
assert.ok(jpegBytes && jpegBytes.byteLength > 100, 'thumbnail JPEG should be non-empty');
assert.equal(jpegBytes[0], 0xff);
assert.equal(jpegBytes[1], 0xd8);
// 2. Begin recording via IPC + captureStream + MediaRecorder + mid-recording dynamic resize
const capture = createStableCanvasCaptureStream(canvas, 10);
assert.ok(capture, 'capture handle should be created');
assert.equal(capture.width, 1280);
assert.equal(capture.height, 720);
const mimeType = pickRemoteDesktopRecordingMimeType(false) || 'video/webm';
const { recordingId } = await ipcRenderer.invoke('netcatty:remote-desktop-recording:begin', {
mimeType,
hostLabel: 'smoke-rdp',
protocol: 'rdp',
});
const thumbSaved = await ipcRenderer.invoke('netcatty:remote-desktop-recording:save-thumbnail', {
id: recordingId,
data: jpegBytes,
});
assert.equal(thumbSaved.ok, true);
const recorder = new MediaRecorder(capture.stream, { mimeType, videoBitsPerSecond: 1_500_000 });
let appendChain = Promise.resolve();
let chunkCount = 0;
recorder.ondataavailable = (ev) => {
if (!ev.data || ev.data.size <= 0) return;
chunkCount += 1;
const blob = ev.data;
appendChain = appendChain.then(async () => {
const buf = await blob.arrayBuffer();
await ipcRenderer.invoke('netcatty:remote-desktop-recording:append', {
recordingId,
chunk: new Uint8Array(buf),
});
});
};
recorder.start(300);
await new Promise((r) => setTimeout(r, 450));
// Simulate dynamic RDP canvas resize mid-recording!
canvas.width = 800;
canvas.height = 600;
ctx.fillStyle = '#065f46';
ctx.fillRect(0, 0, canvas.width, canvas.height);
await new Promise((r) => setTimeout(r, 450));
await new Promise((resolve) => {
recorder.addEventListener('stop', resolve, { once: true });
recorder.stop();
});
capture.dispose();
await appendChain;
// Verify all tracks stopped cleanly after dispose()
for (const track of capture.stream.getTracks()) {
assert.equal(track.readyState, 'ended', 'video track must be ended after dispose()');
}
const finished = await ipcRenderer.invoke('netcatty:remote-desktop-recording:finish', {
recordingId,
durationMs: 1200,
hasAudio: false,
});
assert.ok(finished.bytes > 0, 'finalized .webm must be non-empty');
assert.ok(chunkCount > 0, 'MediaRecorder must emit chunks');
// 3. Verify thumbnail renders over netcatty-media://thumbnail/<id>
const thumbInfo = await ipcRenderer.invoke('netcatty:remote-desktop-recording:get-thumbnail-url', {
id: recordingId,
});
assert.equal(thumbInfo.exists, true);
const imgLoaded = await new Promise((resolve, reject) => {
const img = document.createElement('img');
img.onload = () => resolve({ w: img.naturalWidth, h: img.naturalHeight });
img.onerror = () => reject(new Error('Thumbnail failed to load over netcatty-media://'));
img.src = thumbInfo.url;
});
assert.ok(imgLoaded.w > 0 && imgLoaded.w <= 320, 'thumbnail width should be <= 320px');
// 4. Verify <video> loads patched duration and seeks over netcatty-media://recording/<id>
const video = document.createElement('video');
video.preload = 'metadata';
video.muted = true;
document.getElementById('root').appendChild(video);
const videoMeta = await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('Timed out loading video metadata')), 5000);
video.onloadedmetadata = () => {
clearTimeout(timer);
resolve({
duration: video.duration,
videoWidth: video.videoWidth,
videoHeight: video.videoHeight,
});
};
video.onerror = () => {
clearTimeout(timer);
reject(new Error('Video playback error: ' + (video.error?.message || video.error?.code)));
};
video.src = finished.playbackUrl;
});
assert.ok(Number.isFinite(videoMeta.duration) && videoMeta.duration > 0.5, 'patched WebM duration must be finite and > 0.5s');
assert.equal(videoMeta.videoWidth, 1280);
assert.equal(videoMeta.videoHeight, 720);
// Seek test
await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('Timed out seeking video')), 3000);
video.onseeked = () => {
clearTimeout(timer);
resolve();
};
video.currentTime = 0.5;
});
assert.ok(video.currentTime >= 0.4, 'video seek should land near 0.5s');
// Clean video release
video.pause();
video.removeAttribute('src');
video.load();
// 5. Verify cascade delete removes both .webm and .jpg
await ipcRenderer.invoke('netcatty:remote-desktop-recording:delete', { recordingId });
const afterPlay = await ipcRenderer.invoke('netcatty:remote-desktop-recording:get-playback-url', { recordingId });
const afterThumb = await ipcRenderer.invoke('netcatty:remote-desktop-recording:get-thumbnail-url', { id: recordingId });
assert.equal(afterPlay.exists, false);
assert.equal(afterThumb.exists, false);
return {
bytes: finished.bytes,
chunkCount,
duration: videoMeta.duration,
thumbWidth: imgLoaded.w,
thumbHeight: imgLoaded.h,
};
})()`);
console.log("[Smoke] RDP recording Electron E2E passed:", JSON.stringify(result));
cleanup(0);
}).catch((err) => {
console.error("[Smoke] RDP recording Electron E2E FAILED:", err);
cleanup(1);
});
}