mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-28 12:49:53 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81af709d9b | ||
|
|
fc21162bd7 | ||
|
|
9d64860ba6 | ||
|
|
f208b46b40 | ||
|
|
f6d1ed2deb | ||
|
|
baa8ef5743 | ||
|
|
7a7deba65a | ||
|
|
2433d56d90 | ||
|
|
9ec417cbe4 |
No files matched your search
@@ -16,7 +16,7 @@ workflows:
|
||||
- 'actions/setup-node@v7.1.0'
|
||||
- 'actions/upload-artifact@v7.0.2'
|
||||
- 'ilammy/msvc-dev-cmd@v1.13.0'
|
||||
- 'softprops/action-gh-release@v2.6.2'
|
||||
- 'softprops/action-gh-release@v3.0.4'
|
||||
'.github/workflows/grokbot-issue-relay.yml': []
|
||||
'.github/workflows/issue-format.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
@@ -65,8 +65,8 @@ dependencies:
|
||||
commit: 'sha1-0b201ec74fa43914dc39ae48a89fd1d8cb592756'
|
||||
owner_id: 1256587
|
||||
repo_id: 212181767
|
||||
'softprops/action-gh-release@v2.6.2':
|
||||
ref: 'v2.6.2'
|
||||
commit: 'sha1-3bb12739c298aeb8a4eeaf626c5b8d85266b0e65'
|
||||
'softprops/action-gh-release@v3.0.4':
|
||||
ref: 'v3.0.4'
|
||||
commit: 'sha1-8a0cd651e5b2365bd640854a3fa5dfc70e4875f3'
|
||||
owner_id: 2242
|
||||
repo_id: 204253808
|
||||
@@ -828,7 +828,7 @@ jobs:
|
||||
GITHUB_SHA: ${{ github.sha }}
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2.6.2
|
||||
uses: softprops/action-gh-release@v3.0.4
|
||||
with:
|
||||
body_path: release_notes.md
|
||||
prerelease: ${{ contains(github.ref_name, '-') }}
|
||||
|
||||
@@ -1225,7 +1225,10 @@ Highlight the focused split pane:
|
||||
'vault.groups.details': 'Group Details',
|
||||
'vault.groups.details.general': 'General',
|
||||
'vault.groups.details.ssh': 'SSH',
|
||||
'vault.groups.details.rdp': 'RDP',
|
||||
'vault.groups.details.vnc': 'VNC',
|
||||
'vault.groups.details.telnet': 'Telnet',
|
||||
'vault.groups.details.protocolNotEnabledDesc': 'Default {protocol} settings are not configured for this group yet.',
|
||||
'vault.groups.details.advanced': 'Advanced',
|
||||
'vault.groups.details.appearance': 'Appearance',
|
||||
'vault.groups.details.mosh': 'Mosh',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -1225,7 +1225,10 @@ Resalta el panel dividido enfocado:
|
||||
'vault.groups.details': 'Detalles del grupo',
|
||||
'vault.groups.details.general': 'General',
|
||||
'vault.groups.details.ssh': 'SSH',
|
||||
'vault.groups.details.rdp': 'RDP',
|
||||
'vault.groups.details.vnc': 'VNC',
|
||||
'vault.groups.details.telnet': 'Telnet',
|
||||
'vault.groups.details.protocolNotEnabledDesc': 'La configuración predeterminada de {protocol} aún no está configurada para este grupo.',
|
||||
'vault.groups.details.advanced': 'Avanzado',
|
||||
'vault.groups.details.appearance': 'Apariencia',
|
||||
'vault.groups.details.mosh': 'Mosh',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -8,12 +8,6 @@ import ru from "./ru.ts";
|
||||
import zhCN from "./zh-CN.ts";
|
||||
import zhTW from "./zh-TW.ts";
|
||||
|
||||
// Locales that are not at full key parity with `en` yet. They are tracked here
|
||||
// so the remaining debt stays visible instead of silently rendering in English
|
||||
// through the `DEFAULT_UI_LOCALE` fallback in `I18nProvider.resolveMessage`.
|
||||
// Move a locale out of this list once it covers every `en` key.
|
||||
const LOCALES_PENDING_PARITY = ["ru"] as const;
|
||||
|
||||
const hasKey = (messages: Record<string, string>, key: string) =>
|
||||
Object.hasOwn(messages, key);
|
||||
|
||||
@@ -110,7 +104,7 @@ test("en shortcut labels stay identical to DEFAULT_KEY_BINDINGS", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("every locale outside the pending list is at full parity with en", () => {
|
||||
test("every translated locale defines every message key from en", () => {
|
||||
const locales = [
|
||||
{ name: "es", messages: es },
|
||||
{ name: "ru", messages: ru },
|
||||
@@ -119,10 +113,6 @@ test("every locale outside the pending list is at full parity with en", () => {
|
||||
];
|
||||
|
||||
for (const locale of locales) {
|
||||
if ((LOCALES_PENDING_PARITY as readonly string[]).includes(locale.name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const missing = Object.keys(en).filter(
|
||||
(key) => !hasKey(locale.messages, key),
|
||||
);
|
||||
|
||||
@@ -10,9 +10,28 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.preparing': 'Подготовка…',
|
||||
'ai.chat.modelCatalogWarning': 'Не удалось обновить список моделей. Показаны последние доступные или встроенные модели.',
|
||||
'ai.chat.modelCatalogRetry': 'Повторить',
|
||||
'ai.chat.compactingContext': 'Сжимаем предыдущий контекст…',
|
||||
'ai.chat.compactingStep': 'Сокращаем контекст для следующего шага…',
|
||||
'ai.chat.contextCompacted': 'Контекст сжат',
|
||||
'ai.title': 'AI',
|
||||
'ai.description': 'Настройка AI-провайдеров, агентов и параметров безопасности',
|
||||
'ai.chat.compactionRetry': 'Запрос слишком большой. Сжимаем контекст и повторяем попытку…',
|
||||
'ai.chat.compactionBanner': 'Контекст сжат: с {before} тыс. до {after} тыс. токенов',
|
||||
'ai.chat.activity.title': 'Действия агента',
|
||||
'ai.chat.activity.plan': 'План',
|
||||
'ai.chat.activity.webSearch': 'Поиск в интернете',
|
||||
'ai.chat.activity.fileChanges': 'Изменения файлов',
|
||||
'ai.chat.activity.status.running': 'Выполняется',
|
||||
'ai.chat.activity.status.completed': 'Завершено',
|
||||
'ai.chat.activity.status.failed': 'Ошибка',
|
||||
'ai.chat.activity.file.add': 'Добавление',
|
||||
'ai.chat.activity.file.update': 'Изменение',
|
||||
'ai.chat.activity.file.delete': 'Удаление',
|
||||
'ai.chat.activity.usage': 'Токены',
|
||||
'ai.chat.activity.usage.input': 'вход',
|
||||
'ai.chat.activity.usage.output': 'выход',
|
||||
'ai.chat.activity.usage.cached': 'из кэша',
|
||||
'ai.chat.activity.usage.reasoning': 'рассуждение',
|
||||
'ai.title': 'ИИ',
|
||||
'ai.description': 'Настройка провайдеров ИИ, агентов и параметров безопасности',
|
||||
'ai.providers': 'Провайдеры',
|
||||
'ai.agents': 'Агенты',
|
||||
'ai.providers.empty': 'Провайдеры не настроены. Добавьте провайдера, чтобы начать.',
|
||||
@@ -43,6 +62,15 @@ export const ruAiMessages: Messages = {
|
||||
'ai.providers.apiKey': 'API-ключ',
|
||||
'ai.providers.apiKey.placeholder': 'Введите API-ключ',
|
||||
'ai.providers.apiKey.decrypting': 'Расшифровка...',
|
||||
'ai.providers.headers': 'Пользовательские заголовки HTTP',
|
||||
'ai.providers.headers.help': 'Необязательные заголовки для этого провайдера. Значения скрыты и шифруются при сохранении.',
|
||||
'ai.providers.headers.name': 'Имя заголовка',
|
||||
'ai.providers.headers.value': 'Значение заголовка',
|
||||
'ai.providers.headers.add': 'Добавить заголовок',
|
||||
'ai.providers.headers.remove': 'Удалить заголовок',
|
||||
'ai.providers.headers.invalid': 'Укажите корректные заголовки HTTP без повторяющихся имён. Content-Length и Transfer-Encoding задаются автоматически.',
|
||||
'ai.providers.headers.loadError': 'Не удалось открыть сохранённые заголовки. Отмените операцию, разблокируйте системное хранилище ключей и повторите попытку.',
|
||||
'ai.providers.headers.saveError': 'Не удалось сохранить заголовки в зашифрованном виде. Проверьте, доступно ли системное хранилище ключей, и повторите попытку.',
|
||||
'ai.providers.opencodeGo.help': 'Вставьте API-ключ OpenCode, чтобы использовать OpenCode Go. Базовый URL и список моделей настроятся автоматически.',
|
||||
'ai.providers.opencodeGo.getKey': 'Получить API-ключ',
|
||||
'ai.providers.fixedBaseUrl.help': 'Задаётся провайдером. Netcatty автоматически выбирает путь эндпоинта для каждой модели.',
|
||||
@@ -166,20 +194,20 @@ export const ruAiMessages: Messages = {
|
||||
'ai.cursor.detected': 'Доступен',
|
||||
'ai.cursor.notFound': 'Недоступен',
|
||||
'ai.cursor.path': 'Среда:',
|
||||
'ai.cursor.notFoundHint': 'Укажите API-ключ или переключитесь на CLI login.',
|
||||
'ai.cursor.notFoundHint': 'Укажите API-ключ или переключитесь на вход через CLI.',
|
||||
'ai.cursor.notInstalledHint': 'Cursor SDK / Agent CLI не обнаружен.',
|
||||
'ai.cursor.installStatus': 'Среда Cursor',
|
||||
'ai.cursor.installed': 'Обнаружено',
|
||||
'ai.cursor.notInstalled': 'Не обнаружено',
|
||||
'ai.cursor.modeCli': 'CLI login',
|
||||
'ai.cursor.modeApiKey': 'API Key',
|
||||
'ai.cursor.modeCli': 'Вход через CLI',
|
||||
'ai.cursor.modeApiKey': 'API-ключ',
|
||||
'ai.cursor.modeCliHint': 'Использует локальный `cursor-agent login` и квоту подписки Auto. Сохранённый API-ключ сохраняется, но в этом режиме не используется.',
|
||||
'ai.cursor.modeApiKeyHint': 'Использует платный Cursor API. CLI login в этом режиме игнорируется.',
|
||||
'ai.cursor.cliLoginStatus': 'CLI login',
|
||||
'ai.cursor.modeApiKeyHint': 'Использует платный Cursor API. Вход через CLI в этом режиме игнорируется.',
|
||||
'ai.cursor.cliLoginStatus': 'Вход через CLI',
|
||||
'ai.cursor.cliLoginOk': 'Вход выполнен',
|
||||
'ai.cursor.cliLoginAs': 'Вход как {{email}}',
|
||||
'ai.cursor.cliLoginMissing': 'Нет входа',
|
||||
'ai.cursor.cliLoginHint': 'Выполните `cursor-agent login` в терминале, затем нажмите Check.',
|
||||
'ai.cursor.cliLoginHint': 'Выполните `cursor-agent login` в терминале, затем нажмите «Проверить».',
|
||||
'ai.cursor.apiKeyStatus': 'API-ключ',
|
||||
'ai.cursor.apiKeyConfigured': 'Настроен',
|
||||
'ai.cursor.apiKeyMissing': 'Не указан',
|
||||
@@ -210,22 +238,22 @@ export const ruAiMessages: Messages = {
|
||||
'ai.codebuddy.configSection': 'Аутентификация и конфигурация (необязательно)',
|
||||
'ai.codebuddy.internetEnv': 'Сетевая среда',
|
||||
'ai.codebuddy.internetEnv.default': 'По умолчанию (зарубежная)',
|
||||
'ai.codebuddy.internetEnv.internal': 'Internal',
|
||||
'ai.codebuddy.internetEnv.internal': 'Внутренняя',
|
||||
'ai.codebuddy.internetEnv.ioa': 'IOA',
|
||||
'ai.codebuddy.internetEnv.hint': 'Устанавливает CODEBUDDY_INTERNET_ENVIRONMENT — выберите Internal или IOA для ограниченных сетевых сред.',
|
||||
'ai.codebuddy.internetEnv.hint': 'Задаёт переменную CODEBUDDY_INTERNET_ENVIRONMENT. Для сетей с ограниченным доступом выберите «Внутренняя» или IOA.',
|
||||
'ai.codebuddy.envVars': 'Переменные окружения',
|
||||
'ai.codebuddy.envVars.placeholder': 'CODEBUDDY_API_KEY=...\nCODEBUDDY_AUTH_TOKEN=...\nOTHER_VAR=...',
|
||||
'ai.codebuddy.envVars.hint': 'По одной записи KEY=VALUE на строку, передаются агенту CodeBuddy. Укажите CODEBUDDY_API_KEY или CODEBUDDY_AUTH_TOKEN для аутентификации. Хранятся локально в открытом виде.',
|
||||
'ai.codebuddy.advancedSection': 'Расширенные параметры (SDK 0.3.258)',
|
||||
'ai.codebuddy.effort': 'Усилие рассуждения',
|
||||
'ai.codebuddy.effort': 'Глубина рассуждения',
|
||||
'ai.codebuddy.effort.default': 'По умолчанию',
|
||||
'ai.codebuddy.effort.minimal': 'Minimal',
|
||||
'ai.codebuddy.effort.low': 'Low',
|
||||
'ai.codebuddy.effort.medium': 'Medium',
|
||||
'ai.codebuddy.effort.high': 'High',
|
||||
'ai.codebuddy.effort.xhigh': 'XHigh',
|
||||
'ai.codebuddy.effort.max': 'Max',
|
||||
'ai.codebuddy.effort.hint': 'Управляет глубиной рассуждения модели. Для простых команд используйте Minimal/Low, чтобы экономить токены, а для сложной диагностики — Max/High.',
|
||||
'ai.codebuddy.effort.minimal': 'Минимальная',
|
||||
'ai.codebuddy.effort.low': 'Низкая',
|
||||
'ai.codebuddy.effort.medium': 'Средняя',
|
||||
'ai.codebuddy.effort.high': 'Высокая',
|
||||
'ai.codebuddy.effort.xhigh': 'Очень высокая',
|
||||
'ai.codebuddy.effort.max': 'Максимальная',
|
||||
'ai.codebuddy.effort.hint': 'Для простых команд выбирайте минимальную или низкую глубину рассуждения, чтобы экономить токены. Для сложной диагностики выбирайте высокую или максимальную.',
|
||||
'ai.codebuddy.maxTurns': 'Максимум шагов',
|
||||
'ai.codebuddy.maxTurns.hint': 'Ограничивает максимальное число шагов диалога за запрос, предотвращая зацикливание. Оставьте пустым для значения по умолчанию.',
|
||||
'ai.codebuddy.maxBudget': 'Максимальный бюджет (USD)',
|
||||
@@ -274,22 +302,54 @@ export const ruAiMessages: Messages = {
|
||||
'ai.grok.runtime.streamingJson.hint':
|
||||
'Режим headless streaming-json (grok -p --output-format streaming-json). MCP внедряется через .grok/config.toml проекта.',
|
||||
|
||||
// OpenCode
|
||||
'ai.opencode.title': 'OpenCode',
|
||||
'ai.opencode.description': 'Подключается к OpenCode через официальный SDK. Настройте провайдеров и ключи в OpenCode, затем выберите его как внешнего агента для программирования.',
|
||||
'ai.opencode.detecting': 'Поиск…',
|
||||
'ai.opencode.detected': 'Найден',
|
||||
'ai.opencode.notFound': 'Не найден',
|
||||
'ai.opencode.path': 'Путь:',
|
||||
'ai.opencode.notFoundHint': 'Не удалось найти opencode в PATH. Установите OpenCode или укажите путь к исполняемому файлу ниже.',
|
||||
'ai.opencode.customPathPlaceholder': 'например, /usr/local/bin/opencode',
|
||||
'ai.opencode.check': 'Проверить',
|
||||
'ai.opencode.resetPath': 'Сбросить',
|
||||
'ai.opencode.v2.startupTimeout': 'OpenCode 2 не успел запуститься. Убедитесь, что команда `opencode serve` работает в терминале, и повторите попытку.',
|
||||
'ai.opencode.v2.exited': 'OpenCode 2 завершил работу до запуска чата.',
|
||||
'ai.opencode.v2.unauthorized': 'OpenCode 2 отклонил подключение. Повторите попытку в чате.',
|
||||
'ai.opencode.v2.unavailable': 'Не удалось подключиться к OpenCode 2. Проверьте, установлен ли он, и повторите попытку.',
|
||||
'ai.opencode.v2.sessionFailed': 'OpenCode 2 не смог завершить обработку запроса.',
|
||||
'ai.opencode.v2.empty': 'OpenCode 2 вернул пустой ответ. Запустите `opencode` в терминале, чтобы настроить вход и модели.',
|
||||
'ai.opencode.v2.contextSkipped': 'OpenCode 2 не смог использовать контекст чата Netcatty.',
|
||||
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 не смог подключить инструмент MCP. Чат продолжится без него.',
|
||||
|
||||
// MiMo Code
|
||||
'ai.mimo.title': 'MiMo Code',
|
||||
'ai.mimo.description': 'MiMo Code от Xiaomi — форк OpenCode с интерфейсом командной строки. Установите его и настройте провайдеров в его конфигурации, затем выберите MiMo Code как внешнего агента для программирования.',
|
||||
'ai.mimo.detecting': 'Поиск…',
|
||||
'ai.mimo.detected': 'Найден',
|
||||
'ai.mimo.notFound': 'Не найден',
|
||||
'ai.mimo.path': 'Путь:',
|
||||
'ai.mimo.notFoundHint': 'Не удалось найти mimo в PATH. Установите MiMo Code или укажите путь к исполняемому файлу ниже.',
|
||||
'ai.mimo.customPathPlaceholder': 'например, /usr/local/bin/mimo',
|
||||
'ai.mimo.check': 'Проверить',
|
||||
'ai.mimo.resetPath': 'Сбросить',
|
||||
|
||||
// AI Default Agent
|
||||
'ai.defaultAgent': 'Агент по умолчанию',
|
||||
'ai.defaultAgent.description': 'Агент, который будет использоваться при запуске новой AI-сессии',
|
||||
'ai.defaultAgent.description': 'Агент, который будет использоваться при запуске нового сеанса ИИ',
|
||||
'ai.defaultAgent.catty': 'Catty (встроенный)',
|
||||
'ai.defaultAgent.unavailable': 'Недоступен',
|
||||
'ai.toolAccess.title': 'Доступ к инструментам',
|
||||
'ai.toolAccess.mode': 'Режим доступа Netcatty',
|
||||
'ai.toolAccess.description': 'Выберите, как внешние агенты получают доступ к сессиям Netcatty. MCP предоставляет встроенный сервер, а Skills + CLI указывает агентам на локальный skill Netcatty и команды CLI.',
|
||||
'ai.toolAccess.description': 'Выберите, как внешние агенты получают доступ к сеансам Netcatty. MCP предоставляет встроенный сервер, а режим «Навыки + CLI» указывает агентам на локальный навык Netcatty и команды CLI.',
|
||||
'ai.toolAccess.mode.mcp': 'MCP',
|
||||
'ai.toolAccess.mode.skills': 'Skills + CLI',
|
||||
'ai.toolAccess.mode.skills': 'Навыки + CLI',
|
||||
'ai.toolAccess.mcpPrompt.title': 'Промпт для вашего ИИ-клиента',
|
||||
'ai.toolAccess.mcpPrompt.description': 'Вставьте этот промпт в ИИ-клиент (Codex, Claude Code и т. д.), и он сам зарегистрирует MCP Netcatty.',
|
||||
'ai.toolAccess.mcpPrompt.enableHint': 'Включите внешний MCP ниже, чтобы в промпт попал путь к лаунчеру.',
|
||||
'ai.toolAccess.skills.file': 'Файл skill',
|
||||
'ai.toolAccess.skills.description': 'В режиме Skills + CLI агенты автоматически получают путь к этому локальному skill-файлу. Путь к лаунчеру Netcatty CLI передаётся агенту в каждой сессии.',
|
||||
'ai.toolAccess.skills.unavailable': 'Путь к skill-файлу недоступен',
|
||||
'ai.toolAccess.skills.file': 'Файл навыка',
|
||||
'ai.toolAccess.skills.description': 'В режиме «Навыки + CLI» агенты автоматически получают путь к локальному файлу навыка. Путь к файлу запуска Netcatty CLI передаётся агенту в каждом сеансе.',
|
||||
'ai.toolAccess.skills.unavailable': 'Путь к файлу навыка недоступен',
|
||||
|
||||
'ai.externalMcp.title': 'Внешний MCP',
|
||||
'ai.externalMcp.allowCommandOnHost': 'Всегда',
|
||||
@@ -323,13 +383,13 @@ export const ruAiMessages: Messages = {
|
||||
'ai.externalMcp.sessionIdleTimeout': 'Тайм-аут открытого сеанса',
|
||||
'ai.externalMcp.sessionIdleTimeout.description': 'Автоматически закрывать сеансы, открытые ИИ, после указанного числа минут без операций терминала или файлов.',
|
||||
'ai.externalMcp.usage.title': 'Как пользоваться',
|
||||
'ai.externalMcp.usage.keepRunning': '1. Включите External MCP и держите Netcatty запущенным.',
|
||||
'ai.externalMcp.usage.localhost': '2. Клиенты подключаются через локальный launcher (только 127.0.0.1). Discovery удаляется при отключении.',
|
||||
'ai.externalMcp.usage.permissions': '3. Запись следует Settings → AI → Safety и списку блокировки команд.',
|
||||
'ai.externalMcp.usage.capabilities': '4. Доступен полный catalog: терминал, SFTP, Vault и проброс портов. Секреты не возвращаются.',
|
||||
'ai.externalMcp.help.ariaLabel': 'Справка External MCP',
|
||||
'ai.externalMcp.usage.keepRunning': '1. Включите внешний MCP и оставьте Netcatty запущенным.',
|
||||
'ai.externalMcp.usage.localhost': '2. Клиенты подключаются через локальный файл запуска (только 127.0.0.1). При отключении файл обнаружения удаляется.',
|
||||
'ai.externalMcp.usage.permissions': '3. Для операций записи действуют параметры в разделе «Настройки → ИИ → Безопасность» и список заблокированных команд.',
|
||||
'ai.externalMcp.usage.capabilities': '4. Доступен полный каталог: терминал, SFTP, хранилище и проброс портов. Секреты не возвращаются.',
|
||||
'ai.externalMcp.help.ariaLabel': 'Справка по внешнему MCP',
|
||||
'ai.externalMcp.security': 'Безопасность',
|
||||
'ai.externalMcp.security.description': 'Слушает только 127.0.0.1 с ротацией token, использует AI Permission Mode для записи и удаляет discovery при отключении.',
|
||||
'ai.externalMcp.security.description': 'Принимает подключения только на 127.0.0.1, обновляет токен, применяет режим разрешений ИИ к операциям записи и удаляет файл обнаружения при отключении. Локальный мост приложения работает без OAuth.',
|
||||
"ai.privacy.title": "Конфиденциальность ИИ",
|
||||
"ai.privacy.description": "Фильтрует известные шаблоны конфиденциального текста в контексте и результатах инструментов, управляемых Netcatty, для Catty, встроенных агентов и внешних MCP-клиентов. По умолчанию отключено. Не обнаруживает все секреты. При включении двоичные ответы инструментов блокируются.",
|
||||
"ai.privacy.boundary": "Защищаются только данные и инструменты, управляемые Netcatty. Собственные инструменты сторонних агентов, их прямой доступ к файлам и другие MCP-серверы не входят в эту область.",
|
||||
@@ -362,11 +422,11 @@ export const ruAiMessages: Messages = {
|
||||
'ai.externalMcp.http.invalidClientHost': 'Адрес клиента должен быть доступным IP, а не 0.0.0.0 или ::.',
|
||||
'ai.externalMcp.http.warning': 'Прослушивание не только 127.0.0.1 открывает External MCP другим машинам, которые могут достичь этого адреса. Храните bearer token в секрете и не публикуйте этот порт.',
|
||||
'ai.externalMcp.http.url': 'URL',
|
||||
'ai.externalMcp.http.token': 'Bearer token',
|
||||
'ai.externalMcp.http.token': 'Токен Bearer',
|
||||
'ai.externalMcp.http.regenerate': 'Создать заново',
|
||||
'ai.externalMcp.http.regenerateHint': 'Выпускает новый bearer token. HTTP-клиенты должны использовать новый token. Файл discovery для stdio обновляется; уже подключенные stdio-клиенты остаются подключенными.',
|
||||
'ai.externalMcp.http.wslHint': 'При mirrored networking в WSL достаточно localhost. Иначе слушайте 0.0.0.0 или IP vEthernet и укажите IP узла Windows как адрес клиента.',
|
||||
'ai.externalMcp.http.codexSnippet': 'Codex config.toml',
|
||||
'ai.externalMcp.http.codexSnippet': 'Файл config.toml для Codex',
|
||||
'ai.externalMcp.http.claudeCommand': 'Claude Code',
|
||||
'ai.externalMcp.http.genericSnippet': 'Общий JSON',
|
||||
'ai.externalMcp.http.envLine': 'Переменная окружения token для Codex',
|
||||
@@ -380,12 +440,12 @@ export const ruAiMessages: Messages = {
|
||||
'ai.externalMcp.http.legacySseNote': 'Устаревший HTTP+SSE (2024-11-05) не предоставляется. Используйте этот URL Streamable HTTP.',
|
||||
'ai.externalMcp.permissionMode': 'Текущий режим разрешений: {mode}',
|
||||
'ai.externalMcp.permissionMode.label': 'Режим разрешений на запись',
|
||||
'ai.externalMcp.permissionMode.hint': 'Тот же параметр, что Settings → AI → Safety. Auto выполняет write-инструменты Netcatty без запросов; Confirm спрашивает каждый раз. Внешние клиенты (Codex / Claude / Grok) могут показывать своё подтверждение инструментов.',
|
||||
'ai.externalMcp.permissionMode.hint': 'Тот же параметр, что в разделе «Настройки → ИИ → Безопасность». В режиме «Авто» Netcatty выполняет операции записи без запроса. В режиме «Подтверждение» Netcatty запрашивает разрешение каждый раз. Внешние клиенты (Codex, Claude, Grok) могут запрашивать собственное подтверждение.',
|
||||
'ai.externalMcp.permissionMode.unknown': 'Неизвестно',
|
||||
'ai.externalMcp.discovery': 'Discovery',
|
||||
'ai.externalMcp.launcher': 'Launcher',
|
||||
'ai.externalMcp.discovery': 'Файл обнаружения',
|
||||
'ai.externalMcp.launcher': 'Файл запуска',
|
||||
'ai.externalMcp.unavailable': 'Недоступно',
|
||||
'ai.externalMcp.bridgeUnavailable': 'Мост External MCP недоступен',
|
||||
'ai.externalMcp.bridgeUnavailable': 'Мост внешнего MCP недоступен',
|
||||
'ai.externalMcp.copy': 'Копировать',
|
||||
'ai.externalMcp.copied': 'Скопировано',
|
||||
'ai.externalMcp.copyFailed': 'Не удалось скопировать. Скопируйте вручную.',
|
||||
@@ -440,7 +500,7 @@ export const ruAiMessages: Messages = {
|
||||
|
||||
// AI Quick Messages
|
||||
'ai.quickMessages.title': 'Быстрые сообщения',
|
||||
'ai.quickMessages.description': 'Создавайте часто используемые подсказки и вставляйте их в AI-чат через / или кнопку быстрых сообщений. В отличие от user skills, быстрые сообщения заполняют поле ввода текстом.',
|
||||
'ai.quickMessages.description': 'Создавайте подсказки для повторного использования. Чтобы вставить текст подсказки в поле ввода чата с ИИ, наберите / или нажмите кнопку быстрых сообщений.',
|
||||
'ai.quickMessages.add': 'Добавить быстрое сообщение',
|
||||
'ai.quickMessages.createTitle': 'Новое быстрое сообщение',
|
||||
'ai.quickMessages.editTitle': 'Редактировать быстрое сообщение',
|
||||
@@ -462,14 +522,14 @@ export const ruAiMessages: Messages = {
|
||||
'ai.quickMessages.error.maxItems': 'Можно сохранить не более {max} быстрых сообщений.',
|
||||
|
||||
// AI Chat
|
||||
'ai.chat.noProvider': 'AI-провайдер не настроен. Перейдите в **Настройки → AI → Провайдеры**, чтобы добавить и включить провайдера.',
|
||||
'ai.chat.noProvider': 'Провайдер ИИ не настроен. Перейдите в **Настройки → ИИ → Провайдеры**, чтобы добавить и включить провайдера.',
|
||||
'ai.chat.toolDenied': 'Действие было отклонено пользователем.',
|
||||
'ai.chat.toolApproved': 'Одобрено',
|
||||
'ai.chat.toolApprovalHint': 'Enter — разрешить один раз, Escape — отклонить',
|
||||
'ai.chat.approve': 'Одобрить',
|
||||
'ai.chat.approveOnce': 'Разрешить один раз',
|
||||
'ai.chat.alwaysAllow': 'Всегда разрешать',
|
||||
'ai.chat.slashStopDesc': 'Остановить текущий ход AI и отменить выполняющиеся инструменты',
|
||||
'ai.chat.slashStopDesc': 'Остановить текущий ход ИИ и отменить выполняющиеся инструменты',
|
||||
'ai.chat.slashCompactDesc': 'Сжать ранний контекст разговора',
|
||||
'ai.chat.slashRenameDesc': 'Переименовать текущий чат (/rename <название>)',
|
||||
'ai.chat.slashChatsDesc': 'Показать чаты, видимые в этой панели',
|
||||
@@ -480,12 +540,12 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.copyCommand': 'Копировать',
|
||||
'ai.chat.commandCopied': 'Скопировано',
|
||||
'ai.chat.approvalSession': 'Сессия',
|
||||
'ai.chat.approvalShell': 'Shell',
|
||||
'ai.chat.approvalShell': 'Оболочка',
|
||||
'ai.chat.approvalCwd': 'Каталог',
|
||||
'ai.chat.approvalReason': 'Причина',
|
||||
'ai.chat.approvalInvocation': 'Вызов',
|
||||
'ai.chat.permissionRequired': 'Требуется разрешение',
|
||||
'ai.chat.permissionDescription': 'AI-агент хочет выполнить вызов инструмента, для которого требуется ваше одобрение.',
|
||||
'ai.chat.permissionDescription': 'Агент ИИ хочет вызвать инструмент, для которого требуется ваше разрешение.',
|
||||
'ai.chat.commandBlocked': 'Эта команда заблокирована вашей политикой безопасности и не может быть выполнена.',
|
||||
'ai.chat.recommendAllow': 'Разрешить',
|
||||
'ai.chat.recommendConfirm': 'Подтвердить',
|
||||
@@ -511,7 +571,7 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.placeholder': 'Сообщение {agent} — @ для добавления контекста, / для команд',
|
||||
'ai.chat.placeholderDefault': 'Сообщение агенту Catty...',
|
||||
'ai.chat.noModel': 'Нет модели',
|
||||
'ai.chat.noProviderModel': 'Модель по умолчанию не задана — настройте её в Настройки → AI → Провайдеры.',
|
||||
'ai.chat.noProviderModel': 'Модель по умолчанию не задана. Выберите её в разделе «Настройки → ИИ → Провайдеры».',
|
||||
'ai.chat.selectProvider': 'Выберите провайдера',
|
||||
'ai.chat.selectProviderAndModel': 'Выберите провайдера и модель',
|
||||
'ai.chat.selectModel': 'Выберите модель',
|
||||
@@ -548,7 +608,7 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.importNone': 'В выбранном файле не найдено чатов ИИ.',
|
||||
'ai.chat.chatsHeader': 'Чаты, видимые в этой панели:',
|
||||
'ai.chat.chatsEmpty': 'В этой панели нет видимых чатов.',
|
||||
'ai.chat.chatsScopeWorkspace': 'Workspace',
|
||||
'ai.chat.chatsScopeWorkspace': 'Рабочая область',
|
||||
'ai.chat.chatsScopeTerminal': 'Терминал',
|
||||
'ai.chat.chatsScopeGlobal': 'Глобально',
|
||||
'ai.chat.chatsScopeDangling': 'Связь потеряна',
|
||||
@@ -617,12 +677,12 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.slashUserSkills': 'Пользовательские навыки',
|
||||
'ai.chat.quickMessages': 'Команды /',
|
||||
'ai.chat.slashNoResults': 'Нет подходящих команд',
|
||||
'ai.chat.slashEmptyHint': 'Добавьте подсказки в Настройки → AI → Быстрые сообщения.',
|
||||
'ai.chat.slashEmptyHint': 'Добавьте подсказки в разделе «Настройки → ИИ → Быстрые сообщения».',
|
||||
|
||||
// AI Chat Shortcuts
|
||||
'ai.chatShortcuts.title': 'Быстрые действия чата',
|
||||
'ai.chatShortcuts.selectionAction': 'Показывать «Добавить в чат» при выделении в терминале',
|
||||
'ai.chatShortcuts.selectionAction.description': 'Показывать небольшую кнопку AI рядом с выделенным текстом терминала.',
|
||||
'ai.chatShortcuts.selectionAction.description': 'Показывать небольшую кнопку ИИ рядом с выделенным текстом терминала.',
|
||||
'ai.chatHistory.title': 'История чата',
|
||||
'ai.chatHistory.messageCap': 'Сообщений, сохраняемых в чате',
|
||||
'ai.chatHistory.messageCap.description': 'Максимальное число сообщений, хранимых для одного чата (50–2000). При уменьшении самые старые сообщения удаляются из хранилища при следующей записи. Большие значения увеличивают объём хранилища и синхронизации с облаком.',
|
||||
@@ -634,7 +694,7 @@ export const ruAiMessages: Messages = {
|
||||
// AI Web Search
|
||||
'ai.webSearch.title': 'Веб-поиск',
|
||||
'ai.webSearch.enable': 'Включить веб-поиск',
|
||||
'ai.webSearch.enable.description': 'Разрешить AI-агенту искать в интернете актуальную информацию.',
|
||||
'ai.webSearch.enable.description': 'Разрешить агенту ИИ искать в интернете актуальную информацию.',
|
||||
'ai.webSearch.provider': 'Провайдер поиска',
|
||||
'ai.webSearch.provider.description': 'Выберите провайдера API веб-поиска.',
|
||||
'ai.webSearch.apiKey': 'API-ключ',
|
||||
@@ -649,7 +709,7 @@ export const ruAiMessages: Messages = {
|
||||
// AI Safety Settings
|
||||
'ai.safety.title': 'Безопасность',
|
||||
'ai.safety.permissionMode': 'Режим разрешений',
|
||||
'ai.safety.permissionMode.description': 'Управляет тем, как AI взаимодействует с вашими терминалами. Режим наблюдателя блокирует все операции записи через Netcatty и применяется как к встроенным, так и к внешним агентам. Режим подтверждения носит рекомендательный характер для внешних агентов (они управляют собственным потоком одобрения инструментов).',
|
||||
'ai.safety.permissionMode.description': 'Управляет тем, как ИИ взаимодействует с вашими терминалами. Режим наблюдателя блокирует все операции записи через Netcatty и применяется как к встроенным, так и к внешним агентам. Режим подтверждения носит рекомендательный характер для внешних агентов (они управляют собственным потоком одобрения инструментов).',
|
||||
'ai.safety.permissionMode.observer': 'Наблюдатель — только чтение, без действий',
|
||||
'ai.safety.permissionMode.confirm': 'Подтверждение — спрашивать перед действиями',
|
||||
'ai.safety.permissionMode.auto': 'Авто — выполнять свободно',
|
||||
@@ -660,7 +720,7 @@ export const ruAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.description': 'Отменяет запрос встроенного ИИ после указанного числа секунд без нового ответа. Не управляет общей длительностью ответа и выполнением команд.',
|
||||
'ai.safety.responseIdleTimeout.unit': 'с',
|
||||
'ai.safety.maxIterations': 'Макс. число итераций',
|
||||
'ai.safety.maxIterations.description': 'Максимальное число циклов использования инструментов AI, чтобы предотвратить бесконтрольное выполнение. У внешних агентов могут быть собственные внутренние лимиты итераций, имеющие приоритет.',
|
||||
'ai.safety.maxIterations.description': 'Максимальное число циклов использования инструментов ИИ, чтобы предотвратить бесконтрольное выполнение. У внешних агентов могут быть собственные внутренние лимиты итераций, имеющие приоритет.',
|
||||
'ai.safety.toolOutputMaxChars': 'Лимит вывода инструментов встроенного ИИ',
|
||||
'ai.safety.toolOutputMaxChars.description': 'Максимум символов, оставляемых напрямую в результате инструмента встроенного ИИ (например, вывода команд терминала или чтения SFTP) до обрезки и сохранения полного вывода в дескриптор (2 000–200 000).',
|
||||
'ai.safety.toolOutputMaxChars.unit': 'симв.',
|
||||
@@ -693,12 +753,15 @@ export const ruAiMessages: Messages = {
|
||||
'terminal.layer.history': 'История',
|
||||
'terminal.layer.theme': 'Тема',
|
||||
'terminal.layer.notes': 'Заметки',
|
||||
'terminal.layer.aiChat': 'AI-чат',
|
||||
'terminal.layer.aiChat': 'Чат с ИИ',
|
||||
'terminal.layer.choosePanelPosition': 'Изменить положение',
|
||||
'terminal.layer.dockLeft': 'Слева',
|
||||
'terminal.layer.dockRight': 'Справа',
|
||||
'terminal.layer.dockBottom': 'Снизу',
|
||||
'terminal.layer.closePanel': 'Закрыть панель',
|
||||
'terminal.layer.saveLayoutAsDefault': 'Сохранить расположение панелей по умолчанию',
|
||||
'terminal.layer.layoutSavedAsDefault': 'Расположение панелей по умолчанию сохранено',
|
||||
'terminal.layer.layoutSaveFailed': 'Не удалось сохранить расположение панелей',
|
||||
'terminal.layer.closePane': 'Закрыть область',
|
||||
'terminal.layer.resizeSplit': 'Изменить размер области',
|
||||
'terminal.layer.splitHorizontal': 'Разделить сверху и снизу',
|
||||
@@ -718,9 +781,15 @@ export const ruAiMessages: Messages = {
|
||||
'terminal.layer.hostTree.collapse': 'Свернуть список хостов',
|
||||
'terminal.layer.hostTree.expand': 'Развернуть список хостов',
|
||||
'terminal.layer.hostTree.empty': 'Хосты не найдены',
|
||||
'terminal.layer.hostTree.details.host': 'Хост',
|
||||
'terminal.layer.hostTree.details.user': 'Пользователь',
|
||||
'terminal.layer.hostTree.details.port': 'Порт',
|
||||
'terminal.layer.hostTree.details.protocol': 'Протокол',
|
||||
'terminal.layer.hostTree.details.group': 'Группа',
|
||||
'terminal.layer.hostTree.details.tags': 'Теги',
|
||||
'topTabs.openQuickSwitcher': 'Открыть быстрый переключатель',
|
||||
'topTabs.moreTabs': 'Больше вкладок',
|
||||
'topTabs.aiAssistant': 'AI-помощник',
|
||||
'topTabs.aiAssistant': 'ИИ-помощник',
|
||||
'topTabs.controlPanel': 'Быстрые настройки',
|
||||
'topTabs.controlPanel.externalMcp': 'Внешний MCP',
|
||||
'topTabs.controlPanel.theme': 'Тема',
|
||||
|
||||
@@ -38,6 +38,33 @@ export const ruCoreMessages: Messages = {
|
||||
"settings.plugins.github.error.failed": "Не удалось проверить или установить плагин. Изучите технические подробности перед повторной попыткой.",
|
||||
"settings.plugins.github.error.details": "Технические подробности",
|
||||
|
||||
"settings.plugins.landing.checkUpdates": "Проверить обновления",
|
||||
"settings.plugins.landing.checkingUpdates": "Проверка…",
|
||||
"settings.plugins.landing.updateSummary": "Проверено: {checked} · Опубликовано обновлений: {updates} · Пропущено: {skipped}.",
|
||||
"settings.plugins.landing.updateSourcesFailed": "Недоступных источников: {count}.",
|
||||
"settings.plugins.landing.updateReview": "Перед установкой проверьте обновления в менеджере плагинов.",
|
||||
"settings.plugins.landing.updateAvailable": "Доступна версия {version}",
|
||||
"settings.plugins.landing.loading": "Загрузка установленных плагинов…",
|
||||
"settings.plugins.landing.settingsUnavailable": "Здесь настройки плагинов недоступны.",
|
||||
"settings.plugins.landing.options": "Параметры плагина",
|
||||
"settings.plugins.landing.manager": "Менеджер плагинов",
|
||||
"settings.plugins.landing.managerDescription": "Просматривайте плагины и управляйте установленными пакетами и источниками.",
|
||||
"settings.plugins.landing.browse": "Обзор",
|
||||
"settings.plugins.landing.refresh": "Обновить список установленных плагинов",
|
||||
"settings.plugins.landing.unavailable": "Управление плагинами недоступно в этом сеансе.",
|
||||
"settings.plugins.landing.empty": "Плагины ещё не установлены. Откройте менеджер плагинов, чтобы посмотреть доступные варианты.",
|
||||
"settings.plugins.landing.search": "Поиск установленных плагинов",
|
||||
"settings.plugins.landing.settingsFor": "Настройки плагина {name}",
|
||||
"settings.plugins.landing.enableSettings": "Включите плагин, чтобы открыть его настройки.",
|
||||
"settings.plugins.landing.sourceUnknown": "Источник неизвестен",
|
||||
"settings.plugins.landing.status.running": "Работает",
|
||||
"settings.plugins.landing.status.starting": "Запускается",
|
||||
"settings.plugins.landing.status.stopping": "Останавливается",
|
||||
"settings.plugins.landing.status.error": "Ошибка",
|
||||
"settings.plugins.landing.status.quarantined": "В карантине",
|
||||
"settings.plugins.landing.status.unknown": "Состояние неизвестно",
|
||||
"settings.plugins.landing.status.idle": "Включён, не запущен",
|
||||
|
||||
// Common
|
||||
'common.save': 'Сохранить',
|
||||
'common.cancel': 'Отмена',
|
||||
@@ -150,7 +177,7 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.tab.appearance': 'Внешний вид',
|
||||
'settings.tab.terminal': 'Терминал',
|
||||
'settings.tab.shortcuts': 'Горячие клавиши',
|
||||
'settings.tab.ai': 'AI',
|
||||
'settings.tab.ai': 'ИИ',
|
||||
'settings.tab.syncCloud': 'Синхронизация и облако',
|
||||
'settings.tab.system': 'Система',
|
||||
'settings.search.open': 'Поиск настроек',
|
||||
@@ -245,7 +272,7 @@ export const ruCoreMessages: Messages = {
|
||||
|
||||
// Settings > System > Network Proxy
|
||||
'settings.system.networkProxy.title': 'Сетевой прокси',
|
||||
'settings.system.networkProxy.description': 'HTTP(S)-прокси для облачной синхронизации и AI-провайдеров. Не связан с SSH ProxyJump / ProxyCommand.',
|
||||
'settings.system.networkProxy.description': 'HTTP(S)-прокси для облачной синхронизации и провайдеров ИИ. Не связан с SSH ProxyJump / ProxyCommand.',
|
||||
'settings.system.networkProxy.mode': 'Режим прокси',
|
||||
'settings.system.networkProxy.mode.system': 'Системный прокси',
|
||||
'settings.system.networkProxy.mode.direct': 'Напрямую (без прокси)',
|
||||
@@ -256,7 +283,7 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.system.networkProxy.bypass': 'Список исключений',
|
||||
'settings.system.networkProxy.bypass.placeholder': '<local>,localhost,127.0.0.1',
|
||||
'settings.system.networkProxy.bypass.desc': 'Хосты через запятую, для которых прокси не используется. <local> — localhost и локальные имена.',
|
||||
'settings.system.networkProxy.hint': 'Влияет на вход в Google Drive / OneDrive / GitHub sync и запросы к AI-провайдерам. SSH-подключения не меняет.',
|
||||
'settings.system.networkProxy.hint': 'Влияет на вход в Google Drive, OneDrive и GitHub для синхронизации и на запросы к провайдерам ИИ. SSH-подключения не меняет.',
|
||||
|
||||
// Settings > System > Crash Logs
|
||||
'settings.system.crashLogs.title': 'Журналы сбоев',
|
||||
@@ -296,6 +323,21 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.update.autoUpdateEnabled': 'Автоматические обновления',
|
||||
'settings.update.autoUpdateEnabledDesc': 'Автоматически проверять и загружать обновления, когда они доступны.',
|
||||
|
||||
// Settings > Session Restore
|
||||
'settings.sessionRestore.title': 'Восстановление сеансов',
|
||||
'settings.sessionRestore.startupLanding': 'При запуске',
|
||||
'settings.sessionRestore.startupLandingDesc': 'Выберите, что открывать при запуске Netcatty, если сеансы не восстановлены: главную страницу с хостами или локальный терминал.',
|
||||
'settings.sessionRestore.startupLanding.vault': 'Главная (хосты)',
|
||||
'settings.sessionRestore.startupLanding.localTerminal': 'Локальный терминал',
|
||||
'settings.sessionRestore.restorePreviousSession': 'Восстанавливать вкладки и рабочие области',
|
||||
'settings.sessionRestore.restorePreviousSessionDesc': 'Открывать вкладки терминала и восстанавливать расположение панелей в рабочих областях из предыдущего сеанса приложения.',
|
||||
'settings.sessionRestore.restoreTerminalCwd': 'Восстанавливать рабочий каталог терминала',
|
||||
'settings.sessionRestore.restoreTerminalCwdDesc': 'При переподключении восстановленного терминала пытаться перейти в последний известный рабочий каталог, не задерживая подключение.',
|
||||
'terminal.restore.placeholder.title': 'Восстановленный сеанс',
|
||||
'terminal.restore.placeholder.desc': 'Терминал отключён. Подключитесь снова, чтобы запустить новую оболочку в этой вкладке.',
|
||||
'terminal.restore.placeholder.reconnect': 'Переподключиться',
|
||||
'terminal.restore.cwdLog': 'Восстановление рабочего каталога: {cwd}',
|
||||
|
||||
// Settings > Session Logs
|
||||
'settings.sessionLogs.title': 'Журналы сессий',
|
||||
'settings.sessionLogs.description': 'Настройка экспорта журналов сессий и параметров автосохранения.',
|
||||
@@ -495,7 +537,7 @@ export const ruCoreMessages: Messages = {
|
||||
|
||||
### Боковая панель терминала
|
||||
|
||||
- \`terminal-side-panel\` — панель SFTP / скриптов / темы / AI (только пока открыта)
|
||||
- \`terminal-side-panel\` — панель SFTP / скриптов / темы / ИИ (только пока открыта)
|
||||
- \`terminal-side-panel-tabs\`
|
||||
- \`terminal-side-panel-content\`
|
||||
|
||||
@@ -597,6 +639,7 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.terminal.section.keyboard': 'Клавиатура',
|
||||
'settings.terminal.section.accessibility': 'Доступность',
|
||||
'settings.terminal.section.behavior': 'Поведение',
|
||||
'settings.terminal.section.sidePanel': 'Боковая панель',
|
||||
'settings.terminal.section.scrollback': 'Буфер прокрутки',
|
||||
'settings.terminal.section.keywordHighlight': 'Подсветка ключевых слов',
|
||||
'settings.terminal.font.family': 'Шрифт',
|
||||
@@ -822,6 +865,18 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.terminal.localShell.startDir.placeholder': 'Домашний каталог',
|
||||
'settings.terminal.localShell.startDir.notFound': 'Каталог не найден',
|
||||
'settings.terminal.localShell.startDir.isFile': 'Путь указывает на файл, а не на каталог',
|
||||
'settings.terminal.sidePanel.autoOpen': 'Открывать боковую панель при подключении',
|
||||
'settings.terminal.sidePanel.autoOpen.desc': 'Автоматически открывать боковую панель после подключения терминала.',
|
||||
'settings.terminal.sidePanel.autoOpenPane': 'Боковая панель по умолчанию',
|
||||
'settings.terminal.sidePanel.autoOpenPane.desc': 'Выберите, какую панель открывать в первую очередь.',
|
||||
'settings.terminal.sidePanel.pane.sftp': 'SFTP',
|
||||
'settings.terminal.sidePanel.pane.scripts': 'Скрипты',
|
||||
'settings.terminal.sidePanel.pane.history': 'История',
|
||||
'settings.terminal.sidePanel.pane.theme': 'Тема',
|
||||
'settings.terminal.sidePanel.pane.system': 'Система',
|
||||
'settings.terminal.sidePanel.pane.notes': 'Заметки',
|
||||
'settings.terminal.sidePanel.pane.ai': 'ИИ',
|
||||
|
||||
'settings.terminal.section.localShellSidePanel': 'Боковая панель локальной оболочки',
|
||||
'settings.terminal.localShellSidePanel.autoOpen': 'Развернуть боковую панель при открытии локальной оболочки',
|
||||
'settings.terminal.localShellSidePanel.autoOpen.desc': 'Автоматически открывать боковую панель после открытия локальной оболочки.',
|
||||
@@ -829,10 +884,14 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.terminal.localShellSidePanel.autoOpenPane.desc': 'Выберите, какую панель открывать в первую очередь.',
|
||||
'settings.terminal.localShellSidePanel.pane.files': 'Файлы',
|
||||
'settings.terminal.section.connection': 'Подключение',
|
||||
'settings.terminal.connection.verifyHostKeys': 'Проверять ключи SSH-хостов',
|
||||
'settings.terminal.connection.verifyHostKeys.desc': 'Запрашивать подтверждение при подключении к SSH-хосту с новым или изменившимся ключом. Отключайте проверку только в доверенных частных сетях.',
|
||||
'settings.terminal.connection.temporaryLegacyAlgorithms': 'Устаревшие алгоритмы для временных подключений',
|
||||
'settings.terminal.connection.temporaryLegacyAlgorithms.desc': 'SSH-подключения без сохранённого хоста, включая запуск в стиле PuTTY и быстрое подключение, предлагают те же устаревшие алгоритмы, что и настройка хоста. Сохранённые хосты используют свою настройку. По умолчанию выключено: у этих алгоритмов есть известные слабости.',
|
||||
'settings.terminal.connection.temporaryNetworkDeviceMode': 'Режим сетевого устройства для временных подключений',
|
||||
'settings.terminal.connection.temporaryNetworkDeviceMode.desc': 'SSH-подключения без сохранённого хоста, включая внешний запуск и быстрое подключение, открываются в режиме сетевого устройства. Сохранённые хосты и группы сохраняют свой тип устройства. По умолчанию выключено.',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled': 'Автоматически переподключать SSH-сеансы',
|
||||
'settings.terminal.connection.sshAutoReconnectEnabled.desc': 'При неожиданном разрыве SSH-соединения повторять попытки с заданным интервалом, пока соединение не восстановится или вкладка не будет закрыта.',
|
||||
'settings.terminal.connection.sshAutoReconnectInterval': 'Интервал переподключения SSH (секунды)',
|
||||
'settings.terminal.connection.sshAutoReconnectInterval.desc': 'Ожидание между попытками: 5–3600 секунд (по умолчанию 5). Изменение применяется к следующему ожиданию; уже запущенный таймер не меняется.',
|
||||
'settings.terminal.connection.keepaliveInterval': 'Интервал keepalive',
|
||||
@@ -872,6 +931,18 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.terminal.rendering.renderer': 'Рендерер',
|
||||
'settings.terminal.rendering.renderer.desc': 'Выберите технологию рендеринга терминала. В режиме "Авто" на устройствах с малым объёмом памяти будет использоваться DOM. Изменения применяются к новым терминальным сессиям.',
|
||||
'settings.terminal.rendering.auto': 'Авто',
|
||||
'settings.terminal.rendering.hibernateHiddenTabs': 'Переводить скрытые вкладки в спящий режим',
|
||||
'settings.terminal.rendering.hibernateHiddenTabs.desc': 'В спящем режиме скрытые вкладки освобождают память, занятую рендерером, и сохраняют SSH-соединение. Во время передачи файлов режим не включается.',
|
||||
'settings.terminal.rendering.hibernateHiddenTabsDelay': 'Задержка перед переходом в спящий режим',
|
||||
'settings.terminal.rendering.hibernateHiddenTabsDelay.desc': 'Сколько времени вкладка должна оставаться скрытой до освобождения рендерера (5–600 секунд).',
|
||||
'settings.terminal.rendering.hibernateSkipAltScreen': 'Отключать спящий режим для полноэкранных приложений',
|
||||
'settings.terminal.rendering.hibernateSkipAltScreen.desc': 'Сохранять рендерер терминала, пока vim, htop или агенты с текстовым интерфейсом используют альтернативный экранный буфер.',
|
||||
'settings.terminal.rendering.hibernateKeepRendererCount': 'Сохранять рендереры скрытых вкладок',
|
||||
'settings.terminal.rendering.hibernateKeepRendererCount.desc': 'Количество скрытых вкладок, для которых рендерер сохраняется с приостановленным WebGL перед переходом в спящий режим.',
|
||||
'settings.terminal.rendering.hibernateReplayChunkBytes': 'Объём вывода за кадр при восстановлении',
|
||||
'settings.terminal.rendering.hibernateReplayChunkBytes.desc': 'Сколько данных вывода восстанавливать за один кадр анимации при выходе терминала из спящего режима (4–64 КБ).',
|
||||
'settings.terminal.rendering.hibernatePreferWasmSerialize': 'Предпочитать сериализацию через WASM',
|
||||
'settings.terminal.rendering.hibernatePreferWasmSerialize.desc': 'По возможности сериализовать состояние терминала через WASM. Если WASM недоступен, использовать JavaScript.',
|
||||
|
||||
// Settings > Terminal > Inline Images
|
||||
'settings.terminal.section.inlineImages': 'Встроенные изображения',
|
||||
@@ -1129,6 +1200,7 @@ export const ruCoreMessages: Messages = {
|
||||
'vault.groups.selectedCount': 'Выбрано групп: {count}',
|
||||
'vault.groups.deleteMultiple.success': 'Удалено выбранных элементов: {count}',
|
||||
'vault.groups.ungrouped': 'Без группы',
|
||||
'vault.groups.unnamed': 'Группа без имени',
|
||||
'vault.groups.field.name': 'Имя группы',
|
||||
'vault.groups.placeholder.example': 'например, Production',
|
||||
'vault.groups.parentLabel': 'Родитель',
|
||||
@@ -1137,7 +1209,10 @@ export const ruCoreMessages: Messages = {
|
||||
'vault.groups.details': 'Сведения о группе',
|
||||
'vault.groups.details.general': 'Общие',
|
||||
'vault.groups.details.ssh': 'SSH',
|
||||
'vault.groups.details.rdp': 'RDP',
|
||||
'vault.groups.details.vnc': 'VNC',
|
||||
'vault.groups.details.telnet': 'Telnet',
|
||||
'vault.groups.details.protocolNotEnabledDesc': 'Параметры {protocol} по умолчанию для этой группы ещё не настроены.',
|
||||
'vault.groups.details.advanced': 'Дополнительно',
|
||||
'vault.groups.details.appearance': 'Внешний вид',
|
||||
'vault.groups.details.mosh': 'Mosh',
|
||||
@@ -1163,6 +1238,7 @@ export const ruCoreMessages: Messages = {
|
||||
|
||||
'vault.hosts.header.entries': 'Записей: {count}',
|
||||
'vault.hosts.header.live': 'Активных: {count}',
|
||||
'vault.hosts.errors.nameRequired': 'Укажите имя хоста.',
|
||||
'deepLink.ssh.invalid': 'Недопустимая ссылка ssh://',
|
||||
'deepLink.telnet.invalid': 'Недопустимая ссылка telnet://',
|
||||
'deepLink.jms.invalid': 'Недопустимая ссылка JumpServer',
|
||||
@@ -1196,15 +1272,19 @@ export const ruCoreMessages: Messages = {
|
||||
"plugins.interaction.copy": "Копировать в буфер обмена",
|
||||
"plugins.interaction.failed": "Запрос истёк или не выполнен.",
|
||||
"plugins.command.failed": "Не удалось выполнить команду плагина. Проверьте необходимые выбранные объекты и разрешения.",
|
||||
"plugins.interaction.terminalDisclosure": "Only the current selection from this terminal is shared, up to 4096 UTF-8 bytes. Terminal text can contain passwords, tokens, and other secrets. Inspect the exact preview before sharing. No redaction guarantee is made.",
|
||||
"plugins.interaction.terminalTarget": "Selected terminal",
|
||||
"plugins.interaction.terminalPreview": "Preview terminal selection",
|
||||
"plugins.interaction.draftNote": "Editable draft for review only. This dialog sends no terminal input or Enter. Copy text yourself and use the normal terminal UI if you choose to send it. Your edits stay in this dialog.",
|
||||
"plugins.interaction.draft": "Terminal input draft",
|
||||
"plugins.interaction.exactText": "Exact text with escaped controls",
|
||||
"plugins.interaction.closeDraft": "Close draft",
|
||||
"plugins.interaction.terminalDisclosure": "Плагину передаётся только выделенный в этом терминале текст (до 4096 байт в UTF-8). Он может содержать пароли, токены и другие секреты. Перед передачей проверьте текст целиком. Автоматическое скрытие секретов не гарантируется.",
|
||||
"plugins.interaction.terminalTarget": "Выбранный терминал",
|
||||
"plugins.interaction.terminalPreview": "Предпросмотр выделенного текста",
|
||||
"plugins.interaction.draftNote": "Здесь можно просмотреть и отредактировать черновик. Диалог не отправляет в терминал текст или нажатие Enter. Чтобы отправить текст, скопируйте его и вставьте в терминал. Изменения сохраняются только в этом диалоге.",
|
||||
"plugins.interaction.draft": "Черновик ввода в терминал",
|
||||
"plugins.interaction.exactText": "Исходный текст с экранированными управляющими символами",
|
||||
"plugins.interaction.closeDraft": "Закрыть черновик",
|
||||
"settings.plugins.permissions.current": "Соответствует текущему запуску",
|
||||
"settings.plugins.permissions.inactive": "Не действует для текущего запуска",
|
||||
"settings.plugins.permissions.note": "Заявленные возможности по умолчанию разрешены. В режиме «Спрашивать» Netcatty запрашивает разрешение с ограниченной областью действия. Режим «Запретить» сразу блокирует доступ. Цель можно выбрать, а черновик отредактировать в интерфейсе Netcatty.",
|
||||
"settings.plugins.permissions.allow": "Разрешить",
|
||||
"settings.plugins.permissions.ask": "Спрашивать",
|
||||
"settings.plugins.permissions.deny": "Запретить",
|
||||
"settings.plugins.permissions.title": "Сохранённые разрешения",
|
||||
"settings.plugins.permissions.refresh": "Обновить",
|
||||
"settings.plugins.permissions.loading": "Загрузка разрешений...",
|
||||
@@ -1214,7 +1294,7 @@ export const ruCoreMessages: Messages = {
|
||||
"settings.plugins.permissions.session": "До закрытия сеанса",
|
||||
"settings.plugins.permissions.audit": "Последние события безопасности (до 100)",
|
||||
"settings.plugins.permissions.revoke": "Отключить и отозвать все разрешения",
|
||||
"settings.plugins.permissions.revokeNote": "Плагин будет отключён, его задачи отменены, а сохранённые разрешения удалены. Включите его для нового запроса доступа.",
|
||||
"settings.plugins.permissions.revokeNote": "Плагин будет отключён, его задачи отменены, а сохранённые разрешения отозваны. Выбранные режимы «Разрешить», «Спрашивать» и «Запретить» сохранятся.",
|
||||
"settings.plugins.permissions.unavailable": "Управление разрешениями недоступно",
|
||||
"settings.plugins.manager.permissions": "Заявленные разрешения",
|
||||
"settings.plugins.manager.permissionNote": "Заявленные поддерживаемые возможности по умолчанию разрешены. Для каждой можно выбрать запрос или запрет в настройках разрешений. Проверки приложения и область ресурсов действуют всегда.",
|
||||
@@ -1272,28 +1352,28 @@ export const ruCoreMessages: Messages = {
|
||||
"settings.plugins.manager.unbounded": "Более узкая область ресурсов не заявлена. Проверки приложения и выбранный режим разрешений продолжают действовать.",
|
||||
"settings.plugins.openView": "Открыть",
|
||||
"settings.plugins.openManager": "Открыть управление плагинами",
|
||||
"settings.plugins.sources.conflict": "This ID is installed from another source. Uninstall and explicitly reset its private data before switching. Existing source:",
|
||||
"settings.plugins.sources.clearPrivate": "Also clear this source’s private data, grants and secrets to reinstall from another source. This cannot be undone.",
|
||||
"settings.plugins.sources.conflict": "Плагин с этим идентификатором установлен из другого источника. Перед сменой источника удалите плагин и очистите его приватные данные. Текущий источник:",
|
||||
"settings.plugins.sources.clearPrivate": "Также удалить приватные данные, выданные разрешения и секреты этого источника, чтобы установить плагин из другого источника. Это действие нельзя отменить.",
|
||||
"settings.plugins.sources.short.official": "Официальный",
|
||||
"settings.plugins.sources.short.thirdparty": "Сторонний",
|
||||
"settings.plugins.sources.short.local": "Локальный",
|
||||
"settings.plugins.sources.official": "Official marketplace",
|
||||
"settings.plugins.sources.thirdparty": "Third-party marketplace",
|
||||
"settings.plugins.sources.manage": "Manage sources",
|
||||
"settings.plugins.sources.select": "Select a source",
|
||||
"settings.plugins.sources.empty": "Choose or add a third-party source.",
|
||||
"settings.plugins.sources.add": "Add source",
|
||||
"settings.plugins.sources.remove": "Remove source",
|
||||
"settings.plugins.sources.name": "Source name",
|
||||
"settings.plugins.sources.address": "HTTPS source address",
|
||||
"settings.plugins.sources.risk": "Third-party sources are not maintained or endorsed by Netcatty. Review the real domain, package permissions and author before installing.",
|
||||
"settings.plugins.sources.accept": "I trust this domain to supply plugin metadata and packages. This does not grant plugin permissions.",
|
||||
"settings.plugins.sources.removeNote": "Installed plugins and their data remain. Updates from this source stop; another source will not replace it.",
|
||||
"settings.plugins.sources.disablePlugins": "Also disable plugins installed from this source",
|
||||
"settings.plugins.sources.installConfirm": "Review third-party installation",
|
||||
"settings.plugins.sources.source": "Source",
|
||||
"settings.plugins.sources.local": "Local import",
|
||||
"settings.plugins.sources.all": "All sources",
|
||||
"settings.plugins.sources.official": "Официальный каталог",
|
||||
"settings.plugins.sources.thirdparty": "Сторонний каталог",
|
||||
"settings.plugins.sources.manage": "Управление источниками",
|
||||
"settings.plugins.sources.select": "Выбрать источник",
|
||||
"settings.plugins.sources.empty": "Выберите или добавьте сторонний источник.",
|
||||
"settings.plugins.sources.add": "Добавить источник",
|
||||
"settings.plugins.sources.remove": "Удалить источник",
|
||||
"settings.plugins.sources.name": "Название источника",
|
||||
"settings.plugins.sources.address": "HTTPS-адрес источника",
|
||||
"settings.plugins.sources.risk": "Netcatty не поддерживает и не рекомендует сторонние источники. Перед установкой проверьте фактический домен, разрешения пакета и сведения об авторе.",
|
||||
"settings.plugins.sources.accept": "Я доверяю этому домену как источнику метаданных и пакетов плагинов. Это не выдаёт плагинам разрешений.",
|
||||
"settings.plugins.sources.removeNote": "Установленные плагины и их данные сохранятся. Обновления из этого источника прекратятся. Другой источник не заменит его.",
|
||||
"settings.plugins.sources.disablePlugins": "Также отключить плагины из этого источника",
|
||||
"settings.plugins.sources.installConfirm": "Проверка установки из стороннего источника",
|
||||
"settings.plugins.sources.source": "Источник",
|
||||
"settings.plugins.sources.local": "Импорт из файла",
|
||||
"settings.plugins.sources.all": "Все источники",
|
||||
"settings.plugins.title": "Плагины",
|
||||
"settings.plugins.configuration": "Настройки плагина",
|
||||
"settings.plugins.description": "Управляйте плагинами и просматривайте каталог.",
|
||||
|
||||
@@ -26,6 +26,9 @@ export const ruSystemManagerMessages: Messages = {
|
||||
'systemManager.errors.loadDockerImages': 'Не удалось загрузить образы',
|
||||
'systemManager.errors.loadKubernetes': 'Не удалось загрузить ресурсы Kubernetes',
|
||||
'systemManager.errors.loadPods': 'Не удалось загрузить поды',
|
||||
'systemManager.errors.nerdctlUnreachable': 'nerdctl не может подключиться к containerd',
|
||||
'systemManager.errors.clusterUnreachable': 'Не удалось подключиться к кластеру для контекста {{context}}',
|
||||
'systemManager.errors.clusterUnreachableGeneric': 'Не удалось подключиться к кластеру',
|
||||
'systemManager.errors.loadGpu': 'Не удалось загрузить статистику GPU / NPU',
|
||||
'systemManager.errors.loadPorts': 'Не удалось загрузить слушающие порты',
|
||||
'systemManager.errors.loadServices': 'Не удалось загрузить службы systemd',
|
||||
@@ -187,6 +190,20 @@ export const ruSystemManagerMessages: Messages = {
|
||||
'systemManager.k8s.restarts': '{{count}} перезапусков',
|
||||
'systemManager.k8s.chooseContainer': 'Выберите контейнер',
|
||||
'systemManager.k8s.noContext': 'На этом хосте нет контекста Kubernetes',
|
||||
'systemManager.k8s.status.Running': 'Работает',
|
||||
'systemManager.k8s.status.Pending': 'Ожидает запуска',
|
||||
'systemManager.k8s.status.Completed': 'Завершён',
|
||||
'systemManager.k8s.status.Succeeded': 'Завершён успешно',
|
||||
'systemManager.k8s.status.Failed': 'Завершён с ошибкой',
|
||||
'systemManager.k8s.status.Unknown': 'Состояние неизвестно',
|
||||
'systemManager.k8s.status.CrashLoopBackOff': 'Циклические сбои',
|
||||
'systemManager.k8s.status.ContainerCreating': 'Создаётся контейнер',
|
||||
'systemManager.k8s.status.Terminating': 'Завершается',
|
||||
'systemManager.k8s.status.ImagePullBackOff': 'Повтор загрузки',
|
||||
'systemManager.k8s.status.ErrImagePull': 'Ошибка загрузки образа',
|
||||
'systemManager.k8s.status.Error': 'Ошибка',
|
||||
'systemManager.k8s.status.Evicted': 'Вытеснен',
|
||||
'systemManager.k8s.status.OOMKilled': 'Нехватка памяти',
|
||||
|
||||
'systemManager.ports.unavailable': 'На этом хосте не обнаружены инструменты портов (ss / netstat).',
|
||||
'systemManager.ports.loading': 'Загрузка слушающих портов…',
|
||||
@@ -232,7 +249,7 @@ export const ruSystemManagerMessages: Messages = {
|
||||
'systemManager.services.enable': 'Включить автозапуск',
|
||||
'systemManager.services.disable': 'Отключить автозапуск',
|
||||
'systemManager.services.reload': 'Перезагрузить',
|
||||
'systemManager.services.scope.user': 'user',
|
||||
'systemManager.services.scope.user': 'Пользовательская служба',
|
||||
'systemManager.services.confirmAction': '{{action}} {{name}}?',
|
||||
|
||||
'systemManager.gpu.unavailable': 'На этом хосте не обнаружены инструменты NVIDIA GPU или Ascend NPU.',
|
||||
|
||||
@@ -21,8 +21,8 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.directory.readFailed': 'Не удалось прочитать каталог. Попробуйте обновить.',
|
||||
'terminal.directory.changeFailed': 'Не удалось подтвердить смену каталога. Обновите перед повтором.',
|
||||
'terminal.directory.unsupportedPath': 'Это имя каталога нельзя безопасно передать в терминал.',
|
||||
'settings.terminal.behavior.contextChips': 'Context Chips',
|
||||
'settings.terminal.behavior.contextChips.desc': 'Показывать панель контекста под быстрыми командами.',
|
||||
'settings.terminal.behavior.contextChips': 'Панель контекста',
|
||||
'settings.terminal.behavior.contextChips.desc': 'Показывать панель контекста под быстрыми командами в области ввода.',
|
||||
|
||||
'terminal.toolbar.openSessionLog': 'Открыть журнал сессии',
|
||||
'terminal.toolbar.sessionLogActions': 'Действия с журналом',
|
||||
@@ -75,13 +75,13 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.browser.title': 'Браузер',
|
||||
'terminal.browser.sshOnly': 'Выберите SSH-терминал, чтобы открыть его браузер.',
|
||||
'terminal.browser.open': 'Открыть браузер',
|
||||
'terminal.toolbar.availableAfterConnect': 'Доступно после подключения',
|
||||
'terminal.toolbar.availableAfterConnect': 'Нужно подключение',
|
||||
'terminal.toolbar.sendYmodem': 'Отправить через YMODEM',
|
||||
'terminal.toolbar.receiveYmodem': 'Получить через YMODEM',
|
||||
'terminal.toolbar.more': 'Другие действия',
|
||||
'terminal.toolbar.scripts': 'Скрипты',
|
||||
'terminal.toolbar.history': 'История команд',
|
||||
'terminal.toolbar.configureOsc7': 'Настроить отслеживание каталога',
|
||||
'terminal.toolbar.configureOsc7': 'Отслеживание каталога',
|
||||
'history.scope.label': 'Область истории',
|
||||
'history.tab.host': 'Хост',
|
||||
'history.tab.global': 'Глобальная',
|
||||
@@ -236,7 +236,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.clipboardImageUpload.noImage': 'В буфере обмена нет изображения',
|
||||
'terminal.clipboardImageUpload.failed': 'Не удалось загрузить изображение из буфера обмена',
|
||||
'terminal.selection.addToAI': 'Добавить в чат',
|
||||
'terminal.selection.addToAIDesc': 'Прикрепить выбранный вывод терминала к черновику AI',
|
||||
'terminal.selection.addToAIDesc': 'Прикрепить выделенный вывод терминала к черновику сообщения для ИИ',
|
||||
'terminal.auth.password': 'Пароль',
|
||||
'terminal.auth.sshKey': 'SSH-ключ',
|
||||
'terminal.auth.username': 'Имя пользователя',
|
||||
@@ -273,8 +273,11 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.connection.protocol.ssh': 'SSH',
|
||||
'terminal.connection.protocol.telnet': 'Telnet',
|
||||
'terminal.connection.protocol.mosh': 'Mosh',
|
||||
'terminal.connection.protocol.et': 'EternalTerminal',
|
||||
'terminal.connection.protocol.plugin': 'Подключение плагина',
|
||||
'terminal.connection.protocol.serial': 'Serial',
|
||||
'terminal.et.proxyUnsupported': 'EternalTerminal пока не поддерживает настройки прокси Netcatty. Используйте SSH или уберите прокси для этого хоста.',
|
||||
'terminal.et.multiJumpUnsupported': 'В Netcatty EternalTerminal пока поддерживает только один промежуточный хост.',
|
||||
'terminal.connection.protocol.serial': 'Последовательный порт',
|
||||
'terminal.connection.protocol.local': 'Локальная оболочка',
|
||||
'terminal.hostKey.unknownTitle': 'Подтвердите этот ключ хоста',
|
||||
'terminal.hostKey.changedTitle': 'Ключ хоста изменился',
|
||||
@@ -736,6 +739,8 @@ export const ruTerminalMessages: Messages = {
|
||||
'snippets.action.selectSnippets': 'Выбрать сниппеты',
|
||||
'snippets.panel.newTitle': 'Новый сниппет',
|
||||
'snippets.panel.editTitle': 'Редактировать сниппет',
|
||||
'snippets.panel.newAutomationTitle': 'Новый скрипт автоматизации',
|
||||
'snippets.panel.editAutomationTitle': 'Редактировать скрипт автоматизации',
|
||||
'snippets.panel.resizeWidth': 'Изменить ширину панели',
|
||||
'snippets.field.description': 'Описание действия',
|
||||
'snippets.field.descriptionPlaceholder': 'Например: проверить сетевую нагрузку',
|
||||
@@ -762,6 +767,9 @@ export const ruTerminalMessages: Messages = {
|
||||
'snippets.targets.selectHosts': 'Хосты',
|
||||
'snippets.targets.selectGroups': 'Группы',
|
||||
'snippets.targets.noGroups': 'Группы не найдены',
|
||||
'snippets.targets.allHosts': 'Применять ко всем хостам',
|
||||
'snippets.targets.allHostsShort': 'Все хосты',
|
||||
'snippets.targets.allHostsActive': 'Применяется ко всем хостам, к которым можно подключиться.',
|
||||
'snippets.history.title': 'История оболочки',
|
||||
'snippets.history.subtitle': '{count} команд',
|
||||
'snippets.history.emptyTitle': 'История оболочки пока пуста',
|
||||
@@ -844,7 +852,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'snippets.shortkey.error.snippetConflict': 'Это сочетание уже используется сниппетом: {name}',
|
||||
|
||||
// Serial Port
|
||||
'serial.button': 'Серийный',
|
||||
'serial.button': 'Serial',
|
||||
'serial.modal.title': 'Подключение к последовательному порту',
|
||||
'serial.modal.desc': 'Настройте параметры подключения к последовательному порту',
|
||||
'serial.field.port': 'Последовательный порт',
|
||||
@@ -862,8 +870,8 @@ export const ruTerminalMessages: Messages = {
|
||||
'serial.parity.none': 'Нет',
|
||||
'serial.parity.even': 'Чётная',
|
||||
'serial.parity.odd': 'Нечётная',
|
||||
'serial.parity.mark': 'Mark',
|
||||
'serial.parity.space': 'Space',
|
||||
'serial.parity.mark': 'Всегда 1 (Mark)',
|
||||
'serial.parity.space': 'Всегда 0 (Space)',
|
||||
'serial.flowControl.none': 'Нет',
|
||||
'serial.flowControl.xon/xoff': 'XON/XOFF (программный)',
|
||||
'serial.flowControl.rts/cts': 'RTS/CTS (аппаратный)',
|
||||
|
||||
@@ -861,6 +861,9 @@ export const ruVaultMessages: Messages = {
|
||||
'hostDetails.distro.option.zyxel': 'ZyXEL',
|
||||
'hostDetails.distro.option.ruijie': 'Ruijie',
|
||||
'hostDetails.section.mosh': 'Mosh',
|
||||
'hostDetails.section.et': 'EternalTerminal',
|
||||
'hostDetails.et.port': 'Порт сервера ET',
|
||||
'hostDetails.et.port.desc': 'Порт, на котором etserver принимает подключения (по умолчанию 2022)',
|
||||
'hostDetails.username.placeholder': 'Имя пользователя',
|
||||
'hostDetails.password.placeholder': 'Пароль',
|
||||
'hostDetails.password.show': 'Показать пароль',
|
||||
@@ -939,7 +942,7 @@ export const ruVaultMessages: Messages = {
|
||||
'hostDetails.section.deviceType': 'Тип устройства',
|
||||
'hostDetails.deviceType': 'Режим сетевого устройства',
|
||||
'hostDetails.deviceType.desc': 'Включайте для сетевого оборудования (коммутаторов, маршрутизаторов, межсетевых экранов), подключённого по SSH. Команды отправляются как есть, без обёртки оболочки, что совместимо с CLI вендоров вроде Huawei VRP и Cisco IOS.',
|
||||
'hostDetails.deviceType.warning': 'Команды AI-агента будут отправляться напрямую без отслеживания кода выхода. Включайте только для устройств, на которых нет стандартной оболочки.',
|
||||
'hostDetails.deviceType.warning': 'Команды агента ИИ будут отправляться напрямую без отслеживания кода выхода. Включайте только для устройств, на которых нет стандартной оболочки.',
|
||||
'hostDetails.section.sshAlgorithms': 'SSH-алгоритмы',
|
||||
'hostDetails.section.terminalBehavior': 'Поведение терминала',
|
||||
'hostDetails.lineTimestamps': 'Показывать время вывода',
|
||||
@@ -1025,7 +1028,7 @@ export const ruVaultMessages: Messages = {
|
||||
'hostDetails.startupCommand': 'Команда запуска',
|
||||
'hostDetails.startupCommand.placeholder': 'Команда для запуска при подключении (например, cd /app && ls)',
|
||||
'hostDetails.startupCommand.help':
|
||||
'This command will be executed automatically after SSH connection is established.',
|
||||
'Команда выполняется автоматически после подключения по SSH.',
|
||||
'hostDetails.startupCommand.runMode': 'Многострочный запуск',
|
||||
'hostDetails.startupCommand.runMode.help': 'Выберите, как отправлять многострочные команды запуска после подключения.',
|
||||
'hostDetails.startupCommand.runMode.lineDelay': 'Отправлять построчно',
|
||||
@@ -1331,8 +1334,8 @@ export const ruVaultMessages: Messages = {
|
||||
'remoteDesktop.cert.rejected': 'TLS-сертификат отклонён пользователем.',
|
||||
'remoteDesktop.step.bastion': 'Бастион',
|
||||
'remoteDesktop.step.network': 'Сеть',
|
||||
'remoteDesktop.step.nla': 'NLA Auth',
|
||||
'remoteDesktop.step.rfb': 'RFB Auth',
|
||||
'remoteDesktop.step.nla': 'Аутентификация NLA',
|
||||
'remoteDesktop.step.rfb': 'Аутентификация RFB',
|
||||
'remoteDesktop.step.desktop': 'Рабочий стол',
|
||||
'remoteDesktop.display.resolutionPresets': 'Пресеты разрешения',
|
||||
'remoteDesktop.display.customWidth': 'Ширина',
|
||||
@@ -1394,6 +1397,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 +1444,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': 'Записи удалённого рабочего стола',
|
||||
@@ -1448,7 +1463,7 @@ export const ruVaultMessages: Messages = {
|
||||
'settings.remoteDesktopRecordings.autoRecordDesc': 'Автоматически начинать запись RDP и VNC после подключения (выключено по умолчанию для экономии места).',
|
||||
'settings.remoteDesktopRecordings.fps': 'Частота кадров записи',
|
||||
'settings.remoteDesktopRecordings.fpsDesc': 'Более высокая частота делает видео плавнее, но увеличивает нагрузку на ЦП и размер файлов.',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} кадр/с',
|
||||
'settings.remoteDesktopRecordings.includeAudio': 'Включать звук RDP',
|
||||
'settings.remoteDesktopRecordings.includeAudioDesc': 'Записывать звук удалённого рабочего стола в видео .webm, если он доступен.',
|
||||
'settings.remoteDesktopRecordings.maxStorage': 'Лимит места на диске',
|
||||
|
||||
@@ -785,7 +785,10 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
'vault.groups.details': '分组详情',
|
||||
'vault.groups.details.general': '常规',
|
||||
'vault.groups.details.ssh': 'SSH',
|
||||
'vault.groups.details.rdp': 'RDP',
|
||||
'vault.groups.details.vnc': 'VNC',
|
||||
'vault.groups.details.telnet': 'Telnet',
|
||||
'vault.groups.details.protocolNotEnabledDesc': '当前分组尚未配置 {protocol} 默认协议设置。',
|
||||
'vault.groups.details.advanced': '高级',
|
||||
'vault.groups.details.appearance': '外观',
|
||||
'vault.groups.details.mosh': 'Mosh',
|
||||
|
||||
@@ -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': '远程桌面录屏',
|
||||
|
||||
@@ -785,7 +785,10 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
'vault.groups.details': '群組詳情',
|
||||
'vault.groups.details.general': '常規',
|
||||
'vault.groups.details.ssh': 'SSH',
|
||||
'vault.groups.details.rdp': 'RDP',
|
||||
'vault.groups.details.vnc': 'VNC',
|
||||
'vault.groups.details.telnet': 'Telnet',
|
||||
'vault.groups.details.protocolNotEnabledDesc': '目前群組尚未設定 {protocol} 預設協定設定。',
|
||||
'vault.groups.details.advanced': '高階',
|
||||
'vault.groups.details.appearance': '外觀',
|
||||
'vault.groups.details.mosh': 'Mosh',
|
||||
|
||||
@@ -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': '遠端桌面錄影',
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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({
|
||||
|
||||
@@ -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/);
|
||||
});
|
||||
@@ -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>
|
||||
) : (
|
||||
|
||||
@@ -1,14 +1,27 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import React from "react";
|
||||
import { act, create, type ReactTestRenderer } from "react-test-renderer";
|
||||
|
||||
import {
|
||||
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
|
||||
import type { GroupConfig, Identity } from "../types.ts";
|
||||
import GroupDetailsPanel, {
|
||||
hasGroupRdpFields,
|
||||
hasGroupSshFields,
|
||||
hasGroupTelnetFields,
|
||||
hasGroupVncFields,
|
||||
includeMissingIdentityOption,
|
||||
resolveGroupFormIdentityId,
|
||||
selectGroupRdpIdentity,
|
||||
selectGroupSshIdentity,
|
||||
selectGroupTelnetIdentity,
|
||||
selectGroupVncIdentity,
|
||||
} from "./GroupDetailsPanel.tsx";
|
||||
import { installDomEnvironment } from "./test-support/renderReactDom.tsx";
|
||||
import { AsidePanelFooter } from "./ui/aside-panel.tsx";
|
||||
import { Button } from "./ui/button.tsx";
|
||||
import { Input } from "./ui/input.tsx";
|
||||
import { TooltipProvider } from "./ui/tooltip.tsx";
|
||||
|
||||
test("GroupDetailsPanel treats an empty SSH identity as an explicit setting", () => {
|
||||
assert.equal(hasGroupSshFields({ identityId: "" }), true);
|
||||
@@ -114,4 +127,295 @@ test("GroupDetailsPanel shows saved child manual credentials instead of a parent
|
||||
),
|
||||
undefined,
|
||||
);
|
||||
assert.equal(
|
||||
resolveGroupFormIdentityId(
|
||||
{ rdpConfig: { enabled: true, username: "child-rdp-user" } },
|
||||
"parent-rdp-identity",
|
||||
"rdp",
|
||||
),
|
||||
undefined,
|
||||
);
|
||||
assert.equal(
|
||||
resolveGroupFormIdentityId(
|
||||
{ vncConfig: { enabled: true, useHostCredentials: true } },
|
||||
"parent-vnc-identity",
|
||||
"vnc",
|
||||
),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
test("GroupDetailsPanel detects RDP and VNC configs without falsely enabling SSH on RDP-only groups with proxy/chain", () => {
|
||||
assert.equal(hasGroupRdpFields({ rdpConfig: { enabled: true } }), true);
|
||||
assert.equal(hasGroupRdpFields({}), false);
|
||||
assert.equal(hasGroupVncFields({ vncConfig: { enabled: true } }), true);
|
||||
assert.equal(hasGroupVncFields({}), false);
|
||||
|
||||
// RDP-only group with proxy/chain stays RDP-only.
|
||||
assert.equal(
|
||||
hasGroupSshFields({
|
||||
rdpConfig: { enabled: true, port: 3389 },
|
||||
proxyProfileId: "corp-proxy",
|
||||
hostChain: { hostIds: ["bastion-1"] },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
// Legacy group with only proxy/chain still shows SSH enabled.
|
||||
assert.equal(hasGroupSshFields({ proxyProfileId: "corp-proxy" }), true);
|
||||
// Telnet-only group with startupCommand does not falsely enable SSH.
|
||||
assert.equal(
|
||||
hasGroupSshFields({ telnetEnabled: true, startupCommand: "enable" }),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("GroupDetailsPanel selects and clears RDP and VNC identities cleanly", () => {
|
||||
const identity: Identity = {
|
||||
id: "win-admin",
|
||||
label: "Windows Admin",
|
||||
username: "Administrator",
|
||||
domain: "CORP",
|
||||
authMethod: "password",
|
||||
password: "secret",
|
||||
created: 1,
|
||||
};
|
||||
|
||||
const withRdp = selectGroupRdpIdentity({}, identity, identity.id);
|
||||
assert.equal(withRdp.rdpConfig?.identityId, "win-admin");
|
||||
assert.equal(withRdp.rdpConfig?.domain, "CORP");
|
||||
assert.equal(withRdp.rdpConfig?.useHostCredentials, false);
|
||||
|
||||
const clearedRdp = selectGroupRdpIdentity({}, undefined, "", "parent-rdp-id");
|
||||
assert.equal(clearedRdp.rdpConfig?.identityId, "");
|
||||
|
||||
const withVnc = selectGroupVncIdentity({}, identity, identity.id);
|
||||
assert.equal(withVnc.vncConfig?.identityId, "win-admin");
|
||||
assert.equal(withVnc.vncConfig?.useHostCredentials, false);
|
||||
|
||||
const clearedVnc = selectGroupVncIdentity({}, undefined, "", "parent-vnc-id");
|
||||
assert.equal(clearedVnc.vncConfig?.identityId, "");
|
||||
});
|
||||
|
||||
test("GroupDetailsPanel unifies 4-protocol tabs, adds RDP/VNC defaults, and saves via footer without plaintext passwords", async () => {
|
||||
const dom = installDomEnvironment();
|
||||
const previousRaf = globalThis.requestAnimationFrame;
|
||||
const previousCancelRaf = globalThis.cancelAnimationFrame;
|
||||
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
|
||||
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
|
||||
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
let savedConfig: GroupConfig | undefined;
|
||||
const createdIdentities: Identity[] = [];
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<GroupDetailsPanel
|
||||
groupPath="Windows"
|
||||
config={undefined}
|
||||
availableKeys={[]}
|
||||
identities={[]}
|
||||
onCreateIdentity={(identity) => createdIdentities.push(identity)}
|
||||
allHosts={[]}
|
||||
groups={["Windows"]}
|
||||
terminalThemeId="default"
|
||||
terminalFontSize={14}
|
||||
layout="inline"
|
||||
onSave={(value) => {
|
||||
savedConfig = value;
|
||||
}}
|
||||
onCancel={() => {}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
const protocolTabs = renderer!.root.findAll(
|
||||
(node) => node.type === "button" && typeof node.props["data-group-protocol"] === "string",
|
||||
);
|
||||
assert.deepEqual(
|
||||
protocolTabs.map((node) => node.props["data-group-protocol"]),
|
||||
["ssh", "rdp", "vnc", "telnet"],
|
||||
);
|
||||
|
||||
const collectText = (node: unknown): string => {
|
||||
if (typeof node === "string") return node;
|
||||
if (Array.isArray(node)) return node.map(collectText).join("");
|
||||
if (node && typeof node === "object" && "children" in node) {
|
||||
return collectText((node as { children: unknown }).children);
|
||||
}
|
||||
return "";
|
||||
};
|
||||
const buttonText = (btn: { children: unknown[] }) => collectText(btn.children);
|
||||
|
||||
// Switch to RDP tab and enable RDP
|
||||
const rdpTab = protocolTabs.find((node) => node.props["data-group-protocol"] === "rdp")!;
|
||||
await act(async () => {
|
||||
rdpTab.props.onClick();
|
||||
});
|
||||
const addRdpBtn = renderer!.root.findAllByType(Button).find((btn) =>
|
||||
buttonText(btn).includes("Add RDP"),
|
||||
);
|
||||
assert.ok(addRdpBtn, "expected Add RDP button when RDP is not enabled");
|
||||
await act(async () => {
|
||||
addRdpBtn.props.onClick();
|
||||
});
|
||||
|
||||
// Set RDP port, domain, username, and password (password must become a Keychain identity)
|
||||
const rdpPortInput = renderer!.root.findAllByType(Input).find(
|
||||
(input) => input.props.placeholder === "3389",
|
||||
);
|
||||
const rdpDomainInput = renderer!.root.findAllByType(Input).find(
|
||||
(input) => input.props.placeholder === "CORP (optional)",
|
||||
);
|
||||
const rdpUserInput = renderer!.root.findAllByType(Input).find(
|
||||
(input) => typeof input.props.placeholder === "string" && input.props.placeholder.includes("DOMAIN"),
|
||||
);
|
||||
const rdpPasswordInput = renderer!.root.findAllByType(Input).find(
|
||||
(input) => input.props.type === "password",
|
||||
);
|
||||
assert.ok(rdpPortInput && rdpDomainInput && rdpUserInput && rdpPasswordInput);
|
||||
await act(async () => {
|
||||
rdpPortInput.props.onChange({ target: { value: "13389" } });
|
||||
rdpDomainInput.props.onChange({ target: { value: "CORP" } });
|
||||
rdpUserInput.props.onChange({ target: { value: "admin" } });
|
||||
rdpPasswordInput.props.onChange({ target: { value: "rdp-secret" } });
|
||||
});
|
||||
|
||||
// Switch to VNC tab and enable VNC with :2 display port
|
||||
const vncTab = renderer!.root.findAll(
|
||||
(node) => node.type === "button" && node.props["data-group-protocol"] === "vnc",
|
||||
)[0];
|
||||
await act(async () => {
|
||||
vncTab.props.onClick();
|
||||
});
|
||||
const addVncBtn = renderer!.root.findAllByType(Button).find((btn) =>
|
||||
buttonText(btn).includes("Add VNC"),
|
||||
);
|
||||
assert.ok(addVncBtn, "expected Add VNC button when VNC is not enabled");
|
||||
await act(async () => {
|
||||
addVncBtn.props.onClick();
|
||||
});
|
||||
const vncPortInput = renderer!.root.findAllByType(Input).find(
|
||||
(input) => input.props.placeholder === "5900 or :0",
|
||||
);
|
||||
assert.ok(vncPortInput);
|
||||
await act(async () => {
|
||||
vncPortInput.props.onChange({ target: { value: ":2" } });
|
||||
});
|
||||
|
||||
// Save via the unified AsidePanelFooter Save button
|
||||
const footerSaveBtn = renderer!.root.findByType(AsidePanelFooter).findByType(Button);
|
||||
await act(async () => {
|
||||
footerSaveBtn.props.onClick();
|
||||
});
|
||||
|
||||
assert.ok(savedConfig, "expected GroupDetailsPanel footer save button to emit GroupConfig");
|
||||
assert.equal(savedConfig.protocol, undefined, "SSH should remain disabled");
|
||||
assert.equal(createdIdentities.length, 1);
|
||||
assert.equal(createdIdentities[0].username, "admin");
|
||||
assert.equal(createdIdentities[0].domain, "CORP");
|
||||
assert.equal(createdIdentities[0].password, "rdp-secret");
|
||||
assert.equal(savedConfig.rdpConfig?.enabled, true);
|
||||
assert.equal(savedConfig.rdpConfig?.port, 13389);
|
||||
assert.equal(savedConfig.rdpConfig?.domain, "CORP");
|
||||
assert.equal(savedConfig.rdpConfig?.identityId, createdIdentities[0].id);
|
||||
assert.equal("password" in (savedConfig.rdpConfig ?? {}), false);
|
||||
assert.equal(savedConfig.vncConfig?.enabled, true);
|
||||
assert.equal(savedConfig.vncConfig?.port, 5902);
|
||||
} finally {
|
||||
if (renderer) await act(async () => { renderer!.unmount(); });
|
||||
globalThis.requestAnimationFrame = previousRaf;
|
||||
globalThis.cancelAnimationFrame = previousCancelRaf;
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("GroupDetailsPanel preserves inherited parent RDP/VNC username and domain when creating a password-only identity", async () => {
|
||||
const dom = installDomEnvironment();
|
||||
const previousRaf = globalThis.requestAnimationFrame;
|
||||
const previousCancelRaf = globalThis.cancelAnimationFrame;
|
||||
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
|
||||
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
|
||||
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
let savedConfig: GroupConfig | undefined;
|
||||
const createdIdentities: Identity[] = [];
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<GroupDetailsPanel
|
||||
groupPath="Corp/EU"
|
||||
config={{ path: "Corp/EU", rdpConfig: { enabled: true }, vncConfig: { enabled: true } }}
|
||||
availableKeys={[]}
|
||||
identities={[]}
|
||||
onCreateIdentity={(identity) => createdIdentities.push(identity)}
|
||||
allHosts={[]}
|
||||
groups={["Corp", "Corp/EU"]}
|
||||
groupConfigs={[
|
||||
{
|
||||
path: "Corp",
|
||||
rdpConfig: { enabled: true, username: "corp-admin", domain: "CORP" },
|
||||
vncConfig: { enabled: true, username: "corp-vnc" },
|
||||
},
|
||||
]}
|
||||
terminalThemeId="default"
|
||||
terminalFontSize={14}
|
||||
layout="inline"
|
||||
onSave={(value) => {
|
||||
savedConfig = value;
|
||||
}}
|
||||
onCancel={() => {}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
const rdpPasswordInput = renderer!.root.findAllByType(Input).find(
|
||||
(input) => input.props.type === "password",
|
||||
);
|
||||
assert.ok(rdpPasswordInput);
|
||||
await act(async () => {
|
||||
rdpPasswordInput.props.onChange({ target: { value: "eu-rdp-secret" } });
|
||||
});
|
||||
|
||||
const vncTab = renderer!.root.findAll(
|
||||
(node) => node.type === "button" && node.props["data-group-protocol"] === "vnc",
|
||||
)[0];
|
||||
await act(async () => {
|
||||
vncTab.props.onClick();
|
||||
});
|
||||
const vncPasswordInput = renderer!.root.findAllByType(Input).find(
|
||||
(input) => input.props.type === "password",
|
||||
);
|
||||
assert.ok(vncPasswordInput);
|
||||
await act(async () => {
|
||||
vncPasswordInput.props.onChange({ target: { value: "eu-vnc-secret" } });
|
||||
});
|
||||
|
||||
const footerSaveBtn = renderer!.root.findByType(AsidePanelFooter).findByType(Button);
|
||||
await act(async () => {
|
||||
footerSaveBtn.props.onClick();
|
||||
});
|
||||
|
||||
assert.ok(savedConfig);
|
||||
assert.equal(createdIdentities.length, 2);
|
||||
assert.equal(createdIdentities[0].username, "corp-admin");
|
||||
assert.equal(createdIdentities[0].domain, "CORP");
|
||||
assert.equal(createdIdentities[0].password, "eu-rdp-secret");
|
||||
assert.equal(createdIdentities[1].username, "corp-vnc");
|
||||
assert.equal(createdIdentities[1].password, "eu-vnc-secret");
|
||||
} finally {
|
||||
if (renderer) await act(async () => { renderer!.unmount(); });
|
||||
globalThis.requestAnimationFrame = previousRaf;
|
||||
globalThis.cancelAnimationFrame = previousCancelRaf;
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
+660
-504
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -192,14 +192,36 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
);
|
||||
|
||||
const [vncPortText, setVncPortText] = useState<string>(() =>
|
||||
String(form.port ?? DEFAULT_VNC_PORT),
|
||||
form.port !== undefined
|
||||
? String(form.port)
|
||||
: groupDefaults?.vncConfig?.port !== undefined
|
||||
? ""
|
||||
: String(DEFAULT_VNC_PORT),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (isVncPrimary) {
|
||||
setVncPortText(String(form.port ?? DEFAULT_VNC_PORT));
|
||||
setVncPortText(
|
||||
form.port !== undefined
|
||||
? String(form.port)
|
||||
: groupDefaults?.vncConfig?.port !== undefined
|
||||
? ""
|
||||
: String(DEFAULT_VNC_PORT),
|
||||
);
|
||||
}
|
||||
}, [form.id, form.port, isVncPrimary]);
|
||||
}, [form.id, form.port, isVncPrimary, groupDefaults?.vncConfig?.port]);
|
||||
|
||||
const updateStandaloneDesktopPort = (nextPort: number | undefined) => {
|
||||
setForm((prev: Host) => ({
|
||||
...prev,
|
||||
port: nextPort,
|
||||
...(isRdpPrimary && prev.rdpConfig
|
||||
? { rdpConfig: { ...prev.rdpConfig, port: nextPort } }
|
||||
: isVncPrimary && prev.vncConfig
|
||||
? { vncConfig: { ...prev.vncConfig, port: nextPort } }
|
||||
: {}),
|
||||
}));
|
||||
};
|
||||
|
||||
const handleTabClick = (next: "ssh" | "rdp" | "vnc" | "telnet") => {
|
||||
if (onSelectProtocolTab) {
|
||||
@@ -215,7 +237,7 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
(identity: Identity) => identity.authMethod === "password" || Boolean(identity.password),
|
||||
);
|
||||
const vncDisplayLabel = isVncPrimary
|
||||
? formatVncDisplayNumber(form.port ?? DEFAULT_VNC_PORT)
|
||||
? formatVncDisplayNumber(form.port ?? groupDefaults?.vncConfig?.port ?? DEFAULT_VNC_PORT)
|
||||
: null;
|
||||
|
||||
const selectAuthMethod = (authMethod: "auto" | "password" | "key" | "certificate") => {
|
||||
@@ -382,6 +404,7 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
protocol="vnc"
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
groupDefaults={groupDefaults}
|
||||
identities={identities}
|
||||
availableKeys={availableKeys}
|
||||
onCreateIdentity={onCreateIdentity}
|
||||
@@ -394,6 +417,7 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
protocol="rdp"
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
groupDefaults={groupDefaults}
|
||||
identities={identities}
|
||||
availableKeys={availableKeys}
|
||||
onCreateIdentity={onCreateIdentity}
|
||||
@@ -416,18 +440,30 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value;
|
||||
setVncPortText(raw);
|
||||
if (!raw.trim()) {
|
||||
updateStandaloneDesktopPort(undefined);
|
||||
return;
|
||||
}
|
||||
const parsed = parseVncPortOrDisplay(raw);
|
||||
if (parsed !== null) {
|
||||
update("port", parsed);
|
||||
updateStandaloneDesktopPort(parsed);
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
if (!vncPortText.trim() && groupDefaults?.vncConfig?.port !== undefined) {
|
||||
updateStandaloneDesktopPort(undefined);
|
||||
return;
|
||||
}
|
||||
const parsed = parseVncPortOrDisplay(vncPortText);
|
||||
const resolved = parsed ?? DEFAULT_VNC_PORT;
|
||||
setVncPortText(String(resolved));
|
||||
update("port", resolved);
|
||||
const resolved = parsed ?? (groupDefaults?.vncConfig?.port !== undefined ? undefined : DEFAULT_VNC_PORT);
|
||||
setVncPortText(resolved !== undefined ? String(resolved) : "");
|
||||
updateStandaloneDesktopPort(resolved);
|
||||
}}
|
||||
placeholder={t("hostDetails.vnc.displayPlaceholder")}
|
||||
placeholder={
|
||||
groupDefaults?.vncConfig?.port
|
||||
? String(groupDefaults.vncConfig.port)
|
||||
: t("hostDetails.vnc.displayPlaceholder")
|
||||
}
|
||||
className="h-8 flex-1 min-w-0 text-center font-mono text-sm"
|
||||
/>
|
||||
{vncDisplayLabel ? (
|
||||
@@ -441,9 +477,9 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
type="number"
|
||||
value={form.port ?? ""}
|
||||
onChange={(e) =>
|
||||
update("port", e.target.value ? Number(e.target.value) : undefined)
|
||||
updateStandaloneDesktopPort(e.target.value ? Number(e.target.value) : undefined)
|
||||
}
|
||||
placeholder={String(DEFAULT_RDP_PORT)}
|
||||
placeholder={String(groupDefaults?.rdpConfig?.port ?? DEFAULT_RDP_PORT)}
|
||||
className="h-8 w-44 text-center font-mono text-sm"
|
||||
/>
|
||||
)}
|
||||
@@ -501,8 +537,8 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
onChange={(next) => update("username", next)}
|
||||
placeholder={
|
||||
isRdpPrimary
|
||||
? t("hostDetails.rdp.usernamePlaceholder")
|
||||
: t("hostDetails.vnc.usernamePlaceholder")
|
||||
? (groupDefaults?.rdpConfig?.username || t("hostDetails.rdp.usernamePlaceholder"))
|
||||
: (groupDefaults?.vncConfig?.username || t("hostDetails.vnc.usernamePlaceholder"))
|
||||
}
|
||||
identities={passwordCompatibleIdentities}
|
||||
availableKeys={availableKeys}
|
||||
@@ -563,7 +599,7 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
label={t("hostDetails.rdp.domainLabel")}
|
||||
>
|
||||
<Input
|
||||
placeholder={t("hostDetails.rdp.domainPlaceholder")}
|
||||
placeholder={groupDefaults?.rdpConfig?.domain || t("hostDetails.rdp.domainPlaceholder")}
|
||||
value={form.rdpConfig?.domain ?? ""}
|
||||
onChange={(e) =>
|
||||
setForm((prev: Host) => ({
|
||||
|
||||
@@ -23,6 +23,8 @@ export const resolvePrimaryProtocolSwitchPort = (
|
||||
nextProtocol: "ssh" | "telnet" | "rdp" | "vnc",
|
||||
hasGroupTelnetPortDefault: boolean,
|
||||
hasGroupSshPortDefault: boolean,
|
||||
hasGroupRdpPortDefault = false,
|
||||
hasGroupVncPortDefault = false,
|
||||
): number | undefined => {
|
||||
const isKnownDefaultPort =
|
||||
currentPort === undefined ||
|
||||
@@ -32,9 +34,11 @@ export const resolvePrimaryProtocolSwitchPort = (
|
||||
currentPort === 5900;
|
||||
|
||||
if (nextProtocol === "rdp") {
|
||||
if (hasGroupRdpPortDefault && isKnownDefaultPort) return undefined;
|
||||
return isKnownDefaultPort ? 3389 : currentPort;
|
||||
}
|
||||
if (nextProtocol === "vnc") {
|
||||
if (hasGroupVncPortDefault && isKnownDefaultPort) return undefined;
|
||||
return isKnownDefaultPort ? 5900 : currentPort;
|
||||
}
|
||||
if (nextProtocol === "telnet") {
|
||||
@@ -56,12 +60,18 @@ export const resolvePrimaryProtocolSavePort = (
|
||||
currentPort: number | undefined,
|
||||
hasGroupSshPortDefault: boolean,
|
||||
hasGroupTelnetPortDefault: boolean,
|
||||
hasGroupRdpPortDefault = false,
|
||||
hasGroupVncPortDefault = false,
|
||||
): number | undefined => {
|
||||
if (protocol === "rdp") {
|
||||
return currentPort ?? 3389;
|
||||
if (currentPort !== undefined) return currentPort;
|
||||
if (hasGroupRdpPortDefault) return undefined;
|
||||
return 3389;
|
||||
}
|
||||
if (protocol === "vnc") {
|
||||
return currentPort ?? 5900;
|
||||
if (currentPort !== undefined) return currentPort;
|
||||
if (hasGroupVncPortDefault) return undefined;
|
||||
return 5900;
|
||||
}
|
||||
if (protocol === "telnet") {
|
||||
if (currentPort !== undefined) return currentPort;
|
||||
|
||||
@@ -220,3 +220,159 @@ test("Host Details can restore group jump hosts from the empty-override Direct r
|
||||
assert.ok(section().findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group"));
|
||||
});
|
||||
});
|
||||
|
||||
test("Host Details keeps standalone RDP fields sparse so group RDP defaults are inherited on save", async () => {
|
||||
const group: Partial<GroupConfig> = {
|
||||
rdpConfig: {
|
||||
enabled: true,
|
||||
port: 13389,
|
||||
domain: "CORP",
|
||||
securityMode: "nla",
|
||||
audioEnabled: false,
|
||||
},
|
||||
};
|
||||
const rdpHost: Host = {
|
||||
...host,
|
||||
protocol: "rdp",
|
||||
port: undefined,
|
||||
username: "",
|
||||
password: undefined,
|
||||
authMethod: undefined,
|
||||
rdpConfig: undefined,
|
||||
};
|
||||
await withPanel(group, async ({ root, save }) => {
|
||||
const securitySelect = root.findAllByType(Select).find((item) => item.props.value === "nla");
|
||||
assert.ok(securitySelect, "expected standalone RDP editor to reflect inherited securityMode");
|
||||
const saved = await save();
|
||||
assert.equal(saved.port, undefined);
|
||||
assert.equal(saved.rdpConfig, undefined);
|
||||
const effective = applyGroupDefaults(saved, group);
|
||||
assert.equal(effective.port, 13389);
|
||||
assert.equal(effective.rdpConfig?.domain, "CORP");
|
||||
assert.equal(effective.rdpConfig?.securityMode, "nla");
|
||||
assert.equal(effective.rdpConfig?.audioEnabled, false);
|
||||
}, rdpHost);
|
||||
});
|
||||
|
||||
test("Host Details preserves useHostCredentials fallback when adding companion RDP without group credential defaults", async () => {
|
||||
await withPanel({}, async ({ root, save }) => {
|
||||
const rdpTab = root.findAll(
|
||||
(node) => node.type === "button" && node.props["data-primary-protocol"] === "rdp",
|
||||
)[0];
|
||||
assert.ok(rdpTab);
|
||||
await act(async () => { rdpTab.props.onClick(); });
|
||||
const addRdpBtn = root.findAllByType(Button).find((btn) => {
|
||||
const collect = (n: unknown): string =>
|
||||
typeof n === "string"
|
||||
? n
|
||||
: Array.isArray(n)
|
||||
? n.map(collect).join("")
|
||||
: n && typeof n === "object" && "children" in n
|
||||
? collect((n as { children: unknown }).children)
|
||||
: "";
|
||||
return collect(btn.children).includes("Add RDP");
|
||||
});
|
||||
assert.ok(addRdpBtn);
|
||||
await act(async () => { addRdpBtn.props.onClick(); });
|
||||
const saved = await save();
|
||||
assert.equal(saved.rdpConfig?.enabled, true);
|
||||
assert.equal(saved.rdpConfig?.useHostCredentials, true);
|
||||
});
|
||||
});
|
||||
|
||||
test("Host Details preserves cleared inherited companion RDP identity across save", async () => {
|
||||
const group: Partial<GroupConfig> = {
|
||||
rdpConfig: {
|
||||
enabled: true,
|
||||
identityId: "group-rdp-id",
|
||||
},
|
||||
};
|
||||
const companionHost: Host = {
|
||||
...host,
|
||||
rdpConfig: { enabled: true },
|
||||
};
|
||||
await withPanel(group, async ({ root, save }) => {
|
||||
const rdpTab = root.findAll(
|
||||
(node) => node.type === "button" && node.props["data-primary-protocol"] === "rdp",
|
||||
)[0];
|
||||
await act(async () => { rdpTab.props.onClick(); });
|
||||
const clearBtn = root.findAllByType(Button).find(
|
||||
(btn) => btn.props.size === "icon" && btn.props.className?.includes("h-8 w-8 shrink-0"),
|
||||
);
|
||||
assert.ok(clearBtn, "expected Clear button on inherited companion RDP identity");
|
||||
await act(async () => { clearBtn.props.onClick({ defaultPrevented: false }); });
|
||||
const saved = await save();
|
||||
assert.equal(saved.rdpConfig?.identityId, "");
|
||||
assert.equal(saved.rdpConfig?.useHostCredentials, false);
|
||||
const effective = applyGroupDefaults(saved, group);
|
||||
assert.equal(effective.rdpConfig?.identityId, "");
|
||||
}, companionHost);
|
||||
});
|
||||
|
||||
test("Host Details retains the inherited desktop username and domain when detaching a standalone RDP identity", async () => {
|
||||
const dom = installDomEnvironment();
|
||||
const previousRaf = globalThis.requestAnimationFrame;
|
||||
const previousCancelRaf = globalThis.cancelAnimationFrame;
|
||||
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
|
||||
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
|
||||
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
let saved: Host | undefined;
|
||||
const group: Partial<GroupConfig> = {
|
||||
rdpConfig: { enabled: true, identityId: "win-admin" },
|
||||
};
|
||||
const standaloneRdp: Host = {
|
||||
...host,
|
||||
protocol: "rdp",
|
||||
port: undefined,
|
||||
username: "",
|
||||
password: undefined,
|
||||
authMethod: undefined,
|
||||
rdpConfig: undefined,
|
||||
};
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<HostDetailsPanel
|
||||
{...panelProps(group, standaloneRdp)}
|
||||
identities={[
|
||||
{
|
||||
id: "win-admin",
|
||||
label: "Windows Admin",
|
||||
username: "Administrator",
|
||||
domain: "CORP",
|
||||
authMethod: "password",
|
||||
password: "group-secret",
|
||||
created: 1,
|
||||
},
|
||||
]}
|
||||
onSave={(value) => { saved = value; }}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
const clearBtn = renderer!.root.findAllByType(Button).find(
|
||||
(btn) => btn.props.size === "icon" && btn.props.className?.includes("h-8 w-8 shrink-0"),
|
||||
);
|
||||
assert.ok(clearBtn, "expected Clear button on inherited standalone RDP identity");
|
||||
await act(async () => { clearBtn.props.onClick({ defaultPrevented: false }); });
|
||||
|
||||
const buttons = renderer!.root.findByType(AsidePanelFooter).findAllByType(Button);
|
||||
await act(async () => { await buttons[buttons.length - 1].props.onClick(); });
|
||||
|
||||
assert.ok(saved);
|
||||
assert.equal(saved.identityId, "");
|
||||
assert.equal(saved.username, "Administrator");
|
||||
assert.equal(saved.rdpConfig?.domain, "CORP");
|
||||
} finally {
|
||||
if (renderer) await act(async () => { renderer!.unmount(); });
|
||||
globalThis.requestAnimationFrame = previousRaf;
|
||||
globalThis.cancelAnimationFrame = previousCancelRaf;
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
+175
-52
@@ -82,9 +82,7 @@ import {
|
||||
} from "../domain/pluginConnection";
|
||||
import {
|
||||
applyHostDefaultConnectProtocol,
|
||||
DEFAULT_RDP_CONFIG,
|
||||
DEFAULT_RDP_PORT,
|
||||
DEFAULT_VNC_CONFIG,
|
||||
DEFAULT_VNC_PORT,
|
||||
getHostEnabledProtocols,
|
||||
hasValidRdpFixedResolution,
|
||||
@@ -199,7 +197,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
id: crypto.randomUUID(),
|
||||
label: "",
|
||||
hostname: "",
|
||||
port: DEFAULT_RDP_PORT,
|
||||
port: groupDefaults?.rdpConfig?.port ? undefined : DEFAULT_RDP_PORT,
|
||||
username: "",
|
||||
protocol: "rdp",
|
||||
tags: [],
|
||||
@@ -207,7 +205,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
authMethod: "password",
|
||||
authPolicyVersion: 1,
|
||||
distroMode: "auto",
|
||||
rdpConfig: { ...DEFAULT_RDP_CONFIG },
|
||||
rdpConfig: {},
|
||||
createdAt: Date.now(),
|
||||
group: defaultGroup || undefined,
|
||||
} as Host;
|
||||
@@ -217,7 +215,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
id: crypto.randomUUID(),
|
||||
label: "",
|
||||
hostname: "",
|
||||
port: DEFAULT_VNC_PORT,
|
||||
port: groupDefaults?.vncConfig?.port ? undefined : DEFAULT_VNC_PORT,
|
||||
username: "",
|
||||
protocol: "vnc",
|
||||
tags: [],
|
||||
@@ -225,7 +223,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
authMethod: "password",
|
||||
authPolicyVersion: 1,
|
||||
distroMode: "auto",
|
||||
vncConfig: { ...DEFAULT_VNC_CONFIG },
|
||||
vncConfig: {},
|
||||
createdAt: Date.now(),
|
||||
group: defaultGroup || undefined,
|
||||
} as Host;
|
||||
@@ -250,11 +248,11 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
},
|
||||
);
|
||||
|
||||
const hasRdpConfig = Boolean(form.rdpConfig);
|
||||
const hasRdpProtocol = form.protocol === "rdp" || form.rdpConfig?.enabled === true;
|
||||
const [resolutionDraft, setResolutionDraft] = useState<RdpResolutionDraft>({});
|
||||
useEffect(() => {
|
||||
setResolutionDraft({});
|
||||
}, [form.id, hasRdpConfig]);
|
||||
}, [form.id, hasRdpProtocol]);
|
||||
const onResolutionDraftChange = (dimension: "width" | "height", value: string) => {
|
||||
setResolutionDraft((prev) => ({ ...prev, [dimension]: value }));
|
||||
};
|
||||
@@ -456,10 +454,17 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
[effectiveGroupDefaults, form],
|
||||
);
|
||||
|
||||
const effectiveIdentityId =
|
||||
form.protocol === "rdp"
|
||||
? (effectiveAuthHost.identityId || effectiveAuthHost.rdpConfig?.identityId)
|
||||
: form.protocol === "vnc"
|
||||
? (effectiveAuthHost.identityId || effectiveAuthHost.vncConfig?.identityId)
|
||||
: effectiveAuthHost.identityId;
|
||||
|
||||
const selectedIdentity = useMemo(() => {
|
||||
if (!effectiveAuthHost.identityId) return undefined;
|
||||
return identities.find((i) => i.id === effectiveAuthHost.identityId);
|
||||
}, [effectiveAuthHost.identityId, identities]);
|
||||
if (!effectiveIdentityId) return undefined;
|
||||
return identities.find((i) => i.id === effectiveIdentityId);
|
||||
}, [effectiveIdentityId, identities]);
|
||||
|
||||
const effectiveAuth = useMemo(() => resolveHostAuth({
|
||||
host: effectiveAuthHost,
|
||||
@@ -658,13 +663,17 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
nextProtocol,
|
||||
Boolean(effectiveGroupDefaults?.telnetPort),
|
||||
Boolean(effectiveGroupDefaults?.port),
|
||||
Boolean(effectiveGroupDefaults?.rdpConfig?.port),
|
||||
Boolean(effectiveGroupDefaults?.vncConfig?.port),
|
||||
);
|
||||
const isFreshHost = !initialData;
|
||||
if (nextProtocol === "rdp") {
|
||||
const carriedIdentityId = prev.rdpConfig?.identityId || prev.identityId;
|
||||
return {
|
||||
...prev,
|
||||
protocol: "rdp",
|
||||
port: prev.rdpConfig?.port ?? nextPort ?? DEFAULT_RDP_PORT,
|
||||
port: prev.rdpConfig?.port ?? nextPort,
|
||||
...(carriedIdentityId ? { identityId: carriedIdentityId } : {}),
|
||||
os: isFreshHost && prev.os === "linux" ? "windows" : prev.os,
|
||||
username: isFreshHost && prev.username === "root" ? "" : (prev.username ?? ""),
|
||||
authMethod: "password",
|
||||
@@ -673,20 +682,22 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
telnetEnabled: false,
|
||||
vncConfig: undefined,
|
||||
rdpConfig: {
|
||||
...DEFAULT_RDP_CONFIG,
|
||||
...(prev.rdpConfig ?? {}),
|
||||
enabled: undefined,
|
||||
defaultConnect: undefined,
|
||||
identityId: undefined,
|
||||
tunnelViaHostSsh: undefined,
|
||||
tunnelTargetHost: undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (nextProtocol === "vnc") {
|
||||
const carriedIdentityId = prev.vncConfig?.identityId || prev.identityId;
|
||||
return {
|
||||
...prev,
|
||||
protocol: "vnc",
|
||||
port: prev.vncConfig?.port ?? nextPort ?? DEFAULT_VNC_PORT,
|
||||
port: prev.vncConfig?.port ?? nextPort,
|
||||
...(carriedIdentityId ? { identityId: carriedIdentityId } : {}),
|
||||
username: isFreshHost && prev.username === "root" ? "" : (prev.username ?? ""),
|
||||
authMethod: "password",
|
||||
moshEnabled: false,
|
||||
@@ -694,10 +705,10 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
telnetEnabled: false,
|
||||
rdpConfig: undefined,
|
||||
vncConfig: {
|
||||
...DEFAULT_VNC_CONFIG,
|
||||
...(prev.vncConfig ?? {}),
|
||||
enabled: undefined,
|
||||
defaultConnect: undefined,
|
||||
identityId: undefined,
|
||||
tunnelViaHostSsh: undefined,
|
||||
tunnelTargetHost: undefined,
|
||||
},
|
||||
@@ -727,7 +738,14 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
};
|
||||
});
|
||||
},
|
||||
[effectiveGroupDefaults?.port, effectiveGroupDefaults?.telnetPort, effectiveGroupDefaults?.username, initialData],
|
||||
[
|
||||
effectiveGroupDefaults?.port,
|
||||
effectiveGroupDefaults?.rdpConfig?.port,
|
||||
effectiveGroupDefaults?.telnetPort,
|
||||
effectiveGroupDefaults?.username,
|
||||
effectiveGroupDefaults?.vncConfig?.port,
|
||||
initialData,
|
||||
],
|
||||
);
|
||||
|
||||
const isUntouchedNewHost = !initialData
|
||||
@@ -755,30 +773,44 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
setActiveProtocolTab(proto);
|
||||
setForm((prev) => {
|
||||
const hasSsh = !prev.protocol || prev.protocol === "ssh" || prev.protocol === "mosh" || prev.protocol === "et";
|
||||
const hasGroupRdpCreds = Boolean(
|
||||
effectiveGroupDefaults?.rdpConfig?.identityId
|
||||
|| effectiveGroupDefaults?.rdpConfig?.username
|
||||
|| effectiveGroupDefaults?.rdpConfig?.useHostCredentials !== undefined,
|
||||
);
|
||||
const hasGroupVncCreds = Boolean(
|
||||
effectiveGroupDefaults?.vncConfig?.identityId
|
||||
|| effectiveGroupDefaults?.vncConfig?.username
|
||||
|| effectiveGroupDefaults?.vncConfig?.useHostCredentials !== undefined,
|
||||
);
|
||||
if (hasSsh) {
|
||||
if (proto === "vnc") {
|
||||
const hasExplicitVncCreds = Boolean(
|
||||
prev.vncConfig?.identityId !== undefined
|
||||
|| prev.vncConfig?.username
|
||||
|| prev.vncConfig?.useHostCredentials !== undefined,
|
||||
);
|
||||
return {
|
||||
...prev,
|
||||
vncConfig: {
|
||||
...DEFAULT_VNC_CONFIG,
|
||||
...(prev.vncConfig ?? {}),
|
||||
enabled: true,
|
||||
port: prev.vncConfig?.port ?? DEFAULT_VNC_PORT,
|
||||
tunnelViaHostSsh: prev.vncConfig?.tunnelViaHostSsh ?? true,
|
||||
useHostCredentials: prev.vncConfig?.identityId ? false : (prev.vncConfig?.useHostCredentials ?? true),
|
||||
...(!hasExplicitVncCreds && !hasGroupVncCreds ? { useHostCredentials: true } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (proto === "rdp") {
|
||||
const hasExplicitRdpCreds = Boolean(
|
||||
prev.rdpConfig?.identityId !== undefined
|
||||
|| prev.rdpConfig?.username
|
||||
|| prev.rdpConfig?.useHostCredentials !== undefined,
|
||||
);
|
||||
return {
|
||||
...prev,
|
||||
rdpConfig: {
|
||||
...DEFAULT_RDP_CONFIG,
|
||||
...(prev.rdpConfig ?? {}),
|
||||
enabled: true,
|
||||
port: prev.rdpConfig?.port ?? DEFAULT_RDP_PORT,
|
||||
tunnelViaHostSsh: prev.rdpConfig?.tunnelViaHostSsh ?? true,
|
||||
useHostCredentials: prev.rdpConfig?.identityId ? false : (prev.rdpConfig?.useHostCredentials ?? true),
|
||||
...(!hasExplicitRdpCreds && !hasGroupRdpCreds ? { useHostCredentials: true } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -793,38 +825,54 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
// while keeping the existing protocol enabled (and default for RDP/VNC).
|
||||
if (proto === "ssh") {
|
||||
if (prev.protocol === "rdp") {
|
||||
const existingPort = prev.port ?? prev.rdpConfig?.port;
|
||||
const hasExplicitRdpCreds = Boolean(
|
||||
prev.identityId
|
||||
|| prev.rdpConfig?.identityId !== undefined
|
||||
|| prev.rdpConfig?.username
|
||||
|| prev.rdpConfig?.useHostCredentials !== undefined,
|
||||
);
|
||||
return {
|
||||
...prev,
|
||||
protocol: "ssh",
|
||||
port: effectiveGroupDefaults?.port ? undefined : 22,
|
||||
username: prev.username || (effectiveGroupDefaults?.username ? "" : "root"),
|
||||
rdpConfig: {
|
||||
...DEFAULT_RDP_CONFIG,
|
||||
...(prev.rdpConfig ?? {}),
|
||||
enabled: true,
|
||||
defaultConnect: true,
|
||||
port: prev.port ?? prev.rdpConfig?.port ?? DEFAULT_RDP_PORT,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: prev.identityId ? false : true,
|
||||
...(prev.identityId ? { identityId: prev.identityId } : {}),
|
||||
...(existingPort !== undefined ? { port: existingPort } : {}),
|
||||
...(prev.identityId
|
||||
? { useHostCredentials: false, identityId: prev.identityId }
|
||||
: !hasExplicitRdpCreds && !hasGroupRdpCreds
|
||||
? { useHostCredentials: true }
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (prev.protocol === "vnc") {
|
||||
const existingPort = prev.port ?? prev.vncConfig?.port;
|
||||
const hasExplicitVncCreds = Boolean(
|
||||
prev.identityId
|
||||
|| prev.vncConfig?.identityId !== undefined
|
||||
|| prev.vncConfig?.username
|
||||
|| prev.vncConfig?.useHostCredentials !== undefined,
|
||||
);
|
||||
return {
|
||||
...prev,
|
||||
protocol: "ssh",
|
||||
port: effectiveGroupDefaults?.port ? undefined : 22,
|
||||
username: prev.username || (effectiveGroupDefaults?.username ? "" : "root"),
|
||||
vncConfig: {
|
||||
...DEFAULT_VNC_CONFIG,
|
||||
...(prev.vncConfig ?? {}),
|
||||
enabled: true,
|
||||
defaultConnect: true,
|
||||
port: prev.port ?? prev.vncConfig?.port ?? DEFAULT_VNC_PORT,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: prev.identityId ? false : true,
|
||||
...(prev.identityId ? { identityId: prev.identityId } : {}),
|
||||
...(existingPort !== undefined ? { port: existingPort } : {}),
|
||||
...(prev.identityId
|
||||
? { useHostCredentials: false, identityId: prev.identityId }
|
||||
: !hasExplicitVncCreds && !hasGroupVncCreds
|
||||
? { useHostCredentials: true }
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -842,7 +890,16 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
return prev;
|
||||
});
|
||||
},
|
||||
[effectiveGroupDefaults?.port, effectiveGroupDefaults?.username],
|
||||
[
|
||||
effectiveGroupDefaults?.port,
|
||||
effectiveGroupDefaults?.rdpConfig?.identityId,
|
||||
effectiveGroupDefaults?.rdpConfig?.useHostCredentials,
|
||||
effectiveGroupDefaults?.rdpConfig?.username,
|
||||
effectiveGroupDefaults?.username,
|
||||
effectiveGroupDefaults?.vncConfig?.identityId,
|
||||
effectiveGroupDefaults?.vncConfig?.useHostCredentials,
|
||||
effectiveGroupDefaults?.vncConfig?.username,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSetDefaultProtocol = useCallback((proto: EditableHostProtocol) => {
|
||||
@@ -921,7 +978,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
savingHostRef.current = true;
|
||||
try {
|
||||
if (!pluginProtocolActive && (form.protocol === "rdp" || form.rdpConfig?.enabled)
|
||||
&& !hasValidRdpFixedResolution(form.rdpConfig, resolutionDraft)) {
|
||||
&& !hasValidRdpFixedResolution(effectiveAuthHost.rdpConfig, resolutionDraft)) {
|
||||
setActiveProtocolTab("rdp");
|
||||
toast.error(t("hostDetails.rdp.dimensionHint"));
|
||||
return;
|
||||
@@ -976,11 +1033,15 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
}
|
||||
|
||||
const { proxyConfig: _draftProxyConfig, ...formWithoutProxyDraft } = form;
|
||||
const hasGroupRdpPortDefault = Boolean(effectiveGroupDefaults?.rdpConfig?.port);
|
||||
const hasGroupVncPortDefault = Boolean(effectiveGroupDefaults?.vncConfig?.port);
|
||||
const finalPort = resolvePrimaryProtocolSavePort(
|
||||
form.protocol,
|
||||
form.port,
|
||||
Boolean(groupDefaults?.port),
|
||||
Boolean(groupDefaults?.telnetPort),
|
||||
Boolean(effectiveGroupDefaults?.port),
|
||||
Boolean(effectiveGroupDefaults?.telnetPort),
|
||||
hasGroupRdpPortDefault,
|
||||
hasGroupVncPortDefault,
|
||||
);
|
||||
let cleaned: Host = {
|
||||
...formWithoutProxyDraft,
|
||||
@@ -1014,7 +1075,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
const sanitizedRdp = cleaned.protocol === "rdp"
|
||||
? sanitizeRdpConfig({
|
||||
...(cleaned.rdpConfig ?? {}),
|
||||
port: finalPort ?? DEFAULT_RDP_PORT,
|
||||
port: finalPort ?? (hasGroupRdpPortDefault ? undefined : DEFAULT_RDP_PORT),
|
||||
enabled: undefined,
|
||||
tunnelViaHostSsh: undefined,
|
||||
tunnelTargetHost: undefined,
|
||||
@@ -1023,7 +1084,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
const sanitizedVnc = cleaned.protocol === "vnc"
|
||||
? sanitizeVncConfig({
|
||||
...(cleaned.vncConfig ?? {}),
|
||||
port: finalPort ?? DEFAULT_VNC_PORT,
|
||||
port: finalPort ?? (hasGroupVncPortDefault ? undefined : DEFAULT_VNC_PORT),
|
||||
enabled: undefined,
|
||||
tunnelViaHostSsh: undefined,
|
||||
tunnelTargetHost: undefined,
|
||||
@@ -1035,7 +1096,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
username: typeof cleaned.username === "string" ? cleaned.username.trim() : "",
|
||||
tags: Array.isArray(cleaned.tags) ? cleaned.tags : [],
|
||||
os: cleaned.os || (cleaned.protocol === "rdp" ? "windows" : "linux"),
|
||||
port: finalPort ?? (cleaned.protocol === "rdp" ? DEFAULT_RDP_PORT : DEFAULT_VNC_PORT),
|
||||
port: finalPort,
|
||||
authMethod: hasInlinePassword || cleaned.identityId ? "password" : undefined,
|
||||
authPolicyVersion: 1,
|
||||
identityFileId: undefined,
|
||||
@@ -1055,13 +1116,22 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
nextRdpConfig &&
|
||||
onCreateIdentity &&
|
||||
rdpDraft &&
|
||||
rdpDraft.password.length > 0
|
||||
rdpDraft.password.length > 0 &&
|
||||
!nextRdpConfig.useHostCredentials &&
|
||||
!nextRdpConfig.identityId
|
||||
) {
|
||||
const effectiveRdpDomain =
|
||||
nextRdpConfig.domain || effectiveGroupDefaults?.rdpConfig?.domain;
|
||||
const identity: Identity = {
|
||||
id: crypto.randomUUID(),
|
||||
label: `${finalLabel} RDP`,
|
||||
username: rdpDraft.username.trim(),
|
||||
...(nextRdpConfig.domain ? { domain: nextRdpConfig.domain } : {}),
|
||||
username: (
|
||||
rdpDraft.username ||
|
||||
nextRdpConfig.username ||
|
||||
effectiveGroupDefaults?.rdpConfig?.username ||
|
||||
""
|
||||
).trim(),
|
||||
...(effectiveRdpDomain ? { domain: effectiveRdpDomain } : {}),
|
||||
authMethod: "password",
|
||||
password: rdpDraft.password,
|
||||
created: Date.now(),
|
||||
@@ -1079,12 +1149,19 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
nextVncConfig &&
|
||||
onCreateIdentity &&
|
||||
vncDraft &&
|
||||
vncDraft.password.length > 0
|
||||
vncDraft.password.length > 0 &&
|
||||
!nextVncConfig.useHostCredentials &&
|
||||
!nextVncConfig.identityId
|
||||
) {
|
||||
const identity: Identity = {
|
||||
id: crypto.randomUUID(),
|
||||
label: `${finalLabel} VNC`,
|
||||
username: vncDraft.username.trim(),
|
||||
username: (
|
||||
vncDraft.username ||
|
||||
nextVncConfig.username ||
|
||||
effectiveGroupDefaults?.vncConfig?.username ||
|
||||
""
|
||||
).trim(),
|
||||
authMethod: "password",
|
||||
password: vncDraft.password,
|
||||
created: Date.now(),
|
||||
@@ -1342,9 +1419,17 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
password: undefined,
|
||||
identityFileId: undefined,
|
||||
identityFilePaths: undefined,
|
||||
...(prev.protocol === "rdp" && identity.domain
|
||||
? { rdpConfig: { ...(prev.rdpConfig ?? {}), domain: identity.domain } }
|
||||
: {}),
|
||||
...(prev.protocol === "rdp"
|
||||
? {
|
||||
rdpConfig: {
|
||||
...(prev.rdpConfig ?? {}),
|
||||
identityId: undefined,
|
||||
...(identity.domain ? { domain: identity.domain } : {}),
|
||||
},
|
||||
}
|
||||
: prev.protocol === "vnc" && prev.vncConfig?.identityId !== undefined
|
||||
? { vncConfig: { ...prev.vncConfig, identityId: undefined } }
|
||||
: {}),
|
||||
}));
|
||||
setPendingReferenceKeyPath(null);
|
||||
setSelectedCredentialType(null);
|
||||
@@ -1355,9 +1440,46 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
);
|
||||
|
||||
const clearIdentity = useCallback(() => {
|
||||
setForm((prev) => detachEffectiveHostIdentity(prev, effectiveAuth.username));
|
||||
const effectiveDetachUsername =
|
||||
selectedIdentity?.username
|
||||
|| (form.protocol === "rdp"
|
||||
? effectiveAuthHost.rdpConfig?.username
|
||||
: form.protocol === "vnc"
|
||||
? effectiveAuthHost.vncConfig?.username
|
||||
: undefined)
|
||||
|| effectiveAuth.username;
|
||||
setForm((prev) => {
|
||||
const detached = detachEffectiveHostIdentity(prev, effectiveDetachUsername);
|
||||
if (prev.protocol === "rdp") {
|
||||
const nextDomain = prev.rdpConfig?.domain || selectedIdentity?.domain;
|
||||
if (prev.rdpConfig?.identityId !== undefined || (nextDomain && !prev.rdpConfig?.domain)) {
|
||||
return {
|
||||
...detached,
|
||||
rdpConfig: {
|
||||
...(prev.rdpConfig ?? {}),
|
||||
identityId: undefined,
|
||||
...(nextDomain ? { domain: nextDomain } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
if (prev.protocol === "vnc" && prev.vncConfig?.identityId !== undefined) {
|
||||
return {
|
||||
...detached,
|
||||
vncConfig: { ...prev.vncConfig, identityId: undefined },
|
||||
};
|
||||
}
|
||||
return detached;
|
||||
});
|
||||
setIdentitySuggestionsOpen(false);
|
||||
}, [effectiveAuth.username]);
|
||||
}, [
|
||||
effectiveAuth.username,
|
||||
effectiveAuthHost.rdpConfig?.username,
|
||||
effectiveAuthHost.vncConfig?.username,
|
||||
form.protocol,
|
||||
selectedIdentity?.domain,
|
||||
selectedIdentity?.username,
|
||||
]);
|
||||
|
||||
const updateTelnetIdentity = useCallback((identityId: string) => {
|
||||
setForm((prev) => ({
|
||||
@@ -1650,7 +1772,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
groupDefaults={effectiveGroupDefaults}
|
||||
effectiveAuthMethod={effectiveAuthMethod}
|
||||
effectiveUsername={effectiveAuth.username}
|
||||
effectiveIdentityId={effectiveAuthHost.identityId}
|
||||
effectiveIdentityId={effectiveIdentityId}
|
||||
selectedIdentity={selectedIdentity}
|
||||
clearIdentity={clearIdentity}
|
||||
identities={identities}
|
||||
@@ -1712,6 +1834,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
onResolutionDraftChange={onResolutionDraftChange}
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
groupDefaults={effectiveGroupDefaults}
|
||||
t={t}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -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
File diff suppressed because it is too large.
Load diff
@@ -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();
|
||||
}}
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
} from "../../domain/remoteDesktop";
|
||||
import { cn } from "../../lib/utils";
|
||||
import type {
|
||||
GroupConfig,
|
||||
Host,
|
||||
Identity,
|
||||
RdpConfig,
|
||||
@@ -68,6 +69,7 @@ interface CompanionRemoteDesktopSectionsProps {
|
||||
|
||||
interface CompanionRemoteDesktopInlineFieldsProps extends CompanionRemoteDesktopSectionsProps, RdpResolutionDraftProps {
|
||||
protocol: "vnc" | "rdp";
|
||||
groupDefaults?: Partial<GroupConfig>;
|
||||
credentialDraft?: CompanionCredentialDraft;
|
||||
onCredentialDraftChange?: (draft: CompanionCredentialDraft | undefined) => void;
|
||||
}
|
||||
@@ -80,6 +82,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
protocol,
|
||||
form,
|
||||
setForm,
|
||||
groupDefaults,
|
||||
identities,
|
||||
availableKeys = [],
|
||||
credentialDraft,
|
||||
@@ -89,15 +92,25 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
t,
|
||||
}) => {
|
||||
const [vncPortInput, setVncPortInput] = useState<string>(() =>
|
||||
String(form.vncConfig?.port ?? DEFAULT_VNC_PORT),
|
||||
form.vncConfig?.port !== undefined
|
||||
? String(form.vncConfig.port)
|
||||
: groupDefaults?.vncConfig?.port !== undefined
|
||||
? ""
|
||||
: String(DEFAULT_VNC_PORT),
|
||||
);
|
||||
const [showManualPassword, setShowManualPassword] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (protocol === "vnc") {
|
||||
setVncPortInput(String(form.vncConfig?.port ?? DEFAULT_VNC_PORT));
|
||||
setVncPortInput(
|
||||
form.vncConfig?.port !== undefined
|
||||
? String(form.vncConfig.port)
|
||||
: groupDefaults?.vncConfig?.port !== undefined
|
||||
? ""
|
||||
: String(DEFAULT_VNC_PORT),
|
||||
);
|
||||
}
|
||||
}, [form.id, protocol, form.vncConfig?.port]);
|
||||
}, [form.id, protocol, form.vncConfig?.port, groupDefaults?.vncConfig?.port]);
|
||||
|
||||
const passwordCompatibleIdentities = useMemo(
|
||||
() =>
|
||||
@@ -111,12 +124,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
vncConfig: {
|
||||
...(prev.vncConfig ?? {
|
||||
...DEFAULT_VNC_CONFIG,
|
||||
enabled: true,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: true,
|
||||
}),
|
||||
...(prev.vncConfig ?? { enabled: true }),
|
||||
...patch,
|
||||
},
|
||||
}));
|
||||
@@ -126,25 +134,38 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
rdpConfig: {
|
||||
...(prev.rdpConfig ?? {
|
||||
...DEFAULT_RDP_CONFIG,
|
||||
enabled: true,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: true,
|
||||
}),
|
||||
...(prev.rdpConfig ?? { enabled: true }),
|
||||
...patch,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
if (protocol === "vnc") {
|
||||
const vncTunneled = form.vncConfig?.tunnelViaHostSsh ?? true;
|
||||
const vncNormalized = normalizeVncConfig(form.vncConfig);
|
||||
const groupVnc = groupDefaults?.vncConfig;
|
||||
const effectiveVnc = { ...(groupVnc ?? {}), ...(form.vncConfig ?? {}) };
|
||||
const vncTunneled = effectiveVnc.tunnelViaHostSsh ?? true;
|
||||
const vncNormalized = normalizeVncConfig(effectiveVnc);
|
||||
const vncDisplayLabel = formatVncDisplayNumber(vncNormalized.port);
|
||||
const hostHasManualVncCreds =
|
||||
form.vncConfig?.useHostCredentials === false
|
||||
|| Boolean(form.vncConfig?.username?.trim())
|
||||
|| form.vncConfig?.identityId !== undefined;
|
||||
const effectiveVncIdentityId = form.vncConfig?.identityId !== undefined
|
||||
? (form.vncConfig.identityId || undefined)
|
||||
: (form.vncConfig?.useHostCredentials === true || Boolean(form.vncConfig?.username?.trim()))
|
||||
? undefined
|
||||
: (groupVnc?.identityId || undefined);
|
||||
const useHostCreds =
|
||||
!form.vncConfig?.identityId && form.vncConfig?.useHostCredentials !== false;
|
||||
const selectedVncIdentity = form.vncConfig?.identityId
|
||||
? identities.find((i) => i.id === form.vncConfig?.identityId)
|
||||
!effectiveVncIdentityId
|
||||
&& (
|
||||
form.vncConfig?.useHostCredentials !== undefined
|
||||
? form.vncConfig.useHostCredentials
|
||||
: hostHasManualVncCreds
|
||||
? false
|
||||
: groupVnc?.useHostCredentials === true
|
||||
);
|
||||
const selectedVncIdentity = effectiveVncIdentityId
|
||||
? identities.find((i) => i.id === effectiveVncIdentityId)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
@@ -159,18 +180,26 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value;
|
||||
setVncPortInput(raw);
|
||||
if (!raw.trim()) {
|
||||
updateVncConfig({ port: undefined });
|
||||
return;
|
||||
}
|
||||
const parsed = parseVncPortOrDisplay(raw);
|
||||
if (parsed !== null) {
|
||||
updateVncConfig({ port: parsed });
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
if (!vncPortInput.trim() && groupVnc?.port !== undefined) {
|
||||
updateVncConfig({ port: undefined });
|
||||
return;
|
||||
}
|
||||
const parsed = parseVncPortOrDisplay(vncPortInput);
|
||||
const resolved = parsed ?? DEFAULT_VNC_PORT;
|
||||
setVncPortInput(String(resolved));
|
||||
const resolved = parsed ?? (groupVnc?.port !== undefined ? undefined : DEFAULT_VNC_PORT);
|
||||
setVncPortInput(resolved !== undefined ? String(resolved) : "");
|
||||
updateVncConfig({ port: resolved });
|
||||
}}
|
||||
placeholder={t("hostDetails.vnc.displayPlaceholder")}
|
||||
placeholder={groupVnc?.port ? String(groupVnc.port) : t("hostDetails.vnc.displayPlaceholder")}
|
||||
className="h-8 flex-1 min-w-0 text-center font-mono text-sm"
|
||||
/>
|
||||
{vncDisplayLabel ? (
|
||||
@@ -202,7 +231,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
onChange={(e) =>
|
||||
updateVncConfig({ tunnelTargetHost: e.target.value || undefined })
|
||||
}
|
||||
placeholder="127.0.0.1"
|
||||
placeholder={groupVnc?.tunnelTargetHost || "127.0.0.1"}
|
||||
className="h-8 w-44 font-mono text-sm"
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
@@ -217,7 +246,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
onCheckedChange={(checked) => {
|
||||
if (checked) {
|
||||
onCredentialDraftChange?.(undefined);
|
||||
updateVncConfig({ useHostCredentials: true, identityId: undefined });
|
||||
updateVncConfig({ useHostCredentials: true, identityId: undefined, username: undefined });
|
||||
} else {
|
||||
updateVncConfig({ useHostCredentials: false });
|
||||
}
|
||||
@@ -227,7 +256,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
|
||||
{!useHostCreds && (
|
||||
<div className="space-y-2">
|
||||
{form.vncConfig?.identityId ? (
|
||||
{effectiveVncIdentityId ? (
|
||||
<div className="flex items-center gap-2 h-10 px-3 rounded-lg border border-border/60 bg-transparent">
|
||||
<User size={16} className="text-muted-foreground shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
@@ -244,7 +273,10 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
onClick={() => updateVncConfig({ identityId: undefined, useHostCredentials: false })}
|
||||
onClick={() => updateVncConfig({
|
||||
identityId: groupVnc?.identityId ? "" : undefined,
|
||||
useHostCredentials: false,
|
||||
})}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
@@ -257,13 +289,17 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
<IdentitySuggestInput
|
||||
value={credentialDraft?.username ?? form.vncConfig?.username ?? ""}
|
||||
onChange={(next) => {
|
||||
updateVncConfig({ username: next || undefined, useHostCredentials: false });
|
||||
updateVncConfig({
|
||||
username: next || undefined,
|
||||
useHostCredentials: false,
|
||||
...(groupVnc?.identityId ? { identityId: "" } : {}),
|
||||
});
|
||||
onCredentialDraftChange?.({
|
||||
username: next,
|
||||
password: credentialDraft?.password ?? "",
|
||||
});
|
||||
}}
|
||||
placeholder={t("hostDetails.vnc.usernamePlaceholder")}
|
||||
placeholder={groupVnc?.username || t("hostDetails.vnc.usernamePlaceholder")}
|
||||
identities={passwordCompatibleIdentities}
|
||||
availableKeys={availableKeys}
|
||||
onSelectIdentity={(identity) => {
|
||||
@@ -350,12 +386,30 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
);
|
||||
}
|
||||
|
||||
const rdpTunneled = form.rdpConfig?.tunnelViaHostSsh ?? true;
|
||||
const rdpNormalized = normalizeRdpConfig(form.rdpConfig);
|
||||
const groupRdp = groupDefaults?.rdpConfig;
|
||||
const effectiveRdp = { ...(groupRdp ?? {}), ...(form.rdpConfig ?? {}) };
|
||||
const rdpTunneled = effectiveRdp.tunnelViaHostSsh ?? true;
|
||||
const rdpNormalized = normalizeRdpConfig(effectiveRdp);
|
||||
const hostHasManualRdpCreds =
|
||||
form.rdpConfig?.useHostCredentials === false
|
||||
|| Boolean(form.rdpConfig?.username?.trim())
|
||||
|| form.rdpConfig?.identityId !== undefined;
|
||||
const effectiveRdpIdentityId = form.rdpConfig?.identityId !== undefined
|
||||
? (form.rdpConfig.identityId || undefined)
|
||||
: (form.rdpConfig?.useHostCredentials === true || Boolean(form.rdpConfig?.username?.trim()))
|
||||
? undefined
|
||||
: (groupRdp?.identityId || undefined);
|
||||
const useHostCreds =
|
||||
!form.rdpConfig?.identityId && form.rdpConfig?.useHostCredentials !== false;
|
||||
const selectedRdpIdentity = form.rdpConfig?.identityId
|
||||
? identities.find((i) => i.id === form.rdpConfig?.identityId)
|
||||
!effectiveRdpIdentityId
|
||||
&& (
|
||||
form.rdpConfig?.useHostCredentials !== undefined
|
||||
? form.rdpConfig.useHostCredentials
|
||||
: hostHasManualRdpCreds
|
||||
? false
|
||||
: groupRdp?.useHostCredentials === true
|
||||
);
|
||||
const selectedRdpIdentity = effectiveRdpIdentityId
|
||||
? identities.find((i) => i.id === effectiveRdpIdentityId)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
@@ -368,11 +422,12 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
value={form.rdpConfig?.port ?? DEFAULT_RDP_PORT}
|
||||
value={form.rdpConfig?.port ?? (groupRdp?.port !== undefined ? "" : DEFAULT_RDP_PORT)}
|
||||
onChange={(e) => {
|
||||
const n = Number.parseInt(e.target.value, 10);
|
||||
updateRdpConfig({ port: Number.isFinite(n) ? n : undefined });
|
||||
}}
|
||||
placeholder={String(groupRdp?.port ?? DEFAULT_RDP_PORT)}
|
||||
className="h-8 w-44 text-center font-mono text-sm"
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
@@ -398,7 +453,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
onChange={(e) =>
|
||||
updateRdpConfig({ tunnelTargetHost: e.target.value || undefined })
|
||||
}
|
||||
placeholder="127.0.0.1"
|
||||
placeholder={groupRdp?.tunnelTargetHost || "127.0.0.1"}
|
||||
className="h-8 w-44 font-mono text-sm"
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
@@ -413,7 +468,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
onCheckedChange={(checked) => {
|
||||
if (checked) {
|
||||
onCredentialDraftChange?.(undefined);
|
||||
updateRdpConfig({ useHostCredentials: true, identityId: undefined });
|
||||
updateRdpConfig({ useHostCredentials: true, identityId: undefined, username: undefined });
|
||||
} else {
|
||||
updateRdpConfig({ useHostCredentials: false });
|
||||
}
|
||||
@@ -423,7 +478,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
|
||||
{!useHostCreds && (
|
||||
<div className="space-y-2">
|
||||
{form.rdpConfig?.identityId ? (
|
||||
{effectiveRdpIdentityId ? (
|
||||
<div className="flex items-center gap-2 h-10 px-3 rounded-lg border border-border/60 bg-transparent">
|
||||
<User size={16} className="text-muted-foreground shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
@@ -440,7 +495,10 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
onClick={() => updateRdpConfig({ identityId: undefined, useHostCredentials: false })}
|
||||
onClick={() => updateRdpConfig({
|
||||
identityId: groupRdp?.identityId ? "" : undefined,
|
||||
useHostCredentials: false,
|
||||
})}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
@@ -453,13 +511,17 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
<IdentitySuggestInput
|
||||
value={credentialDraft?.username ?? form.rdpConfig?.username ?? ""}
|
||||
onChange={(next) => {
|
||||
updateRdpConfig({ username: next || undefined, useHostCredentials: false });
|
||||
updateRdpConfig({
|
||||
username: next || undefined,
|
||||
useHostCredentials: false,
|
||||
...(groupRdp?.identityId ? { identityId: "" } : {}),
|
||||
});
|
||||
onCredentialDraftChange?.({
|
||||
username: next,
|
||||
password: credentialDraft?.password ?? "",
|
||||
});
|
||||
}}
|
||||
placeholder={t("hostDetails.rdp.usernamePlaceholder")}
|
||||
placeholder={groupRdp?.username || t("hostDetails.rdp.usernamePlaceholder")}
|
||||
identities={passwordCompatibleIdentities}
|
||||
availableKeys={availableKeys}
|
||||
onSelectIdentity={(identity) => {
|
||||
@@ -520,7 +582,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
onChange={(e) =>
|
||||
updateRdpConfig({ domain: e.target.value || undefined })
|
||||
}
|
||||
placeholder={t("hostDetails.rdp.domainPlaceholder")}
|
||||
placeholder={groupRdp?.domain || t("hostDetails.rdp.domainPlaceholder")}
|
||||
className="h-8 w-44 text-sm"
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
@@ -550,6 +612,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
<RdpResolutionFields
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
inheritedRdpConfig={groupRdp}
|
||||
t={t}
|
||||
resolutionDraft={resolutionDraft}
|
||||
onResolutionDraftChange={onResolutionDraftChange}
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
parseRdpDimensionDraft,
|
||||
type RdpResolutionDraft,
|
||||
} from "../../domain/remoteDesktop";
|
||||
import type { Host } from "../../types";
|
||||
import type { Host, RdpConfig } from "../../types";
|
||||
import { Input } from "../ui/input";
|
||||
|
||||
export interface RdpResolutionDraftProps {
|
||||
@@ -14,13 +14,14 @@ export interface RdpResolutionDraftProps {
|
||||
}
|
||||
|
||||
interface RdpResolutionFieldsProps extends RdpResolutionDraftProps {
|
||||
form: Host;
|
||||
form: Pick<Host, "rdpConfig">;
|
||||
setForm: React.Dispatch<React.SetStateAction<Host>>;
|
||||
inheritedRdpConfig?: Partial<RdpConfig>;
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export const RdpResolutionFields: React.FC<RdpResolutionFieldsProps> = ({
|
||||
form, setForm, t, resolutionDraft, onResolutionDraftChange,
|
||||
form, setForm, inheritedRdpConfig, t, resolutionDraft, onResolutionDraftChange,
|
||||
}) => {
|
||||
const [localDraft, setLocalDraft] = useState<RdpResolutionDraft>({});
|
||||
const id = useId();
|
||||
@@ -29,8 +30,11 @@ export const RdpResolutionFields: React.FC<RdpResolutionFieldsProps> = ({
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{(["width", "height"] as const).map((dimension) => {
|
||||
const value = draft[dimension] ?? String(form.rdpConfig?.[dimension]
|
||||
?? (dimension === "width" ? DEFAULT_RDP_WIDTH : DEFAULT_RDP_HEIGHT));
|
||||
const value = draft[dimension] ?? String(
|
||||
form.rdpConfig?.[dimension]
|
||||
?? inheritedRdpConfig?.[dimension]
|
||||
?? (dimension === "width" ? DEFAULT_RDP_WIDTH : DEFAULT_RDP_HEIGHT),
|
||||
);
|
||||
const invalid = parseRdpDimensionDraft(value) === undefined;
|
||||
const inputId = `${id}-${dimension}`;
|
||||
return (
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
normalizeVncConfig,
|
||||
} from "../../domain/remoteDesktop";
|
||||
import type {
|
||||
GroupConfig,
|
||||
Host,
|
||||
RdpColorDepth,
|
||||
RdpConfig,
|
||||
@@ -45,12 +46,14 @@ type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||
interface RemoteDesktopOptionsSectionProps extends RdpResolutionDraftProps {
|
||||
form: Host;
|
||||
setForm: React.Dispatch<React.SetStateAction<Host>>;
|
||||
groupDefaults?: Partial<GroupConfig>;
|
||||
t: Translate;
|
||||
}
|
||||
|
||||
export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionProps> = ({
|
||||
form,
|
||||
setForm,
|
||||
groupDefaults,
|
||||
t,
|
||||
resolutionDraft,
|
||||
onResolutionDraftChange,
|
||||
@@ -59,12 +62,18 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
|
||||
Boolean(
|
||||
form.rdpConfig?.loadBalanceInfo ||
|
||||
form.rdpConfig?.alternateShell ||
|
||||
form.rdpConfig?.shellWorkingDir,
|
||||
form.rdpConfig?.shellWorkingDir ||
|
||||
groupDefaults?.rdpConfig?.loadBalanceInfo ||
|
||||
groupDefaults?.rdpConfig?.alternateShell ||
|
||||
groupDefaults?.rdpConfig?.shellWorkingDir,
|
||||
),
|
||||
);
|
||||
|
||||
if (form.protocol === "rdp") {
|
||||
const rdp = normalizeRdpConfig(form.rdpConfig);
|
||||
const rdp = normalizeRdpConfig({
|
||||
...(groupDefaults?.rdpConfig ?? {}),
|
||||
...(form.rdpConfig ?? {}),
|
||||
});
|
||||
const updateRdp = <K extends keyof RdpConfig>(key: K, value: RdpConfig[K]) => {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
@@ -105,6 +114,7 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
|
||||
<RdpResolutionFields
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
inheritedRdpConfig={groupDefaults?.rdpConfig}
|
||||
t={t}
|
||||
resolutionDraft={resolutionDraft}
|
||||
onResolutionDraftChange={onResolutionDraftChange}
|
||||
@@ -224,7 +234,7 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
|
||||
onChange={(e) =>
|
||||
updateRdp("loadBalanceInfo", e.target.value || undefined)
|
||||
}
|
||||
placeholder={t("hostDetails.rdp.loadBalanceInfoPlaceholder")}
|
||||
placeholder={groupDefaults?.rdpConfig?.loadBalanceInfo || t("hostDetails.rdp.loadBalanceInfoPlaceholder")}
|
||||
className="h-10 rounded-lg text-sm font-mono"
|
||||
/>
|
||||
</div>
|
||||
@@ -237,7 +247,7 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
|
||||
onChange={(e) =>
|
||||
updateRdp("alternateShell", e.target.value || undefined)
|
||||
}
|
||||
placeholder={t("hostDetails.rdp.alternateShellPlaceholder")}
|
||||
placeholder={groupDefaults?.rdpConfig?.alternateShell || t("hostDetails.rdp.alternateShellPlaceholder")}
|
||||
className="h-10 rounded-lg text-sm font-mono"
|
||||
/>
|
||||
</div>
|
||||
@@ -250,7 +260,7 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
|
||||
onChange={(e) =>
|
||||
updateRdp("shellWorkingDir", e.target.value || undefined)
|
||||
}
|
||||
placeholder={t("hostDetails.rdp.shellWorkingDirPlaceholder")}
|
||||
placeholder={groupDefaults?.rdpConfig?.shellWorkingDir || t("hostDetails.rdp.shellWorkingDirPlaceholder")}
|
||||
className="h-10 rounded-lg text-sm font-mono"
|
||||
/>
|
||||
</div>
|
||||
@@ -261,7 +271,10 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
|
||||
}
|
||||
|
||||
if (form.protocol === "vnc") {
|
||||
const vnc = normalizeVncConfig(form.vncConfig);
|
||||
const vnc = normalizeVncConfig({
|
||||
...(groupDefaults?.vncConfig ?? {}),
|
||||
...(form.vncConfig ?? {}),
|
||||
});
|
||||
const updateVnc = <K extends keyof VncConfig>(key: K, value: VncConfig[K]) => {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -46,6 +46,7 @@ test('magnified side panels use an inner rounded 1px border in the side panel ac
|
||||
const strokeSource = source.slice(strokeStart, source.indexOf('/>', strokeStart));
|
||||
|
||||
assert.match(chromeSource, /overflow-hidden rounded-md bg-background shadow-2xl/);
|
||||
assert.match(chromeSource, /\[clip-path:inset\(0_round_0\.375rem\)\]/);
|
||||
assert.doesNotMatch(chromeSource, /\b(?:outline|outlineOffset|border|borderColor|borderWidth|borderStyle)\b/);
|
||||
assert.match(strokeSource, /className="pointer-events-none absolute inset-0 z-50"/);
|
||||
assert.match(strokeSource, /boxSizing: 'border-box'/);
|
||||
|
||||
@@ -1583,7 +1583,7 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
|
||||
data-section="pane-magnification-backdrop"
|
||||
/>
|
||||
<div
|
||||
className="absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl animate-in fade-in zoom-in-95 duration-150"
|
||||
className="absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl [clip-path:inset(0_round_0.375rem)] animate-in fade-in zoom-in-95 duration-150"
|
||||
style={{
|
||||
backgroundColor: sidePanelTheme.termBg,
|
||||
color: sidePanelTheme.termFg,
|
||||
|
||||
@@ -1826,7 +1826,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
"absolute bg-background",
|
||||
inActiveWorkspace && "workspace-pane",
|
||||
isVisible && "z-10",
|
||||
magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl",
|
||||
magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl [clip-path:inset(0_round_0.375rem)]",
|
||||
)}
|
||||
style={style}
|
||||
tabIndex={-1}
|
||||
|
||||
@@ -15,7 +15,7 @@ test("terminal pane chrome uses an inner rounded 1px border while retaining over
|
||||
const hostSource = paneSource.slice(0, paneSource.indexOf("<LazyLoadBoundary"));
|
||||
const strokeSource = paneSource.slice(paneSource.indexOf("{magnifiedSurfaceBounds && ("));
|
||||
|
||||
assert.match(hostSource, /^\s*magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl",$/m);
|
||||
assert.match(hostSource, /^\s*magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl \[clip-path:inset\(0_round_0\.375rem\)\]",$/m);
|
||||
assert.match(hostSource, /style=\{style\}/);
|
||||
assert.doesNotMatch(hostSource, /\b(?:outline|outlineOffset|border|borderColor|borderWidth|borderStyle)\b/);
|
||||
assert.match(strokeSource, /aria-hidden="true"/);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { MonitorNavButton } from './MonitorNavButton';
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { Combobox } from "../ui/combobox";
|
||||
import React, { useCallback } from "react";
|
||||
import React, { useCallback, useRef } from "react";
|
||||
|
||||
const LazyMonitorPanels = React.lazy(() =>
|
||||
import("./MonitorPanels").then((mod) => ({ default: mod.MonitorPanels })),
|
||||
@@ -508,6 +508,16 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
|
||||
} = ctx;
|
||||
const { importProgress, onCommitPluginImporterData, resetImportProgress } =
|
||||
ctx;
|
||||
const latestIdentitiesRef = useRef(identities);
|
||||
latestIdentitiesRef.current = identities;
|
||||
const handleCreateIdentity = useCallback(
|
||||
(identity: any) => {
|
||||
const next = [...latestIdentitiesRef.current, identity];
|
||||
latestIdentitiesRef.current = next;
|
||||
onUpdateIdentities(next);
|
||||
},
|
||||
[onUpdateIdentities],
|
||||
);
|
||||
// Host aside panel (SSH/new host) or the local-shell host panel occupies the
|
||||
// aside area — both collapse the header action buttons the same way.
|
||||
const isHostAsideOpen = isHostPanelOpen || isLocalShellHostPanelOpen;
|
||||
@@ -1622,6 +1632,7 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
|
||||
config={groupConfigs.find((c) => c.path === editingGroupPath)}
|
||||
availableKeys={keys}
|
||||
identities={identities}
|
||||
onCreateIdentity={handleCreateIdentity}
|
||||
proxyProfiles={proxyProfiles}
|
||||
allHosts={hosts}
|
||||
groups={allGroupPaths}
|
||||
@@ -1650,9 +1661,7 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
|
||||
initialProtocol={editingHost ? undefined : newHostProtocol}
|
||||
availableKeys={keys}
|
||||
identities={identities}
|
||||
onCreateIdentity={(identity) =>
|
||||
onUpdateIdentities([...identities, identity])
|
||||
}
|
||||
onCreateIdentity={handleCreateIdentity}
|
||||
proxyProfiles={proxyProfiles}
|
||||
groups={allGroupPaths}
|
||||
managedSources={managedSources}
|
||||
|
||||
@@ -950,3 +950,292 @@ test("applyGroupDefaults inherits hostChain and proxy for vnc/rdp hosts while sk
|
||||
assert.equal(result.etEnabled, undefined);
|
||||
}
|
||||
});
|
||||
|
||||
test("sanitizeGroupConfig strips accidental plaintext passwords from rdpConfig and vncConfig while keeping identityId opt-out", () => {
|
||||
const sanitized = sanitizeGroupConfig({
|
||||
path: "desktops",
|
||||
rdpConfig: {
|
||||
enabled: true,
|
||||
port: 13389,
|
||||
domain: "CORP",
|
||||
identityId: "",
|
||||
password: "never-store-plaintext",
|
||||
} as GroupConfig["rdpConfig"],
|
||||
vncConfig: {
|
||||
enabled: true,
|
||||
port: 5902,
|
||||
identityId: "",
|
||||
password: "never-store-plaintext",
|
||||
} as GroupConfig["vncConfig"],
|
||||
});
|
||||
|
||||
assert.equal(sanitized.rdpConfig?.port, 13389);
|
||||
assert.equal(sanitized.rdpConfig?.domain, "CORP");
|
||||
assert.equal(sanitized.rdpConfig?.identityId, "");
|
||||
assert.equal("password" in (sanitized.rdpConfig ?? {}), false);
|
||||
assert.equal(sanitized.vncConfig?.port, 5902);
|
||||
assert.equal(sanitized.vncConfig?.identityId, "");
|
||||
assert.equal("password" in (sanitized.vncConfig ?? {}), false);
|
||||
});
|
||||
|
||||
test("resolveGroupDefaults merges rdpConfig and vncConfig across ancestor groups", () => {
|
||||
const resolved = resolveGroupDefaults("corp/eu", [
|
||||
{
|
||||
path: "corp",
|
||||
rdpConfig: {
|
||||
enabled: true,
|
||||
port: 3389,
|
||||
domain: "CORP",
|
||||
identityId: "parent-rdp-id",
|
||||
resolutionMode: "fixed",
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
securityMode: "nla",
|
||||
audioEnabled: true,
|
||||
},
|
||||
vncConfig: {
|
||||
enabled: true,
|
||||
port: 5901,
|
||||
identityId: "parent-vnc-id",
|
||||
scalingMode: "fit",
|
||||
viewOnly: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "corp/eu",
|
||||
rdpConfig: {
|
||||
enabled: true,
|
||||
port: 13389,
|
||||
audioEnabled: false,
|
||||
},
|
||||
vncConfig: {
|
||||
enabled: true,
|
||||
username: "eu-vnc-user",
|
||||
viewOnly: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
assert.deepEqual(resolved.rdpConfig, {
|
||||
enabled: true,
|
||||
port: 13389,
|
||||
domain: "CORP",
|
||||
identityId: "parent-rdp-id",
|
||||
resolutionMode: "fixed",
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
securityMode: "nla",
|
||||
audioEnabled: false,
|
||||
});
|
||||
assert.deepEqual(resolved.vncConfig, {
|
||||
enabled: true,
|
||||
port: 5901,
|
||||
username: "eu-vnc-user",
|
||||
scalingMode: "fit",
|
||||
viewOnly: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("applyGroupDefaults inherits rdpConfig and vncConfig into standalone remote desktop hosts", () => {
|
||||
const groupDefaults: Partial<GroupConfig> = {
|
||||
port: 2222,
|
||||
username: "ssh-user",
|
||||
rdpConfig: {
|
||||
enabled: true,
|
||||
port: 13389,
|
||||
domain: "CORP",
|
||||
identityId: "group-rdp-id",
|
||||
tunnelViaHostSsh: true,
|
||||
tunnelTargetHost: "10.0.0.5",
|
||||
useHostCredentials: true,
|
||||
resolutionMode: "fixed",
|
||||
width: 1600,
|
||||
height: 900,
|
||||
colorDepth: 24,
|
||||
audioEnabled: false,
|
||||
securityMode: "nla",
|
||||
},
|
||||
vncConfig: {
|
||||
enabled: true,
|
||||
port: 5902,
|
||||
identityId: "group-vnc-id",
|
||||
tunnelViaHostSsh: true,
|
||||
scalingMode: "actual",
|
||||
quality: 8,
|
||||
compressionLevel: 4,
|
||||
viewOnly: true,
|
||||
showRemoteCursor: false,
|
||||
},
|
||||
};
|
||||
|
||||
const rdpResult = applyGroupDefaults(
|
||||
host({ protocol: "rdp", username: "", port: undefined }),
|
||||
groupDefaults,
|
||||
{ globalProxyProfileId: "" },
|
||||
);
|
||||
assert.equal(rdpResult.port, 13389);
|
||||
assert.equal(rdpResult.rdpConfig?.port, 13389);
|
||||
assert.equal(rdpResult.rdpConfig?.domain, "CORP");
|
||||
assert.equal(rdpResult.rdpConfig?.identityId, "group-rdp-id");
|
||||
assert.equal(rdpResult.rdpConfig?.resolutionMode, "fixed");
|
||||
assert.equal(rdpResult.rdpConfig?.width, 1600);
|
||||
assert.equal(rdpResult.rdpConfig?.height, 900);
|
||||
assert.equal(rdpResult.rdpConfig?.colorDepth, 24);
|
||||
assert.equal(rdpResult.rdpConfig?.audioEnabled, false);
|
||||
assert.equal(rdpResult.rdpConfig?.securityMode, "nla");
|
||||
// Companion-only flags must not leak onto standalone RDP hosts.
|
||||
assert.equal(rdpResult.rdpConfig?.enabled, undefined);
|
||||
assert.equal(rdpResult.rdpConfig?.tunnelViaHostSsh, undefined);
|
||||
assert.equal(rdpResult.rdpConfig?.tunnelTargetHost, undefined);
|
||||
assert.equal(rdpResult.rdpConfig?.useHostCredentials, undefined);
|
||||
assert.equal(rdpResult.vncConfig, undefined);
|
||||
|
||||
const vncResult = applyGroupDefaults(
|
||||
host({ protocol: "vnc", username: "", port: undefined }),
|
||||
groupDefaults,
|
||||
{ globalProxyProfileId: "" },
|
||||
);
|
||||
assert.equal(vncResult.port, 5902);
|
||||
assert.equal(vncResult.vncConfig?.port, 5902);
|
||||
assert.equal(vncResult.vncConfig?.identityId, "group-vnc-id");
|
||||
assert.equal(vncResult.vncConfig?.scalingMode, "actual");
|
||||
assert.equal(vncResult.vncConfig?.quality, 8);
|
||||
assert.equal(vncResult.vncConfig?.compressionLevel, 4);
|
||||
assert.equal(vncResult.vncConfig?.viewOnly, true);
|
||||
assert.equal(vncResult.vncConfig?.showRemoteCursor, false);
|
||||
assert.equal(vncResult.vncConfig?.enabled, undefined);
|
||||
assert.equal(vncResult.vncConfig?.tunnelViaHostSsh, undefined);
|
||||
assert.equal(vncResult.rdpConfig, undefined);
|
||||
});
|
||||
|
||||
test("applyGroupDefaults respects standalone remote desktop host overrides and manual credentials", () => {
|
||||
const groupDefaults: Partial<GroupConfig> = {
|
||||
rdpConfig: {
|
||||
enabled: true,
|
||||
port: 13389,
|
||||
domain: "GROUPDOM",
|
||||
identityId: "group-rdp-id",
|
||||
securityMode: "nla",
|
||||
},
|
||||
};
|
||||
|
||||
const result = applyGroupDefaults(
|
||||
host({
|
||||
protocol: "rdp",
|
||||
port: 3390,
|
||||
username: "local-admin",
|
||||
password: "secret",
|
||||
rdpConfig: { domain: "HOSTDOM" },
|
||||
}),
|
||||
groupDefaults,
|
||||
{ globalProxyProfileId: "" },
|
||||
);
|
||||
|
||||
assert.equal(result.port, 3390);
|
||||
assert.equal(result.rdpConfig?.port, undefined);
|
||||
assert.equal(result.rdpConfig?.domain, "HOSTDOM");
|
||||
assert.equal(result.rdpConfig?.identityId, undefined);
|
||||
assert.equal(result.rdpConfig?.securityMode, "nla");
|
||||
});
|
||||
|
||||
test("applyGroupDefaults inherits rdpConfig and vncConfig only into SSH hosts that enabled those protocols", () => {
|
||||
const groupDefaults: Partial<GroupConfig> = {
|
||||
port: 2222,
|
||||
rdpConfig: {
|
||||
enabled: true,
|
||||
port: 13389,
|
||||
domain: "CORP",
|
||||
identityId: "group-rdp-id",
|
||||
tunnelViaHostSsh: false,
|
||||
resolutionMode: "fit",
|
||||
},
|
||||
vncConfig: {
|
||||
enabled: true,
|
||||
port: 5905,
|
||||
useHostCredentials: true,
|
||||
tunnelViaHostSsh: true,
|
||||
tunnelTargetHost: "127.0.0.1",
|
||||
scalingMode: "dynamic",
|
||||
},
|
||||
};
|
||||
|
||||
// Plain SSH host without RDP/VNC enabled must NOT have RDP/VNC enabled by the group.
|
||||
const sshOnly = applyGroupDefaults(
|
||||
host({ protocol: "ssh", port: undefined }),
|
||||
groupDefaults,
|
||||
{ globalProxyProfileId: "" },
|
||||
);
|
||||
assert.equal(sshOnly.port, 2222);
|
||||
assert.equal(sshOnly.rdpConfig, undefined);
|
||||
assert.equal(sshOnly.vncConfig, undefined);
|
||||
|
||||
// SSH host with companion RDP & VNC enabled inherits both protocol configs cleanly.
|
||||
const companion = applyGroupDefaults(
|
||||
host({
|
||||
protocol: "ssh",
|
||||
port: undefined,
|
||||
rdpConfig: { enabled: true },
|
||||
vncConfig: { enabled: true, port: 5910 },
|
||||
}),
|
||||
groupDefaults,
|
||||
{ globalProxyProfileId: "" },
|
||||
);
|
||||
assert.equal(companion.port, 2222);
|
||||
assert.deepEqual(companion.rdpConfig, {
|
||||
enabled: true,
|
||||
port: 13389,
|
||||
domain: "CORP",
|
||||
identityId: "group-rdp-id",
|
||||
tunnelViaHostSsh: false,
|
||||
resolutionMode: "fit",
|
||||
});
|
||||
assert.deepEqual(companion.vncConfig, {
|
||||
enabled: true,
|
||||
port: 5910,
|
||||
useHostCredentials: true,
|
||||
tunnelViaHostSsh: true,
|
||||
tunnelTargetHost: "127.0.0.1",
|
||||
scalingMode: "dynamic",
|
||||
});
|
||||
|
||||
// Companion RDP host explicitly using host credentials must not inherit group RDP identityId.
|
||||
const companionHostCreds = applyGroupDefaults(
|
||||
host({
|
||||
protocol: "ssh",
|
||||
rdpConfig: { enabled: true, useHostCredentials: true },
|
||||
}),
|
||||
groupDefaults,
|
||||
{ globalProxyProfileId: "" },
|
||||
);
|
||||
assert.equal(companionHostCreds.rdpConfig?.useHostCredentials, true);
|
||||
assert.equal(companionHostCreds.rdpConfig?.identityId, undefined);
|
||||
assert.equal(companionHostCreds.rdpConfig?.domain, "CORP");
|
||||
|
||||
// Companion RDP host with explicit empty-string identityId opt-out keeps cleared identity across sanitize + inherit.
|
||||
const clearedCompanion = applyGroupDefaults(
|
||||
host({
|
||||
protocol: "ssh",
|
||||
rdpConfig: { enabled: true, useHostCredentials: false, identityId: "" },
|
||||
}),
|
||||
groupDefaults,
|
||||
{ globalProxyProfileId: "" },
|
||||
);
|
||||
assert.equal(clearedCompanion.rdpConfig?.identityId, "");
|
||||
assert.equal(clearedCompanion.rdpConfig?.useHostCredentials, false);
|
||||
});
|
||||
|
||||
test("applyGroupDefaults lets standalone RDP host with inline password inherit a manual group username", () => {
|
||||
const result = applyGroupDefaults(
|
||||
host({
|
||||
protocol: "rdp",
|
||||
username: "",
|
||||
password: "host-specific-password",
|
||||
}),
|
||||
{
|
||||
rdpConfig: { enabled: true, username: "Administrator" },
|
||||
},
|
||||
{ globalProxyProfileId: "" },
|
||||
);
|
||||
|
||||
assert.equal(result.rdpConfig?.username, "Administrator");
|
||||
});
|
||||
+186
-3
@@ -1,9 +1,47 @@
|
||||
import type { GroupConfig, Host } from './models';
|
||||
import type { GroupConfig, Host, RdpConfig, VncConfig } from './models';
|
||||
import { migrateDeprecatedFontOverride } from '../infrastructure/config/fonts';
|
||||
import {
|
||||
getActiveGlobalDefaultProxyProfileId,
|
||||
normalizeGlobalDefaultProxyProfileId,
|
||||
} from './globalDefaultProxy';
|
||||
import { sanitizeRdpConfig, sanitizeVncConfig } from './remoteDesktop';
|
||||
|
||||
export const hasManualGroupRdpCredentials = (config: Partial<RdpConfig> | undefined): boolean =>
|
||||
Boolean(config && (config.username !== undefined || config.useHostCredentials === true));
|
||||
|
||||
export const hasManualGroupVncCredentials = (config: Partial<VncConfig> | undefined): boolean =>
|
||||
Boolean(config && (config.username !== undefined || config.useHostCredentials === true));
|
||||
|
||||
const mergeRemoteDesktopConfigLayer = <T extends RdpConfig | VncConfig>(
|
||||
parent: T | undefined,
|
||||
child: T | undefined,
|
||||
): T | undefined => {
|
||||
if (!parent) return child ? { ...child } : undefined;
|
||||
if (!child) return { ...parent };
|
||||
const merged: Record<string, unknown> = { ...parent };
|
||||
|
||||
if (child.useHostCredentials === true) {
|
||||
delete merged.identityId;
|
||||
delete merged.username;
|
||||
} else if (child.identityId !== undefined) {
|
||||
delete merged.username;
|
||||
if (child.identityId !== '') {
|
||||
delete merged.useHostCredentials;
|
||||
}
|
||||
} else if (child.username !== undefined) {
|
||||
delete merged.identityId;
|
||||
if (child.useHostCredentials === undefined) {
|
||||
delete merged.useHostCredentials;
|
||||
}
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries(child)) {
|
||||
if (value !== undefined) {
|
||||
merged[key] = value;
|
||||
}
|
||||
}
|
||||
return merged as T;
|
||||
};
|
||||
|
||||
/**
|
||||
* Migrate deprecated primary-font ids out of a GroupConfig's
|
||||
@@ -19,9 +57,19 @@ export function sanitizeGroupConfig(config: GroupConfig): GroupConfig {
|
||||
&& !migrated.identityFileId
|
||||
&& !migrated.identityFilePaths?.length;
|
||||
|
||||
const next = hasLegacyPasswordOnlyCredentials
|
||||
let next: GroupConfig = hasLegacyPasswordOnlyCredentials
|
||||
? { ...migrated, authMethod: 'password' as const }
|
||||
: migrated;
|
||||
: { ...migrated };
|
||||
if (Object.prototype.hasOwnProperty.call(next, 'rdpConfig')) {
|
||||
const rdpConfig = sanitizeRdpConfig(next.rdpConfig);
|
||||
if (rdpConfig) next.rdpConfig = rdpConfig;
|
||||
else delete next.rdpConfig;
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(next, 'vncConfig')) {
|
||||
const vncConfig = sanitizeVncConfig(next.vncConfig);
|
||||
if (vncConfig) next.vncConfig = vncConfig;
|
||||
else delete next.vncConfig;
|
||||
}
|
||||
if (!Object.prototype.hasOwnProperty.call(next, 'singleChannelSsh')) return next;
|
||||
const cleaned = { ...next };
|
||||
delete (cleaned as { singleChannelSsh?: unknown }).singleChannelSsh;
|
||||
@@ -153,6 +201,20 @@ export function resolveGroupDefaults(
|
||||
continue;
|
||||
}
|
||||
if (key !== 'path' && key !== 'notes' && value !== undefined) {
|
||||
if (key === 'rdpConfig') {
|
||||
merged.rdpConfig = mergeRemoteDesktopConfigLayer(
|
||||
merged.rdpConfig as RdpConfig | undefined,
|
||||
value as RdpConfig,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (key === 'vncConfig') {
|
||||
merged.vncConfig = mergeRemoteDesktopConfigLayer(
|
||||
merged.vncConfig as VncConfig | undefined,
|
||||
value as VncConfig,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (key === 'proxyProfileId') {
|
||||
delete merged.proxyConfig;
|
||||
}
|
||||
@@ -237,6 +299,95 @@ const REMOTE_DESKTOP_INHERITABLE_KEYS = new Set<keyof GroupConfig>([
|
||||
'proxyConfig',
|
||||
]);
|
||||
|
||||
const STANDALONE_REMOTE_DESKTOP_SKIP_KEYS = new Set<string>([
|
||||
'enabled',
|
||||
'defaultConnect',
|
||||
'tunnelViaHostSsh',
|
||||
'tunnelTargetHost',
|
||||
'useHostCredentials',
|
||||
]);
|
||||
|
||||
const COMPANION_REMOTE_DESKTOP_SKIP_KEYS = new Set<string>([
|
||||
'enabled',
|
||||
'defaultConnect',
|
||||
]);
|
||||
|
||||
const applyRemoteDesktopGroupConfig = <T extends RdpConfig | VncConfig>(
|
||||
host: Host,
|
||||
hostConfig: T | undefined,
|
||||
groupConfig: T | undefined,
|
||||
isStandalone: boolean,
|
||||
): { config: T | undefined; inheritedPort?: number } => {
|
||||
if (!groupConfig) return { config: hostConfig };
|
||||
const merged: Record<string, unknown> = hostConfig ? { ...hostConfig } : {};
|
||||
const skipKeys = isStandalone
|
||||
? STANDALONE_REMOTE_DESKTOP_SKIP_KEYS
|
||||
: COMPANION_REMOTE_DESKTOP_SKIP_KEYS;
|
||||
|
||||
const standaloneHasExplicitCreds = isStandalone && (
|
||||
host.identityId !== undefined
|
||||
|| Boolean(host.username?.trim())
|
||||
|| host.password !== undefined
|
||||
|| host.savePassword === false
|
||||
|| hostConfig?.identityId !== undefined
|
||||
|| Boolean(hostConfig?.username?.trim())
|
||||
);
|
||||
const standaloneHasExplicitIdentityOrUsername = isStandalone && (
|
||||
host.identityId !== undefined
|
||||
|| Boolean(host.username?.trim())
|
||||
|| hostConfig?.identityId !== undefined
|
||||
|| Boolean(hostConfig?.username?.trim())
|
||||
);
|
||||
|
||||
const companionHasUseHostCreds = !isStandalone && hostConfig?.useHostCredentials === true;
|
||||
const companionHasExplicitIdentity = !isStandalone && hostConfig?.identityId !== undefined;
|
||||
const companionHasManualUsername = !isStandalone && Boolean(hostConfig?.username?.trim());
|
||||
|
||||
let inheritedPort: number | undefined;
|
||||
for (const [key, value] of Object.entries(groupConfig)) {
|
||||
if (value === undefined || skipKeys.has(key)) continue;
|
||||
if (key === 'port') {
|
||||
if (isStandalone) {
|
||||
if (host.port !== undefined || hostConfig?.port !== undefined) continue;
|
||||
inheritedPort = value as number;
|
||||
} else if (hostConfig?.port !== undefined) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (key === 'identityId') {
|
||||
if (value === '') continue;
|
||||
if (isStandalone && standaloneHasExplicitCreds) continue;
|
||||
if (!isStandalone && (companionHasUseHostCreds || companionHasExplicitIdentity || companionHasManualUsername)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (key === 'username') {
|
||||
if (value === '') continue;
|
||||
if (isStandalone && standaloneHasExplicitIdentityOrUsername) continue;
|
||||
if (!isStandalone && (companionHasUseHostCreds || companionHasExplicitIdentity || companionHasManualUsername)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (key === 'useHostCredentials') {
|
||||
if (
|
||||
hostConfig?.useHostCredentials !== undefined
|
||||
|| companionHasExplicitIdentity
|
||||
|| companionHasManualUsername
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (merged[key] === undefined) {
|
||||
merged[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
config: Object.keys(merged).length > 0 ? (merged as T) : undefined,
|
||||
inheritedPort,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Apply group defaults to a host. Only fills in fields the host doesn't already have.
|
||||
* Returns a new host object — does NOT mutate the original.
|
||||
@@ -323,6 +474,38 @@ export function applyGroupDefaults(
|
||||
// Explicit direct beats a host proxy, the nearest group proxy, and the
|
||||
// global default. Clearing the host setting leaves directProxy unset and
|
||||
// still inherits.
|
||||
const isPluginHost = typeof host.protocol === 'string' && host.protocol.startsWith('plugin:');
|
||||
if (!isLocalShellHost && !isSerialHost && !isPluginHost) {
|
||||
const isStandaloneRdp = host.protocol === 'rdp';
|
||||
const hasCompanionRdpEnabled = !isStandaloneRdp && host.rdpConfig?.enabled === true;
|
||||
if ((isStandaloneRdp || hasCompanionRdpEnabled) && groupDefaults.rdpConfig) {
|
||||
const { config, inheritedPort } = applyRemoteDesktopGroupConfig(
|
||||
host,
|
||||
effective.rdpConfig,
|
||||
groupDefaults.rdpConfig,
|
||||
isStandaloneRdp,
|
||||
);
|
||||
if (config) effective.rdpConfig = config;
|
||||
if (isStandaloneRdp && inheritedPort !== undefined && effective.port === undefined) {
|
||||
effective.port = inheritedPort;
|
||||
}
|
||||
}
|
||||
|
||||
const isStandaloneVnc = host.protocol === 'vnc';
|
||||
const hasCompanionVncEnabled = !isStandaloneVnc && host.vncConfig?.enabled === true;
|
||||
if ((isStandaloneVnc || hasCompanionVncEnabled) && groupDefaults.vncConfig) {
|
||||
const { config, inheritedPort } = applyRemoteDesktopGroupConfig(
|
||||
host,
|
||||
effective.vncConfig,
|
||||
groupDefaults.vncConfig,
|
||||
isStandaloneVnc,
|
||||
);
|
||||
if (config) effective.vncConfig = config;
|
||||
if (isStandaloneVnc && inheritedPort !== undefined && effective.port === undefined) {
|
||||
effective.port = inheritedPort;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (host.directProxy === true) return withoutInheritedProxy(effective);
|
||||
if (!effective.proxyConfig && !effective.proxyProfileId) {
|
||||
const globalProxyProfileId = resolveGlobalProxyProfileId(options);
|
||||
|
||||
@@ -547,6 +547,9 @@ export interface GroupConfig {
|
||||
telnetIdentityId?: string;
|
||||
telnetUsername?: string;
|
||||
telnetPassword?: string;
|
||||
// Remote desktop defaults inherited by hosts with RDP/VNC enabled; never holds plaintext passwords.
|
||||
rdpConfig?: RdpConfig;
|
||||
vncConfig?: VncConfig;
|
||||
theme?: string;
|
||||
themeOverride?: boolean;
|
||||
fontFamily?: string;
|
||||
|
||||
@@ -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
|
||||
|
||||
+12
-6
@@ -344,7 +344,6 @@ export const applyHostDefaultConnectProtocol = (
|
||||
protocol: 'ssh',
|
||||
...(host.vncConfig ? { vncConfig: { ...host.vncConfig, defaultConnect: undefined } } : {}),
|
||||
rdpConfig: {
|
||||
...DEFAULT_RDP_CONFIG,
|
||||
...(host.rdpConfig ?? {}),
|
||||
enabled: true,
|
||||
defaultConnect: true,
|
||||
@@ -362,7 +361,6 @@ export const applyHostDefaultConnectProtocol = (
|
||||
protocol: 'ssh',
|
||||
...(host.rdpConfig ? { rdpConfig: { ...host.rdpConfig, defaultConnect: undefined } } : {}),
|
||||
vncConfig: {
|
||||
...DEFAULT_VNC_CONFIG,
|
||||
...(host.vncConfig ?? {}),
|
||||
enabled: true,
|
||||
defaultConnect: true,
|
||||
@@ -549,8 +547,12 @@ export const sanitizeRdpConfig = (value: unknown): RdpConfig | undefined => {
|
||||
if (isValidPort(value.port)) out.port = value.port;
|
||||
const domain = readTrimmedString(value.domain);
|
||||
if (domain !== undefined) out.domain = domain;
|
||||
const identityId = readTrimmedString(value.identityId);
|
||||
if (identityId !== undefined) out.identityId = identityId;
|
||||
if (value.identityId === '') {
|
||||
out.identityId = '';
|
||||
} else {
|
||||
const identityId = readTrimmedString(value.identityId);
|
||||
if (identityId !== undefined) out.identityId = identityId;
|
||||
}
|
||||
const username = readTrimmedString(value.username);
|
||||
if (username !== undefined) out.username = username;
|
||||
const useHostCredentials = readBoolean(value.useHostCredentials);
|
||||
@@ -602,8 +604,12 @@ export const sanitizeVncConfig = (value: unknown): VncConfig | undefined => {
|
||||
const defaultConnect = readBoolean(value.defaultConnect);
|
||||
if (defaultConnect !== undefined) out.defaultConnect = defaultConnect;
|
||||
if (isValidPort(value.port)) out.port = value.port;
|
||||
const identityId = readTrimmedString(value.identityId);
|
||||
if (identityId !== undefined) out.identityId = identityId;
|
||||
if (value.identityId === '') {
|
||||
out.identityId = '';
|
||||
} else {
|
||||
const identityId = readTrimmedString(value.identityId);
|
||||
if (identityId !== undefined) out.identityId = identityId;
|
||||
}
|
||||
const username = readTrimmedString(value.username);
|
||||
if (username !== undefined) out.username = username;
|
||||
const useHostCredentials = readBoolean(value.useHostCredentials);
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
+11
-11
@@ -4,10 +4,8 @@ const nodeProcess = require('node:process');
|
||||
const processEnv = nodeProcess.env;
|
||||
const includeWindowsHelloHelper = processEnv.NETCATTY_SKIP_WINDOWS_HELLO_HELPER !== '1';
|
||||
|
||||
// IronRDP WASM and the AudioWorklet script are bundled into dist/ by Vite.
|
||||
// Platform-specific `files` arrays (mac/win/linux) create their own FileMatcher
|
||||
// in electron-builder, so exclusions must appear both at top-level and in each
|
||||
// platform `files` array to prevent duplicate copies from landing in app.asar.
|
||||
// IronRDP WASM and the AudioWorklet script are bundled into dist/ by Vite, so
|
||||
// exclude source/package copies from app.asar.
|
||||
const REMOTE_DESKTOP_DUPLICATE_EXCLUSIONS = [
|
||||
'!node_modules/@netcatty/ironrdp-wasm/**/*',
|
||||
'!node_modules/ironrdp-wasm/**/*',
|
||||
@@ -86,6 +84,8 @@ module.exports = {
|
||||
// Build-time vector sources copied from public/ into dist/.
|
||||
'!dist/icon.svg',
|
||||
'!dist/tray-iconTemplate.svg',
|
||||
// macOS-only icon variants are opted back in via mac.files.
|
||||
'!dist/icons/variants/macos/**/*',
|
||||
// Main-process terminal flow control reads shared thresholds from here
|
||||
// (terminalFlowAck.cjs). Must ship beside electron/ in app.asar.
|
||||
'infrastructure/config/terminalFlowConstants.cjs',
|
||||
@@ -294,9 +294,12 @@ module.exports = {
|
||||
// iconutil-generated bundle instead so Finder and app switchers do not
|
||||
// render those representations as colored noise.
|
||||
icon: 'build/icon.icns',
|
||||
// Include a positive pattern so electron-builder's platform FileMatcher
|
||||
// never sees an ignore-only list and prepends "**/*" (which would bypass
|
||||
// top-level `files` exclusions and pack the entire repository).
|
||||
files: [
|
||||
'dist/icons/variants/macos/**/*',
|
||||
'!node_modules/@vscode/windows-process-tree/**/*',
|
||||
...REMOTE_DESKTOP_DUPLICATE_EXCLUSIONS,
|
||||
],
|
||||
target: [
|
||||
{
|
||||
@@ -343,10 +346,6 @@ module.exports = {
|
||||
},
|
||||
win: {
|
||||
icon: 'public/icon-win.png',
|
||||
files: [
|
||||
'!dist/icons/variants/macos/**/*',
|
||||
...REMOTE_DESKTOP_DUPLICATE_EXCLUSIONS,
|
||||
],
|
||||
// Do not hard-code arch here. pack:win-x64 / pack:win pass --x64/--arm64,
|
||||
// and electron-builder unions config arch with the CLI set. Hard-coding
|
||||
// ['x64', 'arm64'] made the official x64 CI job also emit win-arm64 and
|
||||
@@ -386,10 +385,11 @@ module.exports = {
|
||||
// installs only hicolor/1024x1024 and launchers miss the icon (#274,
|
||||
// #1340). Do NOT set linux.icon to a single 1024px PNG either.
|
||||
icon: 'icons',
|
||||
// Include a positive pattern (`package.json`, already packed) so this
|
||||
// platform FileMatcher never becomes ignore-only and prepends "**/*".
|
||||
files: [
|
||||
'!dist/icons/variants/macos/**/*',
|
||||
'package.json',
|
||||
'!node_modules/@vscode/windows-process-tree/**/*',
|
||||
...REMOTE_DESKTOP_DUPLICATE_EXCLUSIONS,
|
||||
],
|
||||
target: ['AppImage', 'deb', 'rpm', 'pacman'],
|
||||
category: 'Development',
|
||||
|
||||
@@ -745,6 +745,8 @@ function registerSdkStreamHandlers(ctx) {
|
||||
const injectCliEnv = typeof ctx.withCliDiscoveryEnv === "function"
|
||||
? ctx.withCliDiscoveryEnv
|
||||
: (env) => env;
|
||||
// Inside with (ctx), ctx.require resolves relative to aiBridge.cjs.
|
||||
const requireFromSdk = require;
|
||||
with (ctx) {
|
||||
// chatSessionId -> { sessionId } for resume; controller per requestId.
|
||||
const sdkActiveStreams = new Map(); // requestId -> AbortController
|
||||
@@ -758,7 +760,7 @@ function registerSdkStreamHandlers(ctx) {
|
||||
let _codexAppServerRuntime = null;
|
||||
const getCodexAppServerRuntime = () => {
|
||||
if (!_codexAppServerRuntime) {
|
||||
const { CodexAppServerRuntime } = require("../codexAppServer/runtime.cjs");
|
||||
const { CodexAppServerRuntime } = requireFromSdk("../codexAppServer/runtime.cjs");
|
||||
_codexAppServerRuntime = new CodexAppServerRuntime({
|
||||
appVersion: electronModule?.app?.getVersion?.() || "0.0.0",
|
||||
transformUserInputAnswers(answers, context) {
|
||||
@@ -1570,7 +1572,7 @@ function registerSdkStreamHandlers(ctx) {
|
||||
// win over both the shared default and OpenCode's budget.
|
||||
const catalogBudgetMs = MODEL_LIST_TIMEOUT_OVERRIDES_MS[backendKey]
|
||||
?? (backendKey === "opencode"
|
||||
? require("./opencodeDriver.cjs").OPENCODE_SERVER_START_TIMEOUT_MS + MODEL_LIST_TIMEOUT_MS
|
||||
? requireFromSdk("./opencodeDriver.cjs").OPENCODE_SERVER_START_TIMEOUT_MS + MODEL_LIST_TIMEOUT_MS
|
||||
: MODEL_LIST_TIMEOUT_MS);
|
||||
const raw = await withTimeout(
|
||||
fetchSdkModelCatalog({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { createRequire } = require("node:module");
|
||||
const {
|
||||
registerSdkStreamHandlers,
|
||||
MODEL_LIST_TIMEOUT_OVERRIDES_MS,
|
||||
@@ -29,6 +30,7 @@ const {
|
||||
function registerWithStubbedCtx(overrides = {}) {
|
||||
const handlers = new Map();
|
||||
const ctx = {
|
||||
require: createRequire(require.resolve("../../aiBridge.cjs")),
|
||||
ipcMain: { handle: (channel, fn) => handlers.set(channel, fn) },
|
||||
electronModule: undefined,
|
||||
validateSender: () => true,
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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
@@ -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;
|
||||
|
||||
+3
-3
@@ -1,14 +1,14 @@
|
||||
{
|
||||
version = "1.1.93";
|
||||
version = "1.1.94";
|
||||
|
||||
sources = {
|
||||
x86_64-linux = {
|
||||
appImageArch = "x86_64";
|
||||
hash = "sha256-keMl6RVeMGjkkghul1Q5kVpXLnTbMcJD7sZlNJuQ9Sc=";
|
||||
hash = "sha256-aGZRSKTQQdBsdrP26HWvqEc1W9hKJHBrbEpy/H+jRP8=";
|
||||
};
|
||||
aarch64-linux = {
|
||||
appImageArch = "arm64";
|
||||
hash = "sha256-olngORSTZon5FkE5A+1s/mB8XphCxZRrLu30bEQomgQ=";
|
||||
hash = "sha256-xOF4Rs0vfvmzVPE2vn2QYEFEzy5nPSYriru4Vmbwc2c=";
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -605,3 +605,105 @@ test("app file exclusions prune dev schemas, test helpers/fixtures, svg sources,
|
||||
assert.equal(winFilter(macosVariantIcon, stat), false);
|
||||
assert.equal(linuxFilter(macosVariantIcon, stat), false);
|
||||
});
|
||||
|
||||
test("merged electron-builder config never falls back to **/* and excludes repo sources/tests/docs/public on all platforms", async () => {
|
||||
const { getConfig } = require("app-builder-lib/out/util/config/config");
|
||||
const { getMainFileMatchers } = require("app-builder-lib/out/fileMatcher");
|
||||
const root = path.resolve(__dirname, "..");
|
||||
const outDir = path.join(root, "release");
|
||||
const loadedConfig = await getConfig(
|
||||
root,
|
||||
path.join(root, "electron-builder.config.cjs"),
|
||||
null,
|
||||
);
|
||||
const fileStat = { isDirectory: () => false };
|
||||
|
||||
const buildUnionFilter = (platformName) => {
|
||||
const matchers = getMainFileMatchers(
|
||||
root,
|
||||
outDir,
|
||||
(v) => v,
|
||||
loadedConfig[platformName],
|
||||
{
|
||||
info: {
|
||||
config: loadedConfig,
|
||||
projectDir: root,
|
||||
buildResourcesDir: "build",
|
||||
isPrepackedAppAsar: false,
|
||||
debugLogger: { isEnabled: false },
|
||||
},
|
||||
},
|
||||
outDir,
|
||||
false,
|
||||
);
|
||||
for (const matcher of matchers) {
|
||||
assert.equal(
|
||||
matcher.patterns.includes("**/*"),
|
||||
false,
|
||||
`${platformName} FileMatcher unexpectedly fell back to **/*: ${matcher.patterns.slice(0, 5).join(", ")}`,
|
||||
);
|
||||
}
|
||||
const filters = matchers.map((matcher) => matcher.createFilter());
|
||||
return (relPath) => filters.some((fn) => fn(path.join(root, relPath), fileStat));
|
||||
};
|
||||
|
||||
const filters = {
|
||||
mac: buildUnionFilter("mac"),
|
||||
win: buildUnionFilter("win"),
|
||||
linux: buildUnionFilter("linux"),
|
||||
};
|
||||
|
||||
const mustExcludeEverywhere = [
|
||||
"components/Terminal.tsx",
|
||||
"application/state/useVaultState.ts",
|
||||
"domain/models.ts",
|
||||
"infrastructure/config/defaultData.ts",
|
||||
"public/icon.png",
|
||||
"public/audio/pcm-worklet.js",
|
||||
"docs/assets/readme/overview.webp",
|
||||
"docs/fido2-validation.md",
|
||||
"scripts/afterPackMacUuid.cjs",
|
||||
"examples/plugin-view-hello/index.js",
|
||||
"AGENTS.md",
|
||||
"CLAUDE.md",
|
||||
"electron-builder.config.cjs",
|
||||
"electron/explorerContextMenu.test.cjs",
|
||||
"electron/plugins/fixtures/inProcessBrowserRuntime.cjs",
|
||||
"electron/bridges/aiBridge/codexAppServer/protocol.schema.json",
|
||||
"dist/icon.svg",
|
||||
"dist/tray-iconTemplate.svg",
|
||||
];
|
||||
|
||||
const mustIncludeEverywhere = [
|
||||
"package.json",
|
||||
"dist/index.html",
|
||||
"electron/main.cjs",
|
||||
"domain/totp.shared.cjs",
|
||||
"domain/pluginRuntimePolicy.cjs",
|
||||
"infrastructure/config/terminalFlowConstants.cjs",
|
||||
"lib/localShell.cjs",
|
||||
"skills/netcatty-tool-cli/SKILL.md",
|
||||
];
|
||||
|
||||
for (const [platformName, matches] of Object.entries(filters)) {
|
||||
for (const relPath of mustExcludeEverywhere) {
|
||||
assert.equal(
|
||||
matches(relPath),
|
||||
false,
|
||||
`${platformName} app.asar must exclude ${relPath}`,
|
||||
);
|
||||
}
|
||||
for (const relPath of mustIncludeEverywhere) {
|
||||
assert.equal(
|
||||
matches(relPath),
|
||||
true,
|
||||
`${platformName} app.asar must include ${relPath}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
assert.equal(filters.mac("dist/icons/variants/macos/icon.png"), true);
|
||||
assert.equal(filters.win("dist/icons/variants/macos/icon.png"), false);
|
||||
assert.equal(filters.linux("dist/icons/variants/macos/icon.png"), false);
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user