mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-28 12:49:53 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22c6672f1c | ||
|
|
c48152b15e | ||
|
|
e3310d6b00 |
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@v3.0.4'
|
||||
- 'softprops/action-gh-release@v2.6.2'
|
||||
'.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@v3.0.4':
|
||||
ref: 'v3.0.4'
|
||||
commit: 'sha1-8a0cd651e5b2365bd640854a3fa5dfc70e4875f3'
|
||||
'softprops/action-gh-release@v2.6.2':
|
||||
ref: 'v2.6.2'
|
||||
commit: 'sha1-3bb12739c298aeb8a4eeaf626c5b8d85266b0e65'
|
||||
owner_id: 2242
|
||||
repo_id: 204253808
|
||||
@@ -828,7 +828,7 @@ jobs:
|
||||
GITHUB_SHA: ${{ github.sha }}
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v3.0.4
|
||||
uses: softprops/action-gh-release@v2.6.2
|
||||
with:
|
||||
body_path: release_notes.md
|
||||
prerelease: ${{ contains(github.ref_name, '-') }}
|
||||
|
||||
@@ -75,6 +75,8 @@
|
||||
!packages/**
|
||||
!patches/
|
||||
!patches/**
|
||||
!plugins/
|
||||
!plugins/**
|
||||
!public/
|
||||
!public/**
|
||||
!resources/
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { MonitorHostKeyDialog } from './components/vault/MonitorHostKeyDialog';
|
||||
import { MonitorRuntimeHost } from './application/app/MonitorRuntimeHost';
|
||||
import React, { useEffect } from 'react';
|
||||
|
||||
import { initializeFonts } from './application/state/fontStore';
|
||||
@@ -55,9 +53,7 @@ function App() {
|
||||
}, []);
|
||||
return (
|
||||
<AppLocalStateProvider>
|
||||
<MonitorRuntimeHost />
|
||||
<AppSideEffects />
|
||||
<MonitorHostKeyDialog />
|
||||
<AppShell />
|
||||
</AppLocalStateProvider>
|
||||
);
|
||||
|
||||
@@ -32,41 +32,66 @@ function loadComponent(path: string, name: string, bindings: Record<string, unkn
|
||||
}) as React.ComponentType;
|
||||
}
|
||||
|
||||
test('monitor controls update their runtime without rendering unrelated app siblings', async () => {
|
||||
test('App no longer mounts retired built-in MonitorRuntimeHost or MonitorHostKeyDialog', async () => {
|
||||
const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previous = env.IS_REACT_ACT_ENVIRONMENT;
|
||||
env.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
let sideEffectRenders = 0;
|
||||
let shellRenders = 0;
|
||||
const appSource = readFileSync(new URL('../../App.tsx', import.meta.url), 'utf8');
|
||||
assert.doesNotMatch(appSource, /MonitorRuntimeHost/, 'App must not mount retired MonitorRuntimeHost');
|
||||
assert.doesNotMatch(appSource, /MonitorHostKeyDialog/, 'App must not mount retired MonitorHostKeyDialog');
|
||||
|
||||
const App = loadComponent('../../App.tsx', 'App', {
|
||||
performance: { mark: () => {} },
|
||||
AppLocalStateProvider: ({ children }: { children: React.ReactNode }) => children,
|
||||
AppSideEffects: () => { sideEffectRenders += 1; return null; },
|
||||
AppShell: React.memo(() => { shellRenders += 1; return null; }),
|
||||
});
|
||||
let renderer: ReturnType<typeof create> | undefined;
|
||||
try {
|
||||
await act(async () => { renderer = create(React.createElement(App)); });
|
||||
assert.equal(sideEffectRenders, 1);
|
||||
assert.equal(shellRenders, 1);
|
||||
} finally {
|
||||
await act(async () => renderer?.unmount());
|
||||
env.IS_REACT_ACT_ENVIRONMENT = previous;
|
||||
}
|
||||
});
|
||||
|
||||
test('MonitorRuntimeHost keeps monitor runtime updates isolated from sibling components when mounted', async () => {
|
||||
const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previous = env.IS_REACT_ACT_ENVIRONMENT;
|
||||
env.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
let updateMonitor: (() => void) | undefined;
|
||||
let runtimeRenders = 0;
|
||||
let sideEffectRenders = 0;
|
||||
let shellRenders = 0;
|
||||
let siblingRenders = 0;
|
||||
const useMonitorRuntime = () => {
|
||||
const [, setVersion] = useState(0);
|
||||
updateMonitor = () => setVersion((version) => version + 1);
|
||||
runtimeRenders += 1;
|
||||
};
|
||||
const MonitorRuntimeHost = loadComponent('./MonitorRuntimeHost.tsx', 'MonitorRuntimeHost', { useMonitorRuntime });
|
||||
const App = loadComponent('../../App.tsx', 'App', {
|
||||
performance: { mark: () => {} },
|
||||
useMonitorRuntime,
|
||||
MonitorRuntimeHost,
|
||||
AppLocalStateProvider: ({ children }: { children: React.ReactNode }) => children,
|
||||
AppSideEffects: () => { sideEffectRenders += 1; return null; },
|
||||
MonitorHostKeyDialog: () => null,
|
||||
AppShell: React.memo(() => { shellRenders += 1; return null; }),
|
||||
});
|
||||
const StableSibling = React.memo(() => { siblingRenders += 1; return null; });
|
||||
let renderer: ReturnType<typeof create> | undefined;
|
||||
try {
|
||||
await act(async () => { renderer = create(React.createElement(App)); });
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
React.createElement(
|
||||
React.Fragment,
|
||||
null,
|
||||
React.createElement(MonitorRuntimeHost),
|
||||
React.createElement(StableSibling),
|
||||
),
|
||||
);
|
||||
});
|
||||
const initialRuntimeRenders = runtimeRenders;
|
||||
const initialSideEffectRenders = sideEffectRenders;
|
||||
const initialShellRenders = shellRenders;
|
||||
const initialSiblingRenders = siblingRenders;
|
||||
for (let i = 0; i < 10; i += 1) {
|
||||
await act(async () => updateMonitor!());
|
||||
}
|
||||
assert.equal(runtimeRenders - initialRuntimeRenders, 10, 'monitor updates must still run');
|
||||
assert.equal(sideEffectRenders - initialSideEffectRenders, 0, 'monitor-only state must not render AppSideEffects');
|
||||
assert.equal(shellRenders - initialShellRenders, 0, 'monitor controls must leave the shell stable');
|
||||
assert.equal(runtimeRenders - initialRuntimeRenders, 10, 'monitor updates must run inside MonitorRuntimeHost');
|
||||
assert.equal(siblingRenders - initialSiblingRenders, 0, 'monitor updates must not re-render siblings');
|
||||
} finally {
|
||||
await act(async () => renderer?.unmount());
|
||||
env.IS_REACT_ACT_ENVIRONMENT = previous;
|
||||
|
||||
@@ -1174,6 +1174,16 @@ Highlight the focused split pane:
|
||||
'vault.nav.notes': 'Notes',
|
||||
'vault.nav.knownHosts': 'Known Hosts',
|
||||
'vault.nav.logs': 'Logs',
|
||||
'vault.nav.customize': 'Customize sidebar',
|
||||
'vault.nav.customizeHint': 'Drag items to reorder or toggle visibility.',
|
||||
'vault.nav.hideItem': 'Hide {label}',
|
||||
'vault.nav.moveUp': 'Move up',
|
||||
'vault.nav.moveDown': 'Move down',
|
||||
'vault.nav.resetDefault': 'Reset to default',
|
||||
'vault.nav.alwaysVisible': 'Always visible',
|
||||
'vault.nav.pluginBadge': 'Plugin',
|
||||
'vault.nav.dragToReorder': 'Drag to reorder {label}',
|
||||
'vault.nav.toggleVisibility': 'Toggle {label} visibility',
|
||||
|
||||
'proxyProfiles.action.add': 'Add Proxy',
|
||||
'proxyProfiles.search.placeholder': 'Search proxies…',
|
||||
@@ -1225,10 +1235,7 @@ 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',
|
||||
@@ -1321,6 +1328,9 @@ Highlight the focused split pane:
|
||||
"plugins.sidebar.loading": "Loading extension page…",
|
||||
"plugins.vault.loading": "Loading plugin page…",
|
||||
"plugins.interaction.title": "Plugin request",
|
||||
"plugins.interaction.openUrlTitle": "Open external link?",
|
||||
"plugins.interaction.openUrlNote": "This plugin wants to open the following HTTPS URL in your default browser:",
|
||||
"plugins.interaction.openUrlAction": "Open URL",
|
||||
"plugins.interaction.sharing": "Text you share becomes available to this plugin and its granted capabilities, including network access. Reading does not approve a new network destination.",
|
||||
"plugins.interaction.input": "Input text",
|
||||
"plugins.interaction.filter": "Filter choices",
|
||||
|
||||
@@ -1319,7 +1319,6 @@ 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',
|
||||
@@ -1425,18 +1424,7 @@ 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',
|
||||
|
||||
@@ -1174,6 +1174,16 @@ Resalta el panel dividido enfocado:
|
||||
'vault.nav.notes': 'Notas',
|
||||
'vault.nav.knownHosts': 'Hosts conocidos',
|
||||
'vault.nav.logs': 'Registros',
|
||||
'vault.nav.customize': 'Personalizar barra lateral',
|
||||
'vault.nav.customizeHint': 'Arrastra elementos para reordenar o alternar visibilidad.',
|
||||
'vault.nav.hideItem': 'Ocultar {label}',
|
||||
'vault.nav.moveUp': 'Subir',
|
||||
'vault.nav.moveDown': 'Bajar',
|
||||
'vault.nav.resetDefault': 'Restablecer a los valores predeterminados',
|
||||
'vault.nav.alwaysVisible': 'Siempre visible',
|
||||
'vault.nav.pluginBadge': 'Complemento',
|
||||
'vault.nav.dragToReorder': 'Arrastra para reordenar {label}',
|
||||
'vault.nav.toggleVisibility': 'Alternar visibilidad de {label}',
|
||||
|
||||
'proxyProfiles.action.add': 'Agregar proxy',
|
||||
'proxyProfiles.search.placeholder': 'Buscar proxies…',
|
||||
@@ -1225,10 +1235,7 @@ 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',
|
||||
@@ -1321,6 +1328,9 @@ Resalta el panel dividido enfocado:
|
||||
"plugins.sidebar.loading": "Cargando página de extensión…",
|
||||
"plugins.vault.loading": "Cargando página del plugin…",
|
||||
"plugins.interaction.title": "Solicitud de complemento",
|
||||
"plugins.interaction.openUrlTitle": "¿Abrir enlace externo?",
|
||||
"plugins.interaction.openUrlNote": "Este complemento solicita abrir la siguiente URL HTTPS en tu navegador predeterminado:",
|
||||
"plugins.interaction.openUrlAction": "Abrir URL",
|
||||
"plugins.interaction.sharing": "El texto compartido estará disponible para este complemento y sus capacidades autorizadas, incluida la red. Leer no autoriza un nuevo destino de red.",
|
||||
"plugins.interaction.input": "Introducir texto",
|
||||
"plugins.interaction.filter": "Filtrar opciones",
|
||||
|
||||
@@ -1378,7 +1378,6 @@ 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',
|
||||
@@ -1425,18 +1424,7 @@ 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,6 +8,12 @@ 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);
|
||||
|
||||
@@ -104,7 +110,7 @@ test("en shortcut labels stay identical to DEFAULT_KEY_BINDINGS", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("every translated locale defines every message key from en", () => {
|
||||
test("every locale outside the pending list is at full parity with en", () => {
|
||||
const locales = [
|
||||
{ name: "es", messages: es },
|
||||
{ name: "ru", messages: ru },
|
||||
@@ -113,6 +119,10 @@ test("every translated locale defines every message key from 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,28 +10,9 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.preparing': 'Подготовка…',
|
||||
'ai.chat.modelCatalogWarning': 'Не удалось обновить список моделей. Показаны последние доступные или встроенные модели.',
|
||||
'ai.chat.modelCatalogRetry': 'Повторить',
|
||||
'ai.chat.compactingContext': 'Сжимаем предыдущий контекст…',
|
||||
'ai.chat.compactingStep': 'Сокращаем контекст для следующего шага…',
|
||||
'ai.chat.contextCompacted': 'Контекст сжат',
|
||||
'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.title': 'AI',
|
||||
'ai.description': 'Настройка AI-провайдеров, агентов и параметров безопасности',
|
||||
'ai.providers': 'Провайдеры',
|
||||
'ai.agents': 'Агенты',
|
||||
'ai.providers.empty': 'Провайдеры не настроены. Добавьте провайдера, чтобы начать.',
|
||||
@@ -62,15 +43,6 @@ 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 автоматически выбирает путь эндпоинта для каждой модели.',
|
||||
@@ -194,20 +166,20 @@ export const ruAiMessages: Messages = {
|
||||
'ai.cursor.detected': 'Доступен',
|
||||
'ai.cursor.notFound': 'Недоступен',
|
||||
'ai.cursor.path': 'Среда:',
|
||||
'ai.cursor.notFoundHint': 'Укажите API-ключ или переключитесь на вход через CLI.',
|
||||
'ai.cursor.notFoundHint': 'Укажите API-ключ или переключитесь на CLI login.',
|
||||
'ai.cursor.notInstalledHint': 'Cursor SDK / Agent CLI не обнаружен.',
|
||||
'ai.cursor.installStatus': 'Среда Cursor',
|
||||
'ai.cursor.installed': 'Обнаружено',
|
||||
'ai.cursor.notInstalled': 'Не обнаружено',
|
||||
'ai.cursor.modeCli': 'Вход через CLI',
|
||||
'ai.cursor.modeApiKey': 'API-ключ',
|
||||
'ai.cursor.modeCli': 'CLI login',
|
||||
'ai.cursor.modeApiKey': 'API Key',
|
||||
'ai.cursor.modeCliHint': 'Использует локальный `cursor-agent login` и квоту подписки Auto. Сохранённый API-ключ сохраняется, но в этом режиме не используется.',
|
||||
'ai.cursor.modeApiKeyHint': 'Использует платный Cursor API. Вход через CLI в этом режиме игнорируется.',
|
||||
'ai.cursor.cliLoginStatus': 'Вход через CLI',
|
||||
'ai.cursor.modeApiKeyHint': 'Использует платный Cursor API. CLI login в этом режиме игнорируется.',
|
||||
'ai.cursor.cliLoginStatus': 'CLI login',
|
||||
'ai.cursor.cliLoginOk': 'Вход выполнен',
|
||||
'ai.cursor.cliLoginAs': 'Вход как {{email}}',
|
||||
'ai.cursor.cliLoginMissing': 'Нет входа',
|
||||
'ai.cursor.cliLoginHint': 'Выполните `cursor-agent login` в терминале, затем нажмите «Проверить».',
|
||||
'ai.cursor.cliLoginHint': 'Выполните `cursor-agent login` в терминале, затем нажмите Check.',
|
||||
'ai.cursor.apiKeyStatus': 'API-ключ',
|
||||
'ai.cursor.apiKeyConfigured': 'Настроен',
|
||||
'ai.cursor.apiKeyMissing': 'Не указан',
|
||||
@@ -238,22 +210,22 @@ export const ruAiMessages: Messages = {
|
||||
'ai.codebuddy.configSection': 'Аутентификация и конфигурация (необязательно)',
|
||||
'ai.codebuddy.internetEnv': 'Сетевая среда',
|
||||
'ai.codebuddy.internetEnv.default': 'По умолчанию (зарубежная)',
|
||||
'ai.codebuddy.internetEnv.internal': 'Внутренняя',
|
||||
'ai.codebuddy.internetEnv.internal': 'Internal',
|
||||
'ai.codebuddy.internetEnv.ioa': 'IOA',
|
||||
'ai.codebuddy.internetEnv.hint': 'Задаёт переменную CODEBUDDY_INTERNET_ENVIRONMENT. Для сетей с ограниченным доступом выберите «Внутренняя» или IOA.',
|
||||
'ai.codebuddy.internetEnv.hint': 'Устанавливает CODEBUDDY_INTERNET_ENVIRONMENT — выберите Internal или 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': 'Минимальная',
|
||||
'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.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.maxTurns': 'Максимум шагов',
|
||||
'ai.codebuddy.maxTurns.hint': 'Ограничивает максимальное число шагов диалога за запрос, предотвращая зацикливание. Оставьте пустым для значения по умолчанию.',
|
||||
'ai.codebuddy.maxBudget': 'Максимальный бюджет (USD)',
|
||||
@@ -302,54 +274,22 @@ 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.defaultAgent.description': 'Агент, который будет использоваться при запуске новой AI-сессии',
|
||||
'ai.defaultAgent.catty': 'Catty (встроенный)',
|
||||
'ai.defaultAgent.unavailable': 'Недоступен',
|
||||
'ai.toolAccess.title': 'Доступ к инструментам',
|
||||
'ai.toolAccess.mode': 'Режим доступа Netcatty',
|
||||
'ai.toolAccess.description': 'Выберите, как внешние агенты получают доступ к сеансам Netcatty. MCP предоставляет встроенный сервер, а режим «Навыки + CLI» указывает агентам на локальный навык Netcatty и команды CLI.',
|
||||
'ai.toolAccess.description': 'Выберите, как внешние агенты получают доступ к сессиям Netcatty. MCP предоставляет встроенный сервер, а Skills + CLI указывает агентам на локальный skill Netcatty и команды CLI.',
|
||||
'ai.toolAccess.mode.mcp': 'MCP',
|
||||
'ai.toolAccess.mode.skills': 'Навыки + CLI',
|
||||
'ai.toolAccess.mode.skills': 'Skills + CLI',
|
||||
'ai.toolAccess.mcpPrompt.title': 'Промпт для вашего ИИ-клиента',
|
||||
'ai.toolAccess.mcpPrompt.description': 'Вставьте этот промпт в ИИ-клиент (Codex, Claude Code и т. д.), и он сам зарегистрирует MCP Netcatty.',
|
||||
'ai.toolAccess.mcpPrompt.enableHint': 'Включите внешний MCP ниже, чтобы в промпт попал путь к лаунчеру.',
|
||||
'ai.toolAccess.skills.file': 'Файл навыка',
|
||||
'ai.toolAccess.skills.description': 'В режиме «Навыки + CLI» агенты автоматически получают путь к локальному файлу навыка. Путь к файлу запуска Netcatty CLI передаётся агенту в каждом сеансе.',
|
||||
'ai.toolAccess.skills.unavailable': 'Путь к файлу навыка недоступен',
|
||||
'ai.toolAccess.skills.file': 'Файл skill',
|
||||
'ai.toolAccess.skills.description': 'В режиме Skills + CLI агенты автоматически получают путь к этому локальному skill-файлу. Путь к лаунчеру Netcatty CLI передаётся агенту в каждой сессии.',
|
||||
'ai.toolAccess.skills.unavailable': 'Путь к skill-файлу недоступен',
|
||||
|
||||
'ai.externalMcp.title': 'Внешний MCP',
|
||||
'ai.externalMcp.allowCommandOnHost': 'Всегда',
|
||||
@@ -383,13 +323,13 @@ export const ruAiMessages: Messages = {
|
||||
'ai.externalMcp.sessionIdleTimeout': 'Тайм-аут открытого сеанса',
|
||||
'ai.externalMcp.sessionIdleTimeout.description': 'Автоматически закрывать сеансы, открытые ИИ, после указанного числа минут без операций терминала или файлов.',
|
||||
'ai.externalMcp.usage.title': 'Как пользоваться',
|
||||
'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.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.security': 'Безопасность',
|
||||
'ai.externalMcp.security.description': 'Принимает подключения только на 127.0.0.1, обновляет токен, применяет режим разрешений ИИ к операциям записи и удаляет файл обнаружения при отключении. Локальный мост приложения работает без OAuth.',
|
||||
'ai.externalMcp.security.description': 'Слушает только 127.0.0.1 с ротацией token, использует AI Permission Mode для записи и удаляет discovery при отключении.',
|
||||
"ai.privacy.title": "Конфиденциальность ИИ",
|
||||
"ai.privacy.description": "Фильтрует известные шаблоны конфиденциального текста в контексте и результатах инструментов, управляемых Netcatty, для Catty, встроенных агентов и внешних MCP-клиентов. По умолчанию отключено. Не обнаруживает все секреты. При включении двоичные ответы инструментов блокируются.",
|
||||
"ai.privacy.boundary": "Защищаются только данные и инструменты, управляемые Netcatty. Собственные инструменты сторонних агентов, их прямой доступ к файлам и другие MCP-серверы не входят в эту область.",
|
||||
@@ -422,11 +362,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',
|
||||
'ai.externalMcp.http.token': 'Bearer token',
|
||||
'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': 'Файл config.toml для Codex',
|
||||
'ai.externalMcp.http.codexSnippet': 'Codex config.toml',
|
||||
'ai.externalMcp.http.claudeCommand': 'Claude Code',
|
||||
'ai.externalMcp.http.genericSnippet': 'Общий JSON',
|
||||
'ai.externalMcp.http.envLine': 'Переменная окружения token для Codex',
|
||||
@@ -440,12 +380,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': 'Тот же параметр, что в разделе «Настройки → ИИ → Безопасность». В режиме «Авто» Netcatty выполняет операции записи без запроса. В режиме «Подтверждение» Netcatty запрашивает разрешение каждый раз. Внешние клиенты (Codex, Claude, Grok) могут запрашивать собственное подтверждение.',
|
||||
'ai.externalMcp.permissionMode.hint': 'Тот же параметр, что Settings → AI → Safety. Auto выполняет write-инструменты Netcatty без запросов; Confirm спрашивает каждый раз. Внешние клиенты (Codex / Claude / Grok) могут показывать своё подтверждение инструментов.',
|
||||
'ai.externalMcp.permissionMode.unknown': 'Неизвестно',
|
||||
'ai.externalMcp.discovery': 'Файл обнаружения',
|
||||
'ai.externalMcp.launcher': 'Файл запуска',
|
||||
'ai.externalMcp.discovery': 'Discovery',
|
||||
'ai.externalMcp.launcher': 'Launcher',
|
||||
'ai.externalMcp.unavailable': 'Недоступно',
|
||||
'ai.externalMcp.bridgeUnavailable': 'Мост внешнего MCP недоступен',
|
||||
'ai.externalMcp.bridgeUnavailable': 'Мост External MCP недоступен',
|
||||
'ai.externalMcp.copy': 'Копировать',
|
||||
'ai.externalMcp.copied': 'Скопировано',
|
||||
'ai.externalMcp.copyFailed': 'Не удалось скопировать. Скопируйте вручную.',
|
||||
@@ -500,7 +440,7 @@ export const ruAiMessages: Messages = {
|
||||
|
||||
// AI Quick Messages
|
||||
'ai.quickMessages.title': 'Быстрые сообщения',
|
||||
'ai.quickMessages.description': 'Создавайте подсказки для повторного использования. Чтобы вставить текст подсказки в поле ввода чата с ИИ, наберите / или нажмите кнопку быстрых сообщений.',
|
||||
'ai.quickMessages.description': 'Создавайте часто используемые подсказки и вставляйте их в AI-чат через / или кнопку быстрых сообщений. В отличие от user skills, быстрые сообщения заполняют поле ввода текстом.',
|
||||
'ai.quickMessages.add': 'Добавить быстрое сообщение',
|
||||
'ai.quickMessages.createTitle': 'Новое быстрое сообщение',
|
||||
'ai.quickMessages.editTitle': 'Редактировать быстрое сообщение',
|
||||
@@ -522,14 +462,14 @@ export const ruAiMessages: Messages = {
|
||||
'ai.quickMessages.error.maxItems': 'Можно сохранить не более {max} быстрых сообщений.',
|
||||
|
||||
// AI Chat
|
||||
'ai.chat.noProvider': 'Провайдер ИИ не настроен. Перейдите в **Настройки → ИИ → Провайдеры**, чтобы добавить и включить провайдера.',
|
||||
'ai.chat.noProvider': 'AI-провайдер не настроен. Перейдите в **Настройки → AI → Провайдеры**, чтобы добавить и включить провайдера.',
|
||||
'ai.chat.toolDenied': 'Действие было отклонено пользователем.',
|
||||
'ai.chat.toolApproved': 'Одобрено',
|
||||
'ai.chat.toolApprovalHint': 'Enter — разрешить один раз, Escape — отклонить',
|
||||
'ai.chat.approve': 'Одобрить',
|
||||
'ai.chat.approveOnce': 'Разрешить один раз',
|
||||
'ai.chat.alwaysAllow': 'Всегда разрешать',
|
||||
'ai.chat.slashStopDesc': 'Остановить текущий ход ИИ и отменить выполняющиеся инструменты',
|
||||
'ai.chat.slashStopDesc': 'Остановить текущий ход AI и отменить выполняющиеся инструменты',
|
||||
'ai.chat.slashCompactDesc': 'Сжать ранний контекст разговора',
|
||||
'ai.chat.slashRenameDesc': 'Переименовать текущий чат (/rename <название>)',
|
||||
'ai.chat.slashChatsDesc': 'Показать чаты, видимые в этой панели',
|
||||
@@ -540,12 +480,12 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.copyCommand': 'Копировать',
|
||||
'ai.chat.commandCopied': 'Скопировано',
|
||||
'ai.chat.approvalSession': 'Сессия',
|
||||
'ai.chat.approvalShell': 'Оболочка',
|
||||
'ai.chat.approvalShell': 'Shell',
|
||||
'ai.chat.approvalCwd': 'Каталог',
|
||||
'ai.chat.approvalReason': 'Причина',
|
||||
'ai.chat.approvalInvocation': 'Вызов',
|
||||
'ai.chat.permissionRequired': 'Требуется разрешение',
|
||||
'ai.chat.permissionDescription': 'Агент ИИ хочет вызвать инструмент, для которого требуется ваше разрешение.',
|
||||
'ai.chat.permissionDescription': 'AI-агент хочет выполнить вызов инструмента, для которого требуется ваше одобрение.',
|
||||
'ai.chat.commandBlocked': 'Эта команда заблокирована вашей политикой безопасности и не может быть выполнена.',
|
||||
'ai.chat.recommendAllow': 'Разрешить',
|
||||
'ai.chat.recommendConfirm': 'Подтвердить',
|
||||
@@ -571,7 +511,7 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.placeholder': 'Сообщение {agent} — @ для добавления контекста, / для команд',
|
||||
'ai.chat.placeholderDefault': 'Сообщение агенту Catty...',
|
||||
'ai.chat.noModel': 'Нет модели',
|
||||
'ai.chat.noProviderModel': 'Модель по умолчанию не задана. Выберите её в разделе «Настройки → ИИ → Провайдеры».',
|
||||
'ai.chat.noProviderModel': 'Модель по умолчанию не задана — настройте её в Настройки → AI → Провайдеры.',
|
||||
'ai.chat.selectProvider': 'Выберите провайдера',
|
||||
'ai.chat.selectProviderAndModel': 'Выберите провайдера и модель',
|
||||
'ai.chat.selectModel': 'Выберите модель',
|
||||
@@ -608,7 +548,7 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.importNone': 'В выбранном файле не найдено чатов ИИ.',
|
||||
'ai.chat.chatsHeader': 'Чаты, видимые в этой панели:',
|
||||
'ai.chat.chatsEmpty': 'В этой панели нет видимых чатов.',
|
||||
'ai.chat.chatsScopeWorkspace': 'Рабочая область',
|
||||
'ai.chat.chatsScopeWorkspace': 'Workspace',
|
||||
'ai.chat.chatsScopeTerminal': 'Терминал',
|
||||
'ai.chat.chatsScopeGlobal': 'Глобально',
|
||||
'ai.chat.chatsScopeDangling': 'Связь потеряна',
|
||||
@@ -677,12 +617,12 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.slashUserSkills': 'Пользовательские навыки',
|
||||
'ai.chat.quickMessages': 'Команды /',
|
||||
'ai.chat.slashNoResults': 'Нет подходящих команд',
|
||||
'ai.chat.slashEmptyHint': 'Добавьте подсказки в разделе «Настройки → ИИ → Быстрые сообщения».',
|
||||
'ai.chat.slashEmptyHint': 'Добавьте подсказки в Настройки → AI → Быстрые сообщения.',
|
||||
|
||||
// AI Chat Shortcuts
|
||||
'ai.chatShortcuts.title': 'Быстрые действия чата',
|
||||
'ai.chatShortcuts.selectionAction': 'Показывать «Добавить в чат» при выделении в терминале',
|
||||
'ai.chatShortcuts.selectionAction.description': 'Показывать небольшую кнопку ИИ рядом с выделенным текстом терминала.',
|
||||
'ai.chatShortcuts.selectionAction.description': 'Показывать небольшую кнопку AI рядом с выделенным текстом терминала.',
|
||||
'ai.chatHistory.title': 'История чата',
|
||||
'ai.chatHistory.messageCap': 'Сообщений, сохраняемых в чате',
|
||||
'ai.chatHistory.messageCap.description': 'Максимальное число сообщений, хранимых для одного чата (50–2000). При уменьшении самые старые сообщения удаляются из хранилища при следующей записи. Большие значения увеличивают объём хранилища и синхронизации с облаком.',
|
||||
@@ -694,7 +634,7 @@ export const ruAiMessages: Messages = {
|
||||
// AI Web Search
|
||||
'ai.webSearch.title': 'Веб-поиск',
|
||||
'ai.webSearch.enable': 'Включить веб-поиск',
|
||||
'ai.webSearch.enable.description': 'Разрешить агенту ИИ искать в интернете актуальную информацию.',
|
||||
'ai.webSearch.enable.description': 'Разрешить AI-агенту искать в интернете актуальную информацию.',
|
||||
'ai.webSearch.provider': 'Провайдер поиска',
|
||||
'ai.webSearch.provider.description': 'Выберите провайдера API веб-поиска.',
|
||||
'ai.webSearch.apiKey': 'API-ключ',
|
||||
@@ -709,7 +649,7 @@ export const ruAiMessages: Messages = {
|
||||
// AI Safety Settings
|
||||
'ai.safety.title': 'Безопасность',
|
||||
'ai.safety.permissionMode': 'Режим разрешений',
|
||||
'ai.safety.permissionMode.description': 'Управляет тем, как ИИ взаимодействует с вашими терминалами. Режим наблюдателя блокирует все операции записи через Netcatty и применяется как к встроенным, так и к внешним агентам. Режим подтверждения носит рекомендательный характер для внешних агентов (они управляют собственным потоком одобрения инструментов).',
|
||||
'ai.safety.permissionMode.description': 'Управляет тем, как AI взаимодействует с вашими терминалами. Режим наблюдателя блокирует все операции записи через Netcatty и применяется как к встроенным, так и к внешним агентам. Режим подтверждения носит рекомендательный характер для внешних агентов (они управляют собственным потоком одобрения инструментов).',
|
||||
'ai.safety.permissionMode.observer': 'Наблюдатель — только чтение, без действий',
|
||||
'ai.safety.permissionMode.confirm': 'Подтверждение — спрашивать перед действиями',
|
||||
'ai.safety.permissionMode.auto': 'Авто — выполнять свободно',
|
||||
@@ -720,7 +660,7 @@ export const ruAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.description': 'Отменяет запрос встроенного ИИ после указанного числа секунд без нового ответа. Не управляет общей длительностью ответа и выполнением команд.',
|
||||
'ai.safety.responseIdleTimeout.unit': 'с',
|
||||
'ai.safety.maxIterations': 'Макс. число итераций',
|
||||
'ai.safety.maxIterations.description': 'Максимальное число циклов использования инструментов ИИ, чтобы предотвратить бесконтрольное выполнение. У внешних агентов могут быть собственные внутренние лимиты итераций, имеющие приоритет.',
|
||||
'ai.safety.maxIterations.description': 'Максимальное число циклов использования инструментов AI, чтобы предотвратить бесконтрольное выполнение. У внешних агентов могут быть собственные внутренние лимиты итераций, имеющие приоритет.',
|
||||
'ai.safety.toolOutputMaxChars': 'Лимит вывода инструментов встроенного ИИ',
|
||||
'ai.safety.toolOutputMaxChars.description': 'Максимум символов, оставляемых напрямую в результате инструмента встроенного ИИ (например, вывода команд терминала или чтения SFTP) до обрезки и сохранения полного вывода в дескриптор (2 000–200 000).',
|
||||
'ai.safety.toolOutputMaxChars.unit': 'симв.',
|
||||
@@ -753,15 +693,12 @@ export const ruAiMessages: Messages = {
|
||||
'terminal.layer.history': 'История',
|
||||
'terminal.layer.theme': 'Тема',
|
||||
'terminal.layer.notes': 'Заметки',
|
||||
'terminal.layer.aiChat': 'Чат с ИИ',
|
||||
'terminal.layer.aiChat': 'AI-чат',
|
||||
'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': 'Разделить сверху и снизу',
|
||||
@@ -781,15 +718,9 @@ 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': 'ИИ-помощник',
|
||||
'topTabs.aiAssistant': 'AI-помощник',
|
||||
'topTabs.controlPanel': 'Быстрые настройки',
|
||||
'topTabs.controlPanel.externalMcp': 'Внешний MCP',
|
||||
'topTabs.controlPanel.theme': 'Тема',
|
||||
|
||||
@@ -38,33 +38,6 @@ 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': 'Отмена',
|
||||
@@ -177,7 +150,7 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.tab.appearance': 'Внешний вид',
|
||||
'settings.tab.terminal': 'Терминал',
|
||||
'settings.tab.shortcuts': 'Горячие клавиши',
|
||||
'settings.tab.ai': 'ИИ',
|
||||
'settings.tab.ai': 'AI',
|
||||
'settings.tab.syncCloud': 'Синхронизация и облако',
|
||||
'settings.tab.system': 'Система',
|
||||
'settings.search.open': 'Поиск настроек',
|
||||
@@ -272,7 +245,7 @@ export const ruCoreMessages: Messages = {
|
||||
|
||||
// Settings > System > Network Proxy
|
||||
'settings.system.networkProxy.title': 'Сетевой прокси',
|
||||
'settings.system.networkProxy.description': 'HTTP(S)-прокси для облачной синхронизации и провайдеров ИИ. Не связан с SSH ProxyJump / ProxyCommand.',
|
||||
'settings.system.networkProxy.description': 'HTTP(S)-прокси для облачной синхронизации и AI-провайдеров. Не связан с SSH ProxyJump / ProxyCommand.',
|
||||
'settings.system.networkProxy.mode': 'Режим прокси',
|
||||
'settings.system.networkProxy.mode.system': 'Системный прокси',
|
||||
'settings.system.networkProxy.mode.direct': 'Напрямую (без прокси)',
|
||||
@@ -283,7 +256,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 для синхронизации и на запросы к провайдерам ИИ. SSH-подключения не меняет.',
|
||||
'settings.system.networkProxy.hint': 'Влияет на вход в Google Drive / OneDrive / GitHub sync и запросы к AI-провайдерам. SSH-подключения не меняет.',
|
||||
|
||||
// Settings > System > Crash Logs
|
||||
'settings.system.crashLogs.title': 'Журналы сбоев',
|
||||
@@ -323,21 +296,6 @@ 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': 'Настройка экспорта журналов сессий и параметров автосохранения.',
|
||||
@@ -537,7 +495,7 @@ export const ruCoreMessages: Messages = {
|
||||
|
||||
### Боковая панель терминала
|
||||
|
||||
- \`terminal-side-panel\` — панель SFTP / скриптов / темы / ИИ (только пока открыта)
|
||||
- \`terminal-side-panel\` — панель SFTP / скриптов / темы / AI (только пока открыта)
|
||||
- \`terminal-side-panel-tabs\`
|
||||
- \`terminal-side-panel-content\`
|
||||
|
||||
@@ -639,7 +597,6 @@ 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': 'Шрифт',
|
||||
@@ -865,18 +822,6 @@ 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': 'Автоматически открывать боковую панель после открытия локальной оболочки.',
|
||||
@@ -884,14 +829,10 @@ 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',
|
||||
@@ -931,18 +872,6 @@ 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': 'Встроенные изображения',
|
||||
@@ -1158,6 +1087,16 @@ export const ruCoreMessages: Messages = {
|
||||
'vault.nav.notes': 'Заметки',
|
||||
'vault.nav.knownHosts': 'Известные хосты',
|
||||
'vault.nav.logs': 'Журналы',
|
||||
'vault.nav.customize': 'Настроить боковую панель',
|
||||
'vault.nav.customizeHint': 'Перетаскивайте элементы для сортировки или переключения видимости.',
|
||||
'vault.nav.hideItem': 'Скрыть «{label}»',
|
||||
'vault.nav.moveUp': 'Переместить выше',
|
||||
'vault.nav.moveDown': 'Переместить ниже',
|
||||
'vault.nav.resetDefault': 'Сбросить по умолчанию',
|
||||
'vault.nav.alwaysVisible': 'Всегда видно',
|
||||
'vault.nav.pluginBadge': 'Плагин',
|
||||
'vault.nav.dragToReorder': 'Перетащите, чтобы изменить порядок «{label}»',
|
||||
'vault.nav.toggleVisibility': 'Переключить видимость «{label}»',
|
||||
|
||||
'proxyProfiles.action.add': 'Добавить прокси',
|
||||
'proxyProfiles.search.placeholder': 'Поиск прокси…',
|
||||
@@ -1200,7 +1139,6 @@ 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': 'Родитель',
|
||||
@@ -1209,10 +1147,7 @@ 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',
|
||||
@@ -1238,7 +1173,6 @@ 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',
|
||||
@@ -1262,6 +1196,9 @@ export const ruCoreMessages: Messages = {
|
||||
"plugins.sidebar.loading": "Загрузка страницы расширения…",
|
||||
"plugins.vault.loading": "Загрузка страницы плагина…",
|
||||
"plugins.interaction.title": "Запрос плагина",
|
||||
"plugins.interaction.openUrlTitle": "Открыть внешнюю ссылку?",
|
||||
"plugins.interaction.openUrlNote": "Этот плагин запрашивает открытие следующего HTTPS-адреса в браузере по умолчанию:",
|
||||
"plugins.interaction.openUrlAction": "Открыть URL",
|
||||
"plugins.interaction.sharing": "Переданный текст доступен плагину и его разрешённым возможностям, включая сеть. Чтение не разрешает новый сетевой адрес.",
|
||||
"plugins.interaction.input": "Ввести текст",
|
||||
"plugins.interaction.filter": "Фильтр вариантов",
|
||||
@@ -1272,19 +1209,15 @@ export const ruCoreMessages: Messages = {
|
||||
"plugins.interaction.copy": "Копировать в буфер обмена",
|
||||
"plugins.interaction.failed": "Запрос истёк или не выполнен.",
|
||||
"plugins.command.failed": "Не удалось выполнить команду плагина. Проверьте необходимые выбранные объекты и разрешения.",
|
||||
"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": "Закрыть черновик",
|
||||
"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",
|
||||
"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": "Загрузка разрешений...",
|
||||
@@ -1294,7 +1227,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": "Заявленные поддерживаемые возможности по умолчанию разрешены. Для каждой можно выбрать запрос или запрет в настройках разрешений. Проверки приложения и область ресурсов действуют всегда.",
|
||||
@@ -1352,28 +1285,28 @@ export const ruCoreMessages: Messages = {
|
||||
"settings.plugins.manager.unbounded": "Более узкая область ресурсов не заявлена. Проверки приложения и выбранный режим разрешений продолжают действовать.",
|
||||
"settings.plugins.openView": "Открыть",
|
||||
"settings.plugins.openManager": "Открыть управление плагинами",
|
||||
"settings.plugins.sources.conflict": "Плагин с этим идентификатором установлен из другого источника. Перед сменой источника удалите плагин и очистите его приватные данные. Текущий источник:",
|
||||
"settings.plugins.sources.clearPrivate": "Также удалить приватные данные, выданные разрешения и секреты этого источника, чтобы установить плагин из другого источника. Это действие нельзя отменить.",
|
||||
"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.short.official": "Официальный",
|
||||
"settings.plugins.sources.short.thirdparty": "Сторонний",
|
||||
"settings.plugins.sources.short.local": "Локальный",
|
||||
"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.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.title": "Плагины",
|
||||
"settings.plugins.configuration": "Настройки плагина",
|
||||
"settings.plugins.description": "Управляйте плагинами и просматривайте каталог.",
|
||||
|
||||
@@ -26,9 +26,6 @@ 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',
|
||||
@@ -190,20 +187,6 @@ 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': 'Загрузка слушающих портов…',
|
||||
@@ -249,7 +232,7 @@ export const ruSystemManagerMessages: Messages = {
|
||||
'systemManager.services.enable': 'Включить автозапуск',
|
||||
'systemManager.services.disable': 'Отключить автозапуск',
|
||||
'systemManager.services.reload': 'Перезагрузить',
|
||||
'systemManager.services.scope.user': 'Пользовательская служба',
|
||||
'systemManager.services.scope.user': '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': 'Панель контекста',
|
||||
'settings.terminal.behavior.contextChips.desc': 'Показывать панель контекста под быстрыми командами в области ввода.',
|
||||
'settings.terminal.behavior.contextChips': 'Context Chips',
|
||||
'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': 'Прикрепить выделенный вывод терминала к черновику сообщения для ИИ',
|
||||
'terminal.selection.addToAIDesc': 'Прикрепить выбранный вывод терминала к черновику AI',
|
||||
'terminal.auth.password': 'Пароль',
|
||||
'terminal.auth.sshKey': 'SSH-ключ',
|
||||
'terminal.auth.username': 'Имя пользователя',
|
||||
@@ -273,11 +273,8 @@ 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.et.proxyUnsupported': 'EternalTerminal пока не поддерживает настройки прокси Netcatty. Используйте SSH или уберите прокси для этого хоста.',
|
||||
'terminal.et.multiJumpUnsupported': 'В Netcatty EternalTerminal пока поддерживает только один промежуточный хост.',
|
||||
'terminal.connection.protocol.serial': 'Последовательный порт',
|
||||
'terminal.connection.protocol.serial': 'Serial',
|
||||
'terminal.connection.protocol.local': 'Локальная оболочка',
|
||||
'terminal.hostKey.unknownTitle': 'Подтвердите этот ключ хоста',
|
||||
'terminal.hostKey.changedTitle': 'Ключ хоста изменился',
|
||||
@@ -739,8 +736,6 @@ 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': 'Например: проверить сетевую нагрузку',
|
||||
@@ -767,9 +762,6 @@ 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': 'История оболочки пока пуста',
|
||||
@@ -852,7 +844,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'snippets.shortkey.error.snippetConflict': 'Это сочетание уже используется сниппетом: {name}',
|
||||
|
||||
// Serial Port
|
||||
'serial.button': 'Serial',
|
||||
'serial.button': 'Серийный',
|
||||
'serial.modal.title': 'Подключение к последовательному порту',
|
||||
'serial.modal.desc': 'Настройте параметры подключения к последовательному порту',
|
||||
'serial.field.port': 'Последовательный порт',
|
||||
@@ -870,8 +862,8 @@ export const ruTerminalMessages: Messages = {
|
||||
'serial.parity.none': 'Нет',
|
||||
'serial.parity.even': 'Чётная',
|
||||
'serial.parity.odd': 'Нечётная',
|
||||
'serial.parity.mark': 'Всегда 1 (Mark)',
|
||||
'serial.parity.space': 'Всегда 0 (Space)',
|
||||
'serial.parity.mark': 'Mark',
|
||||
'serial.parity.space': 'Space',
|
||||
'serial.flowControl.none': 'Нет',
|
||||
'serial.flowControl.xon/xoff': 'XON/XOFF (программный)',
|
||||
'serial.flowControl.rts/cts': 'RTS/CTS (аппаратный)',
|
||||
|
||||
@@ -861,9 +861,6 @@ 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': 'Показать пароль',
|
||||
@@ -942,7 +939,7 @@ export const ruVaultMessages: Messages = {
|
||||
'hostDetails.section.deviceType': 'Тип устройства',
|
||||
'hostDetails.deviceType': 'Режим сетевого устройства',
|
||||
'hostDetails.deviceType.desc': 'Включайте для сетевого оборудования (коммутаторов, маршрутизаторов, межсетевых экранов), подключённого по SSH. Команды отправляются как есть, без обёртки оболочки, что совместимо с CLI вендоров вроде Huawei VRP и Cisco IOS.',
|
||||
'hostDetails.deviceType.warning': 'Команды агента ИИ будут отправляться напрямую без отслеживания кода выхода. Включайте только для устройств, на которых нет стандартной оболочки.',
|
||||
'hostDetails.deviceType.warning': 'Команды AI-агента будут отправляться напрямую без отслеживания кода выхода. Включайте только для устройств, на которых нет стандартной оболочки.',
|
||||
'hostDetails.section.sshAlgorithms': 'SSH-алгоритмы',
|
||||
'hostDetails.section.terminalBehavior': 'Поведение терминала',
|
||||
'hostDetails.lineTimestamps': 'Показывать время вывода',
|
||||
@@ -1028,7 +1025,7 @@ export const ruVaultMessages: Messages = {
|
||||
'hostDetails.startupCommand': 'Команда запуска',
|
||||
'hostDetails.startupCommand.placeholder': 'Команда для запуска при подключении (например, cd /app && ls)',
|
||||
'hostDetails.startupCommand.help':
|
||||
'Команда выполняется автоматически после подключения по SSH.',
|
||||
'This command will be executed automatically after SSH connection is established.',
|
||||
'hostDetails.startupCommand.runMode': 'Многострочный запуск',
|
||||
'hostDetails.startupCommand.runMode.help': 'Выберите, как отправлять многострочные команды запуска после подключения.',
|
||||
'hostDetails.startupCommand.runMode.lineDelay': 'Отправлять построчно',
|
||||
@@ -1334,8 +1331,8 @@ export const ruVaultMessages: Messages = {
|
||||
'remoteDesktop.cert.rejected': 'TLS-сертификат отклонён пользователем.',
|
||||
'remoteDesktop.step.bastion': 'Бастион',
|
||||
'remoteDesktop.step.network': 'Сеть',
|
||||
'remoteDesktop.step.nla': 'Аутентификация NLA',
|
||||
'remoteDesktop.step.rfb': 'Аутентификация RFB',
|
||||
'remoteDesktop.step.nla': 'NLA Auth',
|
||||
'remoteDesktop.step.rfb': 'RFB Auth',
|
||||
'remoteDesktop.step.desktop': 'Рабочий стол',
|
||||
'remoteDesktop.display.resolutionPresets': 'Пресеты разрешения',
|
||||
'remoteDesktop.display.customWidth': 'Ширина',
|
||||
@@ -1397,7 +1394,6 @@ 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': 'Снять экран и спросить ИИ',
|
||||
@@ -1444,18 +1440,7 @@ 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': 'Записи удалённого рабочего стола',
|
||||
@@ -1463,7 +1448,7 @@ export const ruVaultMessages: Messages = {
|
||||
'settings.remoteDesktopRecordings.autoRecordDesc': 'Автоматически начинать запись RDP и VNC после подключения (выключено по умолчанию для экономии места).',
|
||||
'settings.remoteDesktopRecordings.fps': 'Частота кадров записи',
|
||||
'settings.remoteDesktopRecordings.fpsDesc': 'Более высокая частота делает видео плавнее, но увеличивает нагрузку на ЦП и размер файлов.',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} кадр/с',
|
||||
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
|
||||
'settings.remoteDesktopRecordings.includeAudio': 'Включать звук RDP',
|
||||
'settings.remoteDesktopRecordings.includeAudioDesc': 'Записывать звук удалённого рабочего стола в видео .webm, если он доступен.',
|
||||
'settings.remoteDesktopRecordings.maxStorage': 'Лимит места на диске',
|
||||
|
||||
@@ -734,6 +734,16 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
'vault.nav.notes': '笔记',
|
||||
'vault.nav.knownHosts': '已知主机',
|
||||
'vault.nav.logs': '日志',
|
||||
'vault.nav.customize': '自定义侧边栏',
|
||||
'vault.nav.customizeHint': '拖动项目以调整顺序,或切换显示状态。',
|
||||
'vault.nav.hideItem': '隐藏「{label}」',
|
||||
'vault.nav.moveUp': '上移',
|
||||
'vault.nav.moveDown': '下移',
|
||||
'vault.nav.resetDefault': '恢复默认',
|
||||
'vault.nav.alwaysVisible': '始终显示',
|
||||
'vault.nav.pluginBadge': '插件',
|
||||
'vault.nav.dragToReorder': '拖动以调整「{label}」的顺序',
|
||||
'vault.nav.toggleVisibility': '切换「{label}」的显示状态',
|
||||
|
||||
'proxyProfiles.action.add': '添加代理',
|
||||
'proxyProfiles.search.placeholder': '搜索代理…',
|
||||
@@ -785,10 +795,7 @@ 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',
|
||||
@@ -1238,6 +1245,9 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
"plugins.sidebar.loading": "正在加载扩展页面…",
|
||||
"plugins.vault.loading": "正在加载插件页面…",
|
||||
"plugins.interaction.title": "插件请求",
|
||||
"plugins.interaction.openUrlTitle": "打开外部链接?",
|
||||
"plugins.interaction.openUrlNote": "此插件请求在默认浏览器中打开以下 HTTPS 链接:",
|
||||
"plugins.interaction.openUrlAction": "打开链接",
|
||||
"plugins.interaction.sharing": "分享的文本将交给此插件及其已授权的能力(包括网络访问)。读取文本不代表批准新的网络目标。",
|
||||
"plugins.interaction.input": "输入文本",
|
||||
"plugins.interaction.filter": "筛选选项",
|
||||
|
||||
@@ -1283,7 +1283,6 @@ 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',
|
||||
@@ -1389,18 +1388,7 @@ 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': '远程桌面录屏',
|
||||
|
||||
@@ -734,6 +734,16 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
'vault.nav.notes': '筆記',
|
||||
'vault.nav.knownHosts': '已知主機',
|
||||
'vault.nav.logs': '日誌',
|
||||
'vault.nav.customize': '自訂側邊欄',
|
||||
'vault.nav.customizeHint': '拖曳項目以調整順序,或切換顯示狀態。',
|
||||
'vault.nav.hideItem': '隱藏「{label}」',
|
||||
'vault.nav.moveUp': '上移',
|
||||
'vault.nav.moveDown': '下移',
|
||||
'vault.nav.resetDefault': '恢復預設',
|
||||
'vault.nav.alwaysVisible': '始終顯示',
|
||||
'vault.nav.pluginBadge': '外掛',
|
||||
'vault.nav.dragToReorder': '拖曳以調整「{label}」的順序',
|
||||
'vault.nav.toggleVisibility': '切換「{label}」的顯示狀態',
|
||||
|
||||
'proxyProfiles.action.add': '新增代理',
|
||||
'proxyProfiles.search.placeholder': '搜尋代理…',
|
||||
@@ -785,10 +795,7 @@ 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',
|
||||
@@ -1239,6 +1246,9 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
"plugins.sidebar.loading": "正在載入擴充功能頁面…",
|
||||
"plugins.vault.loading": "正在載入擴充功能頁面…",
|
||||
"plugins.interaction.title": "外掛請求",
|
||||
"plugins.interaction.openUrlTitle": "開啟外部連結?",
|
||||
"plugins.interaction.openUrlNote": "此外掛請求在預設瀏覽器中開啟以下 HTTPS 連結:",
|
||||
"plugins.interaction.openUrlAction": "開啟連結",
|
||||
"plugins.interaction.sharing": "分享的文字會交給此外掛及其已授權能力(包括網路存取)。讀取文字不代表核准新的網路目的地。",
|
||||
"plugins.interaction.input": "輸入文字",
|
||||
"plugins.interaction.filter": "篩選選項",
|
||||
|
||||
@@ -1218,7 +1218,6 @@ 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',
|
||||
@@ -1389,18 +1388,7 @@ 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': '遠端桌面錄影',
|
||||
|
||||
@@ -70,7 +70,11 @@ export function pruneInactiveScopedSessions(
|
||||
orphanedSessionIds: string[];
|
||||
} {
|
||||
const orphanedSessionIds = sessions
|
||||
.filter((session) => session.scope.targetId && !activeTargetIds.has(session.scope.targetId))
|
||||
.filter((session) => (
|
||||
(session.scope.type === "terminal" || session.scope.type === "workspace")
|
||||
&& session.scope.targetId
|
||||
&& !activeTargetIds.has(session.scope.targetId)
|
||||
))
|
||||
.filter((session) => !activeSessionIds.has(session.id))
|
||||
.map((session) => session.id);
|
||||
|
||||
|
||||
@@ -116,6 +116,9 @@ function isScopeKeyActive(scopeKey: string, activeTargetIds: Set<string>) {
|
||||
const separatorIndex = scopeKey.indexOf(':');
|
||||
if (separatorIndex === -1) return true;
|
||||
|
||||
const scopeType = scopeKey.slice(0, separatorIndex);
|
||||
if (scopeType === 'global') return true;
|
||||
|
||||
const targetId = scopeKey.slice(separatorIndex + 1);
|
||||
if (!targetId) return true;
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export type ConnectionLogsSnapshot = {
|
||||
};
|
||||
|
||||
export type ConnectionLogsActions = {
|
||||
updateConnectionLog: (id: string, updates: Partial<ConnectionLog>) => void | Promise<unknown>;
|
||||
updateConnectionLog: (id: string, updates: Partial<ConnectionLog>) => void;
|
||||
toggleConnectionLogSaved: (id: string) => void;
|
||||
deleteConnectionLog: (id: string) => void;
|
||||
clearUnsavedConnectionLogs: () => void;
|
||||
|
||||
@@ -24,11 +24,22 @@ export class PluginHostActionResources {
|
||||
const entry = this.entries.get(id);
|
||||
if (!entry) throw new Error('Selected host is unavailable');
|
||||
const host = entry.host;
|
||||
const osValue = typeof host.os === 'string'
|
||||
? Array.from(host.os).filter((ch) => {
|
||||
const code = ch.charCodeAt(0);
|
||||
return code >= 0x20 && code !== 0x7f;
|
||||
}).join('').slice(0, 128)
|
||||
: '';
|
||||
const notesValue = typeof host.notes === 'string'
|
||||
? host.notes.split('\0').join('').slice(0, 4096)
|
||||
: '';
|
||||
return {
|
||||
resourceId: host.id, revision: entry.revision,
|
||||
label: host.label, hostname: host.hostname, username: host.username,
|
||||
...(host.port === undefined ? {} : { port: host.port }), protocol: host.protocol ?? 'ssh',
|
||||
group: host.group ?? '', tags: [...host.tags],
|
||||
...(osValue ? { os: osValue } : {}),
|
||||
...(notesValue ? { notes: notesValue } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,17 @@ type WireNode = { id: string; type: 3 | 8; data: string } | {
|
||||
};
|
||||
type WireTree = { children: WireNode[] };
|
||||
|
||||
const validatedTrees = new WeakSet<object>();
|
||||
|
||||
export function isValidatedPluginRemoteTree(tree: unknown): boolean {
|
||||
return Boolean(tree && typeof tree === 'object' && validatedTrees.has(tree));
|
||||
}
|
||||
|
||||
/** Data-only staging area: untrusted changes are never applied directly to the host DOM. */
|
||||
export function createPluginRemoteTree() {
|
||||
const receiver = new RemoteReceiver();
|
||||
let current: WireTree = { children: [] };
|
||||
validatedTrees.add(current);
|
||||
let failed = false;
|
||||
const project = (node: unknown): WireNode => {
|
||||
const value = node as { id: string; type: number; data?: string; element?: string; attributes?: Record<string, string>; children?: unknown[] };
|
||||
@@ -27,11 +34,13 @@ export function createPluginRemoteTree() {
|
||||
receiver.connection.mutate(batch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
|
||||
const next = { children: receiver.root.children.map(project) };
|
||||
validatePluginRemoteTree(next);
|
||||
validatedTrees.add(next);
|
||||
current = next;
|
||||
return next;
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
current = { children: [] };
|
||||
validatedTrees.add(current);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
import type { Host, PortForwardingRule, Snippet } from '../../domain/models';
|
||||
import { applyGroupDefaults, resolveGroupDefaults } from '../../domain/groupConfig';
|
||||
import { materializeHostProxyProfile } from '../../domain/proxyProfiles';
|
||||
import { resolveEffectiveTerminalProtocol } from '../../domain/terminalProtocol';
|
||||
import {
|
||||
migratePortForwardingRulesFromStorage,
|
||||
toPersistedPortForwardingRules,
|
||||
} from '../../domain/portForwardingPersistence';
|
||||
import { STORAGE_KEY_PORT_FORWARDING } from '../../infrastructure/config/storageKeys';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { preparePluginHostStream } from '../../infrastructure/services/pluginHostStreamService';
|
||||
import { startPortForward, stopAndCleanupRule } from '../../infrastructure/services/portForwardingService';
|
||||
import { captureScreenSnapshot } from '../../infrastructure/scripts/screenSnapshotRegistry';
|
||||
import { activeTabStore } from './activeTabStore';
|
||||
import {
|
||||
getAppSessionRuntime,
|
||||
getAppSettingsRuntime,
|
||||
type AppVaultRuntime,
|
||||
} from './appRuntimeBridge';
|
||||
import type { PluginHostActionResources } from './pluginHostActionResources';
|
||||
|
||||
export type PluginVaultDataContext = {
|
||||
getVault: () => AppVaultRuntime & ReturnType<AppVaultRuntime['readCurrentHostActionState']>;
|
||||
resources: PluginHostActionResources;
|
||||
};
|
||||
|
||||
function readPortForwardRules(): PortForwardingRule[] {
|
||||
const raw = localStorageAdapter.read<PortForwardingRule[]>(STORAGE_KEY_PORT_FORWARDING);
|
||||
return migratePortForwardingRulesFromStorage(Array.isArray(raw) ? raw : []);
|
||||
}
|
||||
|
||||
function writePortForwardRules(rules: PortForwardingRule[]): void {
|
||||
localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, toPersistedPortForwardingRules(rules));
|
||||
}
|
||||
|
||||
function summarizePortForwardRule(rule: PortForwardingRule, hosts: readonly Host[]) {
|
||||
const host = rule.hostId ? hosts.find((candidate) => candidate.id === rule.hostId) : undefined;
|
||||
return {
|
||||
id: rule.id,
|
||||
label: rule.label,
|
||||
type: rule.type,
|
||||
localPort: rule.localPort,
|
||||
bindAddress: rule.bindAddress || '127.0.0.1',
|
||||
...(rule.remoteHost ? { remoteHost: rule.remoteHost } : {}),
|
||||
...(typeof rule.remotePort === 'number' && rule.remotePort >= 1 ? { remotePort: rule.remotePort } : {}),
|
||||
...(host?.label ? { hostLabel: host.label } : {}),
|
||||
...(host?.hostname ? { hostname: host.hostname } : {}),
|
||||
status: rule.status ?? 'inactive',
|
||||
...(rule.error ? { error: rule.error.slice(0, 512) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function summarizeSnippet(snippet: Snippet) {
|
||||
return {
|
||||
id: snippet.id,
|
||||
label: snippet.label,
|
||||
command: snippet.command,
|
||||
...(snippet.package ? { package: snippet.package } : {}),
|
||||
...(Array.isArray(snippet.tags) && snippet.tags.length > 0 ? { tags: [...snippet.tags] } : {}),
|
||||
...(snippet.shortcut ? { shortcut: snippet.shortcut } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function effectiveHost(
|
||||
host: Host,
|
||||
vault: Pick<AppVaultRuntime, 'groupConfigs' | 'proxyProfiles'>,
|
||||
): Host {
|
||||
const validProxyProfileIds = new Set(vault.proxyProfiles.map((p) => p.id));
|
||||
const defaults = host.group
|
||||
? resolveGroupDefaults(host.group, vault.groupConfigs, { validProxyProfileIds })
|
||||
: {};
|
||||
return materializeHostProxyProfile(
|
||||
applyGroupDefaults(host, defaults, { validProxyProfileIds }),
|
||||
vault.proxyProfiles,
|
||||
);
|
||||
}
|
||||
|
||||
export async function handlePluginVaultDataRequest(
|
||||
kind: string,
|
||||
payload: Record<string, unknown>,
|
||||
ctx: PluginVaultDataContext,
|
||||
): Promise<unknown> {
|
||||
const vault = ctx.getVault();
|
||||
|
||||
switch (kind) {
|
||||
case 'resolveMetadata': {
|
||||
const hostIds = Array.isArray(payload.hostIds) ? payload.hostIds : [];
|
||||
const hosts: Record<string, Record<string, unknown>> = {};
|
||||
for (const hostId of hostIds) {
|
||||
if (typeof hostId !== 'string') continue;
|
||||
const found = vault.hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!found) continue;
|
||||
const { resourceId: _resourceId, revision: _revision, ...meta } = ctx.resources.metadata(found.id);
|
||||
hosts[hostId] = meta;
|
||||
}
|
||||
return { hosts };
|
||||
}
|
||||
|
||||
case 'prepareConnection': {
|
||||
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
|
||||
const host = vault.hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!host) throw new Error('Saved SSH host no longer exists');
|
||||
const settings = getAppSettingsRuntime();
|
||||
if (!settings) throw new Error('Terminal settings unavailable');
|
||||
const connectionOptions = await preparePluginHostStream(host, vault, settings.terminalSettings);
|
||||
return { connectionOptions };
|
||||
}
|
||||
|
||||
case 'prepareProbeTarget': {
|
||||
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
|
||||
const rawHost = vault.hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!rawHost) throw new Error('Saved host no longer exists');
|
||||
const host = effectiveHost(rawHost, vault);
|
||||
const defaultProtocol = resolveEffectiveTerminalProtocol(host);
|
||||
const rdpPort = host.rdpConfig?.port ?? (defaultProtocol === 'rdp' ? (host.port || 3389) : undefined);
|
||||
const vncPort = host.vncConfig?.port ?? (defaultProtocol === 'vnc' ? (host.port || 5900) : undefined);
|
||||
const isRemoteDesktopOnly = defaultProtocol === 'rdp' || defaultProtocol === 'vnc';
|
||||
return {
|
||||
hostname: host.hostname,
|
||||
...(!isRemoteDesktopOnly ? { sshPort: host.port || 22 } : {}),
|
||||
...(rdpPort ? { rdpPort } : {}),
|
||||
...(vncPort ? { vncPort } : {}),
|
||||
defaultProtocol,
|
||||
...(host.rdpConfig?.securityMode ? { rdpSecurityMode: host.rdpConfig.securityMode } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
case 'listGroups': {
|
||||
const counts = new Map<string, number>();
|
||||
for (const groupPath of vault.customGroups) {
|
||||
if (groupPath) counts.set(groupPath, counts.get(groupPath) ?? 0);
|
||||
}
|
||||
for (const host of vault.hosts) {
|
||||
if (host.group) counts.set(host.group, (counts.get(host.group) ?? 0) + 1);
|
||||
}
|
||||
const groups = [...counts.entries()]
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.slice(0, 1000)
|
||||
.map(([path, hostCount]) => ({ path, hostCount }));
|
||||
return { groups };
|
||||
}
|
||||
|
||||
case 'updateHostNotes': {
|
||||
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
|
||||
const notes = typeof payload.notes === 'string' ? payload.notes.slice(0, 4096) : '';
|
||||
const host = vault.hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!host) throw new Error('Saved host no longer exists');
|
||||
if (host.managedSourceId) throw new Error('Managed SSH config hosts cannot be edited directly');
|
||||
vault.updateHosts((prev) => prev.map((item) => (item.id === hostId ? { ...item, notes } : item)));
|
||||
return { updated: true };
|
||||
}
|
||||
|
||||
case 'updateHostTags': {
|
||||
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
|
||||
const tags = Array.isArray(payload.tags)
|
||||
? payload.tags.filter((t): t is string => typeof t === 'string' && t.length > 0).slice(0, 128)
|
||||
: [];
|
||||
const host = vault.hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!host) throw new Error('Saved host no longer exists');
|
||||
if (host.managedSourceId) throw new Error('Managed SSH config hosts cannot be edited directly');
|
||||
vault.updateHosts((prev) => prev.map((item) => (item.id === hostId ? { ...item, tags } : item)));
|
||||
return { updated: true };
|
||||
}
|
||||
|
||||
case 'portForward.list': {
|
||||
const rules = readPortForwardRules().slice(0, 500);
|
||||
return { rules: rules.map((rule) => summarizePortForwardRule(rule, vault.hosts)) };
|
||||
}
|
||||
|
||||
case 'portForward.create': {
|
||||
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
|
||||
const host = vault.hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!host) throw new Error('Bound host no longer exists');
|
||||
const rule: PortForwardingRule = {
|
||||
id: crypto.randomUUID(),
|
||||
label: String(payload.label ?? '').slice(0, 256),
|
||||
type: (payload.type === 'remote' || payload.type === 'dynamic' ? payload.type : 'local'),
|
||||
localPort: Number(payload.localPort),
|
||||
bindAddress: typeof payload.bindAddress === 'string' && payload.bindAddress ? payload.bindAddress : '127.0.0.1',
|
||||
...(typeof payload.remoteHost === 'string' ? { remoteHost: payload.remoteHost } : {}),
|
||||
...(typeof payload.remotePort === 'number' ? { remotePort: payload.remotePort } : {}),
|
||||
hostId: host.id,
|
||||
status: 'inactive',
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
const existing = readPortForwardRules();
|
||||
writePortForwardRules([...existing, rule]);
|
||||
return { ok: true, rule: summarizePortForwardRule(rule, vault.hosts) };
|
||||
}
|
||||
|
||||
case 'portForward.start': {
|
||||
const ruleId = typeof payload.ruleId === 'string' ? payload.ruleId : '';
|
||||
const rules = readPortForwardRules();
|
||||
const rule = rules.find((item) => item.id === ruleId);
|
||||
if (!rule) return { ok: false, error: 'Port forwarding rule not found' };
|
||||
const rawHost = rule.hostId ? vault.hosts.find((h) => h.id === rule.hostId) : undefined;
|
||||
if (!rawHost) return { ok: false, error: 'Target host for port forwarding rule not found' };
|
||||
const settings = getAppSettingsRuntime();
|
||||
const resolvedHost = effectiveHost(rawHost, vault);
|
||||
const resolvedHosts = vault.hosts.map((h) => effectiveHost(h, vault));
|
||||
const res = await startPortForward(
|
||||
rule,
|
||||
resolvedHost,
|
||||
resolvedHosts,
|
||||
vault.keys,
|
||||
vault.identities,
|
||||
(status, error) => {
|
||||
const latest = readPortForwardRules();
|
||||
writePortForwardRules(latest.map((item) => (item.id === ruleId ? { ...item, status, error } : item)));
|
||||
},
|
||||
false,
|
||||
settings?.terminalSettings,
|
||||
vault.knownHosts,
|
||||
);
|
||||
const updated = readPortForwardRules().find((item) => item.id === ruleId) ?? rule;
|
||||
return {
|
||||
ok: Boolean(res.success),
|
||||
rule: summarizePortForwardRule(updated, vault.hosts),
|
||||
...(res.error ? { error: String(res.error).slice(0, 512) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
case 'portForward.stop': {
|
||||
const ruleId = typeof payload.ruleId === 'string' ? payload.ruleId : '';
|
||||
const rules = readPortForwardRules();
|
||||
const rule = rules.find((item) => item.id === ruleId);
|
||||
if (!rule) return { ok: false, error: 'Port forwarding rule not found' };
|
||||
await stopAndCleanupRule(ruleId);
|
||||
const latestRules = readPortForwardRules();
|
||||
const nextRules = latestRules.map((item) => (item.id === ruleId ? { ...item, status: 'inactive' as const, error: undefined } : item));
|
||||
writePortForwardRules(nextRules);
|
||||
const updated = nextRules.find((item) => item.id === ruleId) ?? rule;
|
||||
return { ok: true, rule: summarizePortForwardRule(updated, vault.hosts) };
|
||||
}
|
||||
|
||||
case 'portForward.delete': {
|
||||
const ruleId = typeof payload.ruleId === 'string' ? payload.ruleId : '';
|
||||
const rules = readPortForwardRules();
|
||||
if (!rules.some((item) => item.id === ruleId)) {
|
||||
return { ok: false, error: 'Port forwarding rule not found' };
|
||||
}
|
||||
await stopAndCleanupRule(ruleId).catch(() => {});
|
||||
const latestRules = readPortForwardRules();
|
||||
writePortForwardRules(latestRules.filter((item) => item.id !== ruleId));
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
case 'snippets.list': {
|
||||
const query = typeof payload.query === 'string' ? payload.query.trim().toLowerCase() : '';
|
||||
const tag = typeof payload.tag === 'string' ? payload.tag : '';
|
||||
const pkg = typeof payload.package === 'string' ? payload.package : '';
|
||||
const filtered = vault.snippets.filter((snippet) => {
|
||||
if (pkg && snippet.package !== pkg) return false;
|
||||
if (tag && !(snippet.tags ?? []).includes(tag)) return false;
|
||||
if (query) {
|
||||
const hay = `${snippet.label} ${snippet.command} ${(snippet.tags ?? []).join(' ')}`.toLowerCase();
|
||||
if (!hay.includes(query)) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return { snippets: filtered.slice(0, 1000).map(summarizeSnippet) };
|
||||
}
|
||||
|
||||
case 'snippets.get': {
|
||||
const id = typeof payload.id === 'string' ? payload.id : '';
|
||||
const found = vault.snippets.find((item) => item.id === id);
|
||||
return found ? { found: true, snippet: summarizeSnippet(found) } : { found: false };
|
||||
}
|
||||
|
||||
case 'snippets.save': {
|
||||
const id = typeof payload.id === 'string' && payload.id ? payload.id : crypto.randomUUID();
|
||||
const existing = vault.snippets.find((item) => item.id === id);
|
||||
const nextSnippet: Snippet = {
|
||||
...(existing ?? {}),
|
||||
id,
|
||||
label: String(payload.label ?? '').slice(0, 256),
|
||||
command: String(payload.command ?? '').slice(0, 65536),
|
||||
...(typeof payload.package === 'string' ? { package: payload.package } : {}),
|
||||
...(Array.isArray(payload.tags) ? { tags: payload.tags.filter((t): t is string => typeof t === 'string') } : {}),
|
||||
...(typeof payload.shortcut === 'string' ? { shortcut: payload.shortcut } : {}),
|
||||
};
|
||||
const nextList = existing
|
||||
? vault.snippets.map((item) => (item.id === id ? nextSnippet : item))
|
||||
: [...vault.snippets, nextSnippet];
|
||||
vault.updateSnippets(nextList);
|
||||
return { snippet: summarizeSnippet(nextSnippet) };
|
||||
}
|
||||
|
||||
case 'snippets.delete': {
|
||||
const id = typeof payload.id === 'string' ? payload.id : '';
|
||||
const exists = vault.snippets.some((item) => item.id === id);
|
||||
if (exists) {
|
||||
vault.updateSnippets(vault.snippets.filter((item) => item.id !== id));
|
||||
}
|
||||
return { deleted: exists };
|
||||
}
|
||||
|
||||
case 'terminals.listSessions': {
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
const activeId = activeTabStore.getActiveTabId();
|
||||
const sessions = (sessionRuntime?.sessions ?? []).slice(0, 200).map((session) => ({
|
||||
sessionId: session.id,
|
||||
label: session.hostLabel || session.hostname || session.id,
|
||||
hostname: session.hostname || '',
|
||||
...(session.username ? { username: session.username } : {}),
|
||||
protocol: session.protocol || 'ssh',
|
||||
status: session.status || 'connecting',
|
||||
...(session.workspaceId ? { workspaceId: session.workspaceId } : {}),
|
||||
active: session.id === activeId || (Boolean(session.workspaceId) && session.workspaceId === activeId),
|
||||
}));
|
||||
return { sessions };
|
||||
}
|
||||
|
||||
case 'terminals.readScreen': {
|
||||
const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : '';
|
||||
const maxRows = typeof payload.maxRows === 'number' ? Math.max(1, Math.min(300, payload.maxRows)) : 80;
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
if (!sessionRuntime?.sessions.some((s) => s.id === sessionId)) {
|
||||
throw new Error('Terminal session not found');
|
||||
}
|
||||
const snapshot = captureScreenSnapshot(sessionId);
|
||||
const lines = (snapshot.lines ?? []).slice(-maxRows);
|
||||
return {
|
||||
sessionId,
|
||||
rows: snapshot.rows ?? lines.length,
|
||||
cols: snapshot.cols ?? 80,
|
||||
lines,
|
||||
};
|
||||
}
|
||||
|
||||
case 'terminals.sendInput': {
|
||||
const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : '';
|
||||
const data = typeof payload.data === 'string' ? payload.data : '';
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
if (!sessionRuntime?.sessions.some((s) => s.id === sessionId)) {
|
||||
throw new Error('Terminal session not found');
|
||||
}
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.writeToSession) throw new Error('Terminal input bridge is unavailable');
|
||||
bridge.writeToSession(sessionId, data);
|
||||
return { sent: true };
|
||||
}
|
||||
|
||||
case 'terminals.openLocal': {
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
if (!sessionRuntime?.createLocalTerminal) throw new Error('Local terminal is unavailable');
|
||||
const sessionId = sessionRuntime.createLocalTerminal();
|
||||
return { opened: true, ...(typeof sessionId === 'string' ? { sessionId } : {}) };
|
||||
}
|
||||
|
||||
case 'workspace.listTabs': {
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
const activeTabId = activeTabStore.getActiveTabId();
|
||||
const tabs: Array<{ id: string; kind: 'vault' | 'sftp' | 'session' | 'workspace' | 'log'; title: string; active: boolean }> = [
|
||||
{ id: 'vault', kind: 'vault', title: 'Vault', active: activeTabId === 'vault' },
|
||||
{ id: 'sftp', kind: 'sftp', title: 'SFTP', active: activeTabId === 'sftp' },
|
||||
];
|
||||
for (const workspace of sessionRuntime?.workspaces ?? []) {
|
||||
tabs.push({ id: workspace.id, kind: 'workspace', title: workspace.title || 'Workspace', active: activeTabId === workspace.id });
|
||||
}
|
||||
for (const session of sessionRuntime?.sessions ?? []) {
|
||||
if (session.workspaceId) continue;
|
||||
tabs.push({ id: session.id, kind: 'session', title: session.hostLabel || session.hostname || 'Terminal', active: activeTabId === session.id });
|
||||
}
|
||||
for (const logView of sessionRuntime?.logViews ?? []) {
|
||||
tabs.push({ id: logView.id, kind: 'log', title: logView.title || 'Log', active: activeTabId === logView.id });
|
||||
}
|
||||
return { activeTabId, tabs: tabs.slice(0, 200) };
|
||||
}
|
||||
|
||||
case 'workspace.focusTab': {
|
||||
const tabId = typeof payload.tabId === 'string' ? payload.tabId : '';
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
const known = new Set<string>(['vault', 'sftp']);
|
||||
for (const workspace of sessionRuntime?.workspaces ?? []) known.add(workspace.id);
|
||||
for (const session of sessionRuntime?.sessions ?? []) {
|
||||
if (!session.workspaceId) known.add(session.id);
|
||||
}
|
||||
for (const logView of sessionRuntime?.logViews ?? []) known.add(logView.id);
|
||||
let resolvedTabId = known.has(tabId) ? tabId : null;
|
||||
if (!resolvedTabId) {
|
||||
const memberSession = (sessionRuntime?.sessions ?? []).find((s) => s.id === tabId && s.workspaceId);
|
||||
if (memberSession?.workspaceId && known.has(memberSession.workspaceId)) {
|
||||
resolvedTabId = memberSession.workspaceId;
|
||||
}
|
||||
}
|
||||
if (!resolvedTabId) return { focused: false };
|
||||
if (sessionRuntime?.setActiveTabId) sessionRuntime.setActiveTabId(resolvedTabId);
|
||||
else activeTabStore.setActiveTabId(resolvedTabId);
|
||||
return { focused: true };
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported Vault data request: ${kind}`);
|
||||
}
|
||||
}
|
||||
@@ -39,3 +39,24 @@ test('idle instances are evicted while active instances are never silently repla
|
||||
assert.throws(() => store.acquire('two', f.bridge, request), /Too many/); first.release();
|
||||
const second = store.acquire('two', f.bridge, request); assert.notEqual(second, first); assert.equal(f.closes.length, 1); store.dispose();
|
||||
});
|
||||
test('cssUnchanged updates retain previously validated stylesheet and peek returns live session synchronously', () => {
|
||||
const f = fixture(); const store = new PluginViewSessions();
|
||||
assert.equal(store.peek('view'), null);
|
||||
const view = store.acquire('view', f.bridge, request); const id = f.opened[0].instanceId;
|
||||
assert.equal(store.peek('view'), view);
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.a{display:flex}', mutations: [] });
|
||||
assert.equal(view.getSnapshot().css, '.a{display:flex}');
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 2, css: '', cssUnchanged: true, mutations: [[0, '~', { id: 't', type: 3, data: 'hi' }, 0]] } as Update);
|
||||
assert.equal(view.getSnapshot().css, '.a{display:flex}');
|
||||
assert.deepEqual(view.getSnapshot().tree.children[0], { id: 't', type: 3, data: 'hi' });
|
||||
store.dispose();
|
||||
});
|
||||
test('empty first update holds loading briefly to prevent blank-frame flash then completes cleanly', async () => {
|
||||
const f = fixture(); const store = new PluginViewSessions();
|
||||
const view = store.acquire('empty-grace', f.bridge, request); const id = f.opened[0].instanceId;
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '', mutations: [] });
|
||||
assert.equal(view.getSnapshot().loading, true, 'empty first update holds loading briefly');
|
||||
await new Promise((resolve) => setTimeout(resolve, 90));
|
||||
assert.equal(view.getSnapshot().loading, false, 'truly empty view finishes loading after grace window');
|
||||
store.dispose();
|
||||
});
|
||||
@@ -6,6 +6,17 @@ import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
type Bridge = Pick<NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>;
|
||||
export type PluginViewSnapshot = { tree: ReturnType<ReturnType<typeof createPluginRemoteTree>['snapshot']>; css: string; loading: boolean; error: boolean; settled: boolean };
|
||||
const empty = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
|
||||
const EMPTY_FIRST_FRAME_GRACE_MS = 60;
|
||||
|
||||
function hasRenderableTreeContent(tree: PluginViewSnapshot['tree']): boolean {
|
||||
for (const child of tree.children) {
|
||||
if (child.type === 3 && child.data.trim().length > 0) return true;
|
||||
if (child.type === 1) {
|
||||
if (child.element !== 'div' || child.children.length > 0) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Owns a window's bounded, retained UI instances independently of React mounts. */
|
||||
export class PluginViewSessions {
|
||||
@@ -15,13 +26,15 @@ export class PluginViewSessions {
|
||||
const id = crypto.randomUUID();
|
||||
const tree = createPluginRemoteTree();
|
||||
let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0;
|
||||
let lastRawCss: string | null = null;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let emptyFrameTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const listeners = new Set<() => void>();
|
||||
const publish = (next: PluginViewSnapshot) => { state = next; for (const listener of listeners) listener(); };
|
||||
const cleanup: Array<() => void> = [];
|
||||
const dispose = (failed = false) => {
|
||||
if (disposed) return;
|
||||
disposed = true; clearTimeout(timer); cleanup.forEach((stop) => stop());
|
||||
disposed = true; clearTimeout(timer); clearTimeout(emptyFrameTimer); cleanup.forEach((stop) => stop());
|
||||
this.sessions.delete(key);
|
||||
publish({ ...empty(), loading: false, error: failed });
|
||||
void bridge.closeHostDrawnPluginView?.(id).catch(() => {});
|
||||
@@ -31,7 +44,30 @@ export class PluginViewSessions {
|
||||
if (disposed || update.kind !== 'host-ui.update' || update.instanceId !== id || update.viewId !== request.viewId) return;
|
||||
try {
|
||||
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
|
||||
publish({ tree: tree.apply(update.mutations), css: validatePluginStylesheet(update.css), loading: false, error: false, settled: (update.acknowledgedEvent ?? 0) >= eventId });
|
||||
const nextCss = update.cssUnchanged
|
||||
? state.css
|
||||
: (lastRawCss !== null && update.css === lastRawCss)
|
||||
? state.css
|
||||
: ((lastRawCss = update.css), validatePluginStylesheet(update.css));
|
||||
const nextTree = tree.apply(update.mutations);
|
||||
const settled = (update.acknowledgedEvent ?? 0) >= eventId;
|
||||
if (state.loading && !hasRenderableTreeContent(nextTree)) {
|
||||
// Hold the host loading surface briefly while an older SDK flushes its
|
||||
// initial React commit so users never see an empty blank frame flash.
|
||||
publish({ tree: nextTree, css: nextCss, loading: true, error: false, settled });
|
||||
if (emptyFrameTimer === undefined) {
|
||||
emptyFrameTimer = setTimeout(() => {
|
||||
emptyFrameTimer = undefined;
|
||||
if (!disposed && state.loading) publish({ ...state, loading: false });
|
||||
}, EMPTY_FIRST_FRAME_GRACE_MS);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (emptyFrameTimer !== undefined) {
|
||||
clearTimeout(emptyFrameTimer);
|
||||
emptyFrameTimer = undefined;
|
||||
}
|
||||
publish({ tree: nextTree, css: nextCss, loading: false, error: false, settled });
|
||||
} catch { dispose(true); }
|
||||
}));
|
||||
cleanup.push(bridge.onPluginViewClosed((event) => { if (event.instanceId === id) dispose(true); }));
|
||||
@@ -69,6 +105,9 @@ export class PluginViewSessions {
|
||||
dispose,
|
||||
};
|
||||
}
|
||||
peek(key: string) {
|
||||
return this.sessions.get(key) ?? null;
|
||||
}
|
||||
acquire(key: string, bridge: Bridge, request: Omit<import('@netcatty/plugin-contract').HostDrawnViewOpenRequest, 'instanceId'>) {
|
||||
let session = this.sessions.get(key);
|
||||
if (!session) {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
type CloseablePluginViewSessions = {
|
||||
closeView(viewId: string): void;
|
||||
};
|
||||
@@ -16,3 +18,7 @@ export function registerLoadedPluginViewSessions(sessions: CloseablePluginViewSe
|
||||
export function closePluginViewSessionIfLoaded(viewId: string): void {
|
||||
loadedSessions?.closeView(viewId);
|
||||
}
|
||||
|
||||
export function prewarmHostDrawnPluginView(viewId: string): void {
|
||||
void netcattyBridge.get()?.prewarmHostDrawnPluginView?.(viewId)?.catch?.(() => {});
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
@@ -1,207 +0,0 @@
|
||||
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 };
|
||||
}
|
||||
@@ -109,7 +109,8 @@ export interface UseAIChatStreamingReturn {
|
||||
export interface SendToCattyContext {
|
||||
activeProvider: ProviderConfig | undefined;
|
||||
activeModelId: string;
|
||||
scopeType: 'terminal' | 'workspace';
|
||||
reasoningEffort?: string;
|
||||
scopeType: 'terminal' | 'workspace' | 'global';
|
||||
scopeTargetId?: string;
|
||||
scopeLabel?: string;
|
||||
globalPermissionMode: AIPermissionMode;
|
||||
@@ -125,6 +126,7 @@ export interface SendToCattyContext {
|
||||
selectedUserSkillSlugs?: string[];
|
||||
permissionMode?: AIPermissionMode;
|
||||
forceCompaction?: boolean;
|
||||
pluginContext?: import('../../infrastructure/ai/pluginAiSidebarTypes').PluginAISidebarTurnContext | null;
|
||||
}
|
||||
|
||||
export interface SendToExternalContext {
|
||||
|
||||
@@ -11,21 +11,33 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
}) {
|
||||
const contextKey = JSON.stringify(context);
|
||||
const key = JSON.stringify([viewId, version, slot, contextKey]);
|
||||
const scopeId = typeof window !== 'undefined'
|
||||
? resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` })
|
||||
: '';
|
||||
const sessionKey = scopeId ? JSON.stringify([scopeId, key]) : '';
|
||||
const cachedSession = active && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
|
||||
const [state, setState] = useState<{
|
||||
key: string;
|
||||
snapshot: PluginViewSnapshot;
|
||||
image?: (path: string) => Promise<string>;
|
||||
}>({ key: '', snapshot: initial() });
|
||||
}>(() => (
|
||||
cachedSession
|
||||
? { key, snapshot: cachedSession.getSnapshot(), image: cachedSession.image }
|
||||
: { key: '', snapshot: initial() }
|
||||
));
|
||||
const [hidden, setHidden] = useState(false);
|
||||
const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable;
|
||||
const sessionRef = useRef<{ key: string; image(path: string): Promise<string>; send(event: HostDrawnViewEvent): void } | null>(null);
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
if (!active) {
|
||||
setHidden(false);
|
||||
return;
|
||||
}
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge) { unavailableRef.current(); return; }
|
||||
const scopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
|
||||
const resolvedScopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
|
||||
try {
|
||||
const session = pluginViewSessions.acquire(JSON.stringify([scopeId, key]), bridge, { viewId, scopeId, context: JSON.parse(contextKey) });
|
||||
const session = pluginViewSessions.acquire(JSON.stringify([resolvedScopeId, key]), bridge, { viewId, scopeId: resolvedScopeId, context: JSON.parse(contextKey) });
|
||||
sessionRef.current = { key, send: session.send, image: session.image };
|
||||
const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot, image: session.image }); if (snapshot.error) unavailableRef.current(); };
|
||||
const stop = session.subscribe(update); update(); setHidden(false);
|
||||
@@ -37,11 +49,19 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
const session = sessionRef.current;
|
||||
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
|
||||
}, [active, key]);
|
||||
const loadImage = active && state.key === key && state.image ? state.image : fallbackLoadImage;
|
||||
const hasCurrentState = active && state.key === key && cachedSession !== null && state.image === cachedSession.image;
|
||||
const resolvedSnapshot = hasCurrentState
|
||||
? state.snapshot
|
||||
: cachedSession
|
||||
? cachedSession.getSnapshot()
|
||||
: initial();
|
||||
const loadImage = hasCurrentState && state.image
|
||||
? state.image
|
||||
: (cachedSession?.image ?? fallbackLoadImage);
|
||||
const sendEvent = useCallback((event: HostDrawnViewEvent) => {
|
||||
const session = sessionRef.current; if (active && session?.key === key) session.send(event);
|
||||
}, [active, key]);
|
||||
// A newly selected plugin must never receive values from the previous tree,
|
||||
// even during the render before effect cleanup and the next activation.
|
||||
return { ...(state.key === key ? state.snapshot : initial()), visible: active && !hidden, loadImage, sendEvent };
|
||||
return { ...resolvedSnapshot, visible: active && !hidden, loadImage, sendEvent };
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import type {
|
||||
PluginAISidebarContextSnapshot,
|
||||
PluginAISidebarToolSpec,
|
||||
PluginAISidebarTurnContext,
|
||||
} from '../../infrastructure/ai/pluginAiSidebarTypes';
|
||||
|
||||
const WIDTH_STORAGE_KEY = 'netcatty:plugin-ai-sidebar-width';
|
||||
export const DEFAULT_PLUGIN_AI_SIDEBAR_WIDTH = 400;
|
||||
export const MIN_PLUGIN_AI_SIDEBAR_WIDTH = 320;
|
||||
export const MAX_PLUGIN_AI_SIDEBAR_WIDTH = 680;
|
||||
|
||||
export function readPluginAiSidebarWidth(): number {
|
||||
const parsed = localStorageAdapter.readNumber(WIDTH_STORAGE_KEY);
|
||||
if (
|
||||
typeof parsed === 'number'
|
||||
&& Number.isFinite(parsed)
|
||||
&& parsed >= MIN_PLUGIN_AI_SIDEBAR_WIDTH
|
||||
&& parsed <= MAX_PLUGIN_AI_SIDEBAR_WIDTH
|
||||
) {
|
||||
return Math.round(parsed);
|
||||
}
|
||||
return DEFAULT_PLUGIN_AI_SIDEBAR_WIDTH;
|
||||
}
|
||||
|
||||
export function writePluginAiSidebarWidth(width: number): void {
|
||||
const clamped = Math.max(
|
||||
MIN_PLUGIN_AI_SIDEBAR_WIDTH,
|
||||
Math.min(MAX_PLUGIN_AI_SIDEBAR_WIDTH, Math.round(width)),
|
||||
);
|
||||
localStorageAdapter.writeNumber(WIDTH_STORAGE_KEY, clamped);
|
||||
}
|
||||
|
||||
const EMPTY_STATE: NetcattyPluginAiSidebarState = Object.freeze({
|
||||
contexts: Object.freeze([]),
|
||||
tools: Object.freeze([]),
|
||||
});
|
||||
|
||||
export interface PendingPluginSidebarPrompt {
|
||||
readonly id: number;
|
||||
readonly prompt: string;
|
||||
readonly autoSend?: boolean;
|
||||
}
|
||||
|
||||
let nextPromptSeq = 1;
|
||||
|
||||
export function usePluginAiSidebarForView(options: {
|
||||
pluginId: string;
|
||||
pluginName: string;
|
||||
viewId: string;
|
||||
enabled?: boolean;
|
||||
onCommand?: (command: NetcattyPluginAiSidebarCommand) => void;
|
||||
}) {
|
||||
const { pluginId, pluginName, viewId, enabled = true, onCommand } = options;
|
||||
const [state, setState] = useState<NetcattyPluginAiSidebarState>(EMPTY_STATE);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
setState(EMPTY_STATE);
|
||||
return;
|
||||
}
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.getPluginAiSidebarState && !bridge?.onPluginAiSidebarStateChanged) {
|
||||
setState(EMPTY_STATE);
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
let receivedPush = false;
|
||||
const unsubscribeState = bridge.onPluginAiSidebarStateChanged?.((next) => {
|
||||
if (!active) return;
|
||||
receivedPush = true;
|
||||
setState(next ?? EMPTY_STATE);
|
||||
});
|
||||
void bridge.getPluginAiSidebarState?.().then((next) => {
|
||||
if (!active || receivedPush) return;
|
||||
setState(next ?? EMPTY_STATE);
|
||||
}).catch(() => {
|
||||
if (!active || receivedPush) return;
|
||||
setState(EMPTY_STATE);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
unsubscribeState?.();
|
||||
};
|
||||
}, [enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !onCommand) return;
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.onPluginAiSidebarCommand) return;
|
||||
return bridge.onPluginAiSidebarCommand((command) => {
|
||||
if (!command || command.pluginId !== pluginId) return;
|
||||
if (command.viewId && command.viewId !== viewId) return;
|
||||
onCommand(command);
|
||||
});
|
||||
}, [enabled, onCommand, pluginId, viewId]);
|
||||
|
||||
const contextSnapshot: PluginAISidebarContextSnapshot | null = useMemo(() => {
|
||||
const match = state.contexts.find(
|
||||
(entry) => entry.pluginId === pluginId && entry.viewId === viewId,
|
||||
);
|
||||
return match ?? null;
|
||||
}, [pluginId, state.contexts, viewId]);
|
||||
|
||||
const tools: readonly PluginAISidebarToolSpec[] = useMemo(() => (
|
||||
state.tools.filter(
|
||||
(tool) => tool.pluginId === pluginId && (!tool.viewId || tool.viewId === viewId),
|
||||
)
|
||||
), [pluginId, state.tools, viewId]);
|
||||
|
||||
const turnContext: PluginAISidebarTurnContext | null = useMemo(() => {
|
||||
if (!contextSnapshot && tools.length === 0) return null;
|
||||
return {
|
||||
pluginId,
|
||||
pluginName: contextSnapshot?.pluginName || pluginName,
|
||||
viewId,
|
||||
...(contextSnapshot?.title ? { title: contextSnapshot.title } : {}),
|
||||
...(contextSnapshot?.subtitle ? { subtitle: contextSnapshot.subtitle } : {}),
|
||||
...(contextSnapshot?.summary ? { summary: contextSnapshot.summary } : {}),
|
||||
tools,
|
||||
};
|
||||
}, [contextSnapshot, pluginId, pluginName, tools, viewId]);
|
||||
|
||||
const suggestedPrompts = contextSnapshot?.suggestedPrompts;
|
||||
|
||||
const createPendingPrompt = useCallback(
|
||||
(prompt: string, autoSend?: boolean): PendingPluginSidebarPrompt => ({
|
||||
id: nextPromptSeq++,
|
||||
prompt,
|
||||
autoSend,
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
contextSnapshot,
|
||||
tools,
|
||||
turnContext,
|
||||
suggestedPrompts,
|
||||
createPendingPrompt,
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import { getAppHandlers } from '../app/appHandlersBridge';
|
||||
import { getAppAppLockRuntime, getAppVaultRuntime, getAppSettingsRuntime } from './appRuntimeBridge';
|
||||
import { PluginHostActionResources } from './pluginHostActionResources';
|
||||
import { executePluginHostAction, type PluginHostAction } from './pluginHostActionExecution';
|
||||
import { handlePluginVaultDataRequest } from './pluginVaultDataHandlers';
|
||||
import { requestOpenDualPaneSftp } from './sftp/sftpDualPaneOpenStore';
|
||||
import { pluginHostRunsSavedScripts, type PluginHostDraftFields } from '../../domain/pluginHostActions';
|
||||
import type { Host, GroupConfig, ManagedSource, Snippet } from '../../domain/models';
|
||||
|
||||
@@ -120,6 +122,27 @@ export function usePluginHostActions() {
|
||||
});
|
||||
return;
|
||||
}
|
||||
const openHostSession = (host: Host) => {
|
||||
const mode = request.kind === 'vault.requestConnect' ? (request.mode ?? 'terminal') : 'terminal';
|
||||
if (mode === 'sftp') {
|
||||
requestOpenDualPaneSftp(host.id);
|
||||
return;
|
||||
}
|
||||
const connect = getAppHandlers()?.handleConnectToHost;
|
||||
if (typeof connect !== 'function') throw new Error('Host connection flow unavailable');
|
||||
return connect(host);
|
||||
};
|
||||
if (request.kind === 'vault.requestConnect' && entry.prompt.durableHostId && entry.host) {
|
||||
assertCurrent(entry);
|
||||
const receipt = await bridge.respondPluginInteraction!({ requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action: 'commit' });
|
||||
if (!receipt || typeof receipt !== 'object' || !receipt.completionToken) throw new Error('Host action was revoked');
|
||||
entry.completionToken = receipt.completionToken;
|
||||
entry.claimed = true;
|
||||
assertCurrent(entry);
|
||||
await openHostSession(entry.host);
|
||||
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
|
||||
return;
|
||||
}
|
||||
let action: PluginHostAction;
|
||||
if (request.kind === 'vault.requestConnect' && target) action = { kind: 'connect', target };
|
||||
else if (request.kind === 'vault.requestHostDraft' && entry.prompt.reviewedDraft) {
|
||||
@@ -136,11 +159,7 @@ export function usePluginHostActions() {
|
||||
entry.claimed = true;
|
||||
assertCurrent(entry);
|
||||
},
|
||||
connect: (host) => {
|
||||
const connect = getAppHandlers()?.handleConnectToHost;
|
||||
if (typeof connect !== 'function') throw new Error('Host connection flow unavailable');
|
||||
return connect(host);
|
||||
},
|
||||
connect: openHostSession,
|
||||
});
|
||||
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
|
||||
} catch { await fail(entry); }
|
||||
@@ -191,7 +210,12 @@ export function usePluginHostActions() {
|
||||
}
|
||||
const vault = getVault();
|
||||
const candidates = [...vault.hosts];
|
||||
const host = prompt.vaultTarget ? resources.current.resolve(prompt.vaultTarget.resourceId, prompt.vaultTarget.revision) : undefined;
|
||||
const host = prompt.durableHostId
|
||||
? vault.hosts.find((candidate) => candidate.id === prompt.durableHostId)
|
||||
: prompt.vaultTarget
|
||||
? resources.current.resolve(prompt.vaultTarget.resourceId, prompt.vaultTarget.revision)
|
||||
: undefined;
|
||||
if (prompt.durableHostId && !host) throw new Error('Saved SSH host no longer exists');
|
||||
const entry: Review = {
|
||||
prompt, candidates, candidateRevisions: new Map(candidates.map((candidate) => [candidate.id, resources.current.metadata(candidate.id).revision])),
|
||||
customGroups: vault.customGroups, host, groups: vault.groupConfigs, snippets: vault.snippets,
|
||||
@@ -220,6 +244,39 @@ export function usePluginHostActions() {
|
||||
};
|
||||
}, [execute, fail, getVault]);
|
||||
|
||||
useEffect(() => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.onPluginVaultDataRequest || !bridge.respondPluginVaultData || !bridge.setPluginVaultDataReady) return;
|
||||
const unsubscribe = bridge.onPluginVaultDataRequest((request) => {
|
||||
void (async () => {
|
||||
try {
|
||||
const data = await handlePluginVaultDataRequest(request.kind, request.payload ?? {}, {
|
||||
getVault,
|
||||
resources: resources.current,
|
||||
});
|
||||
await bridge.respondPluginVaultData!({
|
||||
requestId: request.requestId,
|
||||
actionToken: request.actionToken,
|
||||
ok: true,
|
||||
data,
|
||||
});
|
||||
} catch (err) {
|
||||
await bridge.respondPluginVaultData!({
|
||||
requestId: request.requestId,
|
||||
actionToken: request.actionToken,
|
||||
ok: false,
|
||||
error: err instanceof Error ? err.message : 'Vault data request failed',
|
||||
}).catch(() => {});
|
||||
}
|
||||
})();
|
||||
});
|
||||
void bridge.setPluginVaultDataReady(true).catch(() => {});
|
||||
return () => {
|
||||
unsubscribe();
|
||||
void bridge.setPluginVaultDataReady?.(false).catch(() => {});
|
||||
};
|
||||
}, [getVault]);
|
||||
|
||||
const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields, rememberOverride?: boolean) => {
|
||||
const entry = current.current;
|
||||
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
const EMPTY_BADGES: ReadonlyMap<string, NetcattyPluginViewBadge> = new Map();
|
||||
|
||||
function buildBadgeMap(
|
||||
badges: ReadonlyArray<NetcattyPluginViewBadge> | null | undefined,
|
||||
): ReadonlyMap<string, NetcattyPluginViewBadge> {
|
||||
if (!Array.isArray(badges) || badges.length === 0) return EMPTY_BADGES;
|
||||
const map = new Map<string, NetcattyPluginViewBadge>();
|
||||
for (const badge of badges) {
|
||||
if (badge && typeof badge.viewId === 'string' && badge.viewId.length > 0) {
|
||||
map.set(badge.viewId, badge);
|
||||
}
|
||||
}
|
||||
return map.size > 0 ? map : EMPTY_BADGES;
|
||||
}
|
||||
|
||||
export function usePluginViewBadges(enabled = true): ReadonlyMap<string, NetcattyPluginViewBadge> {
|
||||
const [badgesByViewId, setBadgesByViewId] = useState<ReadonlyMap<string, NetcattyPluginViewBadge>>(EMPTY_BADGES);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
setBadgesByViewId(EMPTY_BADGES);
|
||||
return;
|
||||
}
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.listPluginViewBadges && !bridge?.onPluginViewBadgesChanged) {
|
||||
setBadgesByViewId(EMPTY_BADGES);
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
let receivedPush = false;
|
||||
const unsubscribe = bridge.onPluginViewBadgesChanged?.((badges) => {
|
||||
if (!active) return;
|
||||
receivedPush = true;
|
||||
setBadgesByViewId(buildBadgeMap(badges));
|
||||
});
|
||||
void bridge.listPluginViewBadges?.().then((badges) => {
|
||||
if (!active || receivedPush) return;
|
||||
setBadgesByViewId(buildBadgeMap(badges));
|
||||
}).catch(() => {
|
||||
if (!active || receivedPush) return;
|
||||
setBadgesByViewId(EMPTY_BADGES);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
unsubscribe?.();
|
||||
};
|
||||
}, [enabled]);
|
||||
|
||||
return badgesByViewId;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
const DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.main' as const;
|
||||
const MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.main' as const;
|
||||
|
||||
test('useVaultNavConfig persists order & visibility, survives cold-start loading, prunes uninstalled plugins, and resets cleanly', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'localStorage', 'StorageEvent', 'CustomEvent', 'Event']) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window],
|
||||
});
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: true,
|
||||
});
|
||||
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { useVaultNavConfig } = await import('./useVaultNavConfig');
|
||||
const { STORAGE_KEY_VAULT_NAV_CONFIG } = await import('../../infrastructure/config/storageKeys');
|
||||
|
||||
let model!: ReturnType<typeof useVaultNavConfig>;
|
||||
let activePluginIds: (typeof DB_PLUGIN | typeof MONITOR_PLUGIN)[] = [DB_PLUGIN, MONITOR_PLUGIN];
|
||||
let pluginsLoading = false;
|
||||
|
||||
function Fixture() {
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading });
|
||||
return <div />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const render = async () => {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
await render();
|
||||
assert.equal(model.isCustomized, false);
|
||||
assert.ok(model.visibleIds.includes(DB_PLUGIN));
|
||||
assert.ok(model.visibleIds.includes(MONITOR_PLUGIN));
|
||||
|
||||
// Back-to-back mutations in the same act batch under StrictMode return fresh
|
||||
// synchronous configs and preserve both mutations without updater side effects.
|
||||
let afterReorder!: ReturnType<typeof model.reorder>;
|
||||
let afterHide!: ReturnType<typeof model.setVisible>;
|
||||
await act(async () => {
|
||||
afterReorder = model.reorder(MONITOR_PLUGIN, 'hosts', 'after');
|
||||
afterHide = model.setVisible('logs', false);
|
||||
});
|
||||
assert.equal(afterReorder.order[1], MONITOR_PLUGIN);
|
||||
assert.equal(afterHide.order[1], MONITOR_PLUGIN);
|
||||
assert.deepEqual(afterHide.hidden, ['logs']);
|
||||
|
||||
assert.equal(model.visibleIds[1], MONITOR_PLUGIN);
|
||||
assert.equal(model.isHidden('logs'), true);
|
||||
assert.equal(model.visibleIds.includes('logs'), false);
|
||||
assert.equal(model.isCustomized, true);
|
||||
|
||||
// Locked 'hosts' cannot be hidden.
|
||||
await act(async () => {
|
||||
model.setVisible('hosts', false);
|
||||
});
|
||||
assert.equal(model.isHidden('hosts'), false);
|
||||
|
||||
// Simulate cold start: unmount, remount with pluginsLoading = true & activePluginIds = [].
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
const coldRoot = createRoot(document.getElementById('root')!);
|
||||
activePluginIds = [];
|
||||
pluginsLoading = true;
|
||||
await act(async () => {
|
||||
coldRoot.render(<Fixture />);
|
||||
});
|
||||
// Plugin preferences stay preserved in config while loading, but don't show in visibleIds yet.
|
||||
assert.equal(model.visibleIds.includes(MONITOR_PLUGIN), false);
|
||||
assert.ok(model.config.order.includes(MONITOR_PLUGIN));
|
||||
|
||||
// Plugins finish loading, but DB_PLUGIN was uninstalled.
|
||||
activePluginIds = [MONITOR_PLUGIN];
|
||||
pluginsLoading = false;
|
||||
await act(async () => {
|
||||
coldRoot.render(<Fixture />);
|
||||
});
|
||||
assert.equal(model.visibleIds[1], MONITOR_PLUGIN, 'custom slot of remaining plugin survives cold start');
|
||||
assert.equal(model.config.order.includes(DB_PLUGIN), false, 'uninstalled plugin is pruned cleanly');
|
||||
const persisted = JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}');
|
||||
assert.equal(persisted.order.includes(DB_PLUGIN), false, 'pruned plugin is also removed from storage');
|
||||
assert.deepEqual(persisted.hidden, ['logs']);
|
||||
|
||||
// Reset restores defaults.
|
||||
await act(async () => {
|
||||
model.reset();
|
||||
});
|
||||
assert.equal(model.isCustomized, false);
|
||||
assert.equal(model.isHidden('logs'), false);
|
||||
assert.equal(model.visibleIds.at(-1), MONITOR_PLUGIN);
|
||||
|
||||
await act(async () => {
|
||||
coldRoot.unmount();
|
||||
});
|
||||
} finally {
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import {
|
||||
areVaultNavConfigsEqual,
|
||||
canHideVaultNavItem,
|
||||
getManageableVaultNavIds,
|
||||
getVisibleVaultNavIds,
|
||||
isCustomVaultNavConfig,
|
||||
moveVaultNavItem,
|
||||
normalizeVaultNavConfig,
|
||||
reconcileVaultNavConfig,
|
||||
reorderVaultNavItems,
|
||||
resetVaultNavConfig,
|
||||
setVaultNavItemVisibility,
|
||||
toggleVaultNavItemVisibility,
|
||||
type PluginVaultNavId,
|
||||
type VaultNavConfig,
|
||||
type VaultNavDropPosition,
|
||||
type VaultNavItemId,
|
||||
} from '../../domain/vaultNavConfig';
|
||||
import { STORAGE_KEY_VAULT_NAV_CONFIG } from '../../infrastructure/config/storageKeys';
|
||||
import {
|
||||
LOCAL_STORAGE_ADAPTER_CHANGED_EVENT,
|
||||
localStorageAdapter,
|
||||
} from '../../infrastructure/persistence/localStorageAdapter';
|
||||
|
||||
export interface UseVaultNavConfigOptions {
|
||||
activePluginIds: readonly PluginVaultNavId[];
|
||||
/** Pass true while plugin contributions are still loading on cold start. */
|
||||
pluginsLoading?: boolean;
|
||||
}
|
||||
|
||||
export interface UseVaultNavConfigResult {
|
||||
config: VaultNavConfig;
|
||||
visibleIds: VaultNavItemId[];
|
||||
manageableIds: VaultNavItemId[];
|
||||
hiddenSet: ReadonlySet<VaultNavItemId>;
|
||||
isCustomized: boolean;
|
||||
isHidden: (id: VaultNavItemId) => boolean;
|
||||
canHide: (id: VaultNavItemId) => boolean;
|
||||
setVisible: (id: VaultNavItemId, visible: boolean) => VaultNavConfig;
|
||||
toggleVisible: (id: VaultNavItemId) => VaultNavConfig;
|
||||
reorder: (
|
||||
draggedId: VaultNavItemId,
|
||||
targetId: VaultNavItemId,
|
||||
position?: VaultNavDropPosition,
|
||||
) => VaultNavConfig;
|
||||
move: (
|
||||
id: VaultNavItemId,
|
||||
direction: 'up' | 'down',
|
||||
scopeIds?: readonly VaultNavItemId[],
|
||||
) => VaultNavConfig;
|
||||
reset: () => VaultNavConfig;
|
||||
}
|
||||
|
||||
function readStoredVaultNavConfig(
|
||||
activePluginIds: readonly PluginVaultNavId[],
|
||||
pruneMissingPlugins: boolean,
|
||||
): VaultNavConfig {
|
||||
try {
|
||||
const raw = localStorageAdapter.read(STORAGE_KEY_VAULT_NAV_CONFIG);
|
||||
return normalizeVaultNavConfig(raw, activePluginIds, { pruneMissingPlugins });
|
||||
} catch {
|
||||
return resetVaultNavConfig(activePluginIds);
|
||||
}
|
||||
}
|
||||
|
||||
function writeStoredVaultNavConfig(config: VaultNavConfig): void {
|
||||
try {
|
||||
localStorageAdapter.write(STORAGE_KEY_VAULT_NAV_CONFIG, config);
|
||||
} catch {
|
||||
// Best effort; in-memory state still applies for the current session.
|
||||
}
|
||||
}
|
||||
|
||||
export function useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading = false,
|
||||
}: UseVaultNavConfigOptions): UseVaultNavConfigResult {
|
||||
const pluginKey = activePluginIds.join('\0');
|
||||
const stablePluginIds = useMemo<PluginVaultNavId[]>(
|
||||
() => (pluginKey ? (pluginKey.split('\0') as PluginVaultNavId[]) : []),
|
||||
[pluginKey],
|
||||
);
|
||||
const pruneMissingPlugins = !pluginsLoading;
|
||||
|
||||
const [config, setConfig] = useState<VaultNavConfig>(() =>
|
||||
readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins),
|
||||
);
|
||||
const configRef = useRef<VaultNavConfig>(config);
|
||||
configRef.current = config;
|
||||
|
||||
// Reconcile when active plugin list changes or cold-start loading finishes.
|
||||
// Kept strictly outside React state updaters so storage writes and sync events
|
||||
// never execute re-entrantly during rendering or StrictMode double-invocations.
|
||||
useEffect(() => {
|
||||
const current = configRef.current;
|
||||
const reconciled = reconcileVaultNavConfig(current, stablePluginIds, {
|
||||
pruneMissingPlugins,
|
||||
});
|
||||
if (!areVaultNavConfigsEqual(current, reconciled)) {
|
||||
configRef.current = reconciled;
|
||||
setConfig(reconciled);
|
||||
}
|
||||
if (pruneMissingPlugins) {
|
||||
try {
|
||||
const rawStored = localStorageAdapter.read(STORAGE_KEY_VAULT_NAV_CONFIG);
|
||||
if (rawStored != null) {
|
||||
const normalizedStored = normalizeVaultNavConfig(rawStored, stablePluginIds, {
|
||||
pruneMissingPlugins: false,
|
||||
});
|
||||
if (!areVaultNavConfigsEqual(normalizedStored, reconciled)) {
|
||||
writeStoredVaultNavConfig(reconciled);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore storage read errors.
|
||||
}
|
||||
}
|
||||
}, [pruneMissingPlugins, stablePluginIds]);
|
||||
|
||||
// Cross-window and adapter sync.
|
||||
useEffect(() => {
|
||||
const sync = (event: Event) => {
|
||||
if (event instanceof StorageEvent && event.key !== STORAGE_KEY_VAULT_NAV_CONFIG) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
event instanceof CustomEvent
|
||||
&& event.detail?.key !== STORAGE_KEY_VAULT_NAV_CONFIG
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const next = readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins);
|
||||
if (!areVaultNavConfigsEqual(configRef.current, next)) {
|
||||
configRef.current = next;
|
||||
setConfig(next);
|
||||
}
|
||||
};
|
||||
window.addEventListener('storage', sync);
|
||||
window.addEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, sync);
|
||||
return () => {
|
||||
window.removeEventListener('storage', sync);
|
||||
window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, sync);
|
||||
};
|
||||
}, [pruneMissingPlugins, stablePluginIds]);
|
||||
|
||||
const commit = useCallback((next: VaultNavConfig): VaultNavConfig => {
|
||||
if (areVaultNavConfigsEqual(configRef.current, next)) {
|
||||
return configRef.current;
|
||||
}
|
||||
configRef.current = next;
|
||||
setConfig(next);
|
||||
writeStoredVaultNavConfig(next);
|
||||
return next;
|
||||
}, []);
|
||||
|
||||
const setVisible = useCallback(
|
||||
(id: VaultNavItemId, visible: boolean): VaultNavConfig =>
|
||||
commit(setVaultNavItemVisibility(configRef.current, id, visible, stablePluginIds)),
|
||||
[commit, stablePluginIds],
|
||||
);
|
||||
|
||||
const toggleVisible = useCallback(
|
||||
(id: VaultNavItemId): VaultNavConfig =>
|
||||
commit(toggleVaultNavItemVisibility(configRef.current, id, stablePluginIds)),
|
||||
[commit, stablePluginIds],
|
||||
);
|
||||
|
||||
const reorder = useCallback(
|
||||
(
|
||||
draggedId: VaultNavItemId,
|
||||
targetId: VaultNavItemId,
|
||||
position: VaultNavDropPosition = 'before',
|
||||
): VaultNavConfig =>
|
||||
commit(reorderVaultNavItems(configRef.current, draggedId, targetId, position)),
|
||||
[commit],
|
||||
);
|
||||
|
||||
const move = useCallback(
|
||||
(
|
||||
id: VaultNavItemId,
|
||||
direction: 'up' | 'down',
|
||||
scopeIds?: readonly VaultNavItemId[],
|
||||
): VaultNavConfig =>
|
||||
commit(moveVaultNavItem(configRef.current, id, direction, scopeIds)),
|
||||
[commit],
|
||||
);
|
||||
|
||||
const reset = useCallback((): VaultNavConfig => {
|
||||
const next = resetVaultNavConfig(stablePluginIds);
|
||||
configRef.current = next;
|
||||
setConfig(next);
|
||||
writeStoredVaultNavConfig(next);
|
||||
return next;
|
||||
}, [stablePluginIds]);
|
||||
|
||||
const visibleIds = useMemo(
|
||||
() => getVisibleVaultNavIds(config, stablePluginIds),
|
||||
[config, stablePluginIds],
|
||||
);
|
||||
const manageableIds = useMemo(
|
||||
() => getManageableVaultNavIds(config, stablePluginIds),
|
||||
[config, stablePluginIds],
|
||||
);
|
||||
const hiddenSet = useMemo(
|
||||
() => new Set<VaultNavItemId>(config.hidden),
|
||||
[config.hidden],
|
||||
);
|
||||
const isCustomized = useMemo(
|
||||
() => isCustomVaultNavConfig(config, stablePluginIds),
|
||||
[config, stablePluginIds],
|
||||
);
|
||||
|
||||
const isHidden = useCallback(
|
||||
(id: VaultNavItemId) => hiddenSet.has(id),
|
||||
[hiddenSet],
|
||||
);
|
||||
const canHide = useCallback(
|
||||
(id: VaultNavItemId) => canHideVaultNavItem(config, id, stablePluginIds),
|
||||
[config, stablePluginIds],
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
config,
|
||||
visibleIds,
|
||||
manageableIds,
|
||||
hiddenSet,
|
||||
isCustomized,
|
||||
isHidden,
|
||||
canHide,
|
||||
setVisible,
|
||||
toggleVisible,
|
||||
reorder,
|
||||
move,
|
||||
reset,
|
||||
}),
|
||||
[
|
||||
canHide,
|
||||
config,
|
||||
hiddenSet,
|
||||
isCustomized,
|
||||
isHidden,
|
||||
manageableIds,
|
||||
move,
|
||||
reorder,
|
||||
reset,
|
||||
setVisible,
|
||||
toggleVisible,
|
||||
visibleIds,
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -12,7 +12,6 @@ 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,
|
||||
@@ -635,18 +634,16 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
|
||||
}
|
||||
const remainingRecordingIds = new Set<string>();
|
||||
for (const log of next) {
|
||||
for (const mediaId of getConnectionLogMediaIds(log)) {
|
||||
remainingRecordingIds.add(mediaId);
|
||||
}
|
||||
if (log.recordingId) remainingRecordingIds.add(log.recordingId);
|
||||
}
|
||||
const removedRecordingIds: string[] = [];
|
||||
for (const log of prev) {
|
||||
if (!nextIds.has(log.id)) {
|
||||
for (const mediaId of getConnectionLogMediaIds(log)) {
|
||||
if (!remainingRecordingIds.has(mediaId)) {
|
||||
removedRecordingIds.push(mediaId);
|
||||
}
|
||||
}
|
||||
if (
|
||||
!nextIds.has(log.id)
|
||||
&& log.recordingId
|
||||
&& !remainingRecordingIds.has(log.recordingId)
|
||||
) {
|
||||
removedRecordingIds.push(log.recordingId);
|
||||
}
|
||||
}
|
||||
if (removedRecordingIds.length > 0) {
|
||||
@@ -1589,25 +1586,19 @@ 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 (!isInitialized || !syncConnectionLogTerminalData || hasRunRecordingStartupGcRef.current) return;
|
||||
if (!syncConnectionLogTerminalData || hasRunRecordingStartupGcRef.current) return;
|
||||
hasRunRecordingStartupGcRef.current = true;
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.remoteDesktopRecordings?.runGc) return;
|
||||
const logs = connectionLogsRef.current;
|
||||
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 referencedIds = logs
|
||||
.map((log) => log.recordingId)
|
||||
.filter((id): id is string => typeof id === "string" && id.length > 0);
|
||||
const protectedIds = logs
|
||||
.filter((log) => log.saved && typeof log.recordingId === "string" && log.recordingId.length > 0)
|
||||
.map((log) => log.recordingId as string);
|
||||
const storedMaxMb = localStorageAdapter.readNumber(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB);
|
||||
const maxMb = storedMaxMb != null && storedMaxMb >= 64 ? storedMaxMb : 1024;
|
||||
const storedRetention = localStorageAdapter.readNumber(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS);
|
||||
@@ -1620,7 +1611,7 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
|
||||
protectedIds,
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [isInitialized, syncConnectionLogTerminalData]);
|
||||
}, [syncConnectionLogTerminalData]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
registerConnectionLogsActions({
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import React, { type Dispatch, type SetStateAction } from 'react';
|
||||
import { History, Plus, Undo2, X } from 'lucide-react';
|
||||
import React, { useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import { History, Plus, Sparkles, Undo2, Wrench, X } from 'lucide-react';
|
||||
import type { AIPermissionMode, AISession, ChatMessage, DiscoveredAgent, ExternalAgentConfig, AgentModelPreset, ProviderConfig, UploadedFile } from '../infrastructure/ai/types';
|
||||
import type {
|
||||
PluginAISidebarPrompt,
|
||||
PluginAISidebarTurnContext,
|
||||
} from '../infrastructure/ai/pluginAiSidebarTypes';
|
||||
import type { Host, VaultNote } from '../types';
|
||||
import type { UserSkillOption } from './ai/userSkillsState';
|
||||
import type { AIQuickMessage } from '../infrastructure/ai/quickMessages';
|
||||
@@ -135,6 +139,11 @@ interface AIChatPanelContentProps {
|
||||
parked?: boolean;
|
||||
/** Disable header transitions while send preflight is in flight. */
|
||||
sending?: boolean;
|
||||
/** Contextual plugin view metadata & registered tools injected into Catty Agent. */
|
||||
pluginContext?: PluginAISidebarTurnContext | null;
|
||||
pluginSuggestedPrompts?: readonly PluginAISidebarPrompt[];
|
||||
onClosePanel?: () => void;
|
||||
borderlessChrome?: boolean;
|
||||
}
|
||||
|
||||
export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
@@ -224,7 +233,12 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
onOpenVaultSection,
|
||||
parked = false,
|
||||
sending = false,
|
||||
pluginContext = null,
|
||||
pluginSuggestedPrompts,
|
||||
onClosePanel,
|
||||
borderlessChrome = false,
|
||||
}) => {
|
||||
const [showPluginTools, setShowPluginTools] = useState(false);
|
||||
const handleContinue = React.useCallback(() => handleSend(t('ai.chat.continue')), [handleSend, t]);
|
||||
const mentionHosts = React.useMemo(
|
||||
() => terminalSessions.map((session) => ({
|
||||
@@ -269,7 +283,9 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.Header')}>
|
||||
<div className={cn(
|
||||
TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS,
|
||||
'px-2 flex items-center justify-between border-b border-border/50',
|
||||
borderlessChrome
|
||||
? 'px-2.5 flex items-center justify-between'
|
||||
: 'px-2 flex items-center justify-between border-b border-border/50',
|
||||
)}>
|
||||
<AgentSelector
|
||||
currentAgentId={currentAgentId}
|
||||
@@ -334,11 +350,79 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('ai.chat.newChat')}</TooltipContent>
|
||||
</Tooltip>
|
||||
{onClosePanel && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 rounded-md text-muted-foreground/62 hover:bg-white/[0.05] hover:text-foreground"
|
||||
aria-label={t('common.close')}
|
||||
onClick={onClosePanel}
|
||||
>
|
||||
<X size={13} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('common.close')}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</React.Profiler>
|
||||
)}
|
||||
|
||||
{/* ── Borderless Plugin Context Strip ── */}
|
||||
{!parked && pluginContext && !showHistory && (
|
||||
<div
|
||||
data-section="plugin-ai-context-strip"
|
||||
className="shrink-0 px-3 pt-2 pb-1"
|
||||
>
|
||||
<div className="rounded-xl bg-muted/30 dark:bg-white/[0.035] px-2.5 py-2">
|
||||
<div className="flex items-center justify-between gap-2 min-w-0">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<Sparkles size={12} className="shrink-0 text-primary/80" />
|
||||
<span className="truncate text-[12px] font-medium text-foreground/90">
|
||||
{pluginContext.title || pluginContext.pluginName}
|
||||
</span>
|
||||
</div>
|
||||
{pluginContext.tools.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPluginTools((prev) => !prev)}
|
||||
className={cn(
|
||||
'inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-[10.5px] font-medium transition-colors cursor-pointer',
|
||||
showPluginTools
|
||||
? 'bg-primary/15 text-primary'
|
||||
: 'bg-background/60 text-muted-foreground hover:bg-background hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<Wrench size={10} />
|
||||
<span>{pluginContext.tools.length} tools</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{pluginContext.subtitle && (
|
||||
<p className="mt-0.5 truncate text-[11px] text-muted-foreground/75">
|
||||
{pluginContext.subtitle}
|
||||
</p>
|
||||
)}
|
||||
{showPluginTools && pluginContext.tools.length > 0 && (
|
||||
<div className="mt-2 flex flex-wrap gap-1 pt-1.5 border-t border-border/20">
|
||||
{pluginContext.tools.map((tool) => (
|
||||
<span
|
||||
key={tool.qualifiedName}
|
||||
title={tool.description}
|
||||
className="inline-flex items-center gap-1 rounded-md bg-background/65 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground"
|
||||
>
|
||||
<span>{tool.name}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Main content ── */}
|
||||
{!parked && showHistory && !hideHistory ? (
|
||||
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.History')}>
|
||||
@@ -376,6 +460,28 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
</React.Profiler>
|
||||
)}
|
||||
|
||||
{/* Borderless Plugin Starter Prompt Chips (when chat is empty) */}
|
||||
{!parked && messages.length === 0 && pluginSuggestedPrompts && pluginSuggestedPrompts.length > 0 && (
|
||||
<div
|
||||
data-section="plugin-ai-suggested-prompts"
|
||||
className="shrink-0 px-3 pb-2"
|
||||
>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{pluginSuggestedPrompts.map((item, idx) => (
|
||||
<button
|
||||
key={`${item.label}-${idx}`}
|
||||
type="button"
|
||||
disabled={sending || isStreaming || !canSendCurrentAgent}
|
||||
onClick={() => handleSend(item.prompt)}
|
||||
className="rounded-lg bg-muted/35 dark:bg-white/[0.045] hover:bg-muted/65 dark:hover:bg-white/[0.09] px-2.5 py-1.5 text-left text-[11.5px] leading-snug text-foreground/80 hover:text-foreground transition-colors cursor-pointer disabled:pointer-events-none disabled:opacity-45"
|
||||
>
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Recent sessions (Zed-style, shown when no messages) */}
|
||||
{!parked && messages.length === 0 && historySessions.length > 0 && !hideRecent && (
|
||||
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.Recent')}>
|
||||
|
||||
@@ -346,6 +346,12 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
onOpenVaultHost,
|
||||
onOpenVaultSnippet,
|
||||
onOpenVaultSection,
|
||||
pluginContext = null,
|
||||
pluginSuggestedPrompts,
|
||||
pendingPluginPrompt = null,
|
||||
onPendingPluginPromptConsumed,
|
||||
onClosePanel,
|
||||
borderlessChrome = false,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const scopeKey = `${scopeType}:${scopeTargetId ?? ''}`;
|
||||
@@ -622,7 +628,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
const liveTargets = new Set(liveScopeTargetIds ?? workspaceMemberTerminalIds ?? []);
|
||||
for (const workspace of workspaces) liveTargets.add(workspace.id);
|
||||
liveTargets.add(scopeTargetId);
|
||||
if (canRebindChat(session, liveTargets)) {
|
||||
if (canRebindChat(session, liveTargets) && (scopeType === 'terminal' || scopeType === 'workspace')) {
|
||||
// Same race as the manager rebind: stop any in-flight turn first so the
|
||||
// scope rewrite never happens under a live stream.
|
||||
await stopActiveTurnBeforeScopeRebind(target.sessionId, {
|
||||
@@ -1687,7 +1693,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
}, [updateSessionTitle]);
|
||||
|
||||
const buildExecutorContextForScope = useCallback((scope: {
|
||||
type: 'terminal' | 'workspace';
|
||||
type: 'terminal' | 'workspace' | 'global';
|
||||
targetId?: string;
|
||||
label?: string;
|
||||
}): ExecutorContext => {
|
||||
@@ -2002,6 +2008,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
autoTitleSession,
|
||||
selectedUserSkillSlugs: selectedSkillSlugs,
|
||||
titleText,
|
||||
pluginContext,
|
||||
}, modelAttachments.length > 0 ? modelAttachments : undefined);
|
||||
}
|
||||
} finally {
|
||||
@@ -2024,6 +2031,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
clearScopeDraft, showScopeSessionView, setActiveSessionId,
|
||||
flushDraftText, currentAgentConfig, buildExternalAgentRuntimeModelTarget,
|
||||
loadSdkRuntimeModelCatalog, applySdkRuntimeModelCatalog, collectCustomModelIds,
|
||||
pluginContext,
|
||||
]);
|
||||
|
||||
const handleCompact = useCallback(async () => {
|
||||
@@ -2074,6 +2082,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
autoTitleSession: () => {},
|
||||
selectedUserSkillSlugs: [],
|
||||
forceCompaction: true,
|
||||
pluginContext,
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
@@ -2096,6 +2105,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
selectedCattyThinking,
|
||||
globalPermissionMode,
|
||||
isStreaming,
|
||||
pluginContext,
|
||||
scopeKey,
|
||||
scopeLabel,
|
||||
scopeTargetId,
|
||||
@@ -2318,7 +2328,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
&& session.scope.type === scopeType
|
||||
&& session.scope.targetId === scopeTargetId,
|
||||
);
|
||||
if (isAlreadyInScope || !scopeTargetId || !rebindSessionScope) {
|
||||
if (isAlreadyInScope || !scopeTargetId || !rebindSessionScope || scopeType === 'global') {
|
||||
handleSelectSession(sessionId);
|
||||
return;
|
||||
}
|
||||
@@ -2435,24 +2445,28 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
}, [exportSessionsBackup, t]);
|
||||
|
||||
const globalManagerNode = useMemo(() => (
|
||||
<GlobalAIChatSessionManager
|
||||
sessions={sessions}
|
||||
activeSessionIdMap={activeSessionIdMap}
|
||||
currentScopeType={scopeType}
|
||||
currentScopeTargetId={scopeTargetId}
|
||||
currentScopeHostIds={scopeHostIds}
|
||||
workspaces={workspaces}
|
||||
terminalInfos={managerTerminalInfos}
|
||||
hosts={hosts}
|
||||
externalAgents={externalAgents}
|
||||
rebindTargets={managerRebindTargets}
|
||||
onSelect={(sessionId) => { void handleManagerActivate(sessionId); }}
|
||||
onFocusScope={onFocusAIScopeTarget ? handleManagerFocusScope : undefined}
|
||||
onRebind={handleManagerRebind}
|
||||
onRename={handleRenameSession}
|
||||
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
|
||||
onExport={handleManagerExport}
|
||||
/>
|
||||
scopeType === 'global'
|
||||
? undefined
|
||||
: (
|
||||
<GlobalAIChatSessionManager
|
||||
sessions={sessions}
|
||||
activeSessionIdMap={activeSessionIdMap}
|
||||
currentScopeType={scopeType}
|
||||
currentScopeTargetId={scopeTargetId}
|
||||
currentScopeHostIds={scopeHostIds}
|
||||
workspaces={workspaces}
|
||||
terminalInfos={managerTerminalInfos}
|
||||
hosts={hosts}
|
||||
externalAgents={externalAgents}
|
||||
rebindTargets={managerRebindTargets}
|
||||
onSelect={(sessionId) => { void handleManagerActivate(sessionId); }}
|
||||
onFocusScope={onFocusAIScopeTarget ? handleManagerFocusScope : undefined}
|
||||
onRebind={handleManagerRebind}
|
||||
onRename={handleRenameSession}
|
||||
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
|
||||
onExport={handleManagerExport}
|
||||
/>
|
||||
)
|
||||
), [
|
||||
sessions,
|
||||
activeSessionIdMap,
|
||||
@@ -2486,6 +2500,22 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
setShowHistory(false);
|
||||
}, [ensureScopeDraft, showScopeDraftView, updateScopeDraft]);
|
||||
|
||||
const consumedPluginPromptIdRef = useRef<number | null>(null);
|
||||
useEffect(() => {
|
||||
if (!pendingPluginPrompt) return;
|
||||
if (consumedPluginPromptIdRef.current === pendingPluginPrompt.id) return;
|
||||
consumedPluginPromptIdRef.current = pendingPluginPrompt.id;
|
||||
onPendingPluginPromptConsumed?.(pendingPluginPrompt.id);
|
||||
const trimmedPrompt = pendingPluginPrompt.prompt.trim();
|
||||
if (!trimmedPrompt) return;
|
||||
setShowHistory(false);
|
||||
if (pendingPluginPrompt.autoSend && !isStreaming) {
|
||||
void handleSend(trimmedPrompt);
|
||||
} else {
|
||||
setInputValue(trimmedPrompt);
|
||||
}
|
||||
}, [handleSend, isStreaming, onPendingPluginPromptConsumed, pendingPluginPrompt, setInputValue]);
|
||||
|
||||
// Hidden retained panels keep the composer mounted (parent is `hidden` +
|
||||
// inert) so reopen does not remount ChatInput. Skip the message list.
|
||||
return (
|
||||
@@ -2609,6 +2639,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
onOpenVaultHost={onOpenVaultHost}
|
||||
onOpenVaultSnippet={onOpenVaultSnippet}
|
||||
onOpenVaultSection={onOpenVaultSection}
|
||||
pluginContext={pluginContext}
|
||||
pluginSuggestedPrompts={pluginSuggestedPrompts}
|
||||
onClosePanel={onClosePanel}
|
||||
borderlessChrome={borderlessChrome}
|
||||
/>
|
||||
</div>
|
||||
</React.Profiler>
|
||||
@@ -2698,6 +2732,12 @@ export function aiChatSidePanelPropsAreEqual(
|
||||
if (prev.onOpenVaultSnippet !== next.onOpenVaultSnippet) return false;
|
||||
if (prev.onOpenVaultSection !== next.onOpenVaultSection) return false;
|
||||
if (prev.onFocusAIScopeTarget !== next.onFocusAIScopeTarget) return false;
|
||||
if (prev.pluginContext !== next.pluginContext) return false;
|
||||
if (prev.pluginSuggestedPrompts !== next.pluginSuggestedPrompts) return false;
|
||||
if (prev.pendingPluginPrompt !== next.pendingPluginPrompt) return false;
|
||||
if (prev.onPendingPluginPromptConsumed !== next.onPendingPluginPromptConsumed) return false;
|
||||
if (prev.onClosePanel !== next.onClosePanel) return false;
|
||||
if (prev.borderlessChrome !== next.borderlessChrome) return false;
|
||||
|
||||
const scopeKey = `${prev.scopeType}:${prev.scopeTargetId ?? ''}`;
|
||||
if (
|
||||
|
||||
@@ -104,7 +104,7 @@ export interface AIChatSidePanelProps {
|
||||
quickMessages?: AIQuickMessage[];
|
||||
|
||||
// Context
|
||||
scopeType: 'terminal' | 'workspace';
|
||||
scopeType: 'terminal' | 'workspace' | 'global';
|
||||
scopeTargetId?: string;
|
||||
scopeHostIds?: string[];
|
||||
scopeLabel?: string;
|
||||
@@ -143,7 +143,7 @@ export interface AIChatSidePanelProps {
|
||||
connected: boolean;
|
||||
}>;
|
||||
resolveExecutorContext?: (scope: {
|
||||
type: 'terminal' | 'workspace';
|
||||
type: 'terminal' | 'workspace' | 'global';
|
||||
targetId?: string;
|
||||
label?: string;
|
||||
}) => ExecutorContext;
|
||||
@@ -151,6 +151,14 @@ export interface AIChatSidePanelProps {
|
||||
// Visibility
|
||||
isVisible?: boolean;
|
||||
|
||||
// Plugin contextual sidebar integration (native Catty Agent + plugin tools)
|
||||
pluginContext?: import('../infrastructure/ai/pluginAiSidebarTypes').PluginAISidebarTurnContext | null;
|
||||
pluginSuggestedPrompts?: readonly import('../infrastructure/ai/pluginAiSidebarTypes').PluginAISidebarPrompt[];
|
||||
pendingPluginPrompt?: { id: number; prompt: string; autoSend?: boolean } | null;
|
||||
onPendingPluginPromptConsumed?: (id: number) => void;
|
||||
onClosePanel?: () => void;
|
||||
borderlessChrome?: boolean;
|
||||
|
||||
// Vault artifact navigation (from AI chat tool results)
|
||||
notes?: VaultNote[];
|
||||
hosts?: Host[];
|
||||
|
||||
@@ -81,64 +81,4 @@ 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,7 +2,6 @@ import {
|
||||
Bookmark,
|
||||
ChevronDown,
|
||||
CircleUserRound,
|
||||
Monitor,
|
||||
Server,
|
||||
Terminal,
|
||||
Trash2,
|
||||
@@ -12,8 +11,7 @@ import {
|
||||
import React, { memo, useCallback, useMemo, useState } from "react";
|
||||
import { useI18n } from "../application/i18n/I18nProvider";
|
||||
import { resolveHostIconAppearance } from "../domain/hostIcon";
|
||||
import { isRdpProtocol, isRemoteDesktopProtocol, isVncProtocol } from "../domain/remoteDesktop";
|
||||
import { getConnectionLogRecordingSummary } from "../domain/remoteDesktopRecording";
|
||||
import { isRdpProtocol, isVncProtocol } from "../domain/remoteDesktop";
|
||||
import { cn } from "../lib/utils";
|
||||
import { ConnectionLog, Host } from "../types";
|
||||
import { DistroAvatar } from "./DistroAvatar";
|
||||
@@ -30,8 +28,6 @@ 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";
|
||||
@@ -114,28 +110,8 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
|
||||
iconColorCustom: log.hostIconColorCustom,
|
||||
});
|
||||
const hasPersistedHostIcon = !isLocal && !isSerial && !isRemoteDesktop && (!!log.hostDistro || !!customHostIcon);
|
||||
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);
|
||||
}
|
||||
const recordingSizeText = formatRecordingBytes(log.recordingBytes);
|
||||
const recordingDurationText = formatRecordingDuration(log.recordingDurationMs);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -209,16 +185,13 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
|
||||
<div className="text-sm font-medium truncate">
|
||||
{isLocal ? t("logs.localTerminal") : log.hostLabel}
|
||||
</div>
|
||||
{recordingSummary.primaryClip && (
|
||||
{log.recordingId && (
|
||||
<span
|
||||
data-recording-badge={recordingSummary.primaryClip.id}
|
||||
data-recording-badge={log.recordingId}
|
||||
className="inline-flex items-center gap-1 rounded-md border border-primary/25 bg-primary/10 px-1.5 py-0.5 text-[11px] font-medium tabular-nums text-primary shrink-0"
|
||||
>
|
||||
<Video size={12} />
|
||||
<span>
|
||||
{recordingSummary.clipCount > 1
|
||||
? `${t("logs.recording.clipsCount", { count: recordingSummary.clipCount })} · `
|
||||
: ""}
|
||||
{recordingDurationText}
|
||||
{recordingSizeText ? ` · ${recordingSizeText}` : ""}
|
||||
</span>
|
||||
@@ -226,7 +199,13 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground truncate">
|
||||
{subtitleParts.join(" · ")}
|
||||
{isLocal
|
||||
? "local"
|
||||
: isSerial
|
||||
? `serial, ${log.hostname}`
|
||||
: log.username
|
||||
? `${log.protocol}, ${log.username}`
|
||||
: `${log.protocol}, ${log.hostname}`}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -285,40 +264,13 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
|
||||
const INITIAL_RENDER_LIMIT = 30;
|
||||
const LOAD_MORE_COUNT = 30;
|
||||
|
||||
const [filter, setFilter] = useState<ConnectionLogFilter>("all");
|
||||
// Track how many items to show
|
||||
const [renderLimit, setRenderLimit] = useState(INITIAL_RENDER_LIMIT);
|
||||
|
||||
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
|
||||
// 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]);
|
||||
return [...logs].sort((a, b) => b.startTime - a.startTime);
|
||||
}, [logs]);
|
||||
|
||||
const displayedLogs = useMemo(() => {
|
||||
return filteredLogs.slice(0, renderLimit);
|
||||
@@ -326,11 +278,6 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
|
||||
|
||||
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);
|
||||
}, []);
|
||||
@@ -345,6 +292,7 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
|
||||
[onDelete],
|
||||
);
|
||||
|
||||
// Rendered items
|
||||
const renderedItems = useMemo(() => {
|
||||
return displayedLogs.map((log) => (
|
||||
<LogItem
|
||||
@@ -359,46 +307,9 @@ 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 shrink-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="w-32 shrink-0 flex items-center gap-1">
|
||||
{t("logs.table.date")}
|
||||
<ChevronDown size={12} />
|
||||
@@ -418,19 +329,13 @@ 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">
|
||||
{effectiveFilter === "recorded" ? (
|
||||
<Video size={32} className="opacity-60" />
|
||||
) : effectiveFilter === "remoteDesktop" ? (
|
||||
<Monitor size={32} className="opacity-60" />
|
||||
) : (
|
||||
<Terminal size={32} className="opacity-60" />
|
||||
)}
|
||||
<Terminal size={32} className="opacity-60" />
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold text-foreground mb-2">
|
||||
{effectiveFilter === "all" ? t("logs.empty.title") : t("logs.filter.emptyTitle")}
|
||||
{t("logs.empty.title")}
|
||||
</h3>
|
||||
<p className="text-sm text-center max-w-sm">
|
||||
{effectiveFilter === "all" ? t("logs.empty.desc") : t("logs.filter.emptyDesc")}
|
||||
{t("logs.empty.desc")}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
|
||||
@@ -1,27 +1,14 @@
|
||||
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 { I18nProvider } from "../application/i18n/I18nProvider.tsx";
|
||||
import type { GroupConfig, Identity } from "../types.ts";
|
||||
import GroupDetailsPanel, {
|
||||
hasGroupRdpFields,
|
||||
import {
|
||||
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);
|
||||
@@ -127,295 +114,4 @@ 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();
|
||||
}
|
||||
});
|
||||
+505
-661
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,36 +192,14 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
);
|
||||
|
||||
const [vncPortText, setVncPortText] = useState<string>(() =>
|
||||
form.port !== undefined
|
||||
? String(form.port)
|
||||
: groupDefaults?.vncConfig?.port !== undefined
|
||||
? ""
|
||||
: String(DEFAULT_VNC_PORT),
|
||||
String(form.port ?? DEFAULT_VNC_PORT),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (isVncPrimary) {
|
||||
setVncPortText(
|
||||
form.port !== undefined
|
||||
? String(form.port)
|
||||
: groupDefaults?.vncConfig?.port !== undefined
|
||||
? ""
|
||||
: String(DEFAULT_VNC_PORT),
|
||||
);
|
||||
setVncPortText(String(form.port ?? DEFAULT_VNC_PORT));
|
||||
}
|
||||
}, [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 } }
|
||||
: {}),
|
||||
}));
|
||||
};
|
||||
}, [form.id, form.port, isVncPrimary]);
|
||||
|
||||
const handleTabClick = (next: "ssh" | "rdp" | "vnc" | "telnet") => {
|
||||
if (onSelectProtocolTab) {
|
||||
@@ -237,7 +215,7 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
(identity: Identity) => identity.authMethod === "password" || Boolean(identity.password),
|
||||
);
|
||||
const vncDisplayLabel = isVncPrimary
|
||||
? formatVncDisplayNumber(form.port ?? groupDefaults?.vncConfig?.port ?? DEFAULT_VNC_PORT)
|
||||
? formatVncDisplayNumber(form.port ?? DEFAULT_VNC_PORT)
|
||||
: null;
|
||||
|
||||
const selectAuthMethod = (authMethod: "auto" | "password" | "key" | "certificate") => {
|
||||
@@ -404,7 +382,6 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
protocol="vnc"
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
groupDefaults={groupDefaults}
|
||||
identities={identities}
|
||||
availableKeys={availableKeys}
|
||||
onCreateIdentity={onCreateIdentity}
|
||||
@@ -417,7 +394,6 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
protocol="rdp"
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
groupDefaults={groupDefaults}
|
||||
identities={identities}
|
||||
availableKeys={availableKeys}
|
||||
onCreateIdentity={onCreateIdentity}
|
||||
@@ -440,30 +416,18 @@ 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) {
|
||||
updateStandaloneDesktopPort(parsed);
|
||||
update("port", parsed);
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
if (!vncPortText.trim() && groupDefaults?.vncConfig?.port !== undefined) {
|
||||
updateStandaloneDesktopPort(undefined);
|
||||
return;
|
||||
}
|
||||
const parsed = parseVncPortOrDisplay(vncPortText);
|
||||
const resolved = parsed ?? (groupDefaults?.vncConfig?.port !== undefined ? undefined : DEFAULT_VNC_PORT);
|
||||
setVncPortText(resolved !== undefined ? String(resolved) : "");
|
||||
updateStandaloneDesktopPort(resolved);
|
||||
const resolved = parsed ?? DEFAULT_VNC_PORT;
|
||||
setVncPortText(String(resolved));
|
||||
update("port", resolved);
|
||||
}}
|
||||
placeholder={
|
||||
groupDefaults?.vncConfig?.port
|
||||
? String(groupDefaults.vncConfig.port)
|
||||
: t("hostDetails.vnc.displayPlaceholder")
|
||||
}
|
||||
placeholder={t("hostDetails.vnc.displayPlaceholder")}
|
||||
className="h-8 flex-1 min-w-0 text-center font-mono text-sm"
|
||||
/>
|
||||
{vncDisplayLabel ? (
|
||||
@@ -477,9 +441,9 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
type="number"
|
||||
value={form.port ?? ""}
|
||||
onChange={(e) =>
|
||||
updateStandaloneDesktopPort(e.target.value ? Number(e.target.value) : undefined)
|
||||
update("port", e.target.value ? Number(e.target.value) : undefined)
|
||||
}
|
||||
placeholder={String(groupDefaults?.rdpConfig?.port ?? DEFAULT_RDP_PORT)}
|
||||
placeholder={String(DEFAULT_RDP_PORT)}
|
||||
className="h-8 w-44 text-center font-mono text-sm"
|
||||
/>
|
||||
)}
|
||||
@@ -537,8 +501,8 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
onChange={(next) => update("username", next)}
|
||||
placeholder={
|
||||
isRdpPrimary
|
||||
? (groupDefaults?.rdpConfig?.username || t("hostDetails.rdp.usernamePlaceholder"))
|
||||
: (groupDefaults?.vncConfig?.username || t("hostDetails.vnc.usernamePlaceholder"))
|
||||
? t("hostDetails.rdp.usernamePlaceholder")
|
||||
: t("hostDetails.vnc.usernamePlaceholder")
|
||||
}
|
||||
identities={passwordCompatibleIdentities}
|
||||
availableKeys={availableKeys}
|
||||
@@ -599,7 +563,7 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
|
||||
label={t("hostDetails.rdp.domainLabel")}
|
||||
>
|
||||
<Input
|
||||
placeholder={groupDefaults?.rdpConfig?.domain || t("hostDetails.rdp.domainPlaceholder")}
|
||||
placeholder={t("hostDetails.rdp.domainPlaceholder")}
|
||||
value={form.rdpConfig?.domain ?? ""}
|
||||
onChange={(e) =>
|
||||
setForm((prev: Host) => ({
|
||||
|
||||
@@ -23,8 +23,6 @@ export const resolvePrimaryProtocolSwitchPort = (
|
||||
nextProtocol: "ssh" | "telnet" | "rdp" | "vnc",
|
||||
hasGroupTelnetPortDefault: boolean,
|
||||
hasGroupSshPortDefault: boolean,
|
||||
hasGroupRdpPortDefault = false,
|
||||
hasGroupVncPortDefault = false,
|
||||
): number | undefined => {
|
||||
const isKnownDefaultPort =
|
||||
currentPort === undefined ||
|
||||
@@ -34,11 +32,9 @@ 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") {
|
||||
@@ -60,18 +56,12 @@ export const resolvePrimaryProtocolSavePort = (
|
||||
currentPort: number | undefined,
|
||||
hasGroupSshPortDefault: boolean,
|
||||
hasGroupTelnetPortDefault: boolean,
|
||||
hasGroupRdpPortDefault = false,
|
||||
hasGroupVncPortDefault = false,
|
||||
): number | undefined => {
|
||||
if (protocol === "rdp") {
|
||||
if (currentPort !== undefined) return currentPort;
|
||||
if (hasGroupRdpPortDefault) return undefined;
|
||||
return 3389;
|
||||
return currentPort ?? 3389;
|
||||
}
|
||||
if (protocol === "vnc") {
|
||||
if (currentPort !== undefined) return currentPort;
|
||||
if (hasGroupVncPortDefault) return undefined;
|
||||
return 5900;
|
||||
return currentPort ?? 5900;
|
||||
}
|
||||
if (protocol === "telnet") {
|
||||
if (currentPort !== undefined) return currentPort;
|
||||
|
||||
@@ -220,159 +220,3 @@ 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();
|
||||
}
|
||||
});
|
||||
+52
-175
@@ -82,7 +82,9 @@ import {
|
||||
} from "../domain/pluginConnection";
|
||||
import {
|
||||
applyHostDefaultConnectProtocol,
|
||||
DEFAULT_RDP_CONFIG,
|
||||
DEFAULT_RDP_PORT,
|
||||
DEFAULT_VNC_CONFIG,
|
||||
DEFAULT_VNC_PORT,
|
||||
getHostEnabledProtocols,
|
||||
hasValidRdpFixedResolution,
|
||||
@@ -197,7 +199,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
id: crypto.randomUUID(),
|
||||
label: "",
|
||||
hostname: "",
|
||||
port: groupDefaults?.rdpConfig?.port ? undefined : DEFAULT_RDP_PORT,
|
||||
port: DEFAULT_RDP_PORT,
|
||||
username: "",
|
||||
protocol: "rdp",
|
||||
tags: [],
|
||||
@@ -205,7 +207,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
authMethod: "password",
|
||||
authPolicyVersion: 1,
|
||||
distroMode: "auto",
|
||||
rdpConfig: {},
|
||||
rdpConfig: { ...DEFAULT_RDP_CONFIG },
|
||||
createdAt: Date.now(),
|
||||
group: defaultGroup || undefined,
|
||||
} as Host;
|
||||
@@ -215,7 +217,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
id: crypto.randomUUID(),
|
||||
label: "",
|
||||
hostname: "",
|
||||
port: groupDefaults?.vncConfig?.port ? undefined : DEFAULT_VNC_PORT,
|
||||
port: DEFAULT_VNC_PORT,
|
||||
username: "",
|
||||
protocol: "vnc",
|
||||
tags: [],
|
||||
@@ -223,7 +225,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
authMethod: "password",
|
||||
authPolicyVersion: 1,
|
||||
distroMode: "auto",
|
||||
vncConfig: {},
|
||||
vncConfig: { ...DEFAULT_VNC_CONFIG },
|
||||
createdAt: Date.now(),
|
||||
group: defaultGroup || undefined,
|
||||
} as Host;
|
||||
@@ -248,11 +250,11 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
},
|
||||
);
|
||||
|
||||
const hasRdpProtocol = form.protocol === "rdp" || form.rdpConfig?.enabled === true;
|
||||
const hasRdpConfig = Boolean(form.rdpConfig);
|
||||
const [resolutionDraft, setResolutionDraft] = useState<RdpResolutionDraft>({});
|
||||
useEffect(() => {
|
||||
setResolutionDraft({});
|
||||
}, [form.id, hasRdpProtocol]);
|
||||
}, [form.id, hasRdpConfig]);
|
||||
const onResolutionDraftChange = (dimension: "width" | "height", value: string) => {
|
||||
setResolutionDraft((prev) => ({ ...prev, [dimension]: value }));
|
||||
};
|
||||
@@ -454,17 +456,10 @@ 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 (!effectiveIdentityId) return undefined;
|
||||
return identities.find((i) => i.id === effectiveIdentityId);
|
||||
}, [effectiveIdentityId, identities]);
|
||||
if (!effectiveAuthHost.identityId) return undefined;
|
||||
return identities.find((i) => i.id === effectiveAuthHost.identityId);
|
||||
}, [effectiveAuthHost.identityId, identities]);
|
||||
|
||||
const effectiveAuth = useMemo(() => resolveHostAuth({
|
||||
host: effectiveAuthHost,
|
||||
@@ -663,17 +658,13 @@ 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,
|
||||
...(carriedIdentityId ? { identityId: carriedIdentityId } : {}),
|
||||
port: prev.rdpConfig?.port ?? nextPort ?? DEFAULT_RDP_PORT,
|
||||
os: isFreshHost && prev.os === "linux" ? "windows" : prev.os,
|
||||
username: isFreshHost && prev.username === "root" ? "" : (prev.username ?? ""),
|
||||
authMethod: "password",
|
||||
@@ -682,22 +673,20 @@ 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,
|
||||
...(carriedIdentityId ? { identityId: carriedIdentityId } : {}),
|
||||
port: prev.vncConfig?.port ?? nextPort ?? DEFAULT_VNC_PORT,
|
||||
username: isFreshHost && prev.username === "root" ? "" : (prev.username ?? ""),
|
||||
authMethod: "password",
|
||||
moshEnabled: false,
|
||||
@@ -705,10 +694,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,
|
||||
},
|
||||
@@ -738,14 +727,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
};
|
||||
});
|
||||
},
|
||||
[
|
||||
effectiveGroupDefaults?.port,
|
||||
effectiveGroupDefaults?.rdpConfig?.port,
|
||||
effectiveGroupDefaults?.telnetPort,
|
||||
effectiveGroupDefaults?.username,
|
||||
effectiveGroupDefaults?.vncConfig?.port,
|
||||
initialData,
|
||||
],
|
||||
[effectiveGroupDefaults?.port, effectiveGroupDefaults?.telnetPort, effectiveGroupDefaults?.username, initialData],
|
||||
);
|
||||
|
||||
const isUntouchedNewHost = !initialData
|
||||
@@ -773,44 +755,30 @@ 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,
|
||||
...(!hasExplicitVncCreds && !hasGroupVncCreds ? { useHostCredentials: true } : {}),
|
||||
port: prev.vncConfig?.port ?? DEFAULT_VNC_PORT,
|
||||
tunnelViaHostSsh: prev.vncConfig?.tunnelViaHostSsh ?? true,
|
||||
useHostCredentials: prev.vncConfig?.identityId ? false : (prev.vncConfig?.useHostCredentials ?? true),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (proto === "rdp") {
|
||||
const hasExplicitRdpCreds = Boolean(
|
||||
prev.rdpConfig?.identityId !== undefined
|
||||
|| prev.rdpConfig?.username
|
||||
|| prev.rdpConfig?.useHostCredentials !== undefined,
|
||||
);
|
||||
return {
|
||||
...prev,
|
||||
rdpConfig: {
|
||||
...DEFAULT_RDP_CONFIG,
|
||||
...(prev.rdpConfig ?? {}),
|
||||
enabled: true,
|
||||
...(!hasExplicitRdpCreds && !hasGroupRdpCreds ? { useHostCredentials: true } : {}),
|
||||
port: prev.rdpConfig?.port ?? DEFAULT_RDP_PORT,
|
||||
tunnelViaHostSsh: prev.rdpConfig?.tunnelViaHostSsh ?? true,
|
||||
useHostCredentials: prev.rdpConfig?.identityId ? false : (prev.rdpConfig?.useHostCredentials ?? true),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -825,54 +793,38 @@ 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,
|
||||
...(existingPort !== undefined ? { port: existingPort } : {}),
|
||||
...(prev.identityId
|
||||
? { useHostCredentials: false, identityId: prev.identityId }
|
||||
: !hasExplicitRdpCreds && !hasGroupRdpCreds
|
||||
? { useHostCredentials: true }
|
||||
: {}),
|
||||
port: prev.port ?? prev.rdpConfig?.port ?? DEFAULT_RDP_PORT,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: prev.identityId ? false : true,
|
||||
...(prev.identityId ? { identityId: prev.identityId } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (prev.protocol === "vnc") {
|
||||
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,
|
||||
...(existingPort !== undefined ? { port: existingPort } : {}),
|
||||
...(prev.identityId
|
||||
? { useHostCredentials: false, identityId: prev.identityId }
|
||||
: !hasExplicitVncCreds && !hasGroupVncCreds
|
||||
? { useHostCredentials: true }
|
||||
: {}),
|
||||
port: prev.port ?? prev.vncConfig?.port ?? DEFAULT_VNC_PORT,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: prev.identityId ? false : true,
|
||||
...(prev.identityId ? { identityId: prev.identityId } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -890,16 +842,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
return prev;
|
||||
});
|
||||
},
|
||||
[
|
||||
effectiveGroupDefaults?.port,
|
||||
effectiveGroupDefaults?.rdpConfig?.identityId,
|
||||
effectiveGroupDefaults?.rdpConfig?.useHostCredentials,
|
||||
effectiveGroupDefaults?.rdpConfig?.username,
|
||||
effectiveGroupDefaults?.username,
|
||||
effectiveGroupDefaults?.vncConfig?.identityId,
|
||||
effectiveGroupDefaults?.vncConfig?.useHostCredentials,
|
||||
effectiveGroupDefaults?.vncConfig?.username,
|
||||
],
|
||||
[effectiveGroupDefaults?.port, effectiveGroupDefaults?.username],
|
||||
);
|
||||
|
||||
const handleSetDefaultProtocol = useCallback((proto: EditableHostProtocol) => {
|
||||
@@ -978,7 +921,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
savingHostRef.current = true;
|
||||
try {
|
||||
if (!pluginProtocolActive && (form.protocol === "rdp" || form.rdpConfig?.enabled)
|
||||
&& !hasValidRdpFixedResolution(effectiveAuthHost.rdpConfig, resolutionDraft)) {
|
||||
&& !hasValidRdpFixedResolution(form.rdpConfig, resolutionDraft)) {
|
||||
setActiveProtocolTab("rdp");
|
||||
toast.error(t("hostDetails.rdp.dimensionHint"));
|
||||
return;
|
||||
@@ -1033,15 +976,11 @@ 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(effectiveGroupDefaults?.port),
|
||||
Boolean(effectiveGroupDefaults?.telnetPort),
|
||||
hasGroupRdpPortDefault,
|
||||
hasGroupVncPortDefault,
|
||||
Boolean(groupDefaults?.port),
|
||||
Boolean(groupDefaults?.telnetPort),
|
||||
);
|
||||
let cleaned: Host = {
|
||||
...formWithoutProxyDraft,
|
||||
@@ -1075,7 +1014,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
const sanitizedRdp = cleaned.protocol === "rdp"
|
||||
? sanitizeRdpConfig({
|
||||
...(cleaned.rdpConfig ?? {}),
|
||||
port: finalPort ?? (hasGroupRdpPortDefault ? undefined : DEFAULT_RDP_PORT),
|
||||
port: finalPort ?? DEFAULT_RDP_PORT,
|
||||
enabled: undefined,
|
||||
tunnelViaHostSsh: undefined,
|
||||
tunnelTargetHost: undefined,
|
||||
@@ -1084,7 +1023,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
const sanitizedVnc = cleaned.protocol === "vnc"
|
||||
? sanitizeVncConfig({
|
||||
...(cleaned.vncConfig ?? {}),
|
||||
port: finalPort ?? (hasGroupVncPortDefault ? undefined : DEFAULT_VNC_PORT),
|
||||
port: finalPort ?? DEFAULT_VNC_PORT,
|
||||
enabled: undefined,
|
||||
tunnelViaHostSsh: undefined,
|
||||
tunnelTargetHost: undefined,
|
||||
@@ -1096,7 +1035,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,
|
||||
port: finalPort ?? (cleaned.protocol === "rdp" ? DEFAULT_RDP_PORT : DEFAULT_VNC_PORT),
|
||||
authMethod: hasInlinePassword || cleaned.identityId ? "password" : undefined,
|
||||
authPolicyVersion: 1,
|
||||
identityFileId: undefined,
|
||||
@@ -1116,22 +1055,13 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
nextRdpConfig &&
|
||||
onCreateIdentity &&
|
||||
rdpDraft &&
|
||||
rdpDraft.password.length > 0 &&
|
||||
!nextRdpConfig.useHostCredentials &&
|
||||
!nextRdpConfig.identityId
|
||||
rdpDraft.password.length > 0
|
||||
) {
|
||||
const effectiveRdpDomain =
|
||||
nextRdpConfig.domain || effectiveGroupDefaults?.rdpConfig?.domain;
|
||||
const identity: Identity = {
|
||||
id: crypto.randomUUID(),
|
||||
label: `${finalLabel} RDP`,
|
||||
username: (
|
||||
rdpDraft.username ||
|
||||
nextRdpConfig.username ||
|
||||
effectiveGroupDefaults?.rdpConfig?.username ||
|
||||
""
|
||||
).trim(),
|
||||
...(effectiveRdpDomain ? { domain: effectiveRdpDomain } : {}),
|
||||
username: rdpDraft.username.trim(),
|
||||
...(nextRdpConfig.domain ? { domain: nextRdpConfig.domain } : {}),
|
||||
authMethod: "password",
|
||||
password: rdpDraft.password,
|
||||
created: Date.now(),
|
||||
@@ -1149,19 +1079,12 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
nextVncConfig &&
|
||||
onCreateIdentity &&
|
||||
vncDraft &&
|
||||
vncDraft.password.length > 0 &&
|
||||
!nextVncConfig.useHostCredentials &&
|
||||
!nextVncConfig.identityId
|
||||
vncDraft.password.length > 0
|
||||
) {
|
||||
const identity: Identity = {
|
||||
id: crypto.randomUUID(),
|
||||
label: `${finalLabel} VNC`,
|
||||
username: (
|
||||
vncDraft.username ||
|
||||
nextVncConfig.username ||
|
||||
effectiveGroupDefaults?.vncConfig?.username ||
|
||||
""
|
||||
).trim(),
|
||||
username: vncDraft.username.trim(),
|
||||
authMethod: "password",
|
||||
password: vncDraft.password,
|
||||
created: Date.now(),
|
||||
@@ -1419,17 +1342,9 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
password: undefined,
|
||||
identityFileId: undefined,
|
||||
identityFilePaths: undefined,
|
||||
...(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 } }
|
||||
: {}),
|
||||
...(prev.protocol === "rdp" && identity.domain
|
||||
? { rdpConfig: { ...(prev.rdpConfig ?? {}), domain: identity.domain } }
|
||||
: {}),
|
||||
}));
|
||||
setPendingReferenceKeyPath(null);
|
||||
setSelectedCredentialType(null);
|
||||
@@ -1440,46 +1355,9 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
);
|
||||
|
||||
const clearIdentity = useCallback(() => {
|
||||
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;
|
||||
});
|
||||
setForm((prev) => detachEffectiveHostIdentity(prev, effectiveAuth.username));
|
||||
setIdentitySuggestionsOpen(false);
|
||||
}, [
|
||||
effectiveAuth.username,
|
||||
effectiveAuthHost.rdpConfig?.username,
|
||||
effectiveAuthHost.vncConfig?.username,
|
||||
form.protocol,
|
||||
selectedIdentity?.domain,
|
||||
selectedIdentity?.username,
|
||||
]);
|
||||
}, [effectiveAuth.username]);
|
||||
|
||||
const updateTelnetIdentity = useCallback((identityId: string) => {
|
||||
setForm((prev) => ({
|
||||
@@ -1772,7 +1650,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
groupDefaults={effectiveGroupDefaults}
|
||||
effectiveAuthMethod={effectiveAuthMethod}
|
||||
effectiveUsername={effectiveAuth.username}
|
||||
effectiveIdentityId={effectiveIdentityId}
|
||||
effectiveIdentityId={effectiveAuthHost.identityId}
|
||||
selectedIdentity={selectedIdentity}
|
||||
clearIdentity={clearIdentity}
|
||||
identities={identities}
|
||||
@@ -1834,7 +1712,6 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
onResolutionDraftChange={onResolutionDraftChange}
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
groupDefaults={effectiveGroupDefaults}
|
||||
t={t}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -126,85 +126,10 @@ test("LogView renders clean non-terminal metadata card for unrecorded VNC/RDP se
|
||||
assert.doesNotMatch(markup, /Appearance/);
|
||||
});
|
||||
|
||||
test("LogView memo comparator checks recordingId, recordings, remoteDesktopEvents, and recordingBytes", () => {
|
||||
test("LogView memo comparator checks recordingId and recordingBytes", () => {
|
||||
const source = readFileSync(new URL("./LogView.tsx", import.meta.url), "utf8");
|
||||
const comparator = source.match(/const logViewAreEqual[\s\S]*?^};/m)?.[0] ?? "";
|
||||
assert.ok(comparator, "expected logViewAreEqual in LogView.tsx");
|
||||
assert.match(comparator, /prev\.log\.recordingId === next\.log\.recordingId/);
|
||||
assert.match(comparator, /prev\.log\.recordingBytes === next\.log\.recordingBytes/);
|
||||
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/);
|
||||
});
|
||||
+191
-668
File diff suppressed because it is too large.
Load diff
@@ -262,3 +262,90 @@ test('usePluginTerminalSidebar skips tab/focus subscriptions when zero pages exi
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('PluginTerminalSidebarLauncher renders live view badges and clears them on updates', async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { pretendToBeVisual: true, url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const install = (key: string, value: unknown) => {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'SVGElement', 'Node', 'NodeFilter', 'MutationObserver', 'CustomEvent', 'Event', 'MouseEvent']) {
|
||||
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
install('PointerEvent', dom.window.MouseEvent);
|
||||
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
|
||||
install('requestAnimationFrame', (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0));
|
||||
install('cancelAnimationFrame', (id: number) => clearTimeout(id));
|
||||
install('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { I18nProvider } = await import('../application/i18n/I18nProvider');
|
||||
const { TooltipProvider } = await import('./ui/tooltip');
|
||||
const { PluginTerminalSidebarLauncher } = await import('./plugins/PluginTerminalSidebar');
|
||||
|
||||
const viewA = { id: 'com.example.sidebar.alerts', title: 'Alerts', location: 'terminal-sidebar', visible: true };
|
||||
const snapshot = {
|
||||
locale: 'en',
|
||||
plugins: [{ id: 'com.example.sidebar', displayName: 'Synthetic Monitor', version: '1.0.0', commands: [], keybindings: [], menus: [], settings: [], views: [viewA] }],
|
||||
};
|
||||
let badges: ReadonlyArray<NetcattyPluginViewBadge> = [
|
||||
{ pluginId: 'com.example.sidebar', viewId: viewA.id, count: 5, tone: 'danger', tooltip: '5 active alerts' },
|
||||
];
|
||||
const badgeListeners = new Set<(next: ReadonlyArray<NetcattyPluginViewBadge>) => void>();
|
||||
|
||||
Object.assign(dom.window, {
|
||||
netcatty: {
|
||||
async getPluginRuntimeStatus() { return { available: true }; },
|
||||
async getPluginContributions() { return snapshot; },
|
||||
onPluginContributionsChanged() { return () => {}; },
|
||||
async listPluginViewBadges() { return badges; },
|
||||
onPluginViewBadgesChanged(cb: (next: ReadonlyArray<NetcattyPluginViewBadge>) => void) {
|
||||
badgeListeners.add(cb);
|
||||
return () => badgeListeners.delete(cb);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 40));
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<PluginTerminalSidebarLauncher sessionId="session-1" />
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
await settle();
|
||||
});
|
||||
|
||||
const btn = document.querySelector<HTMLButtonElement>('button[aria-label="Alerts — Synthetic Monitor (5 active alerts)"]')!;
|
||||
assert.ok(btn, 'terminal sidebar launcher includes badge tooltip in aria-label');
|
||||
const badgeEl = btn.querySelector<HTMLElement>('[data-plugin-view-badge]')!;
|
||||
assert.equal(badgeEl.textContent, '5');
|
||||
assert.equal(badgeEl.getAttribute('data-plugin-view-badge-tone'), 'danger');
|
||||
|
||||
// Clear badge via push event
|
||||
badges = [];
|
||||
await act(async () => {
|
||||
for (const listener of badgeListeners) listener(badges);
|
||||
await settle();
|
||||
});
|
||||
assert.equal(document.querySelector('[data-plugin-view-badge]'), null);
|
||||
assert.ok(document.querySelector('button[aria-label="Alerts — Synthetic Monitor"]'));
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await settle();
|
||||
});
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -2348,7 +2348,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
// here dismisses the panel.
|
||||
const handleToggleAiFromTopBar = useCallback(() => {
|
||||
const tabId = activeTabIdRef.current;
|
||||
if (!tabId) return;
|
||||
if (!tabId || tabId === 'vault') return;
|
||||
|
||||
const intent = resolveAiSidePanelToggleIntent(
|
||||
sidePanelOpenTabsRef.current.get(tabId) ?? null,
|
||||
|
||||
@@ -14,15 +14,10 @@ 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,
|
||||
@@ -367,8 +362,6 @@ function TerminalPopupPageInner({
|
||||
snippets,
|
||||
snippetPackages,
|
||||
groupConfigs,
|
||||
addConnectionLog,
|
||||
updateConnectionLog,
|
||||
updateKnownHosts,
|
||||
deleteSelectedSnippets,
|
||||
} = useVaultState({ syncConnectionLogTerminalData: false });
|
||||
@@ -404,8 +397,6 @@ function TerminalPopupPageInner({
|
||||
}
|
||||
await markAttachClosePrepared(attachSessionId, attachAuthorization);
|
||||
} catch { /* The main-process close handshake owns the final fallback. */ }
|
||||
} else {
|
||||
captureClosingTerminalSessions([sessionId]);
|
||||
}
|
||||
await close();
|
||||
})();
|
||||
@@ -415,7 +406,7 @@ function TerminalPopupPageInner({
|
||||
};
|
||||
void closePromise.then(clearClosePromise, clearClosePromise);
|
||||
return closePromise;
|
||||
}, [attachAuthorization, attachSessionId, close, isAttachMode, markAttachClosePrepared, sessionId]);
|
||||
}, [attachAuthorization, attachSessionId, close, isAttachMode, markAttachClosePrepared]);
|
||||
const effectiveKnownHosts = useMemo(
|
||||
() => getEffectiveKnownHosts(knownHosts) ?? [],
|
||||
[knownHosts],
|
||||
@@ -495,63 +486,6 @@ 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;
|
||||
@@ -628,7 +562,6 @@ function TerminalPopupPageInner({
|
||||
knownHosts={effectiveKnownHosts}
|
||||
isVisible
|
||||
isFocused
|
||||
onTerminalDataCapture={handlePopupRemoteDesktopCloseCapture}
|
||||
onCloseSession={() => {
|
||||
void handleClose();
|
||||
}}
|
||||
|
||||
@@ -1294,7 +1294,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
size="icon"
|
||||
className="h-7 w-7 shrink-0 app-no-drag top-tab-utility-btn"
|
||||
style={{ color: 'var(--top-tabs-muted, hsl(var(--muted-foreground)))' }}
|
||||
onClick={() => window.dispatchEvent(new CustomEvent('netcatty:toggle-ai-panel'))}
|
||||
onClick={() => window.dispatchEvent(new CustomEvent('netcatty:toggle-ai-panel', { cancelable: true }))}
|
||||
>
|
||||
<Sparkles size={16} />
|
||||
</Button>
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
Key,
|
||||
LayoutGrid,
|
||||
List,
|
||||
Monitor,
|
||||
Network,
|
||||
NotebookText,
|
||||
Pin,
|
||||
@@ -127,7 +126,6 @@ import { useHostTreeInlineGroupActions } from "./vault/useHostTreeInlineGroupAct
|
||||
import { useHostTreeInlineHostActions } from "./vault/useHostTreeInlineHostActions";
|
||||
import { useRegisterVaultHostTreeActions } from "./vault/useRegisterVaultHostTreeActions";
|
||||
import { Button } from "./ui/button";
|
||||
import { RippleButton } from "./ui/ripple";
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
@@ -161,6 +159,12 @@ import { useVaultHostCollections } from "./vault/useVaultHostCollections";
|
||||
import { useVaultImportHandlers } from "../application/state/useVaultImportHandlers";
|
||||
import { useVaultGroupDragHandlers } from "./vault/useVaultGroupDragHandlers";
|
||||
import { usePluginVaultPages } from "../application/state/usePluginVaultPages";
|
||||
import { useVaultNavConfig } from "../application/state/useVaultNavConfig";
|
||||
import {
|
||||
getVisibleVaultNavIds,
|
||||
resolveFallbackVaultSection,
|
||||
type VaultNavItemId,
|
||||
} from "../domain/vaultNavConfig";
|
||||
|
||||
const GroupDetailsPanel = lazy(() => import("./GroupDetailsPanel"));
|
||||
const HostDetailsPanel = lazy(() => import("./HostDetailsPanel"));
|
||||
@@ -179,7 +183,6 @@ const SnippetsManager = lazy(() => import("./SnippetsManager"));
|
||||
|
||||
export type VaultSection =
|
||||
| "hosts"
|
||||
| "monitor"
|
||||
| "keys"
|
||||
| "proxies"
|
||||
| "snippets"
|
||||
@@ -384,6 +387,59 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
hostsRef.current = hosts;
|
||||
const [currentSection, setCurrentSection] = useState<VaultSection>("hosts");
|
||||
const pluginVault = usePluginVaultPages({ locale, section: currentSection, select: setCurrentSection });
|
||||
const activePluginNavIds = useMemo(
|
||||
() => pluginVault.pages.map((page) => page.key),
|
||||
[pluginVault.pages],
|
||||
);
|
||||
const vaultNavConfig = useVaultNavConfig({
|
||||
activePluginIds: activePluginNavIds,
|
||||
pluginsLoading: pluginVault.contributions.loading,
|
||||
});
|
||||
const previousHiddenNavRef = useRef<ReadonlySet<VaultNavItemId>>(vaultNavConfig.hiddenSet);
|
||||
useEffect(() => {
|
||||
const previousHidden = previousHiddenNavRef.current;
|
||||
previousHiddenNavRef.current = vaultNavConfig.hiddenSet;
|
||||
if (
|
||||
!previousHidden.has(currentSection)
|
||||
&& vaultNavConfig.hiddenSet.has(currentSection)
|
||||
) {
|
||||
setCurrentSection(
|
||||
resolveFallbackVaultSection(currentSection, vaultNavConfig.visibleIds),
|
||||
);
|
||||
}
|
||||
}, [currentSection, vaultNavConfig.hiddenSet, vaultNavConfig.visibleIds]);
|
||||
|
||||
const handleSelectVaultNavItem = useCallback(
|
||||
(id: VaultNavItemId) => {
|
||||
setCurrentSection(id);
|
||||
if (id === "hosts") {
|
||||
setSelectedGroupPath(null);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleHideVaultNavItem = useCallback(
|
||||
(id: VaultNavItemId) => {
|
||||
const next = vaultNavConfig.setVisible(id, false);
|
||||
if (currentSection === id) {
|
||||
const nextVisible = getVisibleVaultNavIds(next, activePluginNavIds);
|
||||
setCurrentSection(resolveFallbackVaultSection(currentSection, nextVisible));
|
||||
}
|
||||
},
|
||||
[activePluginNavIds, currentSection, vaultNavConfig],
|
||||
);
|
||||
|
||||
const handleToggleVaultNavItemVisible = useCallback(
|
||||
(id: VaultNavItemId) => {
|
||||
const next = vaultNavConfig.toggleVisible(id);
|
||||
if (currentSection === id && next.hidden.includes(id)) {
|
||||
const nextVisible = getVisibleVaultNavIds(next, activePluginNavIds);
|
||||
setCurrentSection(resolveFallbackVaultSection(currentSection, nextVisible));
|
||||
}
|
||||
},
|
||||
[activePluginNavIds, currentSection, vaultNavConfig],
|
||||
);
|
||||
const [search, setSearch] = useState("");
|
||||
const [selectedGroupPath, setSelectedGroupPath] = useState<string | null>(
|
||||
null,
|
||||
@@ -1577,6 +1633,10 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
Copy,
|
||||
currentSection,
|
||||
pluginVault,
|
||||
vaultNavConfig,
|
||||
handleSelectVaultNavItem,
|
||||
handleHideVaultNavItem,
|
||||
handleToggleVaultNavItemVisible,
|
||||
customGroups,
|
||||
deleteGroupPath,
|
||||
deleteGroupPaths,
|
||||
@@ -1671,7 +1731,6 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
List,
|
||||
managedGroupPaths,
|
||||
managedSources,
|
||||
Monitor,
|
||||
moveGroup,
|
||||
moveHostToGroup,
|
||||
moveHostsToGroup,
|
||||
@@ -1724,7 +1783,6 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
reorderGroup,
|
||||
reorderHost,
|
||||
resetImportProgress,
|
||||
RippleButton,
|
||||
rootRef,
|
||||
sanitizeHost,
|
||||
ScreenShare,
|
||||
|
||||
@@ -40,6 +40,8 @@ import {
|
||||
} from './toolArtifacts/toolArtifactNames';
|
||||
import { parseVaultToolArtifact } from './toolArtifacts/vaultToolArtifact';
|
||||
import { VaultArtifactToolResult } from './toolArtifacts/VaultArtifactToolResult';
|
||||
import { parsePluginToolArtifact } from './toolArtifacts/pluginToolArtifact';
|
||||
import { PluginArtifactToolResult } from './toolArtifacts/PluginArtifactToolResult';
|
||||
import type { Host, Snippet, VaultNote } from '../../types';
|
||||
import {
|
||||
onApprovalRequest,
|
||||
@@ -620,6 +622,15 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
&& displayedMessages[end].role === "assistant";
|
||||
|
||||
const renderToolResultItem = (item: typeof toolResults[number]) => {
|
||||
const pluginArtifact = parsePluginToolArtifact(item.name, item.content, item.isError);
|
||||
if (pluginArtifact) {
|
||||
return (
|
||||
<PluginArtifactToolResult
|
||||
key={item.toolCallId}
|
||||
artifact={pluginArtifact}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const artifactToolName = item.artifactToolName ?? item.name;
|
||||
const remoteDesktopArtifact = parseRemoteDesktopToolArtifact(
|
||||
artifactToolName,
|
||||
@@ -688,6 +699,31 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
);
|
||||
}
|
||||
|
||||
const pluginArtifactItems = toolResults
|
||||
.map((item) => ({ item, artifact: parsePluginToolArtifact(item.name, item.content, item.isError) }))
|
||||
.filter((entry): entry is { item: typeof toolResults[number]; artifact: NonNullable<ReturnType<typeof parsePluginToolArtifact>> } => entry.artifact !== null);
|
||||
const nonPluginItems = toolResults.filter(
|
||||
(item) => parsePluginToolArtifact(item.name, item.content, item.isError) === null,
|
||||
);
|
||||
|
||||
if (pluginArtifactItems.length > 0) {
|
||||
return (
|
||||
<div key={`tool-group-${message.id}`} className="space-y-2 py-0.5">
|
||||
{nonPluginItems.length > 0 && (
|
||||
<ToolCallGroup
|
||||
count={nonPluginItems.length}
|
||||
defaultExpanded={!hasAssistantAfter}
|
||||
>
|
||||
{nonPluginItems.map(renderToolResultItem)}
|
||||
</ToolCallGroup>
|
||||
)}
|
||||
{pluginArtifactItems.map(({ item, artifact }) => (
|
||||
<PluginArtifactToolResult key={item.toolCallId} artifact={artifact} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ToolCallGroup
|
||||
key={`tool-group-${message.id}`}
|
||||
|
||||
@@ -38,7 +38,7 @@ export function resolveDisplayedPanelView(
|
||||
hasDraft: boolean,
|
||||
sessions: AISession[],
|
||||
persistedSessionId?: string | null,
|
||||
scopeType: "terminal" | "workspace" = "workspace",
|
||||
scopeType: "terminal" | "workspace" | "global" = "workspace",
|
||||
anchorChatId?: string | null,
|
||||
preferredHistorySessionId?: string | null,
|
||||
): AIPanelView {
|
||||
|
||||
@@ -6,7 +6,7 @@ const MAX_HISTORY_CACHE_ENTRIES_PER_SESSION_LIST = 64;
|
||||
const historyCache = new WeakMap<AISession[], Map<HistoryCacheKey, AISession[]>>();
|
||||
|
||||
function buildHistoryCacheKey(
|
||||
scopeType: 'terminal' | 'workspace',
|
||||
scopeType: 'terminal' | 'workspace' | 'global',
|
||||
scopeTargetId: string | undefined,
|
||||
scopeHostIds: string[] | undefined,
|
||||
activeTerminalSessionIds: Set<string>,
|
||||
@@ -26,7 +26,7 @@ function buildHistoryCacheKey(
|
||||
|
||||
export function getScopedHistorySessions(
|
||||
sessions: AISession[],
|
||||
scopeType: 'terminal' | 'workspace',
|
||||
scopeType: 'terminal' | 'workspace' | 'global',
|
||||
scopeTargetId: string | undefined,
|
||||
scopeHostIds: string[] | undefined,
|
||||
activeTerminalSessionIds: Set<string>,
|
||||
@@ -103,7 +103,7 @@ export function _getScopedHistoryCacheSizeForTests(sessions: AISession[]): numbe
|
||||
*/
|
||||
export function getPreferredAutoResumeSessionId(
|
||||
historySessions: readonly AISession[],
|
||||
scopeType: 'terminal' | 'workspace',
|
||||
scopeType: 'terminal' | 'workspace' | 'global',
|
||||
scopeTargetId: string | undefined,
|
||||
scopeHostIds: string[] | undefined,
|
||||
activeTerminalSessionIds: Set<string>,
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { AISession } from "../../infrastructure/ai/types";
|
||||
|
||||
export function getSessionScopeMatchRank(
|
||||
session: AISession,
|
||||
scopeType: "terminal" | "workspace",
|
||||
scopeType: "terminal" | "workspace" | "global",
|
||||
scopeTargetId?: string,
|
||||
scopeHostIds?: string[],
|
||||
/**
|
||||
@@ -37,6 +37,7 @@ export function getSessionScopeMatchRank(
|
||||
|
||||
if (session.scope.type !== scopeType) return 0;
|
||||
if (session.scope.targetId === scopeTargetId) return 3;
|
||||
if (scopeType === "global") return 0;
|
||||
|
||||
if (scopeType === "terminal" && activeTerminalSessionIds?.has(session.id)) {
|
||||
return 0;
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
import React, { useCallback, useState } from 'react';
|
||||
import { BarChart3, Check, Code2, ExternalLink, Loader2, Pin, Table2 } from 'lucide-react';
|
||||
import { cn } from '../../../lib/utils';
|
||||
import { netcattyBridge } from '../../../infrastructure/services/netcattyBridge';
|
||||
import { toast } from '../../ui/toast';
|
||||
import { PluginBiChart } from '../../plugins/primitives/PluginBiChart';
|
||||
import type {
|
||||
PluginArtifactActionSpec,
|
||||
PluginBiChartRenderedArtifact,
|
||||
PluginRenderedToolArtifact,
|
||||
PluginSqlResultRenderedArtifact,
|
||||
} from './pluginToolArtifact';
|
||||
|
||||
const MAX_PREVIEW_ROWS = 10;
|
||||
const MAX_PREVIEW_COLS = 8;
|
||||
|
||||
function formatCellValue(value: unknown): string {
|
||||
if (value === null || value === undefined) return 'NULL';
|
||||
if (typeof value === 'boolean') return value ? 'true' : 'false';
|
||||
if (typeof value === 'number') {
|
||||
return Number.isFinite(value) ? String(value) : '—';
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return value.length > 64 ? `${value.slice(0, 61)}...` : value;
|
||||
}
|
||||
try {
|
||||
const serialized = JSON.stringify(value);
|
||||
return serialized.length > 64 ? `${serialized.slice(0, 61)}...` : serialized;
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function usePluginArtifactAction(
|
||||
pluginId: string | undefined,
|
||||
viewId: string | undefined,
|
||||
) {
|
||||
const [busyKey, setBusyKey] = useState<string | null>(null);
|
||||
const [doneKeys, setDoneKeys] = useState<Record<string, boolean>>({});
|
||||
|
||||
const runAction = useCallback(async (
|
||||
key: string,
|
||||
action: PluginArtifactActionSpec,
|
||||
successToast: string,
|
||||
) => {
|
||||
if (!pluginId) return;
|
||||
const invoke = netcattyBridge.get()?.invokePluginAiTool;
|
||||
if (typeof invoke !== 'function') {
|
||||
toast.error('Plugin action bridge is unavailable.');
|
||||
return;
|
||||
}
|
||||
setBusyKey(key);
|
||||
try {
|
||||
await invoke({
|
||||
pluginId,
|
||||
toolName: action.toolName,
|
||||
args: action.args,
|
||||
...(viewId ? { viewId } : {}),
|
||||
});
|
||||
setDoneKeys((prev) => ({ ...prev, [key]: true }));
|
||||
toast.success(successToast);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
toast.error(message || 'Action failed.');
|
||||
} finally {
|
||||
setBusyKey((prev) => (prev === key ? null : prev));
|
||||
}
|
||||
}, [pluginId, viewId]);
|
||||
|
||||
return { busyKey, doneKeys, runAction };
|
||||
}
|
||||
|
||||
const BiChartArtifactView: React.FC<{ artifact: PluginBiChartRenderedArtifact }> = ({ artifact }) => {
|
||||
const [showSql, setShowSql] = useState(false);
|
||||
const { busyKey, doneKeys, runAction } = usePluginArtifactAction(artifact.pluginId, artifact.viewId);
|
||||
const canInvoke = Boolean(artifact.pluginId);
|
||||
|
||||
const chartProps = {
|
||||
...artifact.chartSpec,
|
||||
// Render header in our quiet artifact frame instead of duplicating titles.
|
||||
title: undefined,
|
||||
subtitle: undefined,
|
||||
height: artifact.chartSpec.height ?? 215,
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
data-plugin-ai-artifact="bi-chart"
|
||||
className="min-w-0 rounded-xl bg-muted/30 dark:bg-white/[0.035] px-3 py-2.5 space-y-2.5"
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<BarChart3 size={13} className="shrink-0 text-primary/80" />
|
||||
<span className="truncate text-[12px] font-medium text-foreground">
|
||||
{artifact.title || 'BI Chart'}
|
||||
</span>
|
||||
</div>
|
||||
{artifact.subtitle && (
|
||||
<p className="mt-0.5 truncate text-[11px] text-muted-foreground/75">
|
||||
{artifact.subtitle}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
{artifact.sql && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowSql((prev) => !prev)}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium transition-colors cursor-pointer',
|
||||
showSql
|
||||
? 'bg-primary/15 text-primary'
|
||||
: 'bg-background/60 text-muted-foreground hover:bg-background hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<Code2 size={11} />
|
||||
<span>SQL</span>
|
||||
</button>
|
||||
)}
|
||||
{canInvoke && artifact.openAction && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busyKey === 'open'}
|
||||
onClick={() => void runAction('open', artifact.openAction!, 'Opened in SQL Editor')}
|
||||
className="inline-flex items-center gap-1 rounded-md bg-background/60 px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-background hover:text-foreground cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
{busyKey === 'open' ? <Loader2 size={11} className="animate-spin" /> : <ExternalLink size={11} />}
|
||||
<span>{artifact.openAction.label || 'Open SQL'}</span>
|
||||
</button>
|
||||
)}
|
||||
{canInvoke && artifact.pinAction && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busyKey === 'pin'}
|
||||
onClick={() => void runAction('pin', artifact.pinAction!, 'Pinned to BI Dashboard')}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium transition-colors cursor-pointer disabled:opacity-50',
|
||||
doneKeys.pin
|
||||
? 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400'
|
||||
: 'bg-primary/12 text-primary hover:bg-primary/20',
|
||||
)}
|
||||
>
|
||||
{busyKey === 'pin'
|
||||
? <Loader2 size={11} className="animate-spin" />
|
||||
: doneKeys.pin
|
||||
? <Check size={11} />
|
||||
: <Pin size={11} />}
|
||||
<span>{doneKeys.pin ? 'Pinned' : (artifact.pinAction.label || 'Pin to BI Dashboard')}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Optional compact KPI strip */}
|
||||
{artifact.kpis && artifact.kpis.length > 0 && (
|
||||
<div className="grid grid-cols-2 gap-1.5 sm:grid-cols-3">
|
||||
{artifact.kpis.map((kpi, index) => (
|
||||
<div
|
||||
key={`${kpi.label}-${index}`}
|
||||
className="min-w-0 rounded-lg bg-background/55 dark:bg-white/[0.03] px-2.5 py-1.5"
|
||||
>
|
||||
<div className="truncate text-[10px] text-muted-foreground/75">{kpi.label}</div>
|
||||
<div className="mt-0.5 flex items-baseline gap-1.5 min-w-0">
|
||||
<span className="truncate text-[13px] font-semibold tabular-nums text-foreground">
|
||||
{kpi.value}
|
||||
</span>
|
||||
{kpi.delta && (
|
||||
<span
|
||||
className={cn(
|
||||
'truncate text-[10px] font-medium tabular-nums',
|
||||
kpi.tone === 'positive'
|
||||
? 'text-emerald-600 dark:text-emerald-400'
|
||||
: kpi.tone === 'negative'
|
||||
? 'text-rose-600 dark:text-rose-400'
|
||||
: kpi.tone === 'warning'
|
||||
? 'text-amber-600 dark:text-amber-400'
|
||||
: 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{kpi.delta}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Host-rendered interactive PluginBiChart */}
|
||||
<div className="min-w-0 rounded-lg bg-background/70 dark:bg-black/20 p-1.5">
|
||||
<PluginBiChart {...chartProps} />
|
||||
</div>
|
||||
|
||||
{/* Optional collapsible SQL inspector */}
|
||||
{showSql && artifact.sql && (
|
||||
<pre className="overflow-x-auto rounded-lg bg-background/75 dark:bg-black/25 px-2.5 py-2 font-mono text-[11px] leading-relaxed text-foreground/85 whitespace-pre-wrap break-words">
|
||||
{artifact.sql}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const SqlResultArtifactView: React.FC<{ artifact: PluginSqlResultRenderedArtifact }> = ({ artifact }) => {
|
||||
const [showSql, setShowSql] = useState(false);
|
||||
const { busyKey, doneKeys, runAction } = usePluginArtifactAction(artifact.pluginId, artifact.viewId);
|
||||
const canInvoke = Boolean(artifact.pluginId);
|
||||
|
||||
const visibleColumns = artifact.columns.slice(0, MAX_PREVIEW_COLS);
|
||||
const hiddenColumnCount = Math.max(0, artifact.columns.length - visibleColumns.length);
|
||||
const visibleRows = artifact.rows.slice(0, MAX_PREVIEW_ROWS);
|
||||
|
||||
return (
|
||||
<div
|
||||
data-plugin-ai-artifact="sql-result"
|
||||
className="min-w-0 rounded-xl bg-muted/30 dark:bg-white/[0.035] px-3 py-2.5 space-y-2"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<Table2 size={13} className="shrink-0 text-primary/80" />
|
||||
<span className="truncate text-[12px] font-medium text-foreground">
|
||||
{artifact.title || 'Query Result'}
|
||||
</span>
|
||||
<span className="shrink-0 rounded-md bg-background/60 px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground">
|
||||
{artifact.rowCount} {artifact.rowCount === 1 ? 'row' : 'rows'}
|
||||
{artifact.durationMs != null ? ` · ${artifact.durationMs} ms` : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowSql((prev) => !prev)}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium transition-colors cursor-pointer',
|
||||
showSql
|
||||
? 'bg-primary/15 text-primary'
|
||||
: 'bg-background/60 text-muted-foreground hover:bg-background hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<Code2 size={11} />
|
||||
<span>SQL</span>
|
||||
</button>
|
||||
{canInvoke && artifact.openAction && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busyKey === 'open'}
|
||||
onClick={() => void runAction('open', artifact.openAction!, 'Opened in SQL Editor')}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium transition-colors cursor-pointer disabled:opacity-50',
|
||||
doneKeys.open
|
||||
? 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400'
|
||||
: 'bg-primary/12 text-primary hover:bg-primary/20',
|
||||
)}
|
||||
>
|
||||
{busyKey === 'open'
|
||||
? <Loader2 size={11} className="animate-spin" />
|
||||
: doneKeys.open
|
||||
? <Check size={11} />
|
||||
: <ExternalLink size={11} />}
|
||||
<span>{doneKeys.open ? 'Opened' : (artifact.openAction.label || 'Open in SQL Editor')}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showSql && (
|
||||
<pre className="overflow-x-auto rounded-lg bg-background/75 dark:bg-black/25 px-2.5 py-2 font-mono text-[11px] leading-relaxed text-foreground/85 whitespace-pre-wrap break-words">
|
||||
{artifact.sql}
|
||||
</pre>
|
||||
)}
|
||||
|
||||
{visibleColumns.length > 0 && visibleRows.length > 0 ? (
|
||||
<div className="overflow-x-auto rounded-lg bg-background/65 dark:bg-black/20">
|
||||
<table className="w-full border-collapse text-left text-[11px]">
|
||||
<thead>
|
||||
<tr className="border-b border-border/25 text-muted-foreground/80">
|
||||
{visibleColumns.map((col, idx) => (
|
||||
<th
|
||||
key={`${col}-${idx}`}
|
||||
className="px-2.5 py-1.5 font-medium whitespace-nowrap"
|
||||
>
|
||||
{col}
|
||||
</th>
|
||||
))}
|
||||
{hiddenColumnCount > 0 && (
|
||||
<th className="px-2 py-1.5 font-normal text-muted-foreground/60 whitespace-nowrap">
|
||||
+{hiddenColumnCount}
|
||||
</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border/15">
|
||||
{visibleRows.map((row, rowIdx) => (
|
||||
<tr key={rowIdx} className="hover:bg-muted/25">
|
||||
{visibleColumns.map((_, colIdx) => {
|
||||
const cell = row[colIdx];
|
||||
const isNull = cell === null || cell === undefined;
|
||||
return (
|
||||
<td
|
||||
key={colIdx}
|
||||
className={cn(
|
||||
'px-2.5 py-1 font-mono whitespace-nowrap tabular-nums',
|
||||
isNull ? 'text-muted-foreground/45 italic' : 'text-foreground/85',
|
||||
)}
|
||||
>
|
||||
{formatCellValue(cell)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
{hiddenColumnCount > 0 && (
|
||||
<td className="px-2 py-1 text-muted-foreground/45">…</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{(artifact.rowCount > visibleRows.length || artifact.truncated) && (
|
||||
<div className="px-2.5 py-1 text-[10px] text-muted-foreground/65">
|
||||
Showing {visibleRows.length} of {artifact.totalRows ?? artifact.rowCount} rows
|
||||
{artifact.truncated ? ' (capped)' : ''}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg bg-background/50 px-2.5 py-2 text-[11px] text-muted-foreground">
|
||||
Query returned 0 rows.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const PluginArtifactToolResult: React.FC<{
|
||||
artifact: PluginRenderedToolArtifact;
|
||||
}> = ({ artifact }) => {
|
||||
if (artifact.kind === 'bi-chart') {
|
||||
return <BiChartArtifactView artifact={artifact} />;
|
||||
}
|
||||
return <SqlResultArtifactView artifact={artifact} />;
|
||||
};
|
||||
@@ -0,0 +1,155 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import React from 'react';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { act } from 'react';
|
||||
import { parsePluginToolArtifact } from './pluginToolArtifact';
|
||||
import { PluginArtifactToolResult } from './PluginArtifactToolResult';
|
||||
|
||||
function installDom() {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
|
||||
url: 'https://netcatty.local/',
|
||||
});
|
||||
const prev = {
|
||||
window: globalThis.window,
|
||||
document: globalThis.document,
|
||||
navigator: globalThis.navigator,
|
||||
HTMLElement: globalThis.HTMLElement,
|
||||
SVGElement: globalThis.SVGElement,
|
||||
IS_REACT_ACT_ENVIRONMENT: (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT,
|
||||
};
|
||||
Object.defineProperty(globalThis, 'window', { value: dom.window, configurable: true });
|
||||
Object.defineProperty(globalThis, 'document', { value: dom.window.document, configurable: true });
|
||||
Object.defineProperty(globalThis, 'navigator', { value: dom.window.navigator, configurable: true });
|
||||
Object.defineProperty(globalThis, 'HTMLElement', { value: dom.window.HTMLElement, configurable: true });
|
||||
Object.defineProperty(globalThis, 'SVGElement', { value: dom.window.SVGElement, configurable: true });
|
||||
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
return () => {
|
||||
Object.defineProperty(globalThis, 'window', { value: prev.window, configurable: true });
|
||||
Object.defineProperty(globalThis, 'document', { value: prev.document, configurable: true });
|
||||
Object.defineProperty(globalThis, 'navigator', { value: prev.navigator, configurable: true });
|
||||
Object.defineProperty(globalThis, 'HTMLElement', { value: prev.HTMLElement, configurable: true });
|
||||
Object.defineProperty(globalThis, 'SVGElement', { value: prev.SVGElement, configurable: true });
|
||||
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prev.IS_REACT_ACT_ENVIRONMENT;
|
||||
dom.window.close();
|
||||
};
|
||||
}
|
||||
|
||||
test('parsePluginToolArtifact parses bi-chart and sql-result payloads and rejects spoofed or invalid ones', () => {
|
||||
const chartPayload = JSON.stringify({
|
||||
ok: true,
|
||||
_netcattyArtifact: {
|
||||
kind: 'bi-chart',
|
||||
_netcattyPluginId: 'com.binaricat.netcatty-database',
|
||||
_netcattyViewId: 'com.binaricat.netcatty-database.workbench',
|
||||
_netcattyToolName: 'db_create_bi_chart',
|
||||
title: 'Revenue by Region',
|
||||
chartSpec: {
|
||||
type: 'bar',
|
||||
categories: ['NA', 'EU'],
|
||||
series: [{ id: 'rev', name: 'Revenue', values: [120, 95] }],
|
||||
},
|
||||
kpis: [{ label: 'Total', value: '$215', tone: 'positive' }],
|
||||
sql: 'SELECT region, SUM(revenue) FROM sales GROUP BY region',
|
||||
pinAction: { toolName: 'db_pin_chart_to_dashboard', args: { title: 'Revenue by Region' } },
|
||||
},
|
||||
});
|
||||
const chart = parsePluginToolArtifact('plugin_abc123_db_create_bi_chart', chartPayload);
|
||||
assert.equal(chart?.kind, 'bi-chart');
|
||||
assert.equal(chart?.pluginId, 'com.binaricat.netcatty-database');
|
||||
assert.equal(chart?.kpis?.length, 1);
|
||||
assert.equal(chart?.pinAction?.toolName, 'db_pin_chart_to_dashboard');
|
||||
|
||||
// Non-plugin tools (e.g. terminal_execute, sftp_read) cannot spoof _netcattyArtifact
|
||||
assert.equal(parsePluginToolArtifact('terminal_execute', chartPayload), null);
|
||||
assert.equal(parsePluginToolArtifact('web_search', chartPayload), null);
|
||||
// Mismatched _netcattyToolName vs qualified tool suffix is rejected
|
||||
assert.equal(parsePluginToolArtifact('plugin_abc123_other_tool', chartPayload), null);
|
||||
|
||||
const sql = parsePluginToolArtifact('plugin_abc123_db_run_readonly_sql', {
|
||||
_netcattyArtifact: {
|
||||
kind: 'sql-result',
|
||||
_netcattyPluginId: 'com.binaricat.netcatty-database',
|
||||
_netcattyToolName: 'db_run_readonly_sql',
|
||||
sql: 'SELECT id, name FROM users LIMIT 2',
|
||||
columns: ['id', 'name'],
|
||||
rows: [[1, 'Alice'], [2, 'Bob']],
|
||||
rowCount: 2,
|
||||
durationMs: 4,
|
||||
openAction: { toolName: 'db_open_sql_tab', args: { sql: 'SELECT id, name FROM users' } },
|
||||
},
|
||||
});
|
||||
assert.equal(sql?.kind, 'sql-result');
|
||||
assert.equal(sql?.rows.length, 2);
|
||||
assert.equal(sql?.openAction?.toolName, 'db_open_sql_tab');
|
||||
|
||||
// Error results and unknown chart types are rejected
|
||||
assert.equal(parsePluginToolArtifact('plugin_abc123_db_create_bi_chart', { _netcattyArtifact: { kind: 'bi-chart', _netcattyPluginId: 'com.a.b', _netcattyToolName: 'db_create_bi_chart', chartSpec: { type: 'bar', series: [{ id: 'a', name: 'A', values: [1] }] } } }, true), null);
|
||||
assert.equal(parsePluginToolArtifact('plugin_abc123_db_create_bi_chart', { _netcattyArtifact: { kind: 'bi-chart', _netcattyPluginId: 'com.a.b', _netcattyToolName: 'db_create_bi_chart', chartSpec: { type: 'invalid', series: [{ id: 'a', name: 'A', values: [1] }] } } }), null);
|
||||
});
|
||||
|
||||
test('PluginArtifactToolResult renders inline PluginBiChart and invokes pinAction via netcatty bridge', async () => {
|
||||
const cleanup = installDom();
|
||||
const invoked: Array<Record<string, unknown>> = [];
|
||||
(window as unknown as { netcatty?: Record<string, unknown> }).netcatty = {
|
||||
invokePluginAiTool: async (payload: Record<string, unknown>) => {
|
||||
invoked.push(payload);
|
||||
return { ok: true };
|
||||
},
|
||||
};
|
||||
|
||||
const artifact = parsePluginToolArtifact('plugin_abc123_db_create_bi_chart', {
|
||||
_netcattyArtifact: {
|
||||
kind: 'bi-chart',
|
||||
_netcattyPluginId: 'com.binaricat.netcatty-database',
|
||||
_netcattyViewId: 'com.binaricat.netcatty-database.workbench',
|
||||
_netcattyToolName: 'db_create_bi_chart',
|
||||
title: 'Top Products',
|
||||
chartSpec: {
|
||||
type: 'bar',
|
||||
categories: ['Pro', 'Air'],
|
||||
series: [{ id: 'rev', name: 'Revenue', values: [4200, 3100] }],
|
||||
},
|
||||
kpis: [{ label: 'Total Revenue', value: '$7.3K', tone: 'positive' }],
|
||||
sql: 'SELECT product, SUM(revenue) FROM orders GROUP BY product',
|
||||
pinAction: {
|
||||
toolName: 'db_pin_chart_to_dashboard',
|
||||
args: { title: 'Top Products' },
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.ok(artifact);
|
||||
|
||||
const container = document.getElementById('root')!;
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(React.createElement(PluginArtifactToolResult, { artifact }));
|
||||
});
|
||||
assert.ok(container.querySelector('[data-plugin-ai-artifact="bi-chart"]'));
|
||||
assert.ok(container.querySelector('svg'), 'PluginBiChart SVG should render inline');
|
||||
assert.ok(container.textContent?.includes('$7.3K'));
|
||||
|
||||
const pinButton = Array.from(container.querySelectorAll('button')).find(
|
||||
(btn) => btn.textContent?.includes('Pin to BI Dashboard'),
|
||||
);
|
||||
assert.ok(pinButton, 'Pin to BI Dashboard button should render');
|
||||
await act(async () => {
|
||||
pinButton.click();
|
||||
});
|
||||
assert.equal(invoked.length, 1);
|
||||
assert.deepEqual(invoked[0], {
|
||||
pluginId: 'com.binaricat.netcatty-database',
|
||||
toolName: 'db_pin_chart_to_dashboard',
|
||||
args: { title: 'Top Products' },
|
||||
viewId: 'com.binaricat.netcatty-database.workbench',
|
||||
});
|
||||
assert.ok(container.textContent?.includes('Pinned'));
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,206 @@
|
||||
import type { PluginBiChartWidgetProps } from '../../plugins/primitives/types';
|
||||
import { parseResultPayload } from './toolArtifactResultPayload';
|
||||
|
||||
const VALID_BI_CHART_TYPES = new Set([
|
||||
'bar',
|
||||
'horizontal-bar',
|
||||
'stacked-bar',
|
||||
'line',
|
||||
'area',
|
||||
'pie',
|
||||
'donut',
|
||||
'scatter',
|
||||
'funnel',
|
||||
'combo',
|
||||
]);
|
||||
|
||||
const VALID_TOOL_NAME_RE = /^[a-z][a-z0-9_]{0,47}$/;
|
||||
const QUALIFIED_PLUGIN_TOOL_RE = /^plugin_[0-9a-f]{6}_([a-z][a-z0-9_]{0,47})$/;
|
||||
|
||||
export interface PluginArtifactActionSpec {
|
||||
readonly toolName: string;
|
||||
readonly label?: string;
|
||||
readonly args: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface PluginBiChartArtifactKpi {
|
||||
readonly label: string;
|
||||
readonly value: string;
|
||||
readonly delta?: string;
|
||||
readonly tone?: 'default' | 'positive' | 'negative' | 'warning';
|
||||
}
|
||||
|
||||
export interface PluginBiChartRenderedArtifact {
|
||||
readonly kind: 'bi-chart';
|
||||
readonly pluginId?: string;
|
||||
readonly pluginName?: string;
|
||||
readonly viewId?: string;
|
||||
readonly sourceToolName?: string;
|
||||
readonly title?: string;
|
||||
readonly subtitle?: string;
|
||||
readonly chartSpec: PluginBiChartWidgetProps;
|
||||
readonly kpis?: readonly PluginBiChartArtifactKpi[];
|
||||
readonly sql?: string;
|
||||
readonly pinAction?: PluginArtifactActionSpec;
|
||||
readonly openAction?: PluginArtifactActionSpec;
|
||||
}
|
||||
|
||||
export interface PluginSqlResultRenderedArtifact {
|
||||
readonly kind: 'sql-result';
|
||||
readonly pluginId?: string;
|
||||
readonly pluginName?: string;
|
||||
readonly viewId?: string;
|
||||
readonly sourceToolName?: string;
|
||||
readonly title?: string;
|
||||
readonly sql: string;
|
||||
readonly columns: readonly string[];
|
||||
readonly rows: readonly (readonly unknown[])[];
|
||||
readonly rowCount: number;
|
||||
readonly totalRows?: number;
|
||||
readonly durationMs?: number;
|
||||
readonly truncated?: boolean;
|
||||
readonly openAction?: PluginArtifactActionSpec;
|
||||
readonly chartAction?: PluginArtifactActionSpec;
|
||||
}
|
||||
|
||||
export type PluginRenderedToolArtifact =
|
||||
| PluginBiChartRenderedArtifact
|
||||
| PluginSqlResultRenderedArtifact;
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === 'object' && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: null;
|
||||
}
|
||||
|
||||
function asNonEmptyString(value: unknown, maxLength = 240): string | undefined {
|
||||
if (typeof value !== 'string') return undefined;
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return undefined;
|
||||
return trimmed.slice(0, maxLength);
|
||||
}
|
||||
|
||||
function parseArtifactAction(value: unknown): PluginArtifactActionSpec | undefined {
|
||||
const record = asRecord(value);
|
||||
if (!record) return undefined;
|
||||
const toolName = typeof record.toolName === 'string' ? record.toolName.trim() : '';
|
||||
if (!VALID_TOOL_NAME_RE.test(toolName)) return undefined;
|
||||
const args = asRecord(record.args) ?? {};
|
||||
const label = asNonEmptyString(record.label, 64);
|
||||
return {
|
||||
toolName,
|
||||
...(label ? { label } : {}),
|
||||
args,
|
||||
};
|
||||
}
|
||||
|
||||
function parseKpis(value: unknown): PluginBiChartArtifactKpi[] | undefined {
|
||||
if (!Array.isArray(value)) return undefined;
|
||||
const items: PluginBiChartArtifactKpi[] = [];
|
||||
for (const raw of value.slice(0, 4)) {
|
||||
const record = asRecord(raw);
|
||||
if (!record) continue;
|
||||
const label = asNonEmptyString(record.label, 64);
|
||||
const val = asNonEmptyString(record.value, 64);
|
||||
if (!label || !val) continue;
|
||||
const delta = asNonEmptyString(record.delta, 32);
|
||||
const tone = record.tone === 'positive' || record.tone === 'negative' || record.tone === 'warning'
|
||||
? record.tone
|
||||
: 'default';
|
||||
items.push({
|
||||
label,
|
||||
value: val,
|
||||
...(delta ? { delta } : {}),
|
||||
tone,
|
||||
});
|
||||
}
|
||||
return items.length > 0 ? items : undefined;
|
||||
}
|
||||
|
||||
export function parsePluginToolArtifact(
|
||||
toolName: string | undefined,
|
||||
result: unknown,
|
||||
isError?: boolean,
|
||||
): PluginRenderedToolArtifact | null {
|
||||
if (isError) return null;
|
||||
if (typeof toolName !== 'string') return null;
|
||||
const qualifiedMatch = QUALIFIED_PLUGIN_TOOL_RE.exec(toolName.trim());
|
||||
if (!qualifiedMatch) return null;
|
||||
const expectedToolSuffix = qualifiedMatch[1];
|
||||
|
||||
const payload = parseResultPayload(result);
|
||||
if (!payload) return null;
|
||||
const artifact = asRecord(payload._netcattyArtifact);
|
||||
if (!artifact) return null;
|
||||
|
||||
const pluginId = asNonEmptyString(artifact._netcattyPluginId, 160);
|
||||
const pluginName = asNonEmptyString(artifact._netcattyPluginName, 120);
|
||||
const viewId = asNonEmptyString(artifact._netcattyViewId, 256);
|
||||
const sourceToolName = asNonEmptyString(artifact._netcattyToolName, 64);
|
||||
if (!pluginId || sourceToolName !== expectedToolSuffix) return null;
|
||||
|
||||
if (artifact.kind === 'bi-chart') {
|
||||
const rawChartSpec = asRecord(artifact.chartSpec);
|
||||
if (!rawChartSpec) return null;
|
||||
const chartType = typeof rawChartSpec.type === 'string' ? rawChartSpec.type : '';
|
||||
if (!VALID_BI_CHART_TYPES.has(chartType)) return null;
|
||||
const hasSeries = Array.isArray(rawChartSpec.series) && rawChartSpec.series.length > 0;
|
||||
const hasPoints = Array.isArray(rawChartSpec.points) && rawChartSpec.points.length > 0;
|
||||
if (!hasSeries && !hasPoints) return null;
|
||||
|
||||
return {
|
||||
kind: 'bi-chart',
|
||||
pluginId,
|
||||
pluginName,
|
||||
viewId,
|
||||
sourceToolName,
|
||||
title: asNonEmptyString(artifact.title, 140) ?? asNonEmptyString(rawChartSpec.title, 140),
|
||||
subtitle: asNonEmptyString(artifact.subtitle, 180) ?? asNonEmptyString(rawChartSpec.subtitle, 180),
|
||||
chartSpec: rawChartSpec as unknown as PluginBiChartWidgetProps,
|
||||
kpis: parseKpis(artifact.kpis),
|
||||
sql: asNonEmptyString(artifact.sql, 8000),
|
||||
pinAction: parseArtifactAction(artifact.pinAction),
|
||||
openAction: parseArtifactAction(artifact.openAction),
|
||||
};
|
||||
}
|
||||
|
||||
if (artifact.kind === 'sql-result') {
|
||||
const sql = asNonEmptyString(artifact.sql, 8000);
|
||||
if (!sql) return null;
|
||||
const columns = Array.isArray(artifact.columns)
|
||||
? artifact.columns.slice(0, 32).map((col) => String(col ?? ''))
|
||||
: [];
|
||||
const rows = Array.isArray(artifact.rows)
|
||||
? artifact.rows.slice(0, 50).map((row) => (Array.isArray(row) ? row.slice(0, 32) : [row]))
|
||||
: [];
|
||||
const rowCount = typeof artifact.rowCount === 'number' && Number.isFinite(artifact.rowCount)
|
||||
? Math.max(0, Math.floor(artifact.rowCount))
|
||||
: rows.length;
|
||||
const totalRows = typeof artifact.totalRows === 'number' && Number.isFinite(artifact.totalRows)
|
||||
? Math.max(rowCount, Math.floor(artifact.totalRows))
|
||||
: undefined;
|
||||
const durationMs = typeof artifact.durationMs === 'number' && Number.isFinite(artifact.durationMs)
|
||||
? Math.max(0, Math.round(artifact.durationMs))
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
kind: 'sql-result',
|
||||
pluginId,
|
||||
pluginName,
|
||||
viewId,
|
||||
sourceToolName,
|
||||
title: asNonEmptyString(artifact.title, 140),
|
||||
sql,
|
||||
columns,
|
||||
rows,
|
||||
rowCount,
|
||||
totalRows,
|
||||
durationMs,
|
||||
truncated: artifact.truncated === true,
|
||||
openAction: parseArtifactAction(artifact.openAction),
|
||||
chartAction: parseArtifactAction(artifact.chartAction),
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
} from "../../domain/remoteDesktop";
|
||||
import { cn } from "../../lib/utils";
|
||||
import type {
|
||||
GroupConfig,
|
||||
Host,
|
||||
Identity,
|
||||
RdpConfig,
|
||||
@@ -69,7 +68,6 @@ interface CompanionRemoteDesktopSectionsProps {
|
||||
|
||||
interface CompanionRemoteDesktopInlineFieldsProps extends CompanionRemoteDesktopSectionsProps, RdpResolutionDraftProps {
|
||||
protocol: "vnc" | "rdp";
|
||||
groupDefaults?: Partial<GroupConfig>;
|
||||
credentialDraft?: CompanionCredentialDraft;
|
||||
onCredentialDraftChange?: (draft: CompanionCredentialDraft | undefined) => void;
|
||||
}
|
||||
@@ -82,7 +80,6 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
protocol,
|
||||
form,
|
||||
setForm,
|
||||
groupDefaults,
|
||||
identities,
|
||||
availableKeys = [],
|
||||
credentialDraft,
|
||||
@@ -92,25 +89,15 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
t,
|
||||
}) => {
|
||||
const [vncPortInput, setVncPortInput] = useState<string>(() =>
|
||||
form.vncConfig?.port !== undefined
|
||||
? String(form.vncConfig.port)
|
||||
: groupDefaults?.vncConfig?.port !== undefined
|
||||
? ""
|
||||
: String(DEFAULT_VNC_PORT),
|
||||
String(form.vncConfig?.port ?? DEFAULT_VNC_PORT),
|
||||
);
|
||||
const [showManualPassword, setShowManualPassword] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (protocol === "vnc") {
|
||||
setVncPortInput(
|
||||
form.vncConfig?.port !== undefined
|
||||
? String(form.vncConfig.port)
|
||||
: groupDefaults?.vncConfig?.port !== undefined
|
||||
? ""
|
||||
: String(DEFAULT_VNC_PORT),
|
||||
);
|
||||
setVncPortInput(String(form.vncConfig?.port ?? DEFAULT_VNC_PORT));
|
||||
}
|
||||
}, [form.id, protocol, form.vncConfig?.port, groupDefaults?.vncConfig?.port]);
|
||||
}, [form.id, protocol, form.vncConfig?.port]);
|
||||
|
||||
const passwordCompatibleIdentities = useMemo(
|
||||
() =>
|
||||
@@ -124,7 +111,12 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
vncConfig: {
|
||||
...(prev.vncConfig ?? { enabled: true }),
|
||||
...(prev.vncConfig ?? {
|
||||
...DEFAULT_VNC_CONFIG,
|
||||
enabled: true,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: true,
|
||||
}),
|
||||
...patch,
|
||||
},
|
||||
}));
|
||||
@@ -134,38 +126,25 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
rdpConfig: {
|
||||
...(prev.rdpConfig ?? { enabled: true }),
|
||||
...(prev.rdpConfig ?? {
|
||||
...DEFAULT_RDP_CONFIG,
|
||||
enabled: true,
|
||||
tunnelViaHostSsh: true,
|
||||
useHostCredentials: true,
|
||||
}),
|
||||
...patch,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
if (protocol === "vnc") {
|
||||
const groupVnc = groupDefaults?.vncConfig;
|
||||
const effectiveVnc = { ...(groupVnc ?? {}), ...(form.vncConfig ?? {}) };
|
||||
const vncTunneled = effectiveVnc.tunnelViaHostSsh ?? true;
|
||||
const vncNormalized = normalizeVncConfig(effectiveVnc);
|
||||
const vncTunneled = form.vncConfig?.tunnelViaHostSsh ?? true;
|
||||
const vncNormalized = normalizeVncConfig(form.vncConfig);
|
||||
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 =
|
||||
!effectiveVncIdentityId
|
||||
&& (
|
||||
form.vncConfig?.useHostCredentials !== undefined
|
||||
? form.vncConfig.useHostCredentials
|
||||
: hostHasManualVncCreds
|
||||
? false
|
||||
: groupVnc?.useHostCredentials === true
|
||||
);
|
||||
const selectedVncIdentity = effectiveVncIdentityId
|
||||
? identities.find((i) => i.id === effectiveVncIdentityId)
|
||||
!form.vncConfig?.identityId && form.vncConfig?.useHostCredentials !== false;
|
||||
const selectedVncIdentity = form.vncConfig?.identityId
|
||||
? identities.find((i) => i.id === form.vncConfig?.identityId)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
@@ -180,26 +159,18 @@ 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 ?? (groupVnc?.port !== undefined ? undefined : DEFAULT_VNC_PORT);
|
||||
setVncPortInput(resolved !== undefined ? String(resolved) : "");
|
||||
const resolved = parsed ?? DEFAULT_VNC_PORT;
|
||||
setVncPortInput(String(resolved));
|
||||
updateVncConfig({ port: resolved });
|
||||
}}
|
||||
placeholder={groupVnc?.port ? String(groupVnc.port) : t("hostDetails.vnc.displayPlaceholder")}
|
||||
placeholder={t("hostDetails.vnc.displayPlaceholder")}
|
||||
className="h-8 flex-1 min-w-0 text-center font-mono text-sm"
|
||||
/>
|
||||
{vncDisplayLabel ? (
|
||||
@@ -231,7 +202,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
onChange={(e) =>
|
||||
updateVncConfig({ tunnelTargetHost: e.target.value || undefined })
|
||||
}
|
||||
placeholder={groupVnc?.tunnelTargetHost || "127.0.0.1"}
|
||||
placeholder="127.0.0.1"
|
||||
className="h-8 w-44 font-mono text-sm"
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
@@ -246,7 +217,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
onCheckedChange={(checked) => {
|
||||
if (checked) {
|
||||
onCredentialDraftChange?.(undefined);
|
||||
updateVncConfig({ useHostCredentials: true, identityId: undefined, username: undefined });
|
||||
updateVncConfig({ useHostCredentials: true, identityId: undefined });
|
||||
} else {
|
||||
updateVncConfig({ useHostCredentials: false });
|
||||
}
|
||||
@@ -256,7 +227,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
|
||||
{!useHostCreds && (
|
||||
<div className="space-y-2">
|
||||
{effectiveVncIdentityId ? (
|
||||
{form.vncConfig?.identityId ? (
|
||||
<div className="flex items-center gap-2 h-10 px-3 rounded-lg border border-border/60 bg-transparent">
|
||||
<User size={16} className="text-muted-foreground shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
@@ -273,10 +244,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
onClick={() => updateVncConfig({
|
||||
identityId: groupVnc?.identityId ? "" : undefined,
|
||||
useHostCredentials: false,
|
||||
})}
|
||||
onClick={() => updateVncConfig({ identityId: undefined, useHostCredentials: false })}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
@@ -289,17 +257,13 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
<IdentitySuggestInput
|
||||
value={credentialDraft?.username ?? form.vncConfig?.username ?? ""}
|
||||
onChange={(next) => {
|
||||
updateVncConfig({
|
||||
username: next || undefined,
|
||||
useHostCredentials: false,
|
||||
...(groupVnc?.identityId ? { identityId: "" } : {}),
|
||||
});
|
||||
updateVncConfig({ username: next || undefined, useHostCredentials: false });
|
||||
onCredentialDraftChange?.({
|
||||
username: next,
|
||||
password: credentialDraft?.password ?? "",
|
||||
});
|
||||
}}
|
||||
placeholder={groupVnc?.username || t("hostDetails.vnc.usernamePlaceholder")}
|
||||
placeholder={t("hostDetails.vnc.usernamePlaceholder")}
|
||||
identities={passwordCompatibleIdentities}
|
||||
availableKeys={availableKeys}
|
||||
onSelectIdentity={(identity) => {
|
||||
@@ -386,30 +350,12 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
);
|
||||
}
|
||||
|
||||
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 rdpTunneled = form.rdpConfig?.tunnelViaHostSsh ?? true;
|
||||
const rdpNormalized = normalizeRdpConfig(form.rdpConfig);
|
||||
const useHostCreds =
|
||||
!effectiveRdpIdentityId
|
||||
&& (
|
||||
form.rdpConfig?.useHostCredentials !== undefined
|
||||
? form.rdpConfig.useHostCredentials
|
||||
: hostHasManualRdpCreds
|
||||
? false
|
||||
: groupRdp?.useHostCredentials === true
|
||||
);
|
||||
const selectedRdpIdentity = effectiveRdpIdentityId
|
||||
? identities.find((i) => i.id === effectiveRdpIdentityId)
|
||||
!form.rdpConfig?.identityId && form.rdpConfig?.useHostCredentials !== false;
|
||||
const selectedRdpIdentity = form.rdpConfig?.identityId
|
||||
? identities.find((i) => i.id === form.rdpConfig?.identityId)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
@@ -422,12 +368,11 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
value={form.rdpConfig?.port ?? (groupRdp?.port !== undefined ? "" : DEFAULT_RDP_PORT)}
|
||||
value={form.rdpConfig?.port ?? 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>
|
||||
@@ -453,7 +398,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
onChange={(e) =>
|
||||
updateRdpConfig({ tunnelTargetHost: e.target.value || undefined })
|
||||
}
|
||||
placeholder={groupRdp?.tunnelTargetHost || "127.0.0.1"}
|
||||
placeholder="127.0.0.1"
|
||||
className="h-8 w-44 font-mono text-sm"
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
@@ -468,7 +413,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
onCheckedChange={(checked) => {
|
||||
if (checked) {
|
||||
onCredentialDraftChange?.(undefined);
|
||||
updateRdpConfig({ useHostCredentials: true, identityId: undefined, username: undefined });
|
||||
updateRdpConfig({ useHostCredentials: true, identityId: undefined });
|
||||
} else {
|
||||
updateRdpConfig({ useHostCredentials: false });
|
||||
}
|
||||
@@ -478,7 +423,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
|
||||
{!useHostCreds && (
|
||||
<div className="space-y-2">
|
||||
{effectiveRdpIdentityId ? (
|
||||
{form.rdpConfig?.identityId ? (
|
||||
<div className="flex items-center gap-2 h-10 px-3 rounded-lg border border-border/60 bg-transparent">
|
||||
<User size={16} className="text-muted-foreground shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
@@ -495,10 +440,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
onClick={() => updateRdpConfig({
|
||||
identityId: groupRdp?.identityId ? "" : undefined,
|
||||
useHostCredentials: false,
|
||||
})}
|
||||
onClick={() => updateRdpConfig({ identityId: undefined, useHostCredentials: false })}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
@@ -511,17 +453,13 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
<IdentitySuggestInput
|
||||
value={credentialDraft?.username ?? form.rdpConfig?.username ?? ""}
|
||||
onChange={(next) => {
|
||||
updateRdpConfig({
|
||||
username: next || undefined,
|
||||
useHostCredentials: false,
|
||||
...(groupRdp?.identityId ? { identityId: "" } : {}),
|
||||
});
|
||||
updateRdpConfig({ username: next || undefined, useHostCredentials: false });
|
||||
onCredentialDraftChange?.({
|
||||
username: next,
|
||||
password: credentialDraft?.password ?? "",
|
||||
});
|
||||
}}
|
||||
placeholder={groupRdp?.username || t("hostDetails.rdp.usernamePlaceholder")}
|
||||
placeholder={t("hostDetails.rdp.usernamePlaceholder")}
|
||||
identities={passwordCompatibleIdentities}
|
||||
availableKeys={availableKeys}
|
||||
onSelectIdentity={(identity) => {
|
||||
@@ -582,7 +520,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
|
||||
onChange={(e) =>
|
||||
updateRdpConfig({ domain: e.target.value || undefined })
|
||||
}
|
||||
placeholder={groupRdp?.domain || t("hostDetails.rdp.domainPlaceholder")}
|
||||
placeholder={t("hostDetails.rdp.domainPlaceholder")}
|
||||
className="h-8 w-44 text-sm"
|
||||
/>
|
||||
</HostDetailsSettingRow>
|
||||
@@ -612,7 +550,6 @@ 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, RdpConfig } from "../../types";
|
||||
import type { Host } from "../../types";
|
||||
import { Input } from "../ui/input";
|
||||
|
||||
export interface RdpResolutionDraftProps {
|
||||
@@ -14,14 +14,13 @@ export interface RdpResolutionDraftProps {
|
||||
}
|
||||
|
||||
interface RdpResolutionFieldsProps extends RdpResolutionDraftProps {
|
||||
form: Pick<Host, "rdpConfig">;
|
||||
form: Host;
|
||||
setForm: React.Dispatch<React.SetStateAction<Host>>;
|
||||
inheritedRdpConfig?: Partial<RdpConfig>;
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export const RdpResolutionFields: React.FC<RdpResolutionFieldsProps> = ({
|
||||
form, setForm, inheritedRdpConfig, t, resolutionDraft, onResolutionDraftChange,
|
||||
form, setForm, t, resolutionDraft, onResolutionDraftChange,
|
||||
}) => {
|
||||
const [localDraft, setLocalDraft] = useState<RdpResolutionDraft>({});
|
||||
const id = useId();
|
||||
@@ -30,11 +29,8 @@ 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]
|
||||
?? inheritedRdpConfig?.[dimension]
|
||||
?? (dimension === "width" ? DEFAULT_RDP_WIDTH : DEFAULT_RDP_HEIGHT),
|
||||
);
|
||||
const value = draft[dimension] ?? String(form.rdpConfig?.[dimension]
|
||||
?? (dimension === "width" ? DEFAULT_RDP_WIDTH : DEFAULT_RDP_HEIGHT));
|
||||
const invalid = parseRdpDimensionDraft(value) === undefined;
|
||||
const inputId = `${id}-${dimension}`;
|
||||
return (
|
||||
|
||||
@@ -24,7 +24,6 @@ import {
|
||||
normalizeVncConfig,
|
||||
} from "../../domain/remoteDesktop";
|
||||
import type {
|
||||
GroupConfig,
|
||||
Host,
|
||||
RdpColorDepth,
|
||||
RdpConfig,
|
||||
@@ -46,14 +45,12 @@ 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,
|
||||
@@ -62,18 +59,12 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
|
||||
Boolean(
|
||||
form.rdpConfig?.loadBalanceInfo ||
|
||||
form.rdpConfig?.alternateShell ||
|
||||
form.rdpConfig?.shellWorkingDir ||
|
||||
groupDefaults?.rdpConfig?.loadBalanceInfo ||
|
||||
groupDefaults?.rdpConfig?.alternateShell ||
|
||||
groupDefaults?.rdpConfig?.shellWorkingDir,
|
||||
form.rdpConfig?.shellWorkingDir,
|
||||
),
|
||||
);
|
||||
|
||||
if (form.protocol === "rdp") {
|
||||
const rdp = normalizeRdpConfig({
|
||||
...(groupDefaults?.rdpConfig ?? {}),
|
||||
...(form.rdpConfig ?? {}),
|
||||
});
|
||||
const rdp = normalizeRdpConfig(form.rdpConfig);
|
||||
const updateRdp = <K extends keyof RdpConfig>(key: K, value: RdpConfig[K]) => {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
@@ -114,7 +105,6 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
|
||||
<RdpResolutionFields
|
||||
form={form}
|
||||
setForm={setForm}
|
||||
inheritedRdpConfig={groupDefaults?.rdpConfig}
|
||||
t={t}
|
||||
resolutionDraft={resolutionDraft}
|
||||
onResolutionDraftChange={onResolutionDraftChange}
|
||||
@@ -234,7 +224,7 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
|
||||
onChange={(e) =>
|
||||
updateRdp("loadBalanceInfo", e.target.value || undefined)
|
||||
}
|
||||
placeholder={groupDefaults?.rdpConfig?.loadBalanceInfo || t("hostDetails.rdp.loadBalanceInfoPlaceholder")}
|
||||
placeholder={t("hostDetails.rdp.loadBalanceInfoPlaceholder")}
|
||||
className="h-10 rounded-lg text-sm font-mono"
|
||||
/>
|
||||
</div>
|
||||
@@ -247,7 +237,7 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
|
||||
onChange={(e) =>
|
||||
updateRdp("alternateShell", e.target.value || undefined)
|
||||
}
|
||||
placeholder={groupDefaults?.rdpConfig?.alternateShell || t("hostDetails.rdp.alternateShellPlaceholder")}
|
||||
placeholder={t("hostDetails.rdp.alternateShellPlaceholder")}
|
||||
className="h-10 rounded-lg text-sm font-mono"
|
||||
/>
|
||||
</div>
|
||||
@@ -260,7 +250,7 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
|
||||
onChange={(e) =>
|
||||
updateRdp("shellWorkingDir", e.target.value || undefined)
|
||||
}
|
||||
placeholder={groupDefaults?.rdpConfig?.shellWorkingDir || t("hostDetails.rdp.shellWorkingDirPlaceholder")}
|
||||
placeholder={t("hostDetails.rdp.shellWorkingDirPlaceholder")}
|
||||
className="h-10 rounded-lg text-sm font-mono"
|
||||
/>
|
||||
</div>
|
||||
@@ -271,10 +261,7 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
|
||||
}
|
||||
|
||||
if (form.protocol === "vnc") {
|
||||
const vnc = normalizeVncConfig({
|
||||
...(groupDefaults?.vncConfig ?? {}),
|
||||
...(form.vncConfig ?? {}),
|
||||
});
|
||||
const vnc = normalizeVncConfig(form.vncConfig);
|
||||
const updateVnc = <K extends keyof VncConfig>(key: K, value: VncConfig[K]) => {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { Suspense } from 'react';
|
||||
import { prewarmHostDrawnPluginView } from '../../application/state/pluginViewSessionRegistry';
|
||||
import type { PluginHostDrawnPageProps } from './PluginHostDrawnPage';
|
||||
|
||||
let preloadPromise: Promise<unknown> | null = null;
|
||||
@@ -11,8 +12,41 @@ export function preloadPluginHostDrawnPage(): void {
|
||||
void loadPluginHostDrawnPage().catch(() => { preloadPromise = null; });
|
||||
}
|
||||
|
||||
export function prewarmPluginView(viewId?: string): void {
|
||||
preloadPluginHostDrawnPage();
|
||||
if (viewId) prewarmHostDrawnPluginView(viewId);
|
||||
}
|
||||
|
||||
const PluginHostDrawnPageImpl = React.lazy(loadPluginHostDrawnPage);
|
||||
|
||||
export function PluginViewLoadingSurface({ slot, loadingLabel }: { slot: string; loadingLabel: string }) {
|
||||
return (
|
||||
<div
|
||||
data-plugin-view-slot={slot}
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className="flex h-full min-h-0 w-full flex-1 flex-col gap-3 bg-background p-4 text-sm text-muted-foreground"
|
||||
>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-muted-foreground/30 border-t-foreground/70" aria-hidden="true" />
|
||||
<span className="text-xs font-medium text-muted-foreground">{loadingLabel}</span>
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 gap-3 opacity-60" aria-hidden="true">
|
||||
<div className="hidden w-52 shrink-0 flex-col gap-2 rounded-lg border border-border/40 bg-muted/20 p-3 sm:flex">
|
||||
<div className="h-3 w-2/3 animate-pulse rounded bg-muted/60" />
|
||||
<div className="h-3 w-4/5 animate-pulse rounded bg-muted/40" />
|
||||
<div className="h-3 w-1/2 animate-pulse rounded bg-muted/40" />
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-2.5 rounded-lg border border-border/40 bg-muted/10 p-3">
|
||||
<div className="h-3.5 w-1/3 animate-pulse rounded bg-muted/50" />
|
||||
<div className="h-24 w-full animate-pulse rounded bg-muted/30" />
|
||||
<div className="min-h-0 flex-1 animate-pulse rounded bg-muted/20" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy boundary for host-drawn plugin views so css-tree, mdn-data, and
|
||||
* @remote-dom/core stay out of the startup entry bundle until a plugin view
|
||||
@@ -24,9 +58,7 @@ export function LazyPluginHostDrawnPage(props: PluginHostDrawnPageProps) {
|
||||
<Suspense
|
||||
fallback={
|
||||
props.active ? (
|
||||
<p data-plugin-view-slot={slot} role="status" className="p-4 text-sm text-muted-foreground">
|
||||
{props.loadingLabel}
|
||||
</p>
|
||||
<PluginViewLoadingSurface slot={slot} loadingLabel={props.loadingLabel} />
|
||||
) : null
|
||||
}
|
||||
>
|
||||
|
||||
@@ -14,10 +14,12 @@ export function PluginHostActionHost() {
|
||||
if (!entry) return null;
|
||||
const request = entry.prompt.request;
|
||||
const selection = request.kind === 'vault.selectHosts';
|
||||
const durableSelection = selection && request.durable === true;
|
||||
const stream = request.kind === 'network.stream.connectViaHost';
|
||||
const directStreamConfirm = request.kind === 'network.stream.confirm';
|
||||
const tlsConfirm = request.kind === 'network.stream.tlsConfirm';
|
||||
const connection = request.kind === 'vault.requestConnect' || stream;
|
||||
const isSftpConnect = request.kind === 'vault.requestConnect' && request.mode === 'sftp';
|
||||
const effective = entry.host ? applyGroupDefaults(entry.host, entry.host.group ? resolveGroupDefaults(entry.host.group, entry.groups) : {}) : undefined;
|
||||
const protocol = effective ? resolveEffectiveTerminalProtocol(effective) : undefined;
|
||||
const dialogTitle = selection
|
||||
@@ -26,11 +28,13 @@ export function PluginHostActionHost() {
|
||||
? 'Confirm Network Connection'
|
||||
: tlsConfirm
|
||||
? 'Verify TLS Certificate'
|
||||
: connection
|
||||
? t('plugins.hostActions.connect')
|
||||
: entry.host
|
||||
? t('plugins.hostActions.edit')
|
||||
: t('plugins.hostActions.create');
|
||||
: isSftpConnect
|
||||
? t('vault.hosts.openSftp')
|
||||
: connection
|
||||
? t('plugins.hostActions.connect')
|
||||
: entry.host
|
||||
? t('plugins.hostActions.edit')
|
||||
: t('plugins.hostActions.create');
|
||||
|
||||
return <Dialog open onOpenChange={(open) => { if (!open) void state.respond('cancel'); }}>
|
||||
<DialogContent className={selection ? 'max-w-md h-[min(85vh,640px)] flex flex-col p-0 gap-0 overflow-hidden' : 'sm:max-w-[560px] max-h-[85vh] overflow-y-auto'} hideCloseButton>
|
||||
@@ -40,6 +44,11 @@ export function PluginHostActionHost() {
|
||||
</DialogHeader>
|
||||
{selection ? <>
|
||||
<p className="px-4 pt-3 text-xs text-muted-foreground">{t('plugins.hostActions.selectionNote')}</p>
|
||||
{durableSelection && (
|
||||
<p className="px-4 pt-1 text-xs text-amber-600 dark:text-amber-400">
|
||||
Selected hosts will remain bound to this plugin across sessions until revoked. SSH passwords and private keys are never shared.
|
||||
</p>
|
||||
)}
|
||||
<p className="px-4 pt-2 text-sm font-medium break-words">{request.title}</p>
|
||||
{state.selectedIds.length > 50 && <p role="alert" className="px-4 text-sm text-destructive">{t('plugins.hostActions.selectionLimit')}</p>}
|
||||
<SelectHostPanelContent hosts={entry.candidates} customGroups={entry.customGroups} selectedHostIds={state.selectedIds} multiSelect className="flex-1 min-h-0" confirmDisabled={state.busy || state.selectedIds.length > 50} onSelect={(host) => state.setSelectedIds((ids) => ids.includes(host.id) ? ids.filter((id) => id !== host.id) : [...ids, host.id])} onSelectionChange={state.setSelectedIds} onConfirm={() => { if (!state.busy && state.selectedIds.length <= 50) void state.respond('submit'); }} />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useHostDrawnPluginView } from '../../application/state/useHostDrawnPluginView';
|
||||
import { PluginViewLoadingSurface } from './LazyPluginHostDrawnPage';
|
||||
import { PluginSettingsEntry } from './PluginSettingsEntry';
|
||||
import { PluginRemoteSurface } from './PluginRemoteSurface';
|
||||
|
||||
@@ -32,7 +33,7 @@ function hasFullBleedChrome(tree: unknown): boolean {
|
||||
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
|
||||
const view = useHostDrawnPluginView(props);
|
||||
if (!view.visible) return null;
|
||||
if (view.loading) return <p data-plugin-view-slot={props.slot.split(':')[0]} role="status" className="p-4 text-sm text-muted-foreground">{props.loadingLabel}</p>;
|
||||
if (view.loading) return <PluginViewLoadingSurface slot={props.slot.split(':')[0]} loadingLabel={props.loadingLabel} />;
|
||||
const fullBleed = hasFullBleedChrome(view.tree);
|
||||
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={props.slot.split(':')[0]} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
|
||||
<PluginRemoteSurface key={`${props.viewId}:${props.version}:${props.slot}`} tree={view.tree} css={view.css} settled={view.settled} loadImage={view.loadImage} onEvent={view.sendEvent} />
|
||||
|
||||
@@ -21,18 +21,30 @@ function HostInteractionDialog({ state, prompt }: {
|
||||
const request = prompt.request;
|
||||
const terminalShare = request.kind === 'terminal.selection.read';
|
||||
const inputDraft = request.kind === 'terminal.input.propose';
|
||||
const isConfirm = request.kind === 'confirm';
|
||||
const isOpenExternalUrl = request.kind === 'openExternalUrl';
|
||||
const previewClipboard = request.kind === 'clipboard.read' && prompt.phase === 'request';
|
||||
const needsPreview = previewClipboard || (terminalShare && prompt.phase === 'request');
|
||||
const textBytes = new TextEncoder().encode(state.value).length;
|
||||
const canSubmit = request.kind === 'quickPick' ? request.items.some((item) => item.id === state.value) : textBytes <= PLUGIN_HOST_INTERACTION_LIMITS.textBytes;
|
||||
const canSubmit = request.kind === 'quickPick'
|
||||
? request.items.some((item) => item.id === state.value)
|
||||
: (isConfirm || isOpenExternalUrl || textBytes <= PLUGIN_HOST_INTERACTION_LIMITS.textBytes);
|
||||
const displayTitle = isOpenExternalUrl
|
||||
? (request.title ?? t('plugins.interaction.openUrlTitle'))
|
||||
: request.title;
|
||||
return <Dialog open onOpenChange={(open) => { if (!open) void state.respond('cancel'); }}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-[520px]" hideCloseButton>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('plugins.interaction.title')}</DialogTitle>
|
||||
<DialogDescription className="break-all">{prompt.pluginId} · {prompt.pluginVersion}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<p className="break-words text-sm font-medium">{request.title}</p>
|
||||
<p className="text-xs text-muted-foreground">{t(inputDraft ? 'plugins.interaction.draftNote' : terminalShare ? 'plugins.interaction.terminalDisclosure' : 'plugins.interaction.sharing')}</p>
|
||||
<p className="break-words text-sm font-medium">{displayTitle}</p>
|
||||
{isConfirm && request.message && <p className="break-words text-sm text-muted-foreground whitespace-pre-wrap">{request.message}</p>}
|
||||
{isOpenExternalUrl && <>
|
||||
<p className="text-xs text-muted-foreground">{t('plugins.interaction.openUrlNote')}</p>
|
||||
<code className="block rounded-md border bg-muted/40 p-2.5 font-mono text-xs break-all">{request.url}</code>
|
||||
</>}
|
||||
{!isConfirm && !isOpenExternalUrl && <p className="text-xs text-muted-foreground">{t(inputDraft ? 'plugins.interaction.draftNote' : terminalShare ? 'plugins.interaction.terminalDisclosure' : 'plugins.interaction.sharing')}</p>}
|
||||
{(terminalShare || inputDraft) && <p className="break-all text-sm">{t('plugins.interaction.terminalTarget')}: {prompt.terminalLabel} ({prompt.terminalSessionId})</p>}
|
||||
{inputDraft && <textarea aria-label={t('plugins.interaction.draft')} className="min-h-28 max-h-64 w-full rounded-md border bg-muted/30 p-3 font-mono text-xs" value={state.value} maxLength={PLUGIN_HOST_INTERACTION_LIMITS.textBytes} disabled={state.busy} onChange={(event) => state.setValue(event.target.value)} />}
|
||||
{(inputDraft || (terminalShare && prompt.phase === 'preview')) && <pre aria-label={t('plugins.interaction.exactText')} className="max-h-40 overflow-auto whitespace-pre-wrap break-all rounded-md border p-2 font-mono text-xs">{JSON.stringify(inputDraft ? state.value : prompt.previewText)}</pre>}
|
||||
@@ -50,9 +62,19 @@ function HostInteractionDialog({ state, prompt }: {
|
||||
{(request.kind === 'clipboard.write' || prompt.phase === 'preview') && <textarea aria-label={t('plugins.interaction.preview')} readOnly className="min-h-28 max-h-64 w-full resize-none rounded-md border bg-muted/30 p-3 font-mono text-xs" value={request.kind === 'clipboard.write' ? request.text : prompt.previewText ?? ''} />}
|
||||
{state.error && <p role="alert" className="text-sm text-destructive">{t('plugins.interaction.failed')}</p>}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" disabled={state.busy} onClick={() => void state.respond('cancel')}>{t('common.cancel')}</Button>
|
||||
<Button disabled={state.busy || !canSubmit} onClick={() => void state.respond(needsPreview ? 'preview' : 'submit')}>
|
||||
{t(needsPreview ? terminalShare ? 'plugins.interaction.terminalPreview' : 'plugins.interaction.previewAction' : inputDraft ? 'plugins.interaction.closeDraft' : request.kind === 'clipboard.read' || terminalShare ? 'plugins.interaction.share' : request.kind === 'clipboard.write' ? 'plugins.interaction.copy' : 'common.continue')}
|
||||
<Button variant="outline" disabled={state.busy} onClick={() => void state.respond('cancel')}>
|
||||
{isConfirm && request.cancelLabel ? request.cancelLabel : t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={isConfirm && request.destructive ? 'destructive' : 'default'}
|
||||
disabled={state.busy || !canSubmit}
|
||||
onClick={() => void state.respond(needsPreview ? 'preview' : 'submit')}
|
||||
>
|
||||
{isConfirm && request.confirmLabel
|
||||
? request.confirmLabel
|
||||
: isOpenExternalUrl
|
||||
? t('plugins.interaction.openUrlAction')
|
||||
: t(needsPreview ? terminalShare ? 'plugins.interaction.terminalPreview' : 'plugins.interaction.previewAction' : inputDraft ? 'plugins.interaction.closeDraft' : request.kind === 'clipboard.read' || terminalShare ? 'plugins.interaction.share' : request.kind === 'clipboard.write' ? 'plugins.interaction.copy' : 'common.continue')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { parseWidgetPropsJson, PluginSlottedWidget, type SlottedWidgetKind } fro
|
||||
import { matchWorkbenchShortcut } from './primitives/shortcuts';
|
||||
import type { PluginSplitPaneWidgetProps } from './primitives/types';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { isValidatedPluginRemoteTree } from '../../application/state/pluginRemoteTree';
|
||||
import { validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs';
|
||||
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
|
||||
|
||||
@@ -28,7 +29,7 @@ const SURFACE_EVENTS = [
|
||||
'scroll',
|
||||
] as const;
|
||||
const SURFACE_EVENT_SET = new Set<string>(SURFACE_EVENTS);
|
||||
const SLOTTED_WIDGET_KINDS = new Set<string>(['code-editor', 'data-grid', 'er-canvas']);
|
||||
const SLOTTED_WIDGET_KINDS = new Set<string>(['code-editor', 'data-grid', 'er-canvas', 'metric-chart', 'bi-chart']);
|
||||
|
||||
const ATTRIBUTE_NAMES: Record<string, string> = { class: 'className', for: 'htmlFor', readonly: 'readOnly', tabindex: 'tabIndex', maxlength: 'maxLength', minlength: 'minLength', colspan: 'colSpan', rowspan: 'rowSpan', autocomplete: 'autoComplete' };
|
||||
const BOOLEAN_ATTRIBUTES = new Set(['checked', 'disabled', 'readonly', 'required', 'multiple', 'selected', 'open']);
|
||||
@@ -339,6 +340,7 @@ function readSelectionRange(
|
||||
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
|
||||
export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadImage, depth = 0 }: { depth?: number; tree: unknown; css: string; settled?: boolean; loadImage?(path: string): Promise<string>; onEvent(event: PluginSurfaceEvent): void }) {
|
||||
const checkedTree = useMemo(() => {
|
||||
if (isValidatedPluginRemoteTree(tree)) return tree as { children: RemoteNode[] };
|
||||
try {
|
||||
validatePluginRemoteTree(tree);
|
||||
return tree as { children: RemoteNode[] };
|
||||
@@ -537,11 +539,14 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
};
|
||||
}, [shadow, depth]);
|
||||
|
||||
const baseStyleElement = useMemo(() => <style>{SHADOW_BASE_SCROLLBAR_CSS}</style>, []);
|
||||
const pluginStyleElement = useMemo(() => <style>{css}</style>, [css]);
|
||||
|
||||
return (
|
||||
<SurfaceContext.Provider value={surfaceContextValue}>
|
||||
<div ref={surfaceRef} className="h-full w-full min-h-0 min-w-0 overflow-hidden [contain:paint] isolate relative" data-plugin-remote-surface>
|
||||
<div ref={hostRef} className="h-full min-h-0 overflow-auto [container-type:inline-size] [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-corner]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-transparent hover:[&::-webkit-scrollbar-thumb]:bg-muted-foreground/25" />
|
||||
{shadow && createPortal(<><style>{SHADOW_BASE_SCROLLBAR_CSS}</style><style>{css}</style>{tree.children.map((node) => renderRemoteNode(node, settled))}</>, shadow)}
|
||||
{shadow && createPortal(<>{baseStyleElement}{pluginStyleElement}{tree.children.map((node) => renderRemoteNode(node, settled))}</>, shadow)}
|
||||
</div>
|
||||
</SurfaceContext.Provider>
|
||||
);
|
||||
|
||||
@@ -3,28 +3,49 @@ import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { activeTabStore } from '../../application/state/activeTabStore';
|
||||
import { subscribeSidePanelLiveSnapshot } from '../../application/state/sidePanelLiveStore';
|
||||
import { usePluginContributions } from '../../application/state/usePluginContributions';
|
||||
import { usePluginViewBadges } from '../../application/state/usePluginViewBadges';
|
||||
import { collectPluginTerminalSidebarPages, PLUGIN_TERMINAL_SIDEBAR_CONTEXT, requestOpenPluginTerminalSidebar,
|
||||
type PluginTerminalSidebarPage } from '../../application/state/usePluginTerminalSidebar';
|
||||
import { formatPluginViewBadgeAriaText, formatPluginViewBadgeLabel, isPluginViewBadgeVisible } from '../../domain/pluginViewBadge';
|
||||
import { cn } from '../../lib/utils';
|
||||
import { PluginContributionIcon } from './PluginContributionIcon';
|
||||
import { PluginViewBadge } from './PluginViewBadge';
|
||||
import { Button } from '../ui/button';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip';
|
||||
import { LazyPluginHostDrawnPage } from './LazyPluginHostDrawnPage';
|
||||
import { LazyPluginHostDrawnPage, prewarmPluginView } from './LazyPluginHostDrawnPage';
|
||||
|
||||
export function PluginTerminalSidebarLauncher({ sessionId, buttonClassName = 'h-6 w-6' }: { sessionId: string; buttonClassName?: string }) {
|
||||
const { locale } = useI18n();
|
||||
const contributions = usePluginContributions({ locale, context: PLUGIN_TERMINAL_SIDEBAR_CONTEXT });
|
||||
const pages = collectPluginTerminalSidebarPages(contributions.snapshot.plugins);
|
||||
const badgesByViewId = usePluginViewBadges(pages.length > 0);
|
||||
if (!pages.length) return null;
|
||||
return <>{pages.map((page) => <Tooltip key={page.tool}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon" className={buttonClassName}
|
||||
aria-label={`${page.title} — ${page.pluginName}`}
|
||||
onClick={() => requestOpenPluginTerminalSidebar(page.viewId, sessionId)}>
|
||||
<PluginContributionIcon pluginId={page.pluginId} icon={page.icon} size={14} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">{page.title} — {page.pluginName}</TooltipContent>
|
||||
</Tooltip>)}</>;
|
||||
return <>{pages.map((page) => {
|
||||
const rawBadge = badgesByViewId.get(page.viewId);
|
||||
const activeBadge = isPluginViewBadgeVisible(rawBadge) ? rawBadge : null;
|
||||
const badgeLabel = formatPluginViewBadgeLabel(activeBadge);
|
||||
const badgeAria = formatPluginViewBadgeAriaText(activeBadge);
|
||||
const baseLabel = `${page.title} — ${page.pluginName}`;
|
||||
const tooltip = activeBadge?.tooltip
|
||||
? `${baseLabel} · ${activeBadge.tooltip}`
|
||||
: badgeLabel
|
||||
? `${baseLabel} (${badgeLabel})`
|
||||
: baseLabel;
|
||||
const ariaLabel = badgeAria ? `${baseLabel} (${badgeAria})` : baseLabel;
|
||||
return <Tooltip key={page.tool}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon" className={cn('relative overflow-visible', buttonClassName)}
|
||||
aria-label={ariaLabel}
|
||||
onMouseEnter={() => prewarmPluginView(page.viewId)}
|
||||
onFocus={() => prewarmPluginView(page.viewId)}
|
||||
onClick={() => requestOpenPluginTerminalSidebar(page.viewId, sessionId)}>
|
||||
<PluginContributionIcon pluginId={page.pluginId} icon={page.icon} size={14} />
|
||||
{activeBadge && <PluginViewBadge badge={activeBadge} variant="compact-overlay" />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">{tooltip}</TooltipContent>
|
||||
</Tooltip>;
|
||||
})}</>;
|
||||
}
|
||||
|
||||
export function PluginTerminalSidebarPageHost({ page, tabId, sessionId, getSession, unavailable, focused, showHeader = true }: {
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useAIState } from '../../application/state/useAIState';
|
||||
import { useAISessionsStore } from '../../application/state/aiSessionsStore';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import type { AISession } from '../../infrastructure/ai/types';
|
||||
import type {
|
||||
PluginAISidebarPrompt,
|
||||
PluginAISidebarTurnContext,
|
||||
} from '../../infrastructure/ai/pluginAiSidebarTypes';
|
||||
import {
|
||||
MAX_PLUGIN_AI_SIDEBAR_WIDTH,
|
||||
MIN_PLUGIN_AI_SIDEBAR_WIDTH,
|
||||
readPluginAiSidebarWidth,
|
||||
writePluginAiSidebarWidth,
|
||||
type PendingPluginSidebarPrompt,
|
||||
} from '../../application/state/usePluginAiSidebar';
|
||||
import { LazyLoadBoundary } from '../ui/lazy-load-boundary';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
const LazyAIChatSidePanel = lazy(() => import('../AIChatSidePanel'));
|
||||
|
||||
const PluginAISidebarFallback: React.FC = () => {
|
||||
const { t } = useI18n();
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center bg-background text-xs text-muted-foreground">
|
||||
<div className="flex items-center gap-2">
|
||||
<Loader2 size={14} className="animate-spin" />
|
||||
{t('ai.chat.preparing')}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export interface PluginVaultAISidebarProps {
|
||||
pluginId: string;
|
||||
pluginName: string;
|
||||
viewId: string;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
pluginContext: PluginAISidebarTurnContext | null;
|
||||
suggestedPrompts?: readonly PluginAISidebarPrompt[];
|
||||
pendingPrompt?: PendingPluginSidebarPrompt | null;
|
||||
onPendingPromptConsumed?: (id: number) => void;
|
||||
}
|
||||
|
||||
export const PluginVaultAISidebar: React.FC<PluginVaultAISidebarProps> = ({
|
||||
pluginName,
|
||||
viewId,
|
||||
open,
|
||||
onClose,
|
||||
pluginContext,
|
||||
suggestedPrompts,
|
||||
pendingPrompt,
|
||||
onPendingPromptConsumed,
|
||||
}) => {
|
||||
const aiConfig = useAIState();
|
||||
const {
|
||||
sessions,
|
||||
activeSessionIdMap,
|
||||
draftsByScope,
|
||||
panelViewByScope,
|
||||
} = useAISessionsStore();
|
||||
const [width, setWidth] = useState<number>(readPluginAiSidebarWidth);
|
||||
const [resizing, setResizing] = useState(false);
|
||||
const widthRef = useRef(width);
|
||||
widthRef.current = width;
|
||||
|
||||
useEffect(() => {
|
||||
if (!resizing) return;
|
||||
const onMove = (event: PointerEvent) => {
|
||||
const next = Math.max(
|
||||
MIN_PLUGIN_AI_SIDEBAR_WIDTH,
|
||||
Math.min(MAX_PLUGIN_AI_SIDEBAR_WIDTH, Math.round(window.innerWidth - event.clientX - 8)),
|
||||
);
|
||||
widthRef.current = next;
|
||||
setWidth(next);
|
||||
};
|
||||
const onUp = () => {
|
||||
setResizing(false);
|
||||
document.body.style.cursor = '';
|
||||
writePluginAiSidebarWidth(widthRef.current);
|
||||
};
|
||||
document.body.style.cursor = 'col-resize';
|
||||
window.addEventListener('pointermove', onMove);
|
||||
window.addEventListener('pointerup', onUp, { once: true });
|
||||
return () => {
|
||||
document.body.style.cursor = '';
|
||||
window.removeEventListener('pointermove', onMove);
|
||||
window.removeEventListener('pointerup', onUp);
|
||||
};
|
||||
}, [resizing]);
|
||||
|
||||
const handleStartResize = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
setResizing(true);
|
||||
}, []);
|
||||
|
||||
const scopeTargetId = `plugin-view:${viewId}`;
|
||||
|
||||
return (
|
||||
<aside
|
||||
data-plugin-ai-sidebar={viewId}
|
||||
data-open={open ? 'true' : 'false'}
|
||||
aria-label={`${pluginName} AI Assistant`}
|
||||
style={open ? { width } : undefined}
|
||||
className={cn(
|
||||
'relative flex h-full min-h-0 shrink-0 flex-col bg-background',
|
||||
open ? 'border-l border-border/35' : 'hidden',
|
||||
)}
|
||||
>
|
||||
{open && (
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label="Resize AI sidebar"
|
||||
onPointerDown={handleStartResize}
|
||||
className={cn(
|
||||
'absolute top-0 bottom-0 left-0 z-20 w-1.5 -translate-x-1/2 cursor-col-resize transition-colors',
|
||||
resizing ? 'bg-primary/40' : 'hover:bg-primary/25',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<div className="min-h-0 flex-1 overflow-hidden">
|
||||
<LazyLoadBoundary name="Plugin AI sidebar" resetKey={viewId}>
|
||||
<Suspense fallback={<PluginAISidebarFallback />}>
|
||||
<LazyAIChatSidePanel
|
||||
sessions={sessions as AISession[]}
|
||||
activeSessionIdMap={activeSessionIdMap as Record<string, string | null>}
|
||||
draftsByScope={draftsByScope}
|
||||
panelViewByScope={panelViewByScope}
|
||||
setActiveSessionId={aiConfig.setActiveSessionId}
|
||||
ensureDraftForScope={aiConfig.ensureDraftForScope}
|
||||
updateDraft={aiConfig.updateDraft}
|
||||
showDraftView={aiConfig.showDraftView}
|
||||
showSessionView={aiConfig.showSessionView}
|
||||
clearDraftForScope={aiConfig.clearDraftForScope}
|
||||
addDraftFiles={aiConfig.addDraftFiles}
|
||||
removeDraftFile={aiConfig.removeDraftFile}
|
||||
createSession={aiConfig.createSession}
|
||||
undoLastTurnInSession={aiConfig.undoLastTurnInSession}
|
||||
deleteSession={aiConfig.deleteSession}
|
||||
updateSessionTitle={aiConfig.updateSessionTitle}
|
||||
exportSessionsBackup={aiConfig.exportSessionsBackup}
|
||||
importSessionsBackup={aiConfig.importSessionsBackup}
|
||||
updateSessionExternalSessionId={aiConfig.updateSessionExternalSessionId}
|
||||
addMessageToSession={aiConfig.addMessageToSession}
|
||||
updateLastMessage={aiConfig.updateLastMessage}
|
||||
updateMessageById={aiConfig.updateMessageById}
|
||||
persistContextCompaction={aiConfig.persistContextCompaction}
|
||||
forkSessionFromMessage={aiConfig.forkSessionFromMessage}
|
||||
providers={aiConfig.providers}
|
||||
activeProviderId={aiConfig.activeProviderId}
|
||||
activeModelId={aiConfig.activeModelId}
|
||||
defaultAgentId="catty"
|
||||
toolIntegrationMode={aiConfig.toolIntegrationMode}
|
||||
externalAgents={aiConfig.externalAgents}
|
||||
setExternalAgents={aiConfig.setExternalAgents}
|
||||
agentModelMap={aiConfig.agentModelMap}
|
||||
setAgentModel={aiConfig.setAgentModel}
|
||||
agentProviderMap={aiConfig.agentProviderMap}
|
||||
setAgentProvider={aiConfig.setAgentProvider}
|
||||
agentThinkingMap={aiConfig.agentThinkingMap}
|
||||
setAgentThinking={aiConfig.setAgentThinking}
|
||||
updateProvider={aiConfig.updateProvider}
|
||||
globalPermissionMode={aiConfig.globalPermissionMode}
|
||||
setGlobalPermissionMode={aiConfig.setGlobalPermissionMode}
|
||||
commandBlocklist={aiConfig.commandBlocklist}
|
||||
commandTimeout={aiConfig.commandTimeout}
|
||||
responseIdleTimeout={aiConfig.responseIdleTimeout}
|
||||
maxIterations={aiConfig.maxIterations}
|
||||
toolOutputMaxChars={aiConfig.toolOutputMaxChars}
|
||||
webSearchConfig={aiConfig.webSearchConfig}
|
||||
quickMessages={aiConfig.quickMessages}
|
||||
scopeType="global"
|
||||
scopeTargetId={scopeTargetId}
|
||||
scopeLabel={pluginContext?.title || pluginName}
|
||||
terminalSessions={[]}
|
||||
isVisible={open}
|
||||
pluginContext={pluginContext}
|
||||
pluginSuggestedPrompts={suggestedPrompts}
|
||||
pendingPluginPrompt={pendingPrompt}
|
||||
onPendingPluginPromptConsumed={onPendingPromptConsumed}
|
||||
onClosePanel={onClose}
|
||||
borderlessChrome
|
||||
/>
|
||||
</Suspense>
|
||||
</LazyLoadBoundary>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
@@ -1,36 +1,132 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { activeTabStore } from '../../application/state/activeTabStore';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import type { usePluginVaultPages } from '../../application/state/usePluginVaultPages';
|
||||
import { usePluginViewBadges } from '../../application/state/usePluginViewBadges';
|
||||
import {
|
||||
usePluginAiSidebarForView,
|
||||
type PendingPluginSidebarPrompt,
|
||||
} from '../../application/state/usePluginAiSidebar';
|
||||
import { formatPluginViewBadgeAriaText, formatPluginViewBadgeLabel, isPluginViewBadgeVisible } from '../../domain/pluginViewBadge';
|
||||
import { PluginContributionIcon } from './PluginContributionIcon';
|
||||
import { PluginViewBadge } from './PluginViewBadge';
|
||||
import { Button } from '../ui/button';
|
||||
import { LazyPluginHostDrawnPage, preloadPluginHostDrawnPage } from './LazyPluginHostDrawnPage';
|
||||
import { LazyPluginHostDrawnPage, prewarmPluginView } from './LazyPluginHostDrawnPage';
|
||||
import { PluginVaultAISidebar } from './PluginVaultAISidebar';
|
||||
|
||||
type VaultPages = ReturnType<typeof usePluginVaultPages>;
|
||||
const subscribeHidden = (hide: () => void) => activeTabStore.subscribeSync((id) => { if (id !== 'vault') hide(); });
|
||||
let nextPluginPromptId = 1;
|
||||
|
||||
export function PluginVaultNavigation({ model, collapsed }: { model: VaultPages; collapsed: boolean }) {
|
||||
const badgesByViewId = usePluginViewBadges(model.pages.length > 0);
|
||||
if (!model.pages.length) return null;
|
||||
return <>
|
||||
{model.pages.map((page) => <Button key={page.key} type="button"
|
||||
variant={model.selected?.key === page.key ? 'secondary' : 'ghost'}
|
||||
className={`w-full h-10 ${collapsed ? 'justify-center p-0' : 'justify-start gap-3'} ${model.selected?.key === page.key ? 'bg-foreground/10 text-foreground hover:bg-foreground/15 border-border/40' : ''}`}
|
||||
title={`${page.title} — ${page.pluginName}`}
|
||||
aria-label={`${page.title} — ${page.pluginName}`}
|
||||
aria-current={model.selected?.key === page.key ? 'page' : undefined}
|
||||
onMouseEnter={preloadPluginHostDrawnPage}
|
||||
onFocus={preloadPluginHostDrawnPage}
|
||||
onClick={() => model.select(page.key)}>
|
||||
<PluginContributionIcon pluginId={page.pluginId} icon={page.icon} size={16} className="shrink-0" />
|
||||
{!collapsed && <span className="truncate">{page.title}</span>}
|
||||
</Button>)}
|
||||
{model.pages.map((page) => {
|
||||
const rawBadge = badgesByViewId.get(page.viewId);
|
||||
const activeBadge = isPluginViewBadgeVisible(rawBadge) ? rawBadge : null;
|
||||
const badgeLabel = formatPluginViewBadgeLabel(activeBadge);
|
||||
const badgeAria = formatPluginViewBadgeAriaText(activeBadge);
|
||||
const baseLabel = `${page.title} — ${page.pluginName}`;
|
||||
const title = activeBadge?.tooltip
|
||||
? `${baseLabel} · ${activeBadge.tooltip}`
|
||||
: badgeLabel
|
||||
? `${baseLabel} (${badgeLabel})`
|
||||
: baseLabel;
|
||||
const ariaLabel = badgeAria ? `${baseLabel} (${badgeAria})` : baseLabel;
|
||||
return <Button key={page.key} type="button"
|
||||
variant={model.selected?.key === page.key ? 'secondary' : 'ghost'}
|
||||
className={`w-full h-10 ${collapsed ? 'justify-center p-0' : 'justify-start gap-3'} ${model.selected?.key === page.key ? 'bg-foreground/10 text-foreground hover:bg-foreground/15 border-border/40' : ''}`}
|
||||
title={title}
|
||||
aria-label={ariaLabel}
|
||||
aria-current={model.selected?.key === page.key ? 'page' : undefined}
|
||||
onMouseEnter={() => prewarmPluginView(page.viewId)}
|
||||
onFocus={() => prewarmPluginView(page.viewId)}
|
||||
onClick={() => model.select(page.key)}>
|
||||
<span className="relative inline-flex shrink-0 items-center justify-center">
|
||||
<PluginContributionIcon pluginId={page.pluginId} icon={page.icon} size={16} className="shrink-0" />
|
||||
{collapsed && activeBadge && <PluginViewBadge badge={activeBadge} variant="overlay" />}
|
||||
</span>
|
||||
{!collapsed && <span className="min-w-0 flex-1 truncate text-left">{page.title}</span>}
|
||||
{!collapsed && activeBadge && <PluginViewBadge badge={activeBadge} variant="inline" />}
|
||||
</Button>;
|
||||
})}
|
||||
</>;
|
||||
}
|
||||
|
||||
export function PluginVaultPage({ model }: { model: VaultPages }) {
|
||||
const { t } = useI18n();
|
||||
const page = model.selected!;
|
||||
return <section className="flex min-h-0 flex-1 flex-col" aria-label={page.title} data-plugin-vault-page={page.key}>
|
||||
<LazyPluginHostDrawnPage pluginId={page.pluginId} viewId={page.viewId} version={page.version} slot="vault-page" active={model.active} context={model.context}
|
||||
subscribeHidden={subscribeHidden} unavailable={model.fallback} loadingLabel={t('plugins.vault.loading')} />
|
||||
const [aiSidebarOpen, setAiSidebarOpen] = useState(false);
|
||||
const [aiSidebarMounted, setAiSidebarMounted] = useState(false);
|
||||
const [pendingPrompt, setPendingPrompt] = useState<PendingPluginSidebarPrompt | null>(null);
|
||||
const activeRef = useRef(model.active);
|
||||
activeRef.current = model.active;
|
||||
|
||||
const handleSidebarCommand = useCallback((command: NetcattyPluginAiSidebarCommand) => {
|
||||
if (command.action === 'close') {
|
||||
setAiSidebarOpen(false);
|
||||
return;
|
||||
}
|
||||
if (command.action === 'open') {
|
||||
if (!activeRef.current) return;
|
||||
setAiSidebarMounted(true);
|
||||
setAiSidebarOpen(true);
|
||||
if (command.prompt && command.prompt.trim()) {
|
||||
setPendingPrompt({
|
||||
id: nextPluginPromptId++,
|
||||
prompt: command.prompt.trim(),
|
||||
autoSend: command.autoSend,
|
||||
});
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const { turnContext, suggestedPrompts } = usePluginAiSidebarForView({
|
||||
pluginId: page.pluginId,
|
||||
pluginName: page.pluginName,
|
||||
viewId: page.viewId,
|
||||
enabled: true,
|
||||
onCommand: handleSidebarCommand,
|
||||
});
|
||||
|
||||
// Top-bar Sparkles AI button toggles the contextual Catty AI sidebar while this plugin page is active.
|
||||
useEffect(() => {
|
||||
if (!model.active) return;
|
||||
const handleToggleAi = (event: Event) => {
|
||||
event.preventDefault();
|
||||
setAiSidebarMounted(true);
|
||||
setAiSidebarOpen((prev) => !prev);
|
||||
};
|
||||
window.addEventListener('netcatty:toggle-ai-panel', handleToggleAi, { capture: true });
|
||||
return () => window.removeEventListener('netcatty:toggle-ai-panel', handleToggleAi, { capture: true });
|
||||
}, [model.active]);
|
||||
|
||||
const handleCloseAiSidebar = useCallback(() => {
|
||||
setAiSidebarOpen(false);
|
||||
}, []);
|
||||
|
||||
const handlePendingPromptConsumed = useCallback((id: number) => {
|
||||
setPendingPrompt((prev) => (prev?.id === id ? null : prev));
|
||||
}, []);
|
||||
|
||||
return <section className="flex min-h-0 flex-1 flex-row overflow-hidden" aria-label={page.title} data-plugin-vault-page={page.key}>
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
<LazyPluginHostDrawnPage pluginId={page.pluginId} viewId={page.viewId} version={page.version} slot="vault-page" active={model.active} context={model.context}
|
||||
subscribeHidden={subscribeHidden} unavailable={model.fallback} loadingLabel={t('plugins.vault.loading')} />
|
||||
</div>
|
||||
{aiSidebarMounted && (
|
||||
<PluginVaultAISidebar
|
||||
pluginId={page.pluginId}
|
||||
pluginName={page.pluginName}
|
||||
viewId={page.viewId}
|
||||
open={aiSidebarOpen}
|
||||
onClose={handleCloseAiSidebar}
|
||||
pluginContext={turnContext}
|
||||
suggestedPrompts={suggestedPrompts}
|
||||
pendingPrompt={pendingPrompt}
|
||||
onPendingPromptConsumed={handlePendingPromptConsumed}
|
||||
/>
|
||||
)}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
formatPluginViewBadgeLabel,
|
||||
isPluginViewBadgeVisible,
|
||||
type PluginViewBadgeDisplay,
|
||||
type PluginViewBadgeTone,
|
||||
} from '../../domain/pluginViewBadge';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
const TONE_CLASSES: Record<PluginViewBadgeTone, string> = {
|
||||
default: 'bg-primary text-primary-foreground',
|
||||
info: 'bg-sky-600 text-white dark:bg-sky-500 dark:text-white',
|
||||
warning: 'bg-amber-500 text-zinc-950',
|
||||
danger: 'bg-red-500 text-white dark:bg-red-500 dark:text-white',
|
||||
};
|
||||
|
||||
export interface PluginViewBadgeProps {
|
||||
badge: PluginViewBadgeDisplay | null | undefined;
|
||||
/**
|
||||
* - `inline`: expanded left sidebar row pill/dot aligned right
|
||||
* - `overlay`: collapsed left sidebar icon rail corner badge
|
||||
* - `compact-overlay`: compact 24px terminal sidebar launcher corner badge
|
||||
*/
|
||||
variant: 'inline' | 'overlay' | 'compact-overlay';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const PluginViewBadge: React.FC<PluginViewBadgeProps> = ({
|
||||
badge,
|
||||
variant,
|
||||
className,
|
||||
}) => {
|
||||
if (!isPluginViewBadgeVisible(badge)) return null;
|
||||
const label = formatPluginViewBadgeLabel(badge);
|
||||
const toneClass = TONE_CLASSES[badge.tone] ?? TONE_CLASSES.default;
|
||||
|
||||
if (label === null) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
data-plugin-view-badge="dot"
|
||||
data-plugin-view-badge-tone={badge.tone}
|
||||
className={cn(
|
||||
'pointer-events-none shrink-0 rounded-full',
|
||||
toneClass,
|
||||
variant === 'inline' && 'ml-auto h-2 w-2',
|
||||
variant === 'overlay' && 'absolute -top-0.5 -right-0.5 h-2 w-2 ring-2 ring-secondary',
|
||||
variant === 'compact-overlay' && 'absolute -top-0.5 -right-0.5 h-1.5 w-1.5 ring-1 ring-background',
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
data-plugin-view-badge={label}
|
||||
data-plugin-view-badge-tone={badge.tone}
|
||||
className={cn(
|
||||
'pointer-events-none shrink-0 inline-flex items-center justify-center rounded-full font-semibold leading-none tabular-nums select-none',
|
||||
toneClass,
|
||||
variant === 'inline' && 'ml-auto min-w-[18px] h-[18px] px-1.5 text-[10px]',
|
||||
variant === 'overlay' && 'absolute -top-1.5 -right-2 min-w-[15px] h-[15px] px-1 text-[9px] font-bold ring-2 ring-secondary',
|
||||
variant === 'compact-overlay' && 'absolute -top-1 -right-1 min-w-[13px] h-[13px] px-0.5 text-[8px] font-bold ring-1 ring-background',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,195 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
function installDom() {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
|
||||
pretendToBeVisual: true,
|
||||
url: 'http://localhost',
|
||||
});
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const install = (key: string, value: unknown) => {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of [
|
||||
'window',
|
||||
'document',
|
||||
'navigator',
|
||||
'HTMLElement',
|
||||
'HTMLButtonElement',
|
||||
'Element',
|
||||
'SVGElement',
|
||||
'Node',
|
||||
'NodeFilter',
|
||||
'MutationObserver',
|
||||
'CustomEvent',
|
||||
'Event',
|
||||
'KeyboardEvent',
|
||||
'MouseEvent',
|
||||
'XMLSerializer',
|
||||
]) {
|
||||
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
install('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
|
||||
install('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => new dom.window.DOMRect(0, 0, 640, 320);
|
||||
|
||||
return {
|
||||
dom,
|
||||
cleanup() {
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('PluginBiChart renders all 10 chart types, supports datumClick cross-filtering, legend toggle, activeFilter, and SVG export', async () => {
|
||||
const env = installDom();
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { PluginBiChart, formatBiValue } = await import('./PluginBiChart');
|
||||
|
||||
assert.equal(formatBiValue(12500, 'currency', 'USD'), '$12.5K');
|
||||
assert.equal(formatBiValue(0.425, 'percent'), '42.5%');
|
||||
assert.equal(formatBiValue(2048, 'bytes'), '2.0 KiB');
|
||||
assert.equal(formatBiValue(1500, 'ms'), '1.50 s');
|
||||
assert.equal(formatBiValue(Number.NaN), '--');
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const events: Array<{ name: string; detail?: Record<string, unknown> }> = [];
|
||||
const onWidgetEvent = (name: string, detail?: Record<string, unknown>) => {
|
||||
events.push({ name, detail });
|
||||
};
|
||||
|
||||
try {
|
||||
const cartesianTypes = ['bar', 'horizontal-bar', 'stacked-bar', 'line', 'area', 'combo'] as const;
|
||||
for (const type of cartesianTypes) {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<PluginBiChart
|
||||
type={type}
|
||||
title={`Test ${type}`}
|
||||
categories={['APAC', 'EMEA', 'NA']}
|
||||
series={[
|
||||
{ id: 'rev', name: 'Revenue', data: [1200, 1800, 2400], renderAs: 'bar', yAxis: 'left', color: 'sky', format: 'currency', currency: 'USD' },
|
||||
{ id: 'orders', name: 'Orders', data: [42, 68, 95], renderAs: 'line', yAxis: 'right', color: 'amber', format: 'compact' },
|
||||
]}
|
||||
xAxisLabel="Region"
|
||||
yAxisLabel="Revenue"
|
||||
yAxisRightLabel="Orders"
|
||||
showDataLabels
|
||||
smooth
|
||||
onWidgetEvent={onWidgetEvent}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
assert.ok(document.querySelector(`[data-plugin-bi-chart="${type}"] svg`), `${type} should render an SVG`);
|
||||
assert.ok(document.querySelector('[data-bi-datum="0:1"]'), `${type} should render clickable datum markers`);
|
||||
}
|
||||
|
||||
// Click datum on combo chart and verify cross-filter event payload
|
||||
events.length = 0;
|
||||
const datum = document.querySelector<SVGElement>('[data-bi-datum="0:1"]')!;
|
||||
await act(async () => {
|
||||
datum.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].name, 'datumClick');
|
||||
assert.deepEqual(events[0].detail, {
|
||||
seriesIndex: 0,
|
||||
seriesName: 'Revenue',
|
||||
datumIndex: 1,
|
||||
category: 'EMEA',
|
||||
value: 1800,
|
||||
});
|
||||
|
||||
// Toggle legend series locally and verify series hides
|
||||
const legendBtn = document.querySelector<HTMLButtonElement>('[data-bi-legend-series="orders"]')!;
|
||||
assert.equal(legendBtn.getAttribute('aria-pressed'), 'true');
|
||||
await act(async () => {
|
||||
legendBtn.click();
|
||||
});
|
||||
assert.equal(legendBtn.getAttribute('aria-pressed'), 'false');
|
||||
|
||||
// Pie, Donut, Funnel, Scatter + activeFilter dimming + SVG export
|
||||
for (const type of ['pie', 'donut', 'funnel'] as const) {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<PluginBiChart
|
||||
type={type}
|
||||
title={`Test ${type}`}
|
||||
categories={['Visited', 'Signed Up', 'Paid']}
|
||||
series={[{ id: 's', name: 'Users', data: [1000, 420, 110] }]}
|
||||
activeFilter={{ category: 'Signed Up' }}
|
||||
showDataLabels
|
||||
onWidgetEvent={onWidgetEvent}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
const matchedEl = document.querySelector<SVGElement>('[data-bi-datum="0:1"]')!;
|
||||
const dimmedEl = document.querySelector<SVGElement>('[data-bi-datum="0:0"]')!;
|
||||
assert.ok(Number(matchedEl.getAttribute('opacity')) > 0.8, `${type} matched datum stays bright`);
|
||||
assert.ok(Number(dimmedEl.getAttribute('opacity')) < 0.4, `${type} non-matched datum dims`);
|
||||
}
|
||||
|
||||
// Scatter with bubble size + NaN/Infinity filtering
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<PluginBiChart
|
||||
type="scatter"
|
||||
title="Latency vs Throughput"
|
||||
series={[
|
||||
{
|
||||
id: 'nodes',
|
||||
name: 'Nodes',
|
||||
points: [
|
||||
{ x: 10, y: 200, label: 'node-a', size: 8 },
|
||||
{ x: Number.NaN, y: 100, label: 'bad' },
|
||||
{ x: 25, y: 450, label: 'node-b', size: 99 },
|
||||
],
|
||||
},
|
||||
]}
|
||||
onWidgetEvent={onWidgetEvent}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
const scatterDots = document.querySelectorAll('[data-bi-datum]');
|
||||
assert.equal(scatterDots.length, 2, 'scatter filters out non-finite points');
|
||||
assert.equal(scatterDots[1].getAttribute('r'), '14', 'bubble radius clamps at 14');
|
||||
|
||||
// Export SVG emits bounded standalone SVG string
|
||||
events.length = 0;
|
||||
const exportSvgBtn = document.querySelector<HTMLButtonElement>('[data-bi-export-svg]')!;
|
||||
await act(async () => {
|
||||
exportSvgBtn.click();
|
||||
});
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].name, 'exportSvg');
|
||||
assert.match(String(events[0].detail?.svg), /^<svg[^>]+xmlns="http:\/\/www\.w3\.org\/2000\/svg"/);
|
||||
assert.equal(events[0].detail?.suggestedName, 'latency-vs-throughput.svg');
|
||||
|
||||
// Empty state
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<PluginBiChart
|
||||
type="bar"
|
||||
categories={[]}
|
||||
series={[]}
|
||||
emptyText="Nothing to chart"
|
||||
onWidgetEvent={onWidgetEvent}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
assert.match(document.body.textContent ?? '', /Nothing to chart/);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,7 +3,17 @@ import React, { Suspense, lazy } from 'react';
|
||||
import { LazyLoadBoundary } from '../../ui/lazy-load-boundary';
|
||||
import type { PluginCodeEditorWidgetProps, PluginWidgetEventCallback } from './types';
|
||||
|
||||
const LazyPluginCodeEditorInner = lazy(() => import('./PluginCodeEditorInner'));
|
||||
let preloadEditorPromise: Promise<unknown> | null = null;
|
||||
const loadPluginCodeEditorInner = () => {
|
||||
preloadEditorPromise ??= import('./PluginCodeEditorInner');
|
||||
return preloadEditorPromise as Promise<{ default: typeof import('./PluginCodeEditorInner').default }>;
|
||||
};
|
||||
|
||||
export function preloadPluginCodeEditor(): void {
|
||||
void loadPluginCodeEditorInner().catch(() => { preloadEditorPromise = null; });
|
||||
}
|
||||
|
||||
const LazyPluginCodeEditorInner = lazy(loadPluginCodeEditorInner);
|
||||
|
||||
export interface PluginCodeEditorProps extends PluginCodeEditorWidgetProps {
|
||||
onWidgetEvent: PluginWidgetEventCallback;
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { PluginMetricChart, formatMetricValue } from './PluginMetricChart';
|
||||
|
||||
test('PluginMetricChart renders area, sparkline, bar, thresholds, and bounds extreme input safely', () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(PluginMetricChart, {
|
||||
variant: 'area',
|
||||
height: 160,
|
||||
rangeMs: 300_000,
|
||||
intervalMs: 5_000,
|
||||
endAt: now,
|
||||
showLegend: true,
|
||||
showAxes: true,
|
||||
thresholds: [
|
||||
{ value: 80, tone: 'warning', label: 'Warn' },
|
||||
{ value: 95, tone: 'critical', label: 'Crit' },
|
||||
],
|
||||
series: [
|
||||
{
|
||||
id: 'cpu',
|
||||
label: 'CPU',
|
||||
color: 'sky',
|
||||
unit: '%',
|
||||
points: [
|
||||
{ at: now - 15_000, value: 22.5 },
|
||||
{ at: now - 10_000, value: 48.2 },
|
||||
{ at: now - 5_000, value: null },
|
||||
{ at: now, value: 64.0 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'mem',
|
||||
label: 'Memory',
|
||||
color: 'emerald',
|
||||
unit: '%',
|
||||
points: [
|
||||
{ at: now - 15_000, value: 51 },
|
||||
{ at: now, value: 53 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.match(html, /role="img"/);
|
||||
assert.match(html, /<svg/);
|
||||
assert.match(html, /CPU/);
|
||||
assert.match(html, /64\.0%/);
|
||||
assert.match(html, /Warn/);
|
||||
assert.match(html, /Crit/);
|
||||
|
||||
const sparkHtml = renderToStaticMarkup(
|
||||
React.createElement(PluginMetricChart, {
|
||||
variant: 'sparkline',
|
||||
height: 36,
|
||||
series: [{ id: 'rx', label: 'RX', unit: 'bytes/s', points: [{ at: now - 5000, value: 1024 }, { at: now, value: 4096 }] }],
|
||||
}),
|
||||
);
|
||||
assert.match(sparkHtml, /<svg/);
|
||||
assert.match(sparkHtml, /height:36px/);
|
||||
|
||||
const barHtml = renderToStaticMarkup(
|
||||
React.createElement(PluginMetricChart, {
|
||||
variant: 'bar',
|
||||
series: [{ id: 'load', label: 'Load', unit: 'count', points: [{ at: now - 5000, value: 2 }, { at: now, value: 5 }] }],
|
||||
}),
|
||||
);
|
||||
assert.match(barHtml, /<rect/);
|
||||
|
||||
// Empty state
|
||||
const emptyHtml = renderToStaticMarkup(
|
||||
React.createElement(PluginMetricChart, {
|
||||
variant: 'line',
|
||||
series: [{ id: 'empty', label: 'Empty', points: [] }],
|
||||
emptyText: 'No metrics yet',
|
||||
}),
|
||||
);
|
||||
assert.match(emptyHtml, /No metrics yet/);
|
||||
});
|
||||
|
||||
test('formatMetricValue formats percent, bytes/s, ms, temp, and count cleanly', () => {
|
||||
assert.equal(formatMetricValue(null, '%'), '--');
|
||||
assert.equal(formatMetricValue(42.34, '%'), '42.3%');
|
||||
assert.equal(formatMetricValue(100, '%'), '100%');
|
||||
assert.equal(formatMetricValue(2048, 'bytes/s'), '2.0 KiB/s');
|
||||
assert.equal(formatMetricValue(3 * 1024 * 1024, 'bytes/s'), '3.0 MiB/s');
|
||||
assert.equal(formatMetricValue(42, 'ms'), '42 ms');
|
||||
assert.equal(formatMetricValue(1500, 'ms'), '1.50 s');
|
||||
assert.equal(formatMetricValue(63.4, 'temp'), '63.4 C');
|
||||
assert.equal(formatMetricValue(2500, 'count'), '2.5k');
|
||||
});
|
||||
@@ -0,0 +1,722 @@
|
||||
import React, { useId, useMemo, useRef, useState, useEffect, useCallback } from 'react';
|
||||
import type {
|
||||
PluginMetricChartColor,
|
||||
PluginMetricChartPoint,
|
||||
PluginMetricChartSeries,
|
||||
PluginMetricChartThreshold,
|
||||
PluginMetricChartUnit,
|
||||
PluginMetricChartWidgetProps,
|
||||
} from './types';
|
||||
|
||||
const MAX_SERIES = 16;
|
||||
const MAX_POINTS_PER_SERIES = 2000;
|
||||
const MAX_THRESHOLDS = 8;
|
||||
const MIN_HEIGHT = 24;
|
||||
const MAX_HEIGHT = 480;
|
||||
const DEFAULT_WIDTH = 360;
|
||||
const DOWNSAMPLE_BUCKETS = 180;
|
||||
|
||||
const COLOR_MAP: Record<PluginMetricChartColor, string> = {
|
||||
primary: 'hsl(var(--primary))',
|
||||
sky: '#0ea5e9',
|
||||
emerald: '#10b981',
|
||||
amber: '#f59e0b',
|
||||
violet: '#8b5cf6',
|
||||
rose: '#f43f5e',
|
||||
cyan: '#06b6d4',
|
||||
muted: 'hsl(var(--muted-foreground))',
|
||||
};
|
||||
|
||||
const DEFAULT_COLOR_CYCLE: PluginMetricChartColor[] = [
|
||||
'sky',
|
||||
'emerald',
|
||||
'amber',
|
||||
'violet',
|
||||
'rose',
|
||||
'cyan',
|
||||
'primary',
|
||||
'muted',
|
||||
];
|
||||
|
||||
function resolveColor(color: PluginMetricChartColor | undefined, index: number): string {
|
||||
if (color && Object.hasOwn(COLOR_MAP, color)) {
|
||||
return COLOR_MAP[color];
|
||||
}
|
||||
return COLOR_MAP[DEFAULT_COLOR_CYCLE[index % DEFAULT_COLOR_CYCLE.length]];
|
||||
}
|
||||
|
||||
export function formatMetricValue(value: number | null | undefined, unit: PluginMetricChartUnit = ''): string {
|
||||
if (value == null || !Number.isFinite(value)) return '--';
|
||||
if (unit === '%') {
|
||||
return `${value.toFixed(value >= 100 || value === 0 ? 0 : 1)}%`;
|
||||
}
|
||||
if (unit === 'ms') {
|
||||
return value >= 1000 ? `${(value / 1000).toFixed(2)} s` : `${Math.round(value)} ms`;
|
||||
}
|
||||
if (unit === 'temp') {
|
||||
return `${value.toFixed(1)} C`;
|
||||
}
|
||||
if (unit === 'bytes/s' || unit === 'bytes') {
|
||||
const suffix = unit === 'bytes/s' ? '/s' : '';
|
||||
const abs = Math.abs(value);
|
||||
if (abs >= 1024 ** 3) return `${(value / (1024 ** 3)).toFixed(2)} GiB${suffix}`;
|
||||
if (abs >= 1024 ** 2) return `${(value / (1024 ** 2)).toFixed(1)} MiB${suffix}`;
|
||||
if (abs >= 1024) return `${(value / 1024).toFixed(1)} KiB${suffix}`;
|
||||
return `${Math.round(value)} B${suffix}`;
|
||||
}
|
||||
if (unit === 'count') {
|
||||
if (Math.abs(value) >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
|
||||
if (Math.abs(value) >= 1_000) return `${(value / 1_000).toFixed(1)}k`;
|
||||
return Number.isInteger(value) ? String(value) : value.toFixed(1);
|
||||
}
|
||||
return Math.abs(value) >= 100 ? value.toFixed(0) : value.toFixed(1);
|
||||
}
|
||||
|
||||
function formatClockTime(epochMs: number): string {
|
||||
if (!Number.isFinite(epochMs)) return '';
|
||||
const date = new Date(epochMs);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
const hh = String(date.getHours()).padStart(2, '0');
|
||||
const mm = String(date.getMinutes()).padStart(2, '0');
|
||||
const ss = String(date.getSeconds()).padStart(2, '0');
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
interface CleanSeries {
|
||||
id: string;
|
||||
label: string;
|
||||
color: string;
|
||||
unit: PluginMetricChartUnit;
|
||||
points: Array<{ at: number; value: number | null }>;
|
||||
latestValue: number | null;
|
||||
}
|
||||
|
||||
interface PlotSegment {
|
||||
linePath: string;
|
||||
areaPath: string;
|
||||
lastX: number;
|
||||
lastY: number;
|
||||
}
|
||||
|
||||
function sanitizeSeries(raw: PluginMetricChartSeries[] | undefined): CleanSeries[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
const limited = raw.slice(0, MAX_SERIES);
|
||||
const seenIds = new Set<string>();
|
||||
return limited
|
||||
.filter((item): item is PluginMetricChartSeries => Boolean(item && typeof item === 'object'))
|
||||
.map((item, idx) => {
|
||||
const rawPoints = Array.isArray(item.points) ? item.points.slice(-MAX_POINTS_PER_SERIES) : [];
|
||||
const points: Array<{ at: number; value: number | null }> = [];
|
||||
for (const pt of rawPoints) {
|
||||
if (!pt || typeof pt !== 'object' || typeof pt.at !== 'number' || !Number.isFinite(pt.at)) continue;
|
||||
const val = typeof pt.value === 'number' && Number.isFinite(pt.value) ? pt.value : null;
|
||||
points.push({ at: pt.at, value: val });
|
||||
}
|
||||
points.sort((a, b) => a.at - b.at);
|
||||
let latestValue: number | null = null;
|
||||
for (let i = points.length - 1; i >= 0; i -= 1) {
|
||||
if (points[i].value !== null) {
|
||||
latestValue = points[i].value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const baseId = typeof item.id === 'string' && item.id ? item.id : `series-${idx}`;
|
||||
const uniqueId = seenIds.has(baseId) ? `${baseId}-${idx}` : baseId;
|
||||
seenIds.add(uniqueId);
|
||||
return {
|
||||
id: uniqueId,
|
||||
label: typeof item.label === 'string' && item.label ? item.label : `Series ${idx + 1}`,
|
||||
color: resolveColor(item.color, idx),
|
||||
unit: item.unit ?? '',
|
||||
points,
|
||||
latestValue,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function sanitizeThresholds(raw: PluginMetricChartThreshold[] | undefined): PluginMetricChartThreshold[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw
|
||||
.slice(0, MAX_THRESHOLDS)
|
||||
.filter(
|
||||
(t): t is PluginMetricChartThreshold =>
|
||||
Boolean(t && typeof t === 'object' && typeof t.value === 'number' && Number.isFinite(t.value) && (t.tone === 'warning' || t.tone === 'critical')),
|
||||
);
|
||||
}
|
||||
|
||||
function buildSegments(
|
||||
points: PluginMetricChartPoint[],
|
||||
startAt: number,
|
||||
endAt: number,
|
||||
yMin: number,
|
||||
yMax: number,
|
||||
gapThresholdMs: number,
|
||||
plotLeft: number,
|
||||
plotTop: number,
|
||||
plotWidth: number,
|
||||
plotHeight: number,
|
||||
): PlotSegment[] {
|
||||
const spanX = Math.max(1, endAt - startAt);
|
||||
const spanY = Math.max(1e-9, yMax - yMin);
|
||||
const visible = points.filter((p) => p.at >= startAt && p.at <= endAt);
|
||||
|
||||
const runs: Array<Array<{ at: number; value: number }>> = [];
|
||||
let currentRun: Array<{ at: number; value: number }> = [];
|
||||
for (const pt of visible) {
|
||||
if (pt.value === null || !Number.isFinite(pt.value)) {
|
||||
if (currentRun.length > 0) {
|
||||
runs.push(currentRun);
|
||||
currentRun = [];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (currentRun.length > 0 && pt.at - currentRun[currentRun.length - 1].at > gapThresholdMs) {
|
||||
runs.push(currentRun);
|
||||
currentRun = [];
|
||||
}
|
||||
currentRun.push({ at: pt.at, value: pt.value });
|
||||
}
|
||||
if (currentRun.length > 0) runs.push(currentRun);
|
||||
|
||||
const baseY = plotTop + plotHeight;
|
||||
return runs.map((samples) => {
|
||||
const selected = new Set([samples[0], samples[samples.length - 1]]);
|
||||
if (samples.length > DOWNSAMPLE_BUCKETS) {
|
||||
const buckets = new Map<number, { min: (typeof samples)[number]; max: (typeof samples)[number] }>();
|
||||
for (const sample of samples) {
|
||||
const col = Math.min(DOWNSAMPLE_BUCKETS - 1, Math.max(0, Math.floor(((sample.at - startAt) / spanX) * DOWNSAMPLE_BUCKETS)));
|
||||
const bucket = buckets.get(col);
|
||||
if (!bucket) {
|
||||
buckets.set(col, { min: sample, max: sample });
|
||||
} else {
|
||||
if (sample.value < bucket.min.value) bucket.min = sample;
|
||||
if (sample.value > bucket.max.value) bucket.max = sample;
|
||||
}
|
||||
}
|
||||
for (const bucket of buckets.values()) {
|
||||
selected.add(bucket.min);
|
||||
selected.add(bucket.max);
|
||||
}
|
||||
} else {
|
||||
for (const sample of samples) selected.add(sample);
|
||||
}
|
||||
|
||||
const coords = samples
|
||||
.filter((sample) => selected.has(sample))
|
||||
.map((sample) => {
|
||||
const ratioX = Math.max(0, Math.min(1, (sample.at - startAt) / spanX));
|
||||
const clampedY = Math.max(yMin, Math.min(yMax, sample.value));
|
||||
const ratioY = (clampedY - yMin) / spanY;
|
||||
return {
|
||||
x: plotLeft + ratioX * plotWidth,
|
||||
y: plotTop + plotHeight - ratioY * plotHeight,
|
||||
};
|
||||
});
|
||||
|
||||
const linePath = coords
|
||||
.map((pt, i) => `${i === 0 ? 'M' : 'L'} ${pt.x.toFixed(2)} ${pt.y.toFixed(2)}`)
|
||||
.join(' ');
|
||||
const first = coords[0];
|
||||
const last = coords[coords.length - 1];
|
||||
const areaPath = coords.length > 1
|
||||
? `${linePath} L ${last.x.toFixed(2)} ${baseY.toFixed(2)} L ${first.x.toFixed(2)} ${baseY.toFixed(2)} Z`
|
||||
: '';
|
||||
return { linePath, areaPath, lastX: last.x, lastY: last.y };
|
||||
});
|
||||
}
|
||||
|
||||
export function PluginMetricChart(props: PluginMetricChartWidgetProps) {
|
||||
const uid = useId().replace(/[^a-zA-Z0-9_-]/g, '');
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [width, setWidth] = useState<number>(DEFAULT_WIDTH);
|
||||
const [hoverX, setHoverX] = useState<number | null>(null);
|
||||
|
||||
const variant = props.variant ?? 'area';
|
||||
const isSparkline = variant === 'sparkline';
|
||||
const showAxes = props.showAxes ?? !isSparkline;
|
||||
const showGrid = props.showGrid ?? !isSparkline;
|
||||
const showLegend = props.showLegend ?? (!isSparkline && (props.series?.length ?? 0) > 1);
|
||||
const interactive = props.interactive ?? !isSparkline;
|
||||
const chartHeight = Math.max(
|
||||
MIN_HEIGHT,
|
||||
Math.min(MAX_HEIGHT, typeof props.height === 'number' && Number.isFinite(props.height) ? props.height : (isSparkline ? 40 : 160)),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const el = containerRef.current;
|
||||
if (!el) return;
|
||||
const updateWidth = () => {
|
||||
const rect = el.getBoundingClientRect();
|
||||
if (rect.width > 16) setWidth(Math.round(rect.width));
|
||||
};
|
||||
updateWidth();
|
||||
if (typeof ResizeObserver === 'function') {
|
||||
const observer = new ResizeObserver(updateWidth);
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}
|
||||
return undefined;
|
||||
}, []);
|
||||
|
||||
const series = useMemo(() => sanitizeSeries(props.series), [props.series]);
|
||||
const thresholds = useMemo(() => sanitizeThresholds(props.thresholds), [props.thresholds]);
|
||||
|
||||
const { startAt, endAt, yMin, yMax, hasData, primaryUnit } = useMemo(() => {
|
||||
let minAt = Infinity;
|
||||
let maxAt = -Infinity;
|
||||
let maxVal = -Infinity;
|
||||
let minVal = Infinity;
|
||||
let dataPoints = 0;
|
||||
|
||||
for (const s of series) {
|
||||
for (const p of s.points) {
|
||||
if (p.at < minAt) minAt = p.at;
|
||||
if (p.at > maxAt) maxAt = p.at;
|
||||
if (p.value !== null) {
|
||||
dataPoints += 1;
|
||||
if (p.value > maxVal) maxVal = p.value;
|
||||
if (p.value < minVal) minVal = p.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const resolvedEnd = typeof props.endAt === 'number' && Number.isFinite(props.endAt)
|
||||
? props.endAt
|
||||
: (Number.isFinite(maxAt) ? maxAt : Date.now());
|
||||
const rawDataSpan = Number.isFinite(minAt) && resolvedEnd > minAt ? resolvedEnd - minAt : NaN;
|
||||
const resolvedRange = typeof props.rangeMs === 'number' && Number.isFinite(props.rangeMs) && props.rangeMs > 0
|
||||
? props.rangeMs
|
||||
: (Number.isFinite(rawDataSpan) ? Math.max(1000, rawDataSpan) : 5 * 60_000);
|
||||
const candidateStart = resolvedEnd - resolvedRange;
|
||||
const resolvedStart = Number.isFinite(candidateStart) && Number.isFinite(resolvedEnd - candidateStart)
|
||||
? candidateStart
|
||||
: resolvedEnd - 5 * 60_000;
|
||||
|
||||
const unit = series[0]?.unit ?? '';
|
||||
const rawMin = typeof props.min === 'number' && Number.isFinite(props.min)
|
||||
? props.min
|
||||
: (Number.isFinite(minVal) && minVal < 0 ? (Number.isFinite(minVal * 1.1) ? minVal * 1.1 : minVal) : 0);
|
||||
let resolvedMin = Number.isFinite(rawMin) ? rawMin : 0;
|
||||
|
||||
let resolvedMax: number;
|
||||
if (typeof props.max === 'number' && Number.isFinite(props.max)) {
|
||||
resolvedMax = props.max;
|
||||
} else if (unit === '%' && (!Number.isFinite(maxVal) || maxVal <= 100)) {
|
||||
resolvedMax = 100;
|
||||
} else {
|
||||
let peak = Number.isFinite(maxVal) ? maxVal : 1;
|
||||
for (const t of thresholds) {
|
||||
if (t.value > peak) peak = t.value;
|
||||
}
|
||||
if (peak <= resolvedMin) {
|
||||
const padded = resolvedMin + (unit === 'ms' ? 10 : 1);
|
||||
resolvedMax = Number.isFinite(padded) ? padded : resolvedMin;
|
||||
} else {
|
||||
const paddedPeak = peak * 1.1;
|
||||
resolvedMax = Number.isFinite(paddedPeak) ? paddedPeak : peak;
|
||||
}
|
||||
}
|
||||
|
||||
if (!Number.isFinite(resolvedMax - resolvedMin) || resolvedMax <= resolvedMin) {
|
||||
resolvedMin = 0;
|
||||
resolvedMax = 100;
|
||||
}
|
||||
|
||||
return {
|
||||
startAt: resolvedStart,
|
||||
endAt: resolvedEnd,
|
||||
yMin: resolvedMin,
|
||||
yMax: resolvedMax,
|
||||
hasData: dataPoints > 0,
|
||||
primaryUnit: unit,
|
||||
};
|
||||
}, [series, thresholds, props.endAt, props.rangeMs, props.min, props.max]);
|
||||
|
||||
const gapThresholdMs = useMemo(() => {
|
||||
const interval = typeof props.intervalMs === 'number' && Number.isFinite(props.intervalMs) && props.intervalMs > 0
|
||||
? props.intervalMs
|
||||
: 5000;
|
||||
return Math.max(5000, interval * 2.5);
|
||||
}, [props.intervalMs]);
|
||||
|
||||
const padLeft = showAxes ? 52 : (isSparkline ? 2 : 8);
|
||||
const padRight = showAxes ? 12 : (isSparkline ? 2 : 8);
|
||||
const padTop = isSparkline ? 3 : 10;
|
||||
const padBottom = showAxes ? 22 : (isSparkline ? 3 : 8);
|
||||
const svgHeight = Math.max(20, chartHeight - (showLegend ? 24 : 0));
|
||||
const plotWidth = Math.max(20, width - padLeft - padRight);
|
||||
const plotHeight = Math.max(12, svgHeight - padTop - padBottom);
|
||||
|
||||
const seriesSegments = useMemo(() => (
|
||||
series.map((s) => ({
|
||||
series: s,
|
||||
segments: buildSegments(
|
||||
s.points,
|
||||
startAt,
|
||||
endAt,
|
||||
yMin,
|
||||
yMax,
|
||||
gapThresholdMs,
|
||||
padLeft,
|
||||
padTop,
|
||||
plotWidth,
|
||||
plotHeight,
|
||||
),
|
||||
}))
|
||||
), [series, startAt, endAt, yMin, yMax, gapThresholdMs, padLeft, padTop, plotWidth, plotHeight]);
|
||||
|
||||
const hoverSnapshot = useMemo(() => {
|
||||
if (!interactive || hoverX === null || !hasData) return null;
|
||||
const ratio = Math.max(0, Math.min(1, (hoverX - padLeft) / plotWidth));
|
||||
const targetAt = startAt + ratio * (endAt - startAt);
|
||||
const tolerance = Math.max(gapThresholdMs, (endAt - startAt) * 0.04);
|
||||
|
||||
let snappedAt: number | null = null;
|
||||
const values: Array<{ id: string; label: string; color: string; value: number | null; unit: PluginMetricChartUnit; x: number; y: number | null }> = [];
|
||||
const spanX = Math.max(1, endAt - startAt);
|
||||
const spanY = Math.max(1e-9, yMax - yMin);
|
||||
|
||||
for (const s of series) {
|
||||
let closest: PluginMetricChartPoint | null = null;
|
||||
let bestDelta = tolerance;
|
||||
for (const pt of s.points) {
|
||||
if (pt.value === null || pt.at < startAt || pt.at > endAt) continue;
|
||||
const delta = Math.abs(pt.at - targetAt);
|
||||
if (delta <= bestDelta) {
|
||||
bestDelta = delta;
|
||||
closest = pt;
|
||||
}
|
||||
}
|
||||
if (closest && closest.value !== null) {
|
||||
if (snappedAt === null) snappedAt = closest.at;
|
||||
const rx = Math.max(0, Math.min(1, (closest.at - startAt) / spanX));
|
||||
const ry = (Math.max(yMin, Math.min(yMax, closest.value)) - yMin) / spanY;
|
||||
values.push({
|
||||
id: s.id,
|
||||
label: s.label,
|
||||
color: s.color,
|
||||
value: closest.value,
|
||||
unit: s.unit,
|
||||
x: padLeft + rx * plotWidth,
|
||||
y: padTop + plotHeight - ry * plotHeight,
|
||||
});
|
||||
} else {
|
||||
values.push({
|
||||
id: s.id,
|
||||
label: s.label,
|
||||
color: s.color,
|
||||
value: null,
|
||||
unit: s.unit,
|
||||
x: hoverX,
|
||||
y: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (snappedAt === null) return null;
|
||||
const snappedX = padLeft + Math.max(0, Math.min(1, (snappedAt - startAt) / spanX)) * plotWidth;
|
||||
return { at: snappedAt, x: snappedX, values };
|
||||
}, [interactive, hoverX, hasData, padLeft, padTop, plotWidth, plotHeight, startAt, endAt, yMin, yMax, gapThresholdMs, series]);
|
||||
|
||||
const handlePointerMove = useCallback((event: React.PointerEvent<SVGSVGElement>) => {
|
||||
if (!interactive) return;
|
||||
const rect = event.currentTarget.getBoundingClientRect();
|
||||
const x = event.clientX - rect.left;
|
||||
if (x >= padLeft && x <= padLeft + plotWidth) {
|
||||
setHoverX(x);
|
||||
} else {
|
||||
setHoverX(null);
|
||||
}
|
||||
}, [interactive, padLeft, plotWidth]);
|
||||
|
||||
const handlePointerLeave = useCallback(() => {
|
||||
setHoverX(null);
|
||||
}, []);
|
||||
|
||||
const yTicks = useMemo(() => {
|
||||
if (!showAxes) return [];
|
||||
const mid = yMin + (yMax - yMin) / 2;
|
||||
return [
|
||||
{ value: yMax, y: padTop },
|
||||
{ value: mid, y: padTop + plotHeight / 2 },
|
||||
{ value: yMin, y: padTop + plotHeight },
|
||||
];
|
||||
}, [showAxes, yMin, yMax, padTop, plotHeight]);
|
||||
|
||||
const xTicks = useMemo(() => {
|
||||
if (!showAxes) return [];
|
||||
const mid = startAt + (endAt - startAt) / 2;
|
||||
return [
|
||||
{ at: startAt, x: padLeft, anchor: 'start' as const },
|
||||
{ at: mid, x: padLeft + plotWidth / 2, anchor: 'middle' as const },
|
||||
{ at: endAt, x: padLeft + plotWidth, anchor: 'end' as const },
|
||||
];
|
||||
}, [showAxes, startAt, endAt, padLeft, plotWidth]);
|
||||
|
||||
const barItems = useMemo(() => {
|
||||
if (variant !== 'bar' || !hasData) return [];
|
||||
const timestamps = Array.from(
|
||||
new Set(
|
||||
series.flatMap((s) =>
|
||||
s.points
|
||||
.filter((p) => p.at >= startAt && p.at <= endAt && p.value !== null)
|
||||
.map((p) => p.at),
|
||||
),
|
||||
),
|
||||
).sort((a, b) => a - b);
|
||||
const maxGroups = Math.min(timestamps.length, 48);
|
||||
const step = timestamps.length > maxGroups ? Math.ceil(timestamps.length / maxGroups) : 1;
|
||||
const sampledTs = timestamps.filter((_ts, i) => i % step === 0);
|
||||
if (sampledTs.length === 0) return [];
|
||||
const groupWidth = Math.max(4, plotWidth / sampledTs.length);
|
||||
const innerWidth = Math.max(2, (groupWidth * 0.78) / Math.max(1, series.length));
|
||||
const spanY = Math.max(1e-9, yMax - yMin);
|
||||
const bars: Array<{ key: string; x: number; y: number; w: number; h: number; color: string }> = [];
|
||||
|
||||
sampledTs.forEach((ts, groupIdx) => {
|
||||
const groupStart = padLeft + groupIdx * groupWidth + groupWidth * 0.11;
|
||||
series.forEach((s, seriesIdx) => {
|
||||
const pt = s.points.find((candidate) => candidate.at === ts);
|
||||
if (!pt || pt.value === null) return;
|
||||
const clamped = Math.max(yMin, Math.min(yMax, pt.value));
|
||||
const barH = Math.max(1, ((clamped - yMin) / spanY) * plotHeight);
|
||||
bars.push({
|
||||
key: `${s.id}-${ts}`,
|
||||
x: groupStart + seriesIdx * innerWidth,
|
||||
y: padTop + plotHeight - barH,
|
||||
w: Math.max(1.5, innerWidth - 1),
|
||||
h: barH,
|
||||
color: s.color,
|
||||
});
|
||||
});
|
||||
});
|
||||
return bars;
|
||||
}, [variant, hasData, series, startAt, endAt, yMin, yMax, padLeft, padTop, plotWidth, plotHeight]);
|
||||
|
||||
const tooltipLeft = hoverSnapshot
|
||||
? (hoverSnapshot.x > width * 0.62 ? Math.max(4, hoverSnapshot.x - 168) : Math.max(4, Math.min(width - 164, hoverSnapshot.x + 10)))
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="relative flex w-full flex-col select-none overflow-hidden text-foreground"
|
||||
style={{ height: `${chartHeight}px` }}
|
||||
role="img"
|
||||
aria-label={props.ariaLabel ?? series.map((s) => s.label).join(', ')}
|
||||
>
|
||||
{showLegend && (
|
||||
<div className="flex h-6 shrink-0 items-center justify-between gap-2 px-1 text-[11px] text-muted-foreground">
|
||||
<div className="flex min-w-0 items-center gap-3 overflow-hidden">
|
||||
{series.map((s) => (
|
||||
<span key={s.id} className="inline-flex min-w-0 items-center gap-1.5 truncate">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: s.color }} />
|
||||
<span className="truncate">{s.label}</span>
|
||||
<span className="font-mono text-foreground">{formatMetricValue(s.latestValue, s.unit)}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<svg
|
||||
width={width}
|
||||
height={svgHeight}
|
||||
viewBox={`0 0 ${width} ${svgHeight}`}
|
||||
className="block h-full w-full overflow-visible"
|
||||
onPointerMove={interactive ? handlePointerMove : undefined}
|
||||
onPointerLeave={interactive ? handlePointerLeave : undefined}
|
||||
>
|
||||
<defs>
|
||||
{series.map((s, idx) => (
|
||||
<linearGradient key={s.id} id={`nc-mc-grad-${uid}-${idx}`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor={s.color} stopOpacity={isSparkline ? 0.28 : 0.24} />
|
||||
<stop offset="100%" stopColor={s.color} stopOpacity={0.01} />
|
||||
</linearGradient>
|
||||
))}
|
||||
</defs>
|
||||
|
||||
{showGrid && yTicks.map((tick, idx) => (
|
||||
<line
|
||||
key={`grid-${idx}`}
|
||||
x1={padLeft}
|
||||
y1={tick.y}
|
||||
x2={padLeft + plotWidth}
|
||||
y2={tick.y}
|
||||
stroke="hsl(var(--border))"
|
||||
strokeOpacity={0.55}
|
||||
strokeWidth={1}
|
||||
strokeDasharray={idx === yTicks.length - 1 ? undefined : '2 3'}
|
||||
/>
|
||||
))}
|
||||
|
||||
{thresholds.map((t, idx) => {
|
||||
if (t.value < yMin || t.value > yMax) return null;
|
||||
const y = padTop + plotHeight - ((t.value - yMin) / Math.max(1e-9, yMax - yMin)) * plotHeight;
|
||||
const stroke = t.tone === 'critical' ? '#f43f5e' : '#f59e0b';
|
||||
return (
|
||||
<g key={`thr-${idx}`}>
|
||||
<line
|
||||
x1={padLeft}
|
||||
y1={y}
|
||||
x2={padLeft + plotWidth}
|
||||
y2={y}
|
||||
stroke={stroke}
|
||||
strokeOpacity={0.75}
|
||||
strokeWidth={1}
|
||||
strokeDasharray="4 3"
|
||||
/>
|
||||
{t.label && !isSparkline && (
|
||||
<text
|
||||
x={padLeft + plotWidth - 2}
|
||||
y={Math.max(padTop + 9, y - 3)}
|
||||
textAnchor="end"
|
||||
fontSize={9}
|
||||
fill={stroke}
|
||||
>
|
||||
{t.label}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{variant === 'bar' ? (
|
||||
barItems.map((bar) => (
|
||||
<rect
|
||||
key={bar.key}
|
||||
x={bar.x}
|
||||
y={bar.y}
|
||||
width={bar.w}
|
||||
height={bar.h}
|
||||
rx={1.5}
|
||||
fill={bar.color}
|
||||
fillOpacity={0.85}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
seriesSegments.map(({ series: s, segments }, idx) => (
|
||||
<g key={s.id}>
|
||||
{(variant === 'area' || isSparkline) && segments.map((seg, segIdx) => (
|
||||
seg.areaPath ? (
|
||||
<path
|
||||
key={`area-${segIdx}`}
|
||||
d={seg.areaPath}
|
||||
fill={`url(#nc-mc-grad-${uid}-${idx})`}
|
||||
/>
|
||||
) : null
|
||||
))}
|
||||
{segments.map((seg, segIdx) => (
|
||||
<path
|
||||
key={`line-${segIdx}`}
|
||||
d={seg.linePath}
|
||||
fill="none"
|
||||
stroke={s.color}
|
||||
strokeWidth={isSparkline ? 1.5 : 1.75}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
))}
|
||||
{segments.length > 0 && !hoverSnapshot && (
|
||||
<circle
|
||||
cx={segments[segments.length - 1].lastX}
|
||||
cy={segments[segments.length - 1].lastY}
|
||||
r={isSparkline ? 2 : 2.5}
|
||||
fill={s.color}
|
||||
/>
|
||||
)}
|
||||
</g>
|
||||
))
|
||||
)}
|
||||
|
||||
{showAxes && yTicks.map((tick, idx) => (
|
||||
<text
|
||||
key={`ytick-${idx}`}
|
||||
x={padLeft - 6}
|
||||
y={tick.y + 3}
|
||||
textAnchor="end"
|
||||
fontSize={10}
|
||||
fill="hsl(var(--muted-foreground))"
|
||||
className="font-mono"
|
||||
>
|
||||
{formatMetricValue(tick.value, primaryUnit)}
|
||||
</text>
|
||||
))}
|
||||
|
||||
{showAxes && xTicks.map((tick, idx) => (
|
||||
<text
|
||||
key={`xtick-${idx}`}
|
||||
x={tick.x}
|
||||
y={svgHeight - 5}
|
||||
textAnchor={tick.anchor}
|
||||
fontSize={10}
|
||||
fill="hsl(var(--muted-foreground))"
|
||||
className="font-mono"
|
||||
>
|
||||
{formatClockTime(tick.at)}
|
||||
</text>
|
||||
))}
|
||||
|
||||
{hoverSnapshot && (
|
||||
<g>
|
||||
<line
|
||||
x1={hoverSnapshot.x}
|
||||
y1={padTop}
|
||||
x2={hoverSnapshot.x}
|
||||
y2={padTop + plotHeight}
|
||||
stroke="hsl(var(--muted-foreground))"
|
||||
strokeOpacity={0.55}
|
||||
strokeWidth={1}
|
||||
strokeDasharray="2 2"
|
||||
/>
|
||||
{hoverSnapshot.values.map((item) => (
|
||||
item.y !== null ? (
|
||||
<circle
|
||||
key={`dot-${item.id}`}
|
||||
cx={item.x}
|
||||
cy={item.y}
|
||||
r={3.5}
|
||||
fill={item.color}
|
||||
stroke="hsl(var(--background))"
|
||||
strokeWidth={1.5}
|
||||
/>
|
||||
) : null
|
||||
))}
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
|
||||
{!hasData && !isSparkline && (
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center text-xs text-muted-foreground">
|
||||
{props.emptyText ?? 'Waiting for samples...'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hoverSnapshot && (
|
||||
<div
|
||||
className="pointer-events-none absolute top-1 z-10 min-w-[140px] max-w-[200px] rounded-md border border-border/80 bg-popover/95 px-2.5 py-1.5 text-[11px] text-popover-foreground shadow-md backdrop-blur-sm"
|
||||
style={{ left: `${tooltipLeft}px` }}
|
||||
>
|
||||
<div className="mb-1 font-mono text-[10px] text-muted-foreground">
|
||||
{formatClockTime(hoverSnapshot.at)}
|
||||
</div>
|
||||
<div className="space-y-0.5">
|
||||
{hoverSnapshot.values.map((item) => (
|
||||
<div key={item.id} className="flex items-center justify-between gap-2">
|
||||
<span className="inline-flex min-w-0 items-center gap-1.5 truncate">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: item.color }} />
|
||||
<span className="truncate text-muted-foreground">{item.label}</span>
|
||||
</span>
|
||||
<span className="font-mono font-medium text-foreground">
|
||||
{formatMetricValue(item.value, item.unit)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +1,20 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { LazyLoadBoundary } from '../../ui/lazy-load-boundary';
|
||||
import { PluginBiChart } from './PluginBiChart';
|
||||
import { PluginCodeEditor } from './PluginCodeEditor';
|
||||
import { PluginDataGrid } from './PluginDataGrid';
|
||||
import { PluginErCanvas } from './PluginErCanvas';
|
||||
import { PluginMetricChart } from './PluginMetricChart';
|
||||
import type {
|
||||
PluginBiChartWidgetProps,
|
||||
PluginCodeEditorWidgetProps,
|
||||
PluginDataGridWidgetProps,
|
||||
PluginErCanvasWidgetProps,
|
||||
PluginMetricChartWidgetProps,
|
||||
PluginWidgetEventCallback,
|
||||
} from './types';
|
||||
|
||||
export type SlottedWidgetKind = 'code-editor' | 'data-grid' | 'er-canvas';
|
||||
export type SlottedWidgetKind = 'code-editor' | 'data-grid' | 'er-canvas' | 'metric-chart' | 'bi-chart';
|
||||
|
||||
export function parseWidgetPropsJson<T extends object>(raw: string | undefined): T {
|
||||
if (!raw) return {} as T;
|
||||
@@ -50,6 +54,12 @@ export function PluginSlottedWidget({
|
||||
{kind === 'er-canvas' && (
|
||||
<PluginErCanvas {...(parsedProps as PluginErCanvasWidgetProps)} onWidgetEvent={onWidgetEvent} />
|
||||
)}
|
||||
{kind === 'metric-chart' && (
|
||||
<PluginMetricChart {...(parsedProps as PluginMetricChartWidgetProps)} />
|
||||
)}
|
||||
{kind === 'bi-chart' && (
|
||||
<PluginBiChart {...(parsedProps as PluginBiChartWidgetProps)} onWidgetEvent={onWidgetEvent} />
|
||||
)}
|
||||
</LazyLoadBoundary>
|
||||
);
|
||||
}
|
||||
@@ -134,3 +134,131 @@ export interface PluginErCanvasWidgetProps {
|
||||
tables?: PluginErTable[];
|
||||
relations?: PluginErRelation[];
|
||||
}
|
||||
|
||||
export type PluginMetricChartColor =
|
||||
| 'primary'
|
||||
| 'sky'
|
||||
| 'emerald'
|
||||
| 'amber'
|
||||
| 'violet'
|
||||
| 'rose'
|
||||
| 'cyan'
|
||||
| 'muted';
|
||||
|
||||
export type PluginMetricChartUnit = '%' | 'bytes/s' | 'ms' | 'count' | 'temp' | 'bytes' | '';
|
||||
|
||||
export interface PluginMetricChartPoint {
|
||||
at: number;
|
||||
value: number | null;
|
||||
}
|
||||
|
||||
export interface PluginMetricChartSeries {
|
||||
id: string;
|
||||
label: string;
|
||||
color?: PluginMetricChartColor;
|
||||
unit?: PluginMetricChartUnit;
|
||||
points: PluginMetricChartPoint[];
|
||||
}
|
||||
|
||||
export interface PluginMetricChartThreshold {
|
||||
value: number;
|
||||
tone: 'warning' | 'critical';
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export interface PluginMetricChartWidgetProps {
|
||||
variant?: 'area' | 'line' | 'sparkline' | 'bar';
|
||||
series?: PluginMetricChartSeries[];
|
||||
rangeMs?: number;
|
||||
intervalMs?: number;
|
||||
endAt?: number;
|
||||
min?: number;
|
||||
max?: number | 'auto';
|
||||
height?: number;
|
||||
thresholds?: PluginMetricChartThreshold[];
|
||||
showGrid?: boolean;
|
||||
showLegend?: boolean;
|
||||
showAxes?: boolean;
|
||||
interactive?: boolean;
|
||||
emptyText?: string;
|
||||
ariaLabel?: string;
|
||||
}
|
||||
|
||||
export type PluginBiChartType =
|
||||
| 'bar'
|
||||
| 'horizontal-bar'
|
||||
| 'stacked-bar'
|
||||
| 'line'
|
||||
| 'area'
|
||||
| 'pie'
|
||||
| 'donut'
|
||||
| 'scatter'
|
||||
| 'funnel'
|
||||
| 'combo';
|
||||
|
||||
export type PluginBiChartColor =
|
||||
| 'primary'
|
||||
| 'sky'
|
||||
| 'emerald'
|
||||
| 'amber'
|
||||
| 'violet'
|
||||
| 'rose'
|
||||
| 'cyan'
|
||||
| 'indigo'
|
||||
| 'teal'
|
||||
| 'orange'
|
||||
| 'slate'
|
||||
| 'muted';
|
||||
|
||||
export type PluginBiChartPalette = 'default' | 'categorical' | 'cool' | 'warm' | 'monochrome';
|
||||
|
||||
export type PluginBiChartValueFormat = 'number' | 'compact' | 'currency' | 'percent' | 'bytes' | 'ms';
|
||||
|
||||
export interface PluginBiChartScatterPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
label?: string;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export interface PluginBiChartSeries {
|
||||
id: string;
|
||||
name: string;
|
||||
data?: Array<number | null>;
|
||||
points?: PluginBiChartScatterPoint[];
|
||||
renderAs?: 'bar' | 'line' | 'area';
|
||||
yAxis?: 'left' | 'right';
|
||||
color?: PluginBiChartColor;
|
||||
format?: PluginBiChartValueFormat;
|
||||
currency?: string;
|
||||
}
|
||||
|
||||
export interface PluginBiChartActiveFilter {
|
||||
seriesIndex?: number;
|
||||
datumIndex?: number;
|
||||
category?: string;
|
||||
}
|
||||
|
||||
export interface PluginBiChartWidgetProps {
|
||||
type?: PluginBiChartType;
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
categories?: string[];
|
||||
series?: PluginBiChartSeries[];
|
||||
palette?: PluginBiChartPalette;
|
||||
xAxisLabel?: string;
|
||||
yAxisLabel?: string;
|
||||
yAxisRightLabel?: string;
|
||||
valueFormat?: PluginBiChartValueFormat;
|
||||
currency?: string;
|
||||
height?: number;
|
||||
showGrid?: boolean;
|
||||
showLegend?: boolean;
|
||||
showDataLabels?: boolean;
|
||||
smooth?: boolean;
|
||||
donutInnerRatio?: number;
|
||||
exportable?: boolean;
|
||||
activeFilter?: PluginBiChartActiveFilter | null;
|
||||
emptyText?: string;
|
||||
ariaLabel?: string;
|
||||
}
|
||||
@@ -47,12 +47,7 @@ import {
|
||||
type RemoteDesktopClipboardTransferState,
|
||||
type RemoteDesktopDisplayMode,
|
||||
type RemoteDesktopRdpdrRequest,
|
||||
type RemoteDesktopRecordingCaptureHandle,
|
||||
} from './remoteDesktopHelpers';
|
||||
import {
|
||||
captureCanvasThumbnailJpeg,
|
||||
createStableCanvasCaptureStream,
|
||||
} from './remoteDesktopVideoCapture';
|
||||
import type { RemoteDesktopSpecialKeyId } from './vncKeymap';
|
||||
|
||||
import type {
|
||||
@@ -415,12 +410,6 @@ 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;
|
||||
@@ -442,22 +431,6 @@ 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);
|
||||
@@ -917,11 +890,9 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
typeText,
|
||||
releaseAllInputs,
|
||||
captureScreenshot,
|
||||
captureThumbnailJpeg,
|
||||
captureFrame,
|
||||
getCanvasRect,
|
||||
getCaptureStream,
|
||||
createRecordingCapture,
|
||||
focusInput,
|
||||
syncClipboardNow,
|
||||
downloadRemoteClipboardFile,
|
||||
@@ -936,8 +907,6 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
addSharedDrive,
|
||||
captureFrame,
|
||||
captureScreenshot,
|
||||
captureThumbnailJpeg,
|
||||
createRecordingCapture,
|
||||
downloadRemoteClipboardFile,
|
||||
focusInput,
|
||||
getCanvasRect,
|
||||
|
||||
@@ -1,25 +1,9 @@
|
||||
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,
|
||||
RemoteDesktopSessionEventKind,
|
||||
RemoteDesktopSessionMetadata,
|
||||
} from '../../domain/models';
|
||||
import {
|
||||
appendRemoteDesktopSessionEvent,
|
||||
getConnectionLogRecordingClips,
|
||||
mergeRemoteDesktopSessionMetadata,
|
||||
} from '../../domain/remoteDesktopRecording';
|
||||
import type { RdpMultiMonitorMode } from '../../domain/models/connection';
|
||||
import {
|
||||
computeMonitorLayoutEntries,
|
||||
formatStandardRdpSecurityBadge,
|
||||
@@ -92,7 +76,6 @@ import { RemoteDesktopCertDialog } from './RemoteDesktopCertDialog';
|
||||
import {
|
||||
buildRemoteDesktopStartPayload,
|
||||
buildSystemRemoteDesktopPayload,
|
||||
formatTransferBytes,
|
||||
getRemoteDesktopBridge,
|
||||
tr,
|
||||
type RemoteDesktopCanvasHandle,
|
||||
@@ -113,8 +96,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;
|
||||
@@ -214,7 +197,6 @@ 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),
|
||||
@@ -327,83 +309,6 @@ 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,
|
||||
@@ -412,32 +317,13 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
status,
|
||||
audioEnabled: isRdp && Boolean(spec.rdpConfig?.audioEnabled),
|
||||
canvasHandleRef,
|
||||
onRecordingLifecycleEvent: handleRecordingLifecycleEvent,
|
||||
});
|
||||
isRecordingOrStoppingRef.current = recorder.isRecording || recorder.isStopping;
|
||||
|
||||
// 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.
|
||||
// Stamp ConnectionLog endTime when this remote desktop session closes via any UI/hotkey path.
|
||||
const handleCloseLogCapture = useCallback(
|
||||
(closingSessionId: string, data: string) => {
|
||||
if (closeCapturePromiseRef.current) return closeCapturePromiseRef.current;
|
||||
closeCaptureDoneRef.current = true;
|
||||
const promise = Promise.resolve(onTerminalDataCapture?.(closingSessionId, data))
|
||||
.catch(() => {})
|
||||
.then(() => undefined);
|
||||
closeCapturePromiseRef.current = promise;
|
||||
return promise;
|
||||
return onTerminalDataCapture?.(closingSessionId, data);
|
||||
},
|
||||
[onTerminalDataCapture],
|
||||
);
|
||||
@@ -450,14 +336,6 @@ 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);
|
||||
@@ -511,17 +389,6 @@ 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'),
|
||||
@@ -534,7 +401,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
}
|
||||
}
|
||||
},
|
||||
[appendSessionEvent, t],
|
||||
[t],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -1135,12 +1002,6 @@ 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(() => {});
|
||||
@@ -1148,7 +1009,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
setWsUrl(null);
|
||||
updateStatus('disconnected');
|
||||
onCloseSession?.(sessionId);
|
||||
}, [appendSessionEvent, captureUnrecordedSessionThumbnail, onCloseSession, releaseKeyboardGrab, sessionId, updateStatus]);
|
||||
}, [onCloseSession, releaseKeyboardGrab, sessionId, updateStatus]);
|
||||
|
||||
const handleOpenSystemClient = useCallback(async () => {
|
||||
const rdBridge = getRemoteDesktopBridge();
|
||||
@@ -1204,13 +1065,12 @@ 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'));
|
||||
}
|
||||
}, [appendSessionEvent, t]);
|
||||
}, [t]);
|
||||
|
||||
const handleScreenshotSave = useCallback(async () => {
|
||||
const blob = await canvasHandleRef.current?.captureScreenshot();
|
||||
@@ -1222,7 +1082,6 @@ 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;
|
||||
@@ -1233,19 +1092,13 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
a.download = fileName;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
appendSessionEvent('screenshot', 'Saved PNG screenshot', { detail: fileName });
|
||||
}, [appendSessionEvent, effectiveLabel, protocol, t]);
|
||||
}, [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');
|
||||
@@ -1257,7 +1110,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
setDisconnectError(err.message);
|
||||
updateStatus('disconnected');
|
||||
},
|
||||
[appendSessionEvent, releaseKeyboardGrab, sessionId, updateStatus],
|
||||
[releaseKeyboardGrab, sessionId, updateStatus],
|
||||
);
|
||||
|
||||
const handleCanvasDisconnected = useCallback(
|
||||
@@ -1265,15 +1118,10 @@ 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');
|
||||
},
|
||||
[appendSessionEvent, releaseKeyboardGrab, sessionId, updateStatus],
|
||||
[releaseKeyboardGrab, sessionId, updateStatus],
|
||||
);
|
||||
|
||||
const handleNegotiationFallback = useCallback((nextStage: Exclude<RdpAutoFallbackStage, 'none'>) => {
|
||||
@@ -1508,9 +1356,6 @@ 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,
|
||||
@@ -1520,7 +1365,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to add shared folder');
|
||||
}
|
||||
}, [appendSessionEvent, host.id, syncDrivesToBackend, t]);
|
||||
}, [host.id, syncDrivesToBackend, t]);
|
||||
|
||||
const handleAddSharedFolderClick = useCallback(() => {
|
||||
void handleAddSharedFolder();
|
||||
@@ -1534,7 +1379,6 @@ 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,
|
||||
@@ -1542,7 +1386,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
);
|
||||
}
|
||||
},
|
||||
[appendSessionEvent, host.id, sharedFolders, status, syncDrivesToBackend, t],
|
||||
[host.id, sharedFolders, status, syncDrivesToBackend, t],
|
||||
);
|
||||
|
||||
const handleToggleSharedFolderReadOnly = useCallback(
|
||||
@@ -1584,28 +1428,6 @@ 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;
|
||||
@@ -1622,34 +1444,8 @@ 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);
|
||||
},
|
||||
[appendSessionEvent, captureUnrecordedSessionThumbnail, tunneled, updateStatus],
|
||||
[updateStatus],
|
||||
);
|
||||
|
||||
const handleRdpConnected = useCallback(
|
||||
@@ -1662,15 +1458,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(
|
||||
legacyBadge
|
||||
badge
|
||||
? tr(
|
||||
t,
|
||||
'remoteDesktop.rdp.fallbackStandardRdpWithCipher',
|
||||
'Connected using Standard RDP Security ({{cipher}}).',
|
||||
{ cipher: legacyBadge },
|
||||
{ cipher: badge },
|
||||
)
|
||||
: tr(
|
||||
t,
|
||||
@@ -1681,38 +1477,8 @@ 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);
|
||||
},
|
||||
[appendSessionEvent, autoFallbackStage, captureUnrecordedSessionThumbnail, monitorLayout.length, t, tunneled, updateStatus],
|
||||
[autoFallbackStage, t, updateStatus],
|
||||
);
|
||||
|
||||
const handleRemoteClipboardFilesChange = useCallback(
|
||||
@@ -1818,10 +1584,9 @@ 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={handleToggleRecordingClick}
|
||||
onToggleRecording={SHOW_REMOTE_DESKTOP_RECORDING_BUTTON ? handleToggleRecordingClick : undefined}
|
||||
quality={quality}
|
||||
onChangeQuality={handleChangeQuality}
|
||||
viewOnly={viewOnly}
|
||||
@@ -1896,7 +1661,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
onRequestReleaseGrab={releaseKeyboardGrab}
|
||||
onConnected={handleVncConnected}
|
||||
onCapabilitiesChange={handleVncCapabilitiesChange}
|
||||
onDesktopResize={handleDesktopResize}
|
||||
onDesktopResize={setResolution}
|
||||
onDesktopName={setDesktopTitle}
|
||||
onBell={handleVncBell}
|
||||
onFpsChange={handleFpsChange}
|
||||
@@ -1934,7 +1699,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
onFpsChange={handleFpsChange}
|
||||
onRequestReleaseGrab={releaseKeyboardGrab}
|
||||
onConnected={handleRdpConnected}
|
||||
onDesktopResize={handleDesktopResize}
|
||||
onDesktopResize={setResolution}
|
||||
onRemoteClipboardFilesChange={handleRemoteClipboardFilesChange}
|
||||
onClipboardFileTransferStatus={setClipboardFileTransferStatus}
|
||||
onClipboardTransferChange={handleClipboardTransferChange}
|
||||
|
||||
@@ -24,7 +24,6 @@ import {
|
||||
History,
|
||||
Keyboard,
|
||||
Layers,
|
||||
Loader2,
|
||||
Lock,
|
||||
Maximize,
|
||||
Maximize2,
|
||||
@@ -162,7 +161,6 @@ export interface RemoteDesktopToolbarProps {
|
||||
onOpenAiAuditLog?: () => void;
|
||||
// Session Recording
|
||||
isRecording?: boolean;
|
||||
isStoppingRecording?: boolean;
|
||||
recordingElapsedLabel?: string;
|
||||
recordingSupported?: boolean;
|
||||
onToggleRecording?: () => void;
|
||||
@@ -684,7 +682,6 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
|
||||
aiAuditCount = 0,
|
||||
onOpenAiAuditLog,
|
||||
isRecording = false,
|
||||
isStoppingRecording = false,
|
||||
recordingElapsedLabel = '00:00',
|
||||
recordingSupported = true,
|
||||
onToggleRecording,
|
||||
@@ -1977,34 +1974,23 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
|
||||
)}
|
||||
|
||||
{/* Session Recording Button / Active Pill (P2-B, visible in fullscreen too) */}
|
||||
{onToggleRecording && (!narrowMode || isRecording || isStoppingRecording) && (
|
||||
{onToggleRecording && (!narrowMode || isRecording) && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
{isRecording || isStoppingRecording ? (
|
||||
{isRecording ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
data-testid="remote-desktop-record-btn"
|
||||
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"
|
||||
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"
|
||||
onClick={onToggleRecording}
|
||||
aria-label={tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')}
|
||||
>
|
||||
{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>
|
||||
<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>
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
@@ -2024,11 +2010,9 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" className="text-xs">
|
||||
{isStoppingRecording
|
||||
? tr(t, 'remoteDesktop.toolbar.savingRecording', 'Saving...')
|
||||
: isRecording
|
||||
? tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')
|
||||
: tr(t, 'remoteDesktop.toolbar.record', 'Record session')}
|
||||
{isRecording
|
||||
? tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')
|
||||
: tr(t, 'remoteDesktop.toolbar.record', 'Record session')}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
@@ -2209,17 +2193,15 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
|
||||
<PopoverClose asChild>
|
||||
<button
|
||||
type="button"
|
||||
disabled={status !== 'connected' || !recordingSupported || isStoppingRecording}
|
||||
disabled={status !== 'connected' || !recordingSupported}
|
||||
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>
|
||||
{isStoppingRecording
|
||||
? tr(t, 'remoteDesktop.toolbar.savingRecording', 'Saving...')
|
||||
: isRecording
|
||||
? tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')
|
||||
: tr(t, 'remoteDesktop.toolbar.record', 'Record session')}
|
||||
{isRecording
|
||||
? tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')
|
||||
: tr(t, 'remoteDesktop.toolbar.record', 'Record session')}
|
||||
</span>
|
||||
</button>
|
||||
</PopoverClose>
|
||||
|
||||
@@ -31,12 +31,7 @@ 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 = {
|
||||
@@ -380,12 +375,6 @@ 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;
|
||||
@@ -397,15 +386,6 @@ 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 });
|
||||
}, []);
|
||||
@@ -693,11 +673,9 @@ export const VncCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Vn
|
||||
typeText,
|
||||
releaseAllInputs,
|
||||
captureScreenshot,
|
||||
captureThumbnailJpeg,
|
||||
captureFrame,
|
||||
getCanvasRect,
|
||||
getCaptureStream,
|
||||
createRecordingCapture,
|
||||
focusInput,
|
||||
syncClipboardNow,
|
||||
requestRefresh,
|
||||
@@ -709,8 +687,6 @@ export const VncCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Vn
|
||||
[
|
||||
captureFrame,
|
||||
captureScreenshot,
|
||||
captureThumbnailJpeg,
|
||||
createRecordingCapture,
|
||||
focusInput,
|
||||
getCanvasRect,
|
||||
getCaptureStream,
|
||||
|
||||
@@ -31,58 +31,17 @@ 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 requestedSampleRate = 0;
|
||||
private currentSampleRate = 0;
|
||||
private userVolume = 1.0;
|
||||
private serverVolume = 1.0;
|
||||
private muted = false;
|
||||
private disposed = false;
|
||||
private pendingChunks: Array<{ data: Uint8Array; channels: number; sampleRate: number }> = [];
|
||||
private pendingChunks: Array<{ data: Uint8Array; channels: number }> = [];
|
||||
|
||||
constructor(options?: { muted?: boolean; volume?: number }) {
|
||||
if (typeof options?.muted === 'boolean') {
|
||||
@@ -111,90 +70,71 @@ export class RdpAudioPlayer {
|
||||
if (this.disposed) return;
|
||||
const targetRate = normalizeSampleRate(sampleRate);
|
||||
|
||||
// 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 && this.workletNode && this.currentSampleRate === targetRate) {
|
||||
if (this.context.state === 'suspended') {
|
||||
await this.context.resume().catch(() => {});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.initPromise) {
|
||||
if (this.initPromise && this.currentSampleRate === targetRate) {
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
// 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;
|
||||
// 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;
|
||||
|
||||
const initTask = (async () => {
|
||||
this.initPromise = (async () => {
|
||||
if (typeof AudioContext === 'undefined') return;
|
||||
let ctx: AudioContext;
|
||||
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;
|
||||
try {
|
||||
ctx = new AudioContext({ sampleRate: targetRate, latencyHint: 'interactive' });
|
||||
} catch {
|
||||
ctx = new AudioContext({ latencyHint: 'interactive' });
|
||||
}
|
||||
|
||||
if (this.disposed) {
|
||||
await ctx.close().catch(() => {});
|
||||
return;
|
||||
}
|
||||
this.context = ctx;
|
||||
try {
|
||||
await ctx.audioWorklet.addModule(resolveWorkletUrl());
|
||||
} catch (err) {
|
||||
console.warn('[RdpAudioPlayer] Failed to load rdp-pcm-worklet.js:', err);
|
||||
this.pendingChunks.length = 0;
|
||||
if (this.context === ctx && this.captureRefCount <= 0) {
|
||||
if (this.context === ctx) {
|
||||
this.teardownContext({ clearPending: true });
|
||||
} else if (this.context !== ctx) {
|
||||
} else {
|
||||
await ctx.close().catch(() => {});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.disposed || this.context !== ctx) {
|
||||
if (this.context !== ctx) await ctx.close().catch(() => {});
|
||||
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, bufferSampleRate),
|
||||
bufferFrames: Math.max(8192, targetRate),
|
||||
},
|
||||
});
|
||||
node.connect(ctx.destination);
|
||||
} catch (err) {
|
||||
console.warn('[RdpAudioPlayer] Failed to create AudioWorkletNode:', err);
|
||||
this.pendingChunks.length = 0;
|
||||
if (this.context === ctx && this.captureRefCount <= 0) {
|
||||
if (this.context === ctx) {
|
||||
this.teardownContext({ clearPending: true });
|
||||
} else if (this.context !== ctx) {
|
||||
} else {
|
||||
await ctx.close().catch(() => {});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.captureDest) {
|
||||
try {
|
||||
node.connect(this.captureDest);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
} else if (typeof ctx.createMediaStreamDestination === 'function') {
|
||||
if (typeof ctx.createMediaStreamDestination === 'function') {
|
||||
try {
|
||||
const captureDest = ctx.createMediaStreamDestination();
|
||||
node.connect(captureDest);
|
||||
@@ -211,44 +151,25 @@ 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, item.sampleRate);
|
||||
this.postPcm(item.data, item.channels);
|
||||
}
|
||||
})();
|
||||
|
||||
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 });
|
||||
}
|
||||
}
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
private postPcm(data: Uint8Array, channels: number, sourceSampleRate?: number): void {
|
||||
private postPcm(data: Uint8Array, channels: number): void {
|
||||
if (!this.workletNode || this.disposed) return;
|
||||
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;
|
||||
// Copy into a dedicated ArrayBuffer so transfer does not detach WASM linear memory.
|
||||
const copy = new Uint8Array(data.byteLength);
|
||||
copy.set(data);
|
||||
this.workletNode.port.postMessage(
|
||||
{
|
||||
type: 'pcm',
|
||||
channels: ch,
|
||||
buffer: prepared.buffer,
|
||||
channels: channels === 1 ? 1 : 2,
|
||||
buffer: copy.buffer,
|
||||
},
|
||||
[prepared.buffer],
|
||||
[copy.buffer],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -259,17 +180,20 @@ 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) {
|
||||
if (this.workletNode && this.currentSampleRate === normalizedRate) {
|
||||
if (this.context?.state === 'suspended') {
|
||||
void this.context.resume().catch(() => {});
|
||||
}
|
||||
this.postPcm(msg.data, channels, normalizedRate);
|
||||
this.postPcm(msg.data, channels);
|
||||
} 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, sampleRate: normalizedRate });
|
||||
this.pendingChunks.push({ data: copy, channels });
|
||||
}
|
||||
void this.ensureInitialized(normalizedRate);
|
||||
}
|
||||
@@ -323,41 +247,6 @@ 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
|
||||
@@ -377,79 +266,10 @@ 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;
|
||||
@@ -457,7 +277,7 @@ export class RdpAudioPlayer {
|
||||
this.captureDest = null;
|
||||
this.context = null;
|
||||
this.initPromise = null;
|
||||
this.requestedSampleRate = 0;
|
||||
this.currentSampleRate = 0;
|
||||
try {
|
||||
node?.port.postMessage({ type: 'reset' });
|
||||
node?.port.close?.();
|
||||
@@ -476,7 +296,6 @@ export class RdpAudioPlayer {
|
||||
public dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
this.captureRefCount = 0;
|
||||
this.teardownContext({ clearPending: true });
|
||||
}
|
||||
}
|
||||
@@ -67,19 +67,11 @@ 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;
|
||||
@@ -91,10 +83,6 @@ 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;
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
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,
|
||||
});
|
||||
});
|
||||
@@ -1,271 +0,0 @@
|
||||
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,135 +400,3 @@ 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,11 +1,10 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import {
|
||||
appendRemoteDesktopClipToConnectionLog,
|
||||
collectProtectedRemoteDesktopMediaIds,
|
||||
getRemoteDesktopRecordingsBridge,
|
||||
registerSessionLogFinalizer,
|
||||
} from '../../application/state/remoteDesktopLogActions';
|
||||
getConnectionLogsActions,
|
||||
getConnectionLogsSnapshot,
|
||||
} from '../../application/state/connectionLogsStore';
|
||||
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
|
||||
import type { RemoteDesktopProtocol } from '../../domain/remoteDesktop';
|
||||
import {
|
||||
STORAGE_KEY_REMOTE_DESKTOP_AUTO_RECORD,
|
||||
@@ -17,21 +16,14 @@ 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;
|
||||
@@ -56,10 +48,6 @@ 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 {
|
||||
@@ -71,6 +59,14 @@ 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;
|
||||
@@ -161,6 +157,39 @@ 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;
|
||||
@@ -169,12 +198,6 @@ 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 {
|
||||
@@ -192,51 +215,19 @@ 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;
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
const CHUNK_TIMESLICE_MS = 2000;
|
||||
const STOP_WAIT_TIMEOUT_MS = 5000;
|
||||
|
||||
export function useRemoteDesktopRecorder({
|
||||
sessionId,
|
||||
@@ -246,7 +237,6 @@ export function useRemoteDesktopRecorder({
|
||||
audioEnabled,
|
||||
canvasHandleRef,
|
||||
recordingsBridgeOverride,
|
||||
onRecordingLifecycleEvent,
|
||||
}: UseRemoteDesktopRecorderOptions): UseRemoteDesktopRecorderResult {
|
||||
const { t } = useI18n();
|
||||
const [settings, setSettings] = useState<RemoteDesktopRecordingSettings>(readRemoteDesktopRecordingSettings);
|
||||
@@ -257,28 +247,12 @@ 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,
|
||||
onRecordingLifecycleEvent,
|
||||
});
|
||||
latestMetaRef.current = {
|
||||
sessionId,
|
||||
protocol,
|
||||
hostLabel,
|
||||
status,
|
||||
audioEnabled,
|
||||
settings,
|
||||
onRecordingLifecycleEvent,
|
||||
};
|
||||
const latestMetaRef = useRef({ sessionId, protocol, hostLabel, status, audioEnabled, settings });
|
||||
latestMetaRef.current = { sessionId, protocol, hostLabel, status, audioEnabled, settings };
|
||||
|
||||
const getBridge = useCallback((): RemoteDesktopRecordingsApi | null => {
|
||||
if (recordingsBridgeOverride !== undefined) return recordingsBridgeOverride;
|
||||
return getRemoteDesktopRecordingsBridge();
|
||||
return getWindowRecordingsBridge();
|
||||
}, [recordingsBridgeOverride]);
|
||||
|
||||
const isSupported = typeof MediaRecorder !== 'undefined' && Boolean(getBridge());
|
||||
@@ -327,6 +301,16 @@ 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;
|
||||
@@ -375,14 +359,10 @@ export function useRemoteDesktopRecorder({
|
||||
|
||||
run.recorder.ondataavailable = null;
|
||||
run.recorder.onerror = null;
|
||||
run.disposeCapture();
|
||||
await Promise.all([
|
||||
run.appendChain.catch(() => {}),
|
||||
run.thumbnailPromise.catch(() => false),
|
||||
]);
|
||||
stopStreamTracks(run.stream);
|
||||
await run.appendChain.catch(() => {});
|
||||
|
||||
const endedAt = Date.now();
|
||||
const durationMs = Math.max(1, endedAt - run.startedAt);
|
||||
const durationMs = Math.max(1, Date.now() - run.startedAt);
|
||||
if (!bridge) return;
|
||||
|
||||
if (run.aborted || run.appendError || run.bytesQueued <= 0) {
|
||||
@@ -394,36 +374,21 @@ 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: collectProtectedRemoteDesktopMediaIds(),
|
||||
protectedIds: collectProtectedRecordingIds(),
|
||||
});
|
||||
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' : ''}`,
|
||||
updateMatchingConnectionLogRecording(latestMetaRef.current.sessionId, {
|
||||
recordingId: finished.recordingId,
|
||||
recordingMimeType: run.mimeType || 'video/webm',
|
||||
recordingDurationMs: finished.durationMs ?? durationMs,
|
||||
recordingBytes: finished.bytes,
|
||||
recordingHasAudio: run.hasAudio,
|
||||
...(options?.stampEndTime ? { endTime: Date.now() } : {}),
|
||||
});
|
||||
if (!options?.silent) {
|
||||
toast.success(
|
||||
@@ -437,8 +402,6 @@ export function useRemoteDesktopRecorder({
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// Ensure capture is always disposed even on unexpected throw.
|
||||
run.disposeCapture();
|
||||
if (activeRunRef.current === run) {
|
||||
activeRunRef.current = null;
|
||||
}
|
||||
@@ -483,9 +446,9 @@ export function useRemoteDesktopRecorder({
|
||||
startingRef.current = true;
|
||||
try {
|
||||
const wantAudio = meta.protocol === 'rdp' && meta.audioEnabled && meta.settings.includeAudio;
|
||||
const capture = acquireCanvasCapture(canvasHandleRef.current, meta.settings.fps, wantAudio);
|
||||
if (!capture || capture.stream.getVideoTracks().length === 0) {
|
||||
capture?.dispose();
|
||||
const stream = canvasHandleRef.current?.getCaptureStream?.(meta.settings.fps, wantAudio) ?? null;
|
||||
if (!stream || stream.getVideoTracks().length === 0) {
|
||||
if (stream) stopStreamTracks(stream);
|
||||
if (!options?.silent) {
|
||||
toast.error(
|
||||
tr(
|
||||
@@ -498,7 +461,7 @@ export function useRemoteDesktopRecorder({
|
||||
return false;
|
||||
}
|
||||
|
||||
const hasAudio = capture.stream.getAudioTracks().length > 0;
|
||||
const hasAudio = stream.getAudioTracks().length > 0;
|
||||
const mimeType = pickRemoteDesktopRecordingMimeType(hasAudio);
|
||||
const videoBitsPerSecond = resolveRecordingVideoBitsPerSecond(meta.settings.fps);
|
||||
|
||||
@@ -511,7 +474,7 @@ export function useRemoteDesktopRecorder({
|
||||
});
|
||||
recordingId = begun.recordingId;
|
||||
} catch {
|
||||
capture.dispose();
|
||||
stopStreamTracks(stream);
|
||||
if (!options?.silent) {
|
||||
toast.error(tr(t, 'remoteDesktop.recording.failed', 'Session recording failed'));
|
||||
}
|
||||
@@ -520,7 +483,7 @@ export function useRemoteDesktopRecorder({
|
||||
|
||||
// Guard against unmount or disconnect while awaiting bridge.begin()
|
||||
if (!mountedRef.current || latestMetaRef.current.status !== 'connected') {
|
||||
capture.dispose();
|
||||
stopStreamTracks(stream);
|
||||
await bridge.abort({ recordingId }).catch(() => {});
|
||||
return false;
|
||||
}
|
||||
@@ -529,9 +492,9 @@ export function useRemoteDesktopRecorder({
|
||||
try {
|
||||
const recorderOptions: MediaRecorderOptions = { videoBitsPerSecond };
|
||||
if (mimeType) recorderOptions.mimeType = mimeType;
|
||||
recorder = new MediaRecorder(capture.stream, recorderOptions);
|
||||
recorder = new MediaRecorder(stream, recorderOptions);
|
||||
} catch {
|
||||
capture.dispose();
|
||||
stopStreamTracks(stream);
|
||||
await bridge.abort({ recordingId }).catch(() => {});
|
||||
if (!options?.silent) {
|
||||
toast.error(tr(t, 'remoteDesktop.recording.failed', 'Session recording failed'));
|
||||
@@ -539,22 +502,16 @@ export function useRemoteDesktopRecorder({
|
||||
return false;
|
||||
}
|
||||
|
||||
const startedAt = Date.now();
|
||||
const run: ActiveRecordingRun = {
|
||||
recordingId,
|
||||
mimeType: recorder.mimeType || mimeType || 'video/webm',
|
||||
hasAudio,
|
||||
width: capture.width || undefined,
|
||||
height: capture.height || undefined,
|
||||
startedAt,
|
||||
startedAt: Date.now(),
|
||||
recorder,
|
||||
stream: capture.stream,
|
||||
disposeCapture: capture.dispose,
|
||||
thumbnailPromise: Promise.resolve(false),
|
||||
stream,
|
||||
appendChain: Promise.resolve(),
|
||||
appendError: null,
|
||||
bytesQueued: 0,
|
||||
pendingIpcBytes: 0,
|
||||
stopPromise: null,
|
||||
aborted: false,
|
||||
settings: meta.settings,
|
||||
@@ -564,18 +521,10 @@ export function useRemoteDesktopRecorder({
|
||||
recorder.ondataavailable = (ev: BlobEvent) => {
|
||||
if (!ev.data || ev.data.size <= 0 || run.aborted) return;
|
||||
const blob = ev.data;
|
||||
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.bytesQueued += blob.size;
|
||||
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({
|
||||
@@ -586,8 +535,6 @@ 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);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -606,7 +553,7 @@ export function useRemoteDesktopRecorder({
|
||||
activeRunRef.current = null;
|
||||
recorder.ondataavailable = null;
|
||||
recorder.onerror = null;
|
||||
capture.dispose();
|
||||
stopStreamTracks(stream);
|
||||
await bridge.abort({ recordingId }).catch(() => {});
|
||||
if (!options?.silent) {
|
||||
toast.error(tr(t, 'remoteDesktop.recording.failed', 'Session recording failed'));
|
||||
@@ -614,29 +561,6 @@ 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);
|
||||
@@ -660,16 +584,6 @@ 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,7 +9,6 @@ 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";
|
||||
@@ -391,11 +390,13 @@ 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 clearAllRemoteDesktopRecordingsAndSyncLogs();
|
||||
setRecordingsClearDeletedCount(res.deleted);
|
||||
const res = await bridge.remoteDesktopRecordings.clearAll({});
|
||||
setRecordingsClearDeletedCount(res?.deleted ?? 0);
|
||||
setClearRecordingsConfirmOpen(false);
|
||||
await loadRecordingStats();
|
||||
} catch (err) {
|
||||
|
||||
@@ -46,7 +46,6 @@ 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 [clip-path:inset(0_round_0.375rem)] animate-in fade-in zoom-in-95 duration-150"
|
||||
className="absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl 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 [clip-path:inset(0_round_0.375rem)]",
|
||||
magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl",
|
||||
)}
|
||||
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 \[clip-path:inset\(0_round_0\.375rem\)\]",$/m);
|
||||
assert.match(hostSource, /^\s*magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl",$/m);
|
||||
assert.match(hostSource, /style=\{style\}/);
|
||||
assert.doesNotMatch(hostSource, /\b(?:outline|outlineOffset|border|borderColor|borderWidth|borderStyle)\b/);
|
||||
assert.match(strokeSource, /aria-hidden="true"/);
|
||||
|
||||
@@ -528,7 +528,10 @@ export function useTerminalLayerEffects(ctx: TerminalLayerEffectsContext) {
|
||||
// Listen for global AI panel toggle (from TopTabs button). Uses the toggle
|
||||
// handler so a second click on an already-open AI panel closes it.
|
||||
useEffect(() => {
|
||||
const handler = () => handleToggleAiFromTopBar();
|
||||
const handler = (event: Event) => {
|
||||
if (event.defaultPrevented) return;
|
||||
handleToggleAiFromTopBar();
|
||||
};
|
||||
window.addEventListener('netcatty:toggle-ai-panel', handler);
|
||||
return () => window.removeEventListener('netcatty:toggle-ai-panel', handler);
|
||||
}, [handleToggleAiFromTopBar]);
|
||||
|
||||
Loaded 100 of 244 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user