Compare commits

..
Author SHA1 Message Date
陈奇 5931eb14f0 fix(plugins): revalidate selected session context after workspace focus changes 2026-10-27 14:26:01 +00:00
陈奇 ca2280ea8b docs(plugins): record cancelled row redesign and preserved foundation fixes 2026-10-27 13:12:10 +00:00
陈奇 7e7b05620f Revert "feat(plugins): share borderless installed settings rows"
This reverts commit e4eb33856b.
2026-10-27 13:04:03 +00:00
陈奇 1f0741698d docs(plugins): consolidate foundation landing ledger and sample provenance 2026-10-27 12:39:52 +00:00
陈奇 50fda91424 fix(plugins): invalidate author identity after rejected install refresh
Reuse the selection-token snapshot comparison for list and install, including a rejected stale or withdrawn selection. Preserve synchronous unavailable-source validation before the asynchronous list operation. The loaded-row regression rejects installation without downloading or executing a package.
2026-10-27 12:32:48 +00:00
陈奇 fc37ac48e1 Merge actual two-profile sync composition coverage into plugin foundation landing 2026-10-27 12:29:25 +00:00
陈奇 d035cbea38 Merge honest directory enumeration availability into plugin foundation landing 2026-10-27 12:29:25 +00:00
陈奇 b3895a477d Merge author identity refresh and borderless plugin rows into plugin foundation landing 2026-10-27 12:29:25 +00:00
陈奇 db1223d161 Merge verified main #4010 #4013 #4016 into plugin foundation landing
# Conflicts:
#	index.css
2026-10-27 12:29:25 +00:00
陈奇 14ed19d2ed test(plugins): compose two-profile settings sidecar collect and hydration 2026-10-27 12:23:21 +00:00
陈奇 a36a906292 fix(plugins): negotiate directory enumeration only with a secure adapter 2026-10-27 12:23:20 +00:00
陈奇 e4eb33856b feat(plugins): share borderless installed settings rows
Apply the exact six-file patch from implement_plugin_row_layout, based on 0c05a96fa1. Patch SHA-256: 5c58150fc3a7f72169b1a23ad1410cf37c51051b29bd6600bf30e848a9f366d6. Native visual acceptance remains pending.
2026-10-27 12:19:09 +00:00
陈奇 b14b65679f fix(plugins): invalidate mounted author identity on catalog changes 2026-10-27 12:18:27 +00:00
陈奇 0c05a96fa1 fix(plugins): align avatar delivery with registry v2 contract 2026-10-27 11:48:35 +00:00
陈奇 05a773b426 docs(plugins): clarify default directory enumeration boundary 2026-10-27 11:25:54 +00:00
陈奇 da16b90e9e feat(plugins): add author avatars and host-controlled maintainer badges 2026-10-27 11:25:54 +00:00
2796d1113a fix(mcp): reconnect external calls that race a closed socket (#4016)
A peer FIN can leave readyState closed while destroyed is still false.
Concurrent tool calls wrote into that socket, hit writeAfterFIN, and
failed with "TCP connection lost" instead of sharing one reconnect.
Treat that socket as down, and make later callers join the in-flight re-auth.

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-10-27 19:01:45 +08:00
陈大猫 c743456a0b Merge pull request #4013 from binaricat/feat/macos-frosted-glass-continued
feat(appearance): macOS frosted glass background (continues #4009)
2026-10-27 17:14:30 +08:00
bincxzandCursor 336ab5ab17 fix(appearance): repaint native background on explicit theme pushes
Keeping the restore guard for registration-time chrome setup is right, but
it also swallowed explicit setTheme/setBackgroundColor pushes: windows that
had never enabled blur stopped repainting their native backing, leaving the
color stale after theme changes on every platform.

Separate the two call kinds with an explicit forceBackgroundColor flag so
registration still preserves the window's creation-time color while theme
and background-color pushes always land.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 16:46:32 +08:00
bincxzandCursor ce9fcdfec6 fix(appearance): sync macOS blur across windows and gate search by platform
Addresses review feedback on the frosted glass background setting.

- Detached #/session-window renderers run with settings sync disabled, so
  `applySharedWindowSetting` now forwards the blur key. Previously the main
  process put native vibrancy on those windows while their renderer class
  stayed stale, leaving them opaque with blur on and double-applying opacity
  with blur off.
- Only settings-owning windows persist the blur preference and drive
  `setWindowBackgroundBlur`, matching the other OS-effect guards. Detached
  windows still apply the transparent backing class locally.
- Search entries can declare `platforms`; the macOS-only blur setting is
  filtered out on Windows/Linux so a hit never jumps to a tab whose anchor is
  not rendered (including the default empty-query list).
- Restoring chrome only rewrites the background of windows this module made
  transparent, falling back to the active theme color when no theme color has
  been pushed yet.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 16:21:07 +08:00
Joseph Hau de06a6aa4d feat(appearance): 支持 macOS 毛玻璃窗口背景 2026-10-27 16:21:07 +08:00
陈大猫 dcf642cf39 Merge pull request #4010 from binaricat/feat/nginx-highlighting-4005
feat(editor): add Nginx syntax highlighting
2026-10-27 15:22:51 +08:00
陈奇 d40b0d3c25 docs(plugins): prepare Settings visibility and current-main acceptance handoff 2026-10-27 07:08:50 +00:00
陈奇 714e2397a4 Merge reviewed Settings native-view visibility correction 2026-10-27 06:59:39 +00:00
陈奇 c4aedfa9ed Merge current main owner handoff and prompt fixes into isolated plugin acceptance 2026-10-27 06:59:39 +00:00
陈奇 1551fa8355 fix(plugins): suspend native views only for active log dialogs 2026-10-27 06:55:01 +00:00
陈大猫 1caf4a6479 feat(editor): add Nginx syntax highlighting 2026-10-27 14:40:29 +08:00
a0cf2b487c fix(mcp): recognize Oh My Zsh ys two-line idle prompts (#4008)
The two-line idle prompt check only accepted a classic user@host host
line, so Oh My Zsh ys (`# user @ host ...` then a bare $/#) never became
ready and terminal_execute sent nothing. Match that host line narrowly
and still reject a lone marker.

Fixes #4007

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-10-27 14:31:21 +08:00
陈大猫 e3e2dcfe02 fix(ai): keep dissolved workspace chat on its surviving owner (#4003)
Fixes #3998

Keep terminal-scoped AI chat on its surviving owner pane when dissolving a workspace; remint onto preferred only when the owner is gone.
2026-10-27 13:58:44 +08:00
陈奇 2433cf0130 docs(plugins): prepare isolated Ask routing QA and preserve 020 results 2026-10-27 05:46:36 +00:00
陈奇 1b21c41fa2 Merge reviewed managed-window Ask routing into isolated acceptance candidate 2026-10-27 05:31:36 +00:00
陈奇 89beeb9374 fix(plugins): route Ask to focused managed app windows 2026-10-27 05:06:38 +00:00
陈奇 02049102b6 docs(plugins): refresh final policy candidate provenance and native limits 2026-10-27 04:07:45 +00:00
陈奇 cfa13680e6 Merge authoritative policy disclosure correction preserving all assertions 2026-10-27 04:01:44 +00:00
陈奇 79a9bd6df1 fix(plugins): describe policy modes without mandatory consent copy 2026-10-27 03:51:51 +00:00
陈奇 7856c664c3 docs(plugins): record isolated policy and AI candidate with exact sample provenance 2026-10-27 03:43:01 +00:00
陈奇 7d8a354404 test(plugins): align package disclosure assertions with declared capability policy 2026-10-27 03:34:50 +00:00
陈奇 da4e80946d test(plugins): align package details with default Allow policy 2026-10-27 03:34:32 +00:00
陈奇 5d2ff1cb86 Merge reviewed AI startup and themed sample while preserving permission policy assertions 2026-10-27 03:25:05 +00:00
陈奇 9aa899059f Merge declared capability policy corrections into isolated acceptance candidate 2026-10-27 03:24:18 +00:00
陈奇 2eee561847 fix(plugins): bind scoped Ask receipts and revoke advanced activations 2026-10-27 03:17:53 +00:00
陈奇 d33c0193cc test(plugin-ai): drain Node module warnings before observing SDK errors 2026-10-27 02:33:17 +00:00
陈奇 643e71b17b feat(plugins): default declared capabilities to allow with scoped policy controls 2026-10-27 02:28:08 +00:00
陈奇 e325742abf fix(example-assistant): follow host theme and accent environment 2026-10-27 02:22:20 +00:00
陈奇 9ca70f3290 docs(plugin-ai): record cold-start evidence and native verification limits 2026-10-27 02:03:21 +00:00
陈奇 092438803b fix(plugin-ai): prepare host provider transport independently of the AI sidebar 2026-10-27 02:00:37 +00:00
148 changed files with 6101 additions and 413 deletions

No files matched your search

+2
View File
@@ -12,6 +12,7 @@ import { ToastProvider } from './components/ui/toast';
import { TooltipProvider } from './components/ui/tooltip';
import { ScriptAutomationRoot } from './components/scripts/ScriptAutomationRoot';
import { ExternalMcpApprovalsHost } from './components/ai/ExternalMcpApprovalsHost';
import { PluginPermissionHost } from './components/plugins/PluginPermissionHost';
import { PluginHostInteractionHost } from './components/plugins/PluginHostInteractionHost';
import { PluginHostActionHost } from './components/plugins/PluginHostActionHost';
import { PluginAuthenticationHost } from './components/plugins/PluginAuthenticationHost';
@@ -88,6 +89,7 @@ function AppWithProviders({ settings, appLock }: { settings: SettingsState; appL
<ScriptAutomationRoot />
<ExternalMcpApprovalsHost />
<PluginAuthenticationHost />
<PluginPermissionHost />
<PluginHostInteractionHost />
<MultilinePasteConfirmHost />
<VaultPublisher>
+15 -7
View File
@@ -582,6 +582,8 @@ Highlight the focused split pane:
'settings.appearance.uiFont.desc': 'Choose the font for the application interface',
'settings.appearance.windowOpacity': 'Window Opacity',
'settings.appearance.windowOpacity.desc': 'Adjust the transparency of the entire application window. Lower values also fade terminal text. Some Linux desktop environments may not support this.',
'settings.appearance.windowBackgroundBlur': 'Frosted glass background',
'settings.appearance.windowBackgroundBlur.desc': 'Blur the desktop behind the window. At 100% opacity the effect is hidden, but your choice is preserved.',
'settings.appearance.appIcon': 'App Icon',
'settings.appearance.appIcon.desc': 'Choose a dock/taskbar icon style to make Netcatty easier to spot when switching apps. On Windows, the notification area icon uses the same style. Applies at runtime; the installed app bundle icon is unchanged.',
'settings.appearance.appIcon.original': 'Original',
@@ -1262,6 +1264,8 @@ Highlight the focused split pane:
'deepLink.jms.unsupported': 'Unsupported JumpServer protocol: {{protocol}}',
'settings.tab.plugins': 'Plugins',
"settings.plugins.manager.installed": "Installed plugins",
"settings.plugins.author.official": "Official maintainer",
"settings.plugins.author.officialMeaning": "Maintained by the Netcatty project. This is not a safety certification.",
"settings.plugins.manager.import": "Import .ncpkg",
"settings.plugins.manager.preview": "Imported packages stay disabled until you review and enable them.",
"settings.plugins.manager.empty": "Import a local plugin package to get started.",
@@ -1298,19 +1302,23 @@ Highlight the focused split pane:
"plugins.interaction.closeDraft": "Close draft",
"settings.plugins.permissions.current": "Matches the current activation",
"settings.plugins.permissions.inactive": "Inactive for the current activation",
"settings.plugins.permissions.title": "Saved grants",
"settings.plugins.permissions.note": "Declared capabilities default to Allow. Ask requests a scoped decision; Deny blocks access immediately. Target selection and draft editing still use the host UI.",
"settings.plugins.permissions.allow": "Allow",
"settings.plugins.permissions.ask": "Ask",
"settings.plugins.permissions.deny": "Deny",
"settings.plugins.permissions.title": "Permissions",
"settings.plugins.permissions.refresh": "Refresh",
"settings.plugins.permissions.loading": "Loading grants...",
"settings.plugins.permissions.loading": "Loading permissions...",
"settings.plugins.permissions.empty": "No saved grants. One-use decisions are not retained.",
"settings.plugins.permissions.always": "Until revoked",
"settings.plugins.permissions.application": "Until Netcatty exits",
"settings.plugins.permissions.session": "Until the session closes",
"settings.plugins.permissions.audit": "Recent security events (up to 100)",
"settings.plugins.permissions.revoke": "Disable and revoke all grants",
"settings.plugins.permissions.revokeNote": "This disables the plugin, cancels its work, and removes saved grants. Enable it again to request new access.",
"settings.plugins.permissions.revokeNote": "This disables the plugin, cancels its work, and removes saved grants. Your Allow / Ask / Deny settings are retained.",
"settings.plugins.permissions.unavailable": "Plugin permission management is unavailable",
"settings.plugins.manager.permissions": "Declared permissions",
"settings.plugins.manager.permissionNote": "From the manifest, not a grant. Enabled allows lazy activation; required permissions are requested before first activation and optional permissions when used. Sensitive operations still pass host checks.",
"settings.plugins.manager.permissionNote": "Declared supported capabilities default to Allow. Change each capability to Ask or Deny in the permission controls. Host validation and resource scope always apply.",
"settings.plugins.manager.noPermissions": "No privileged permissions declared.",
"settings.plugins.manager.required": "Required",
"settings.plugins.manager.optional": "Optional",
@@ -1353,7 +1361,7 @@ Highlight the focused split pane:
"settings.plugins.market.sourceOnly": "First-party source example. Build with the local CLI and import the .ncpkg; no downloadable release has been published.",
"settings.plugins.market.readmeNote": "Pinned to the commit above. HTML is inert and remote images are not loaded. Written by the plugin author.",
"settings.plugins.manager.noVault": "System key storage is unavailable. Secret and credential operations are blocked; browsing and non-secret plugins still work.",
"settings.plugins.manager.sensitive": "Sensitive access: review the data and resource scope before granting.",
"settings.plugins.manager.sensitive": "Sensitive access: this capability may expose private data. Its mode can be changed in permission settings.",
"settings.plugins.manager.dual": "Browser is the default runtime. This package also includes a Node entrypoint with full device authority; developer mode only.",
"settings.plugins.manager.advancedDeclaration": "Browser entrypoint with advanced permission declarations. Not eligible for normal browser-only mode; review every declared permission.",
"settings.plugins.market.retry": "Retry",
@@ -1362,7 +1370,7 @@ Highlight the focused split pane:
"settings.plugins.market.search": "Search name, author or description",
"settings.plugins.market.noResults": "No matching plugins. Try another search.",
"settings.plugins.market.manifest": "Compatibility and permissions",
"settings.plugins.manager.unbounded": "No narrower resource scope is declared. Check the actual scope in the permission prompt.",
"settings.plugins.manager.unbounded": "No narrower resource scope is declared. Host validation and the selected permission mode still apply.",
"settings.plugins.openView": "Open",
"settings.plugins.openManager": "Open plugin manager",
"settings.plugins.sources.conflict": "This ID is installed from another source. Uninstall and explicitly reset its private data before switching. Existing source:",
@@ -1415,7 +1423,7 @@ Highlight the focused split pane:
'plugins.authentication.responseFailedWithMessage': 'Could not send the authentication response: {message}. Try again or cancel the request.',
'plugins.authentication.continue': 'Continue',
'plugins.hostActions.select': 'Share selected host metadata',
'plugins.hostActions.selectionNote': 'Share saved labels, addresses, usernames, protocols, groups and tags with this plugin. Group selection includes only the hosts selected now. Connecting requires a separate confirmation.',
'plugins.hostActions.selectionNote': 'Only the selected hosts\' saved labels, addresses, usernames, protocols, groups and tags are shared. Group selection includes only the hosts selected now. Later edit or connection requests follow this plugin\'s permission settings.',
'plugins.hostActions.create': 'Review host draft',
'plugins.hostActions.edit': 'Review host changes',
'plugins.hostActions.connect': 'Confirm connection',
+13 -5
View File
@@ -582,6 +582,8 @@ Resalta el panel dividido enfocado:
'settings.appearance.uiFont.desc': 'Elige la fuente para la interfaz de la aplicación',
'settings.appearance.windowOpacity': 'Opacidad de la ventana',
'settings.appearance.windowOpacity.desc': 'Ajusta la transparencia de toda la ventana de la aplicación. Los valores más bajos también atenúan el texto de la terminal. Algunos entornos de escritorio de Linux pueden no admitir esto.',
'settings.appearance.windowBackgroundBlur': 'Fondo de cristal esmerilado',
'settings.appearance.windowBackgroundBlur.desc': 'Desenfoca el escritorio detrás de la ventana. Con una opacidad del 100 %, el efecto no es visible, pero se conserva tu elección.',
'settings.appearance.appIcon': 'Ícono de la aplicación',
'settings.appearance.appIcon.desc': 'Elige un estilo de ícono para el dock o la barra de tareas que haga más fácil distinguir Netcatty al cambiar de aplicación. En Windows, el icono del área de notificación usa el mismo estilo. Se aplica en tiempo de ejecución; el ícono del paquete instalado no cambia.',
'settings.appearance.appIcon.original': 'Original',
@@ -1261,6 +1263,8 @@ Resalta el panel dividido enfocado:
'deepLink.jms.invalid': 'Enlace JumpServer inválido',
'deepLink.jms.unsupported': 'Protocolo JumpServer no compatible: {{protocol}}',
'settings.tab.plugins': 'Plugins',
"settings.plugins.author.official": "Mantenimiento oficial",
"settings.plugins.author.officialMeaning": "Mantenido por el proyecto Netcatty. No es una certificación de seguridad.",
"settings.plugins.manager.installed": "Plugins instalados",
"settings.plugins.manager.import": "Importar .ncpkg",
"settings.plugins.manager.preview": "Los paquetes importados permanecen desactivados hasta que los revises y actives.",
@@ -1298,7 +1302,11 @@ Resalta el panel dividido enfocado:
"plugins.interaction.closeDraft": "Close draft",
"settings.plugins.permissions.current": "Coincide con la ejecución actual",
"settings.plugins.permissions.inactive": "No activa para la ejecución actual",
"settings.plugins.permissions.title": "Autorizaciones guardadas",
"settings.plugins.permissions.note": "Las capacidades declaradas se permiten de forma predeterminada. Preguntar solicita una decisión con un alcance concreto; Denegar bloquea el acceso de inmediato. La selección de destinos y la edición de borradores siguen usando la interfaz de la aplicación.",
"settings.plugins.permissions.allow": "Permitir",
"settings.plugins.permissions.ask": "Preguntar",
"settings.plugins.permissions.deny": "Denegar",
"settings.plugins.permissions.title": "Permisos",
"settings.plugins.permissions.refresh": "Actualizar",
"settings.plugins.permissions.loading": "Cargando autorizaciones...",
"settings.plugins.permissions.empty": "No hay autorizaciones guardadas. Las decisiones de un solo uso no se conservan.",
@@ -1310,7 +1318,7 @@ Resalta el panel dividido enfocado:
"settings.plugins.permissions.revokeNote": "Desactiva el complemento, cancela su trabajo y elimina las autorizaciones guardadas. Actívelo para solicitar acceso de nuevo.",
"settings.plugins.permissions.unavailable": "La gestión de permisos no está disponible",
"settings.plugins.manager.permissions": "Permisos declarados",
"settings.plugins.manager.permissionNote": "Del manifiesto, no es una autorización. Activado permite la activación diferida; los permisos obligatorios se solicitan antes del primer uso y los opcionales cuando se necesitan. Las operaciones sensibles siguen verificándose.",
"settings.plugins.manager.permissionNote": "Las capacidades declaradas y compatibles se permiten de forma predeterminada. Puede cambiar cada capacidad a Preguntar o Denegar en los controles de permisos. Siempre se verifican los destinos y el alcance de los recursos.",
"settings.plugins.manager.noPermissions": "No se han declarado permisos privilegiados.",
"settings.plugins.manager.required": "Obligatorio",
"settings.plugins.manager.optional": "Opcional",
@@ -1353,7 +1361,7 @@ Resalta el panel dividido enfocado:
"settings.plugins.market.sourceOnly": "Ejemplo propio con código fuente. Compílalo con la CLI local e importa el .ncpkg; no hay versión publicada para descargar.",
"settings.plugins.market.readmeNote": "Fijado al commit indicado. El HTML no se ejecuta y las imágenes remotas no se cargan. Contenido del autor.",
"settings.plugins.manager.noVault": "El almacén de claves del sistema no está disponible. Se bloquean secretos y credenciales; el catálogo y los plugins que no los usan siguen disponibles.",
"settings.plugins.manager.sensitive": "Acceso sensible: revisa los datos y el alcance antes de autorizar.",
"settings.plugins.manager.sensitive": "Acceso sensible: esta capacidad puede exponer datos privados. Su modo se puede cambiar en los ajustes de permisos.",
"settings.plugins.manager.dual": "El navegador es la opción predeterminada. El paquete también incluye una entrada Node con acceso completo al dispositivo; solo para desarrollo.",
"settings.plugins.manager.advancedDeclaration": "Entrada de navegador con permisos avanzados declarados. No se admite en el modo normal; revisa cada permiso.",
"settings.plugins.market.retry": "Reintentar",
@@ -1362,7 +1370,7 @@ Resalta el panel dividido enfocado:
"settings.plugins.market.search": "Buscar nombre, autor o descripción",
"settings.plugins.market.noResults": "No hay plugins coincidentes. Prueba otra búsqueda.",
"settings.plugins.market.manifest": "Compatibilidad y permisos",
"settings.plugins.manager.unbounded": "No se declara un alcance de recursos más limitado. Revisa el alcance real en la solicitud de permiso.",
"settings.plugins.manager.unbounded": "No se declara un alcance de recursos más limitado. Se siguen aplicando la validación del anfitrión y el modo de permiso seleccionado.",
"settings.plugins.openView": "Abrir",
"settings.plugins.openManager": "Abrir gestor de plugins",
"settings.plugins.sources.conflict": "This ID is installed from another source. Uninstall and explicitly reset its private data before switching. Existing source:",
@@ -1415,7 +1423,7 @@ Resalta el panel dividido enfocado:
'plugins.authentication.responseFailedWithMessage': 'No se pudo enviar la respuesta de autenticación: {message}. Inténtalo de nuevo o cancela la solicitud.',
'plugins.authentication.continue': 'Continuar',
'plugins.hostActions.select': 'Compartir metadatos de los equipos seleccionados',
'plugins.hostActions.selectionNote': 'Comparte nombres, direcciones, usuarios, protocolos, grupos y etiquetas guardados con este complemento. Los grupos solo incluyen los equipos seleccionados ahora. Conectar requiere otra confirmación.',
'plugins.hostActions.selectionNote': 'Solo se comparten los nombres, direcciones, usuarios, protocolos, grupos y etiquetas guardados de los equipos seleccionados. Los grupos solo incluyen los equipos seleccionados ahora. Las solicitudes posteriores de edición o conexión siguen los permisos de este complemento.',
'plugins.hostActions.create': 'Revisar borrador de equipo',
'plugins.hostActions.edit': 'Revisar cambios del equipo',
'plugins.hostActions.connect': 'Confirmar conexión',
+8 -4
View File
@@ -525,6 +525,8 @@ export const ruCoreMessages: Messages = {
'settings.appearance.uiFont.desc': 'Выберите шрифт для интерфейса приложения',
'settings.appearance.windowOpacity': 'Прозрачность окна',
'settings.appearance.windowOpacity.desc': 'Настройте прозрачность всего окна приложения. При низких значениях текст терминала тоже бледнеет. В некоторых средах Linux это может не поддерживаться.',
'settings.appearance.windowBackgroundBlur': 'Матовое стекло',
'settings.appearance.windowBackgroundBlur.desc': 'Размывает рабочий стол за окном. При непрозрачности 100 % эффект не виден, но ваш выбор сохраняется.',
'settings.appearance.appIcon': 'Значок приложения',
'settings.appearance.appIcon.desc': 'Выберите стиль значка для Dock/панели задач, чтобы Netcatty было проще найти при переключении приложений. В Windows значок области уведомлений использует тот же стиль. Применяется во время работы; значок установленного пакета не меняется.',
'settings.appearance.appIcon.original': 'Оригинал',
@@ -1130,6 +1132,8 @@ export const ruCoreMessages: Messages = {
'deepLink.jms.unsupported': 'Неподдерживаемый протокол JumpServer: {{protocol}}',
'settings.tab.plugins': 'Плагины',
"settings.plugins.author.official": "Официальная поддержка",
"settings.plugins.author.officialMeaning": "Поддерживается проектом Netcatty. Это не сертификат безопасности.",
"settings.plugins.manager.installed": "Установленные плагины",
"settings.plugins.manager.import": "Импорт .ncpkg",
"settings.plugins.manager.preview": "Импортированные пакеты отключены до проверки и включения.",
@@ -1179,7 +1183,7 @@ export const ruCoreMessages: Messages = {
"settings.plugins.permissions.revokeNote": "Плагин будет отключён, его задачи отменены, а сохранённые разрешения удалены. Включите его для нового запроса доступа.",
"settings.plugins.permissions.unavailable": "Управление разрешениями недоступно",
"settings.plugins.manager.permissions": "Заявленные разрешения",
"settings.plugins.manager.permissionNote": "Из манифеста, а не предоставленные права. Включение допускает отложенную активацию; обязательные разрешения запрашиваются перед ней, необязательные — при использовании. Чувствительные операции проверяются приложением.",
"settings.plugins.manager.permissionNote": "Заявленные поддерживаемые возможности по умолчанию разрешены. Для каждой можно выбрать запрос или запрет в настройках разрешений. Проверки приложения и область ресурсов действуют всегда.",
"settings.plugins.manager.noPermissions": "Привилегированные разрешения не заявлены.",
"settings.plugins.manager.required": "Обязательно",
"settings.plugins.manager.optional": "Необязательно",
@@ -1222,7 +1226,7 @@ export const ruCoreMessages: Messages = {
"settings.plugins.market.sourceOnly": "Пример из этого проекта. Соберите локальной CLI и импортируйте .ncpkg; готовый пакет для скачивания не опубликован.",
"settings.plugins.market.readmeNote": "Зафиксирован указанный коммит. HTML не выполняется, внешние изображения не загружаются. Текст автора плагина.",
"settings.plugins.manager.noVault": "Системное хранилище ключей недоступно. Операции с секретами и учётными данными заблокированы; каталог и плагины без секретов доступны.",
"settings.plugins.manager.sensitive": "Чувствительный доступ: проверьте данные и область ресурсов перед разрешением.",
"settings.plugins.manager.sensitive": "Чувствительный доступ: эта возможность может раскрыть личные данные. Её режим можно изменить в настройках разрешений.",
"settings.plugins.manager.dual": "По умолчанию используется браузерная среда. Пакет также содержит вход Node с полным доступом к устройству; только для разработчиков.",
"settings.plugins.manager.advancedDeclaration": "Браузерная точка входа с заявленными расширенными разрешениями. Не допускается в обычном режиме; проверьте все разрешения.",
"settings.plugins.market.retry": "Повторить",
@@ -1231,7 +1235,7 @@ export const ruCoreMessages: Messages = {
"settings.plugins.market.search": "Поиск по имени, автору или описанию",
"settings.plugins.market.noResults": "Совпадений нет. Измените запрос.",
"settings.plugins.market.manifest": "Совместимость и разрешения",
"settings.plugins.manager.unbounded": "Более узкая область ресурсов не заявлена. Проверьте фактическую область в запросе разрешения.",
"settings.plugins.manager.unbounded": "Более узкая область ресурсов не заявлена. Проверки приложения и выбранный режим разрешений продолжают действовать.",
"settings.plugins.openView": "Открыть",
"settings.plugins.openManager": "Открыть управление плагинами",
"settings.plugins.sources.conflict": "This ID is installed from another source. Uninstall and explicitly reset its private data before switching. Existing source:",
@@ -1284,7 +1288,7 @@ export const ruCoreMessages: Messages = {
'plugins.authentication.responseFailedWithMessage': 'Не удалось отправить ответ аутентификации: {message}. Повторите попытку или отмените запрос.',
'plugins.authentication.continue': 'Продолжить',
'plugins.hostActions.select': 'Передать метаданные выбранных хостов',
'plugins.hostActions.selectionNote': 'Плагину будут переданы сохранённые имена, адреса, пользователи, протоколы, группы и теги. Группа включает только выбранные сейчас хосты. Подключение требует отдельного подтверждения.',
'plugins.hostActions.selectionNote': 'Передаются только метаданные выбранных хостов: сохранённые имена, адреса, пользователи, протоколы, группы и теги. Группа включает только выбранные сейчас хосты. Дальнейшие запросы изменения или подключения зависят от настроек разрешений плагина.',
'plugins.hostActions.create': 'Проверить черновик хоста',
'plugins.hostActions.edit': 'Проверить изменения хоста',
'plugins.hostActions.connect': 'Подтвердить подключение',
@@ -29,6 +29,16 @@ const ALL_SETTINGS_LOCALES = [
...LOCALIZED_SETTINGS_LOCALES,
];
test("Host selection disclosure describes later permission-controlled actions without promising another confirmation", () => {
const permissionWords: Record<string, RegExp> = { en: /permission settings/i, es: /permisos/i, ru: /разрешени/u, 'zh-CN': /权限设置/u, 'zh-TW': /權限設定/u };
const oldPromise = /requires a separate confirmation|requiere otra confirmación|требует отдельного подтверждения|需要单独确认|需要另外確認/iu;
for (const locale of ALL_SETTINGS_LOCALES) {
const note = locale.messages['plugins.hostActions.selectionNote'];
assert.match(note, permissionWords[locale.name], locale.name);
assert.doesNotMatch(note, oldPromise, locale.name);
}
});
test("localized settings include names for every default shortcut", () => {
for (const locale of ALL_SETTINGS_LOCALES) {
const missing = DEFAULT_KEY_BINDINGS
+15 -7
View File
@@ -586,6 +586,8 @@ Vaults 标签保持扁平,不使用这块背景。
'settings.appearance.uiFont.desc': '选择软件界面使用的字体',
'settings.appearance.windowOpacity': '窗口透明度',
'settings.appearance.windowOpacity.desc': '调节整个应用窗口的透明度,方便叠在其他内容上方。较低时终端文字也会变淡;部分 Linux 桌面环境可能不支持。',
'settings.appearance.windowBackgroundBlur': '毛玻璃背景',
'settings.appearance.windowBackgroundBlur.desc': '模糊窗口后方的桌面。100% 不透明时效果不可见,但会保留你的开关设置。',
'settings.appearance.appIcon': '应用图标',
'settings.appearance.appIcon.desc': '选择 Dock/任务栏图标风格,切换应用时更容易找到 Netcatty。Windows 通知区域图标会使用同一套风格。运行时生效,安装包内的图标不会改变。',
'settings.appearance.appIcon.original': '原始',
@@ -1177,6 +1179,8 @@ Vaults 标签保持扁平,不使用这块背景。
'qs.default': '默认',
'settings.tab.plugins': '插件',
"settings.plugins.manager.installed": "已安装插件",
"settings.plugins.author.official": "官方维护",
"settings.plugins.author.officialMeaning": "由 Netcatty 项目维护。这不是安全认证。",
"settings.plugins.manager.import": "导入 .ncpkg",
"settings.plugins.manager.preview": "导入的插件保持停用,请检查后再启用。",
"settings.plugins.manager.empty": "导入本地插件包以开始使用。",
@@ -1213,19 +1217,23 @@ Vaults 标签保持扁平,不使用这块背景。
"plugins.interaction.closeDraft": "关闭草稿",
"settings.plugins.permissions.current": "匹配当前运行实例",
"settings.plugins.permissions.inactive": "对当前运行实例不生效",
"settings.plugins.permissions.title": "已保存的授权",
"settings.plugins.permissions.note": "已声明且受支持的权限默认允许。询问时显示一次范围明确的确认;拒绝会立即阻止访问。选择目标和编辑草稿仍使用宿主界面。",
"settings.plugins.permissions.allow": "允许",
"settings.plugins.permissions.ask": "询问",
"settings.plugins.permissions.deny": "拒绝",
"settings.plugins.permissions.title": "权限",
"settings.plugins.permissions.refresh": "刷新",
"settings.plugins.permissions.loading": "正在读取授权...",
"settings.plugins.permissions.loading": "正在加载权限...",
"settings.plugins.permissions.empty": "没有已保存的授权。单次决定不会保留。",
"settings.plugins.permissions.always": "直到撤销",
"settings.plugins.permissions.application": "直到退出 Netcatty",
"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": "来自 manifest,不代表已授权。启用表示允许按需激活;必需权限在首次激活前申请,可选权限在用到时申请。敏感操作仍受宿主检查。",
"settings.plugins.manager.permissionNote": "已声明且受支持的权限默认允许。可以在权限设置中逐项改为询问或拒绝;宿主验证和资源范围限制始终生效。",
"settings.plugins.manager.noPermissions": "未声明特权权限。",
"settings.plugins.manager.required": "必需",
"settings.plugins.manager.optional": "可选",
@@ -1268,7 +1276,7 @@ Vaults 标签保持扁平,不使用这块背景。
"settings.plugins.market.sourceOnly": "第一方源码示例。请用本地 CLI 构建并导入 .ncpkg;尚未发布可下载发行包。",
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不执行,远程图片不加载。内容由插件作者提供。",
"settings.plugins.manager.noVault": "系统密钥存储不可用。秘密和凭据操作被阻止;浏览市场和不使用秘密的插件仍可使用。",
"settings.plugins.manager.sensitive": "敏感访问:授权前请检查涉及的数据和资源范围。",
"settings.plugins.manager.sensitive": "敏感访问:此能力可能涉及私密数据,可在权限设置中调整其模式。",
"settings.plugins.manager.dual": "默认使用浏览器运行时,但包中还包含拥有完整设备权限的 Node 入口;仅限开发者模式。",
"settings.plugins.manager.advancedDeclaration": "浏览器入口声明了高级权限。不适用于普通浏览器插件模式;请逐项检查声明权限。",
"settings.plugins.market.retry": "重试",
@@ -1277,7 +1285,7 @@ Vaults 标签保持扁平,不使用这块背景。
"settings.plugins.market.search": "搜索名称、作者或描述",
"settings.plugins.market.noResults": "没有匹配插件,请尝试其他关键词。",
"settings.plugins.market.manifest": "兼容性与权限",
"settings.plugins.manager.unbounded": "未声明更细的资源范围。请在权限提示中检查实际授权范围。",
"settings.plugins.manager.unbounded": "未声明更细的资源范围,仍受应用校验和所选权限模式约束。",
"settings.plugins.openView": "打开",
"settings.plugins.openManager": "打开插件管理",
"settings.plugins.sources.conflict": "此 ID 已从其他来源安装。请先卸载并明确清理旧来源数据,再换源重装。原来源:",
@@ -1330,7 +1338,7 @@ Vaults 标签保持扁平,不使用这块背景。
'plugins.authentication.responseFailedWithMessage': '无法发送认证响应:{message}。请重试或取消此请求。',
'plugins.authentication.continue': '继续',
'plugins.hostActions.select': '分享所选主机的元数据',
'plugins.hostActions.selectionNote': '向此插件分享已保存的名称、地址、用户名、协议、分组和标签。选择分组仅包含本次选中的成员。连接主机需要单独确认。',
'plugins.hostActions.selectionNote': '仅向此插件共享所选主机的元数据:名称、地址、用户名、协议、分组和标签。选择分组仅包含本次选中的成员。后续编辑或连接请求遵循此插件的权限设置。',
'plugins.hostActions.create': '预览主机草稿',
'plugins.hostActions.edit': '预览主机修改',
'plugins.hostActions.connect': '确认连接',
+15 -7
View File
@@ -588,6 +588,8 @@ Vaults 分頁維持扁平,不使用這塊背景。
'settings.appearance.uiFont.desc': '選擇軟體介面使用的字型',
'settings.appearance.windowOpacity': '視窗透明度',
'settings.appearance.windowOpacity.desc': '調節整個應用程式視窗的透明度,方便疊在其他內容上方。較低時終端文字也會變淡;部分 Linux 桌面環境可能不支援。',
'settings.appearance.windowBackgroundBlur': '毛玻璃背景',
'settings.appearance.windowBackgroundBlur.desc': '模糊視窗後方的桌面。100% 不透明時效果不可見,但會保留你的開關設定。',
'settings.appearance.appIcon': '應用程式圖示',
'settings.appearance.appIcon.desc': '選擇 Dock/工作列圖示風格,切換應用程式時更容易找到 Netcatty。Windows 通知區域圖示會使用同一套風格。執行時生效,安裝檔內的圖示不會改變。',
'settings.appearance.appIcon.original': '原始',
@@ -1179,6 +1181,8 @@ Vaults 分頁維持扁平,不使用這塊背景。
'qs.default': '預設',
'settings.tab.plugins': '外掛程式',
"settings.plugins.author.official": "官方維護",
"settings.plugins.author.officialMeaning": "由 Netcatty 專案維護。這不是安全認證。",
"settings.plugins.manager.installed": "已安裝插件",
"settings.plugins.manager.import": "導入 .ncpkg",
"settings.plugins.manager.preview": "導入的插件保持停用,請檢查後再啟用。",
@@ -1216,19 +1220,23 @@ Vaults 分頁維持扁平,不使用這塊背景。
"plugins.interaction.closeDraft": "關閉草稿",
"settings.plugins.permissions.current": "符合目前執行個體",
"settings.plugins.permissions.inactive": "對目前執行個體不生效",
"settings.plugins.permissions.title": "已儲存的授權",
"settings.plugins.permissions.note": "已宣告且受支援的權限預設允許。詢問時顯示一次範圍明確的確認;拒絕會立即阻止存取。選擇目標和編輯草稿仍使用宿主介面。",
"settings.plugins.permissions.allow": "允許",
"settings.plugins.permissions.ask": "詢問",
"settings.plugins.permissions.deny": "拒絕",
"settings.plugins.permissions.title": "權限",
"settings.plugins.permissions.refresh": "重新整理",
"settings.plugins.permissions.loading": "正在讀取授權...",
"settings.plugins.permissions.loading": "正在載入權限...",
"settings.plugins.permissions.empty": "沒有已儲存的授權。單次決定不會保留。",
"settings.plugins.permissions.always": "直到撤銷",
"settings.plugins.permissions.application": "直到退出 Netcatty",
"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": "來自 manifest,不代表已授權。啟用表示允許按需激活;必需權限在首次激活前申請,可選權限在用到時申請。敏感操作仍受宿主檢查。",
"settings.plugins.manager.permissionNote": "已宣告且受支援的權限預設允許。可以在權限設定中逐項改為詢問或拒絕;宿主驗證和資源範圍限制始終生效。",
"settings.plugins.manager.noPermissions": "未聲明特權權限。",
"settings.plugins.manager.required": "必需",
"settings.plugins.manager.optional": "可選",
@@ -1248,7 +1256,7 @@ Vaults 分頁維持扁平,不使用這塊背景。
"settings.plugins.manager.browser": "瀏覽器運行時:特權訪問通過宿主權限代理。",
"settings.plugins.manager.advanced": "高級運行時:擁有完整 Node 文件系統和網絡能力,代理權限無法限制這些訪問。僅供開發預覽。",
"settings.plugins.manager.data": "本地 KV 僅保留在此設備。只有明確標記為同步的非秘密設置進入加密雲 sidecar。插件包和權限授權不參與同步。",
"settings.plugins.manager.unbounded": "未宣告更細的資源範圍。請在權限提示中檢查實際授權範圍。",
"settings.plugins.manager.unbounded": "未宣告更細的資源範圍,仍受應用程式驗證和所選權限模式約束。",
"settings.plugins.openView": "開啟",
"settings.plugins.openManager": "開啟插件管理",
"settings.plugins.sources.conflict": "此 ID 已从其他来源安装。请先卸载并明确清理旧来源数据,再换源重装。原来源:",
@@ -1296,7 +1304,7 @@ Vaults 分頁維持扁平,不使用這塊背景。
"settings.plugins.market.sourceOnly": "第一方源碼示例。請用本地 CLI 構建並導入 .ncpkg;尚未發佈可下載發行包。",
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不執行,遠程圖片不加載。內容由插件作者提供。",
"settings.plugins.manager.noVault": "系統密鑰存儲不可用。秘密和憑據操作被阻止;瀏覽市場和不使用秘密的插件仍可使用。",
"settings.plugins.manager.sensitive": "敏感訪問:授權前請檢查涉及的數據和資源範圍。",
"settings.plugins.manager.sensitive": "敏感存取:此能力可能涉及私密資料,可在權限設定中調整其模式。",
"settings.plugins.manager.dual": "默認使用瀏覽器運行時,但包中還包含擁有完整設備權限的 Node 入口;僅限開發者模式。",
"settings.plugins.manager.advancedDeclaration": "瀏覽器入口聲明瞭高級權限。不適用於普通瀏覽器插件模式;請逐項檢查聲明權限。",
"settings.plugins.market.retry": "重試",
@@ -1333,7 +1341,7 @@ Vaults 分頁維持扁平,不使用這塊背景。
'plugins.authentication.responseFailedWithMessage': '無法送出驗證回應:{message}。請重試或取消此要求。',
'plugins.authentication.continue': '繼續',
'plugins.hostActions.select': '分享所選主機的中繼資料',
'plugins.hostActions.selectionNote': '向此外掛分享已儲存的名稱、位址、使用者名稱、協定、群組和標籤。選擇群組僅包含本次選取的成員。連線需要另外確認。',
'plugins.hostActions.selectionNote': '僅向此外掛分享所選主機的中繼資料:名稱、位址、使用者名稱、協定、群組和標籤。選擇群組僅包含本次選取的成員。後續編輯或連線請求遵循此外掛的權限設定。',
'plugins.hostActions.create': '預覽主機草稿',
'plugins.hostActions.edit': '預覽主機修改',
'plugins.hostActions.connect': '確認連線',
+7
View File
@@ -49,6 +49,7 @@ import {
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN_TAB,
STORAGE_KEY_WINDOW_OPACITY,
STORAGE_KEY_WINDOW_BACKGROUND_BLUR,
STORAGE_KEY_APP_ICON_VARIANT,
STORAGE_KEY_HTTP_NETWORK_PROXY,
STORAGE_KEY_GLOBAL_DEFAULT_PROXY_PROFILE,
@@ -99,6 +100,7 @@ interface UseSettingsIpcSyncParams {
setIsHotkeyRecordingState: Dispatch<SetStateAction<boolean>>;
setGlobalHotkeyEnabled: Dispatch<SetStateAction<boolean>>;
setWindowOpacity: (raw: unknown) => void;
setWindowBackgroundBlur: Dispatch<SetStateAction<boolean>>;
setAppIconVariant: Dispatch<SetStateAction<AppIconVariant>>;
setAutoUpdateEnabled: Dispatch<SetStateAction<boolean>>;
setAutoLaunchEnabled: Dispatch<SetStateAction<boolean>>;
@@ -148,6 +150,7 @@ export function useSettingsIpcSync({
setIsHotkeyRecordingState,
setGlobalHotkeyEnabled,
setWindowOpacity,
setWindowBackgroundBlur,
setAppIconVariant,
setAutoUpdateEnabled,
setAutoLaunchEnabled,
@@ -279,6 +282,9 @@ export function useSettingsIpcSync({
if (key === STORAGE_KEY_WINDOW_OPACITY) {
setWindowOpacity(value);
}
if (key === STORAGE_KEY_WINDOW_BACKGROUND_BLUR && typeof value === 'boolean') {
setWindowBackgroundBlur((prev) => (prev === value ? prev : value));
}
if (key === STORAGE_KEY_APP_ICON_VARIANT) {
const nextVariant = resolveAppIconVariant(value);
setAppIconVariant((prev) => (prev === nextVariant ? prev : nextVariant));
@@ -371,6 +377,7 @@ export function useSettingsIpcSync({
setFollowAppTerminalThemeState,
setGlobalHotkeyEnabled,
setWindowOpacity,
setWindowBackgroundBlur,
setAppIconVariant,
setHotkeyScheme,
setIsHotkeyRecordingState,
+14 -4
View File
@@ -53,6 +53,7 @@ import {
STORAGE_KEY_UI_LANGUAGE,
STORAGE_KEY_WORKSPACE_FOCUS_STYLE,
STORAGE_KEY_WINDOW_OPACITY,
STORAGE_KEY_WINDOW_BACKGROUND_BLUR,
STORAGE_KEY_APP_ICON_VARIANT,
} from '../../infrastructure/config/storageKeys';
import { resolveAppIconVariant, type AppIconVariant } from '../../domain/appIconVariant';
@@ -116,6 +117,7 @@ interface UseSettingsStorageSyncParams {
globalHotkeyEnabled: boolean;
autoUpdateEnabled: boolean;
windowOpacity: number;
windowBackgroundBlur: boolean;
appIconVariant: AppIconVariant;
setTheme: Dispatch<SetStateAction<'dark' | 'light' | 'system'>>;
setLightUiThemeId: Dispatch<SetStateAction<string>>;
@@ -166,6 +168,7 @@ interface UseSettingsStorageSyncParams {
setExplorerContextMenuEnabledState: (enabled: boolean) => void;
setGlobalHotkeyEnabled: Dispatch<SetStateAction<boolean>>;
setWindowOpacity: (raw: unknown) => void;
setWindowBackgroundBlur: Dispatch<SetStateAction<boolean>>;
setAppIconVariant: Dispatch<SetStateAction<AppIconVariant>>;
setAutoUpdateEnabled: Dispatch<SetStateAction<boolean>>;
setWorkspaceFocusStyleState: Dispatch<SetStateAction<'dim' | 'border'>>;
@@ -184,7 +187,7 @@ export function useSettingsStorageSync({
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, windowBackgroundBlur, appIconVariant,
setTheme, setLightUiThemeId, setDarkUiThemeId, setAccentMode, applyIncomingCustomAccent,
setCustomCSS, setUiFontFamilyId, setHotkeyScheme, setUiLanguage,
setTerminalThemeId, setTerminalThemeDarkId, setTerminalThemeLightId,
@@ -193,7 +196,7 @@ export function useSettingsStorageSync({
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled, setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setExplorerContextMenuEnabledState,
setGlobalHotkeyEnabled, setWindowOpacity, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState,
setGlobalHotkeyEnabled, setWindowOpacity, setWindowBackgroundBlur, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState,
setSftpTransferConcurrencyState, setSshTransportIdleTtlMsState,
applyIncomingCustomKeyBindings, mergeIncomingTerminalSettings,
}: UseSettingsStorageSyncParams) {
@@ -208,7 +211,7 @@ export function useSettingsStorageSync({
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, windowBackgroundBlur, appIconVariant,
});
settingsSnapshotRef.current = {
theme, lightUiThemeId, darkUiThemeId, accentMode, customAccent, customAccentVersion,
@@ -218,7 +221,7 @@ export function useSettingsStorageSync({
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, windowBackgroundBlur, appIconVariant,
};
// Listen for storage changes from other windows (cross-window sync)
@@ -523,6 +526,12 @@ export function useSettingsStorageSync({
if (e.key === STORAGE_KEY_WINDOW_OPACITY && e.newValue !== null) {
setWindowOpacity(e.newValue);
}
if (e.key === STORAGE_KEY_WINDOW_BACKGROUND_BLUR && e.newValue !== null) {
const newValue = e.newValue === 'true';
if (newValue !== s.windowBackgroundBlur) {
setWindowBackgroundBlur(newValue);
}
}
if (e.key === STORAGE_KEY_APP_ICON_VARIANT && e.newValue !== null) {
const newValue = resolveAppIconVariant(e.newValue);
if (newValue !== s.appIconVariant) {
@@ -566,6 +575,7 @@ export function useSettingsStorageSync({
setGlobalHotkeyEnabled,
setHostClickBehaviorState,
setWindowOpacity,
setWindowBackgroundBlur,
setAppIconVariant,
setHotkeyScheme,
setLightUiThemeId,
@@ -7,6 +7,7 @@ import {
STORAGE_KEY_GLOBAL_HOTKEY_ENABLED,
STORAGE_KEY_TOGGLE_WINDOW_HOTKEY,
STORAGE_KEY_WINDOW_OPACITY,
STORAGE_KEY_WINDOW_BACKGROUND_BLUR,
STORAGE_KEY_APP_ICON_VARIANT,
STORAGE_KEY_HTTP_NETWORK_PROXY,
} from '../../infrastructure/config/storageKeys';
@@ -17,6 +18,8 @@ import {
} from '../../domain/httpNetworkProxy';
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { isMacPlatform } from '../../lib/utils';
import { isWindowBackgroundBlurActive } from '../../domain/windowBackgroundBlur';
import {
parseWindowOpacityRecord,
serializeWindowOpacityRecord,
@@ -47,6 +50,7 @@ interface UseSystemSettingsEffectsParams {
autoLaunchEnabled: boolean;
windowOpacityRecord: WindowOpacityRecord;
windowOpacityMutationSourceRef: MutableRefObject<WindowOpacityMutationSource>;
windowBackgroundBlur: boolean;
appIconVariant: AppIconVariant;
autoUpdateEnabled: boolean;
httpNetworkProxy: HttpNetworkProxySettings;
@@ -68,6 +72,7 @@ export function useSystemSettingsEffects({
autoLaunchEnabled,
windowOpacityRecord,
windowOpacityMutationSourceRef,
windowBackgroundBlur,
appIconVariant,
autoUpdateEnabled,
httpNetworkProxy,
@@ -300,6 +305,49 @@ export function useSystemSettingsEffects({
persistMountedRef,
]);
// Window chrome also applies in detached sessions, independently of the
// OS-level effects disabled there (tray, global shortcuts, autolaunch, ...).
// Only the windows that own settings persistence drive the shared native
// state; detached/editor windows consume it (see applySharedWindowSetting).
useEffect(() => {
if (!enabled) return;
localStorageAdapter.writeBoolean(STORAGE_KEY_WINDOW_BACKGROUND_BLUR, windowBackgroundBlur);
if (!persistMountedRef.current) return;
notifySettingsChanged(STORAGE_KEY_WINDOW_BACKGROUND_BLUR, windowBackgroundBlur);
}, [
enabled,
windowBackgroundBlur,
notifySettingsChanged,
persistMountedRef,
]);
const windowBackgroundBlurActive = isMacPlatform() && isWindowBackgroundBlurActive(
windowBackgroundBlur,
windowOpacityRecord.opacity,
);
// Applies in every app-content window, including detached sessions: the
// transparent backing only looks right when the renderer class matches the
// native vibrancy the main process put on that window.
useEffect(() => {
if (typeof document === 'undefined') return;
document.documentElement.classList.toggle('window-background-blur', windowBackgroundBlurActive);
document.documentElement.style.setProperty('--window-content-opacity', String(windowOpacityRecord.opacity));
return () => {
document.documentElement.classList.remove('window-background-blur');
document.documentElement.style.removeProperty('--window-content-opacity');
};
}, [windowBackgroundBlurActive, windowOpacityRecord.opacity]);
// setWindowBackgroundBlur is a main-process handler that retargets every
// app-content window, so a single owner must drive it.
useEffect(() => {
if (!enabled) return;
netcattyBridge.get()?.setWindowBackgroundBlur?.(windowBackgroundBlur).catch((err) => {
console.warn('[WindowBackgroundBlur] Failed to apply macOS vibrancy:', err);
});
}, [enabled, windowBackgroundBlur]);
// Persist and sync app icon variant
useEffect(() => {
if (!enabled) return;
@@ -0,0 +1,139 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { JSDOM } from 'jsdom';
import { STORAGE_KEY_WINDOW_BACKGROUND_BLUR } from '../../infrastructure/config/storageKeys';
import { DEFAULT_HTTP_NETWORK_PROXY } from '../../domain/httpNetworkProxy';
import { useSystemSettingsEffects } from './systemSettingsEffects';
type Harness = {
dom: JSDOM;
params: Parameters<typeof useSystemSettingsEffects>[0];
bridgeRequests: boolean[];
blurNotifications: unknown[];
restore: () => void;
};
function setUp(enabled: boolean, windowBackgroundBlur: boolean): Harness {
const dom = new JSDOM('<html><body><div id="root"></div></body></html>', { url: 'http://localhost' });
Object.defineProperty(dom.window.navigator, 'platform', { value: 'MacIntel' });
const previousGlobals = new Map<string, PropertyDescriptor | undefined>();
const replacements = {
window: dom.window,
document: dom.window.document,
navigator: dom.window.navigator,
localStorage: dom.window.localStorage,
IS_REACT_ACT_ENVIRONMENT: true,
};
for (const [key, value] of Object.entries(replacements)) {
previousGlobals.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { value, configurable: true });
}
const bridgeRequests: boolean[] = [];
const blurNotifications: unknown[] = [];
Object.assign(dom.window, {
netcatty: {
setWindowBackgroundBlur: async (value: boolean) => { bridgeRequests.push(value); },
},
});
const noop = () => {};
const params: Parameters<typeof useSystemSettingsEffects>[0] = {
enabled,
toggleWindowHotkey: '',
globalHotkeyEnabled: false,
closeToTray: false,
showTrayIcon: false,
autoLaunchEnabled: false,
windowOpacityRecord: { opacity: 0.7, preferredOpacity: 0.7, version: 1 },
windowOpacityMutationSourceRef: { current: 'local' },
windowBackgroundBlur,
appIconVariant: 'original',
autoUpdateEnabled: false,
httpNetworkProxy: DEFAULT_HTTP_NETWORK_PROXY,
persistMountedRef: { current: true },
setHotkeyRegistrationError: noop,
setAutoUpdateEnabled: noop,
setAppIconVariant: noop,
setAutoLaunchEnabled: noop,
setAutoLaunchSupported: noop,
notifySettingsChanged: (key, value) => {
if (key === STORAGE_KEY_WINDOW_BACKGROUND_BLUR) blurNotifications.push(value);
},
};
return {
dom,
params,
bridgeRequests,
blurNotifications,
restore: () => {
for (const [key, descriptor] of previousGlobals) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
dom.window.close();
},
};
}
const Probe = (props: Parameters<typeof useSystemSettingsEffects>[0]) => {
useSystemSettingsEffects(props);
return null;
};
test('opacity changes and remounts preserve the chosen blur preference', async () => {
const harness = setUp(true, true);
const { dom, params, bridgeRequests, blurNotifications, restore } = harness;
let renderer: ReactTestRenderer | undefined;
try {
await act(async () => { renderer = create(React.createElement(Probe, params)); });
assert.equal(document.documentElement.classList.contains('window-background-blur'), true);
const opaqueParams = { ...params, windowOpacityRecord: { ...params.windowOpacityRecord, opacity: 1, version: 2 } };
await act(async () => { renderer!.update(React.createElement(Probe, opaqueParams)); });
assert.equal(document.documentElement.classList.contains('window-background-blur'), false);
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_WINDOW_BACKGROUND_BLUR), 'true');
assert.deepEqual(bridgeRequests, [true]);
assert.deepEqual(blurNotifications, [true]);
await act(async () => { renderer!.unmount(); });
await act(async () => { renderer = create(React.createElement(Probe, opaqueParams)); });
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_WINDOW_BACKGROUND_BLUR), 'true');
await act(async () => { renderer!.update(React.createElement(Probe, params)); });
assert.equal(document.documentElement.classList.contains('window-background-blur'), true);
await act(async () => { renderer!.update(React.createElement(Probe, { ...params, windowBackgroundBlur: false })); });
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_WINDOW_BACKGROUND_BLUR), 'false');
assert.equal(document.documentElement.classList.contains('window-background-blur'), false);
assert.deepEqual(bridgeRequests, [true, true, false]);
} finally {
await act(async () => { renderer?.unmount(); });
restore();
}
});
test('detached session windows only apply the blur class, never own the setting', async () => {
// Peer session windows run with enableSystemEffects off. They must still
// paint the transparent backing, but persistence, cross-window broadcast and
// the (all-windows) native vibrancy IPC stay with the settings owners.
const harness = setUp(false, true);
const { dom, params, bridgeRequests, blurNotifications, restore } = harness;
let renderer: ReactTestRenderer | undefined;
try {
await act(async () => { renderer = create(React.createElement(Probe, params)); });
assert.equal(document.documentElement.classList.contains('window-background-blur'), true);
assert.equal(document.documentElement.style.getPropertyValue('--window-content-opacity'), '0.7');
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_WINDOW_BACKGROUND_BLUR), null);
assert.deepEqual(bridgeRequests, []);
assert.deepEqual(blurNotifications, []);
await act(async () => {
renderer!.update(React.createElement(Probe, { ...params, windowBackgroundBlur: false }));
});
assert.equal(document.documentElement.classList.contains('window-background-blur'), false);
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_WINDOW_BACKGROUND_BLUR), null);
assert.deepEqual(bridgeRequests, []);
assert.deepEqual(blurNotifications, []);
} finally {
await act(async () => { renderer?.unmount(); });
restore();
}
});
+2 -1
View File
@@ -4,7 +4,7 @@ import { getNotesSnapshot } from './notesStore';
import { useActiveTabId } from './activeTabStore';
import { getAppAppLockRuntime } from './appRuntimeBridge';
import { createTrustedPluginAIHostRuntime } from '../../infrastructure/ai/plugin/trustedHostRuntime';
import { getConfiguredPluginModel } from '../../infrastructure/ai/plugin/configuredModel';
import { getConfiguredPluginModel, prepareConfiguredPluginModel } from '../../infrastructure/ai/plugin/configuredModel';
import { buildSelectedPluginSources } from '../../infrastructure/ai/plugin/selectedSources';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
@@ -29,6 +29,7 @@ export function usePluginAIContextHost({ sessions, workspaces }: { sessions: Ter
const requests = new Map<string, { runtimeId: string; controller: AbortController }>();
const runtime = createTrustedPluginAIHostRuntime({
getModel: getConfiguredPluginModel,
prepareModel: prepareConfiguredPluginModel,
isActive: () => mounted && document.visibilityState === 'visible' && getAppAppLockRuntime()?.locked === false,
chooseSelected: (signal, runtimeId) => new Promise((resolve, reject) => {
if (chooser) { reject(Error('A host selection is already pending')); return; }
@@ -0,0 +1,59 @@
import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
// All visible rows share one IPC subscription. No catalog fetch or polling here.
const generations = new Map<string, number>();
const listeners = new Set<() => void>();
let unsubscribe: (() => void) | undefined;
function subscribe(listener: () => void) {
listeners.add(listener);
if (listeners.size === 1) unsubscribe = netcattyBridge.get()?.onPluginCatalogChanged?.(({ sourceId }) => {
generations.set(sourceId, (generations.get(sourceId) ?? 0) + 1);
for (const notify of listeners) notify();
});
return () => {
listeners.delete(listener);
if (!listeners.size) { unsubscribe?.(); unsubscribe = undefined; generations.clear(); }
};
}
export function usePluginAuthorIdentity({ entry, plugin, sourceId = 'official' }: {
entry?: NetcattyPluginCatalogEntry; plugin?: NetcattyInstalledPlugin; sourceId?: string;
}) {
const [element, setElement] = useState<HTMLElement | null>(null);
const [loaded, setLoaded] = useState<{ key: string; value: NetcattyPluginAuthorPresentation } | null>(null);
const pluginId = plugin?.id;
const entryId = entry?.id;
const selectionToken = entry?.selectionToken;
const request = useMemo<NetcattyPluginAuthorRequest | null>(() => pluginId
? { kind: 'installed', pluginId }
: entryId && selectionToken ? { kind: 'catalog', pluginId: entryId, selectionToken, sourceId } : null,
[pluginId, entryId, selectionToken, sourceId]);
const identitySource = plugin?.source?.id ?? sourceId;
const generation = useSyncExternalStore(subscribe, () => generations.get(identitySource) ?? 0, () => 0);
const key = JSON.stringify([request, plugin?.activeVersion, plugin?.archiveSha256, plugin?.source?.id, plugin?.runtime?.quarantinedAt, generation]);
const installed = Boolean(plugin);
const version = plugin?.activeVersion;
const archiveSha256 = plugin?.archiveSha256 ?? null;
const installedSourceId = plugin?.source?.id ?? 'local';
useEffect(() => {
if (!element || !request) return;
let active = true;
let started = false;
const load = () => {
if (started) return;
started = true;
void netcattyBridge.get()?.getPluginAuthorPresentation?.(request).then((value) => {
if (!active || !value) return;
if (installed && (value.version !== version || value.archiveSha256 !== archiveSha256 || value.sourceId !== installedSourceId)) return;
setLoaded({ key, value });
}).catch(() => { /* The visible author placeholder remains usable offline. */ });
};
const observer = typeof IntersectionObserver === 'undefined' ? null : new IntersectionObserver((entries) => {
if (entries.some((entry) => entry.isIntersecting)) { load(); observer?.disconnect(); }
}, { rootMargin: '64px' });
if (observer) observer.observe(element); else load();
return () => { active = false; observer?.disconnect(); };
}, [element, request, key, installed, version, archiveSha256, installedSourceId]);
return { ref: setElement, identity: loaded?.key === key ? loaded.value : null };
}
+8 -3
View File
@@ -112,7 +112,7 @@ export function usePluginHostActions() {
const entry = current.current;
if (!entry || entry.prompt.requestId !== prompt.requestId || entry.prompt.request.kind !== prompt.request.kind) throw new Error('Host review is unavailable');
entry.prompt = prompt;
setReview({ ...entry });
if (!(prompt.request.kind === 'vault.requestConnect' && prompt.permissionMode === 'allow')) setReview({ ...entry });
void execute(entry);
return;
}
@@ -126,7 +126,12 @@ export function usePluginHostActions() {
scriptsRun: host ? pluginHostRunsSavedScripts(host, vault.groupConfigs, vault.snippets) : false,
claimed: false,
};
current.current = entry; setReview(entry); setSelectedIds([]); setBusy(false); setError(false); responding.current = false;
current.current = entry; setSelectedIds([]); setBusy(false); setError(false); responding.current = false;
if (prompt.request.kind === 'vault.requestConnect' && prompt.permissionMode === 'allow') {
setReview(null);
void bridge.respondPluginInteraction?.({ requestId: prompt.requestId, actionToken: prompt.actionToken,
action: 'submit', scriptsRun: entry.scriptsRun }).catch(() => void fail(entry));
} else setReview(entry);
} catch {
void bridge.respondPluginInteraction?.({ requestId: prompt.requestId, actionToken: prompt.actionToken, action: 'fail' }).catch(() => {});
}
@@ -137,7 +142,7 @@ export function usePluginHostActions() {
unsubscribe();
if (entry && !entry.claimed) void bridge.respondPluginInteraction?.({ requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action: 'cancel' }).catch(() => {});
};
}, [execute, getVault]);
}, [execute, fail, getVault]);
const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields) => {
const entry = current.current;
+10 -1
View File
@@ -20,7 +20,16 @@ export function usePluginHostInteractions() {
current.current = null; setPrompt(null);
} else {
if (event.request.kind.startsWith('vault.')) return;
current.current = event as UiPrompt; setPrompt(event as UiPrompt);
current.current = event as UiPrompt;
if (event.request.kind === 'terminal.selection.read' && event.phase === 'request') {
setPrompt(null);
try {
const selection = readPluginTerminalSelection(event.terminalSessionId ?? '', event.terminalRendererId ?? '');
void bridge.respondPluginInteraction?.({ requestId: event.requestId, actionToken: event.actionToken, action: 'preview', value: selection }).catch(() => {
void bridge.respondPluginInteraction?.({ requestId: event.requestId, actionToken: event.actionToken, action: 'cancel' }).catch(() => {});
});
} catch { void bridge.respondPluginInteraction?.({ requestId: event.requestId, actionToken: event.actionToken, action: 'cancel' }).catch(() => {}); }
} else setPrompt(event as UiPrompt);
setValue(event.request.kind === 'input' ? event.request.initialValue ?? '' : event.request.kind === 'terminal.input.propose' ? event.request.text : '');
}
pending.current = false; setBusy(false); setError(false);
@@ -0,0 +1,31 @@
import { useEffect, useRef, useState } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
export function usePluginPermissionPrompt() {
const [prompts, setPrompts] = useState<NetcattyPluginPermissionPrompt[]>([]);
const [busy, setBusy] = useState(false);
const active = useRef<NetcattyPluginPermissionPrompt | null>(null);
const prompt = prompts[0];
active.current = prompt ?? null;
useEffect(() => {
const bridge = netcattyBridge.get();
if (!bridge?.onPluginPermission || !bridge.setPluginPermissionReady) return;
const unsubscribe = bridge.onPluginPermission((event) => {
setPrompts((previous) => 'closed' in event ? previous.filter((item) => item.requestId !== event.requestId)
: [...previous.filter((item) => item.requestId !== event.requestId), event]);
setBusy(false);
});
void bridge.setPluginPermissionReady(true).catch(() => {});
return () => { unsubscribe(); void bridge.setPluginPermissionReady?.(false).catch(() => {}); };
}, []);
const respond = async (decision: 'allow' | 'deny' | 'cancel') => {
if (!prompt || busy || active.current !== prompt) return;
setBusy(true);
try {
const accepted = await netcattyBridge.require().respondPluginPermission?.({ requestId: prompt.requestId, actionToken: prompt.actionToken, decision });
if (!accepted) setPrompts((previous) => previous.filter((item) => item.requestId !== prompt.requestId));
} catch { setPrompts((previous) => previous.filter((item) => item.requestId !== prompt.requestId)); }
finally { setBusy(false); }
};
return { prompt, busy, respond };
}
+18 -4
View File
@@ -74,6 +74,7 @@ import {
STORAGE_KEY_GLOBAL_DEFAULT_PROXY_PROFILE,
STORAGE_KEY_GLOBAL_HOTKEY_ENABLED,
STORAGE_KEY_WINDOW_OPACITY,
STORAGE_KEY_WINDOW_BACKGROUND_BLUR,
STORAGE_KEY_APP_ICON_VARIANT,
STORAGE_KEY_AUTO_UPDATE_ENABLED,
STORAGE_KEY_WORKSPACE_FOCUS_STYLE,
@@ -645,6 +646,9 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
windowOpacityMutationSourceRef.current = 'local';
setWindowOpacityRecord(toggleWindowOpacityRecord);
}, []);
const [windowBackgroundBlur, setWindowBackgroundBlur] = useState<boolean>(() => {
return readStoredString(STORAGE_KEY_WINDOW_BACKGROUND_BLUR) === 'true';
});
const [appIconVariant, setAppIconVariantState] = useState<AppIconVariant>(() => {
const stored = readStoredString(STORAGE_KEY_APP_ICON_VARIANT);
return resolveAppIconVariant(stored ?? DEFAULT_APP_ICON_VARIANT);
@@ -1276,6 +1280,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setIsHotkeyRecordingState,
setGlobalHotkeyEnabled,
setWindowOpacity: applyIncomingWindowOpacity,
setWindowBackgroundBlur,
setAppIconVariant,
setAutoUpdateEnabled,
setAutoLaunchEnabled,
@@ -1298,12 +1303,18 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setSshTransportIdleTtlMsState,
});
// Detached sessions share opacity and the shortcut configuration needed to
// operate it. Keep general settings listeners and OS effects disabled there.
// Detached sessions share window chrome (opacity, background blur) and the
// shortcut configuration needed to operate it. Keep general settings
// listeners and OS effects disabled there.
useEffect(() => {
if (enableSettingsSync) return;
const applySharedWindowSetting = (key: string, value: unknown) => {
if (key === STORAGE_KEY_WINDOW_OPACITY) applyIncomingWindowOpacity(value);
if (key === STORAGE_KEY_WINDOW_BACKGROUND_BLUR) {
// Storage events deliver the raw string; IPC delivers a boolean.
const incoming = typeof value === 'boolean' ? value : value === 'true';
setWindowBackgroundBlur(incoming);
}
if (key === STORAGE_KEY_HOTKEY_SCHEME && (value === 'disabled' || value === 'mac' || value === 'pc')) {
setHotkeyScheme(value);
}
@@ -1377,7 +1388,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant,
globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, windowBackgroundBlur, appIconVariant,
setTheme, setLightUiThemeId, setDarkUiThemeId, setAccentMode,
applyIncomingCustomAccent,
setCustomCSS, setUiFontFamilyId, setHotkeyScheme, setUiLanguage,
@@ -1387,7 +1398,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled, setSshDebugLogsEnabled, setSshDeepLinkEnabledState: applyIncomingSshDeepLinkEnabled, setJmsDeepLinkEnabledState: applyIncomingJmsDeepLinkEnabled, setExplorerContextMenuEnabledState: applyIncomingExplorerContextMenuEnabled,
setGlobalHotkeyEnabled, setWindowOpacity: applyIncomingWindowOpacity, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState,
setGlobalHotkeyEnabled, setWindowOpacity: applyIncomingWindowOpacity, setWindowBackgroundBlur, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState,
setSftpTransferConcurrencyState, setSshTransportIdleTtlMsState,
applyIncomingCustomKeyBindings, mergeIncomingTerminalSettings,
});
@@ -1896,6 +1907,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
autoLaunchEnabled,
windowOpacityRecord,
windowOpacityMutationSourceRef,
windowBackgroundBlur,
appIconVariant,
autoUpdateEnabled,
httpNetworkProxy,
@@ -2276,6 +2288,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
windowOpacity,
setWindowOpacity,
toggleWindowOpacity,
windowBackgroundBlur,
setWindowBackgroundBlur,
appIconVariant,
setAppIconVariant,
rehydrateAllFromStorage,
+73 -14
View File
@@ -10,7 +10,7 @@ import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
test('default host adapter, real preload, mounted host chooser and installed assistant reach only the local fixture', { timeout: 20_000 }, async () => {
test('cold plugin host reaches the local fixture through the actual main provider allowlist without the AI sidebar', { timeout: 20_000 }, async (t) => {
// JSDOM + the in-process runtime prove app wiring; they are not native sandbox
// evidence. All state is synthetic, with no real provider, key, Note or host.
const rootPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -42,15 +42,40 @@ test('default host adapter, real preload, mounted host chooser and installed ass
const { inProcessBrowserRuntime } = require('../electron/plugins/fixtures/inProcessBrowserRuntime.cjs');
const { createPreloadApi } = require('../electron/preload/api.cjs');
const aiBridge = require('../electron/bridges/aiBridge.cjs');
const { registerProviderHandlers } = require('../electron/bridges/aiBridge/providerHandlers.cjs');
const { server, counts } = createAssistantProviderFixture({ delayMs: 25 });
const oldNotes = getNotesSnapshot(); const oldLock = getAppAppLockRuntime();
let service: ReturnType<typeof createPluginHostService> | undefined;
let panel: JSDOM | undefined;
const root = createRoot(document.getElementById('root')!);
let locked = false; let contentAllowed = false; let reviewAllowed = false;
let locked = false; let contentAllowed = false;
const lockListeners = new Set<(state: { locked: boolean }) => void>();
const reviews: Array<Record<string, unknown>> = [];
const trustedPayloads: unknown[] = [];
const streamResults: Array<{ ok: boolean; statusCode?: number; allowlistRejected: boolean }> = [];
const providerSyncs: Array<{ count: number; selectedPresent: boolean }> = [];
const sdkErrorNames: string[] = [];
let diagnosticPhase = 'setup';
const originalConsoleError = console.error;
// node:sqlite was imported above. Node 22 delivers its ExperimentalWarning
// asynchronously through console.error. Let module warnings reach normal
// stderr before observing SDK/renderer errors; do not suppress that warning.
await new Promise<void>((resolve) => setImmediate(resolve));
// The expected pre-fix SDK error contains request details. Keep diagnostics
// categorical even on the failing-before path; never print payloads/headers.
console.error = (value: unknown) => {
let category = 'unknown';
if (typeof value === 'string' && /not wrapped in act/.test(value)) category = 'react-act-warning';
else if (typeof value === 'string' && /act.*environment|environment.*act/.test(value)) category = 'react-act-environment';
else if (typeof value === 'string' && /ExperimentalWarning: SQLite is an experimental feature/.test(value)) category = 'node-sqlite-experimental';
else if (typeof value === 'string') category = 'other-string';
else if (value && typeof value === 'object') {
const name = (value as { name?: unknown }).name;
if (typeof name === 'string' && ['AbortError', 'AI_APICallError', 'AI_LoadAPIKeyError', 'TypeError', 'Error'].includes(name)) category = name;
}
sdkErrorNames.push(`${diagnosticPhase}:${category}`);
};
t.after(() => { console.error = originalConsoleError; });
try {
server.listen(0, '127.0.0.1'); await once(server, 'listening');
const address = server.address(); assert.ok(address && typeof address !== 'string');
@@ -62,25 +87,50 @@ test('default host adapter, real preload, mounted host chooser and installed ass
ipcRenderer.emit(channel, {}, structuredClone(payload));
} });
const mainWindow = Object.assign(new EventEmitter(), { webContents: sender, isDestroyed: () => false, isVisible: () => true, isFocused: () => true });
const providerContext = {
ipcMain: { handle: (channel: string, handler: (...args: unknown[]) => unknown) => ipcHandlers.set(channel, handler) },
providerConfigs: [] as Array<{ id: string; baseURL?: string; apiKey?: string }>, webSearchApiHost: null,
validateSender: (event: { sender: unknown }) => event.sender === sender,
validateSenderOrSettings: (event: { sender: unknown }) => event.sender === sender,
// Only credential injection is synthetic. Admission, sync and the HTTP
// transport are the production implementations, not a direct-fetch seam.
injectApiKeyIntoRequest: (url: string, headers: Record<string, string>, providerId: string) => {
const config = providerContext.providerConfigs.find((item) => item.id === providerId);
return { url, headers: Object.fromEntries(Object.entries(headers).map(([key, value]) =>
[key, config?.apiKey ? value.replace('__IPC_SECURED__', config.apiKey) : value])) };
},
shouldSkipTLSVerify: () => false,
streamRequest: aiBridge._streamRequestForTests,
};
registerProviderHandlers(providerContext);
assert.equal(providerContext.providerConfigs.length, 0);
ipcRenderer.invoke = async (channel, payload) => {
if (channel === 'netcatty:ai:chat:stream') {
const request = payload as { url: string; headers: Record<string, string>; body: string; requestId: string };
assert.equal(new URL(request.url).origin, new URL(endpoint).origin);
assert.doesNotMatch(JSON.stringify(request), /fixture-only/);
const status = await aiBridge._streamRequestForTests(request.url, { headers: request.headers, body: request.body }, { sender }, request.requestId, false);
return { ok: status.statusCode === 200, ...status };
}
if (channel === 'netcatty:ai:chat:cancel') return aiBridge.cancelPluginAIStreamsForSender(sender) > 0;
const handler = ipcHandlers.get(channel);
assert.ok(handler, `Unexpected trusted IPC: ${channel}`);
return handler({ sender }, structuredClone(payload));
const result = await handler({ sender }, structuredClone(payload));
if (channel === 'netcatty:ai:sync-providers') providerSyncs.push({ count: providerContext.providerConfigs.length,
selectedPresent: providerContext.providerConfigs.some((item) => item.id === 'qa-provider') });
if (channel === 'netcatty:ai:chat:stream') {
const status = result as { ok: boolean; statusCode?: number; error?: string };
streamResults.push({ ok: status.ok, statusCode: status.statusCode, allowlistRejected: status.error === 'URL host is not in the allowed list' });
}
return result;
};
const api = createPreloadApi({ ipcRenderer, webUtils: {} });
Object.defineProperty(dom.window, 'netcatty', { value: api });
const syntheticNote = { id: 'synthetic-note', title: 'Synthetic retry plan', content: 'Synthetic retry plan: add a retry button.', createdAt: 1, updatedAt: 1 };
publishNotesSnapshot({ notes: [syntheticNote], noteGroups: [] });
registerAppAppLockRuntime({ locked: false } as NonNullable<ReturnType<typeof getAppAppLockRuntime>>);
dom.window.localStorage.setItem(STORAGE_KEY_AI_PROVIDERS, JSON.stringify([{ id: 'qa-provider', name: 'QA fixture', providerId: 'custom', enabled: true, baseURL: endpoint, defaultModel: 'deterministic-fixture', apiKey: 'fixture-only' }]));
dom.window.localStorage.setItem(STORAGE_KEY_AI_PROVIDERS, JSON.stringify([
{ id: 'qa-provider', name: 'QA fixture', providerId: 'custom', enabled: true, baseURL: endpoint, defaultModel: 'deterministic-fixture', apiKey: 'fixture-only' },
{ id: 'qa-secondary', name: 'Synthetic secondary', providerId: 'custom', enabled: true, baseURL: 'https://secondary.invalid/v1', defaultModel: 'synthetic', apiKey: 'secondary-fixture-marker' },
]));
dom.window.localStorage.setItem(STORAGE_KEY_AI_ACTIVE_PROVIDER, 'qa-provider');
dom.window.localStorage.setItem(STORAGE_KEY_AI_ACTIVE_MODEL, 'deterministic-fixture');
service = createPluginHostService({
@@ -88,8 +138,8 @@ test('default host adapter, real preload, mounted host chooser and installed ass
getInteractionWindow: () => mainWindow, isAppLocked: () => locked,
subscribeAppLock: (listener: (state: { locked: boolean }) => void) => { lockListeners.add(listener); return () => lockListeners.delete(listener); },
electron: { ipcMain: { handle: (name: string, handler: (...args: unknown[]) => unknown) => ipcHandlers.set(name, handler), removeHandler: (name: string) => ipcHandlers.delete(name) },
dialog: { showMessageBox: async (_window: unknown, options: Record<string, unknown>) => { reviews.push(options); return { response: reviewAllowed ? 0 : 1 }; } } },
requestPermissionDecision: async (request: { requestId: string; permission: string }) => request.permission === 'context.selected.read' && !contentAllowed
dialog: { showMessageBox: async (_window: unknown, options: Record<string, unknown>) => { reviews.push(options); return { response: 1 }; } } },
requestPermissionDecision: async (request: { requestId: string; permission: string; relatedPermissions?: Array<{ permission: string }> }) => (request.permission === 'context.selected.read' || request.relatedPermissions?.some((item) => item.permission === 'context.selected.read')) && !contentAllowed
? { requestId: request.requestId, decision: 'deny' }
: { requestId: request.requestId, decision: 'allow', scope: request.permission === 'context.selected.read' ? 'once' : 'application' },
});
@@ -101,6 +151,7 @@ test('default host adapter, real preload, mounted host chooser and installed ass
fs.copyFileSync(path.join(sample, 'src/index.js'), path.join(staging, 'dist/index.js'));
const { buildPluginPackage } = await import('@netcatty/plugin-cli');
const archive = path.join(fixtureRoot, 'assistant.ncpkg'); await buildPluginPackage(staging, archive);
service.database.setPermissionMode('com.netcatty.assistant', 'context.selected.read', 'ask');
await service.manager.install(archive, { enable: true });
await act(async () => root.render(<I18nProvider locale="en"><PluginAIContextHost sessions={[]} workspaces={[]} /></I18nProvider>));
const waitFor = async (condition: () => boolean) => {
@@ -115,6 +166,7 @@ test('default host adapter, real preload, mounted host chooser and installed ass
executeCommand: async (command: string, args: unknown) => structuredClone(await service!.contributionService.executeCommand(command, structuredClone(args))),
onDidReceiveMessage: () => ({ dispose() {} }),
} });
diagnosticPhase = 'initial-selection';
await act(async () => panel!.window.eval(fs.readFileSync(path.join(sample, 'panel.js'), 'utf8')));
await waitFor(() => document.getElementById('plugin-ai-note') !== null);
const noteChoice = document.getElementById('plugin-ai-note') as HTMLSelectElement;
@@ -128,26 +180,33 @@ test('default host adapter, real preload, mounted host chooser and installed ass
assert.equal(reference.value, ''); assert.equal(reference.options.length, 2);
assert.notEqual(reference.options[1].value, syntheticNote.id); reference.value = reference.options[1].value;
const send = () => element('compose').dispatchEvent(new panel!.window.Event('submit', { cancelable: true }));
diagnosticPhase = 'deny-content';
send(); await waitFor(() => element('status').textContent!.startsWith('Request ended'));
assert.equal(counts.requests, 0); assert.equal(reviews.length, 0);
contentAllowed = true;
send(); await waitFor(() => element('status').textContent!.startsWith('Request ended'));
assert.equal(counts.requests, 0); assert.equal(reviews.length, 1);
assert.equal(reviews[0].defaultId, reviews[0].cancelId); assert.match(String(reviews[0].detail), /Synthetic retry plan: add a retry button/);
reviewAllowed = true;
send(); await waitFor(() => element('status').textContent === 'Complete');
diagnosticPhase = 'complete-stream';
send(); await waitFor(() => counts.completed === 1 || streamResults.some((result) => !result.ok));
assert.deepEqual(streamResults.at(-1), { ok: true, statusCode: 200, allowlistRejected: false },
'Cold plugin startup must synchronize host providers before the main allowlist admits transport');
assert.ok(providerSyncs.some((sync) => sync.selectedPresent && sync.count === 2), 'Preserve other host-configured providers in the shared registry');
await waitFor(() => element('status').textContent === 'Complete');
assert.equal(reviews.length, 0, 'content policy must not open a second native sharing review');
assert.equal(counts.completed, 1); assert.match(element('response').textContent!, /Synthetic plan/); assert.match(element('usage').textContent!, /12 input tokens/);
diagnosticPhase = 'stop-stream';
send(); await waitFor(() => element('response').textContent!.startsWith('Synthetic plan: '));
element('stop').dispatchEvent(new panel.window.Event('click'));
await waitFor(() => element('status').textContent === 'Stopped' && counts.aborted === 1);
const stoppedText = element('response').textContent; await new Promise((resolve) => setTimeout(resolve, 50)); assert.equal(element('response').textContent, stoppedText);
diagnosticPhase = 'lock-stream';
send(); await waitFor(() => element('response').textContent!.startsWith('Synthetic plan: '));
locked = true; registerAppAppLockRuntime({ locked: true } as NonNullable<ReturnType<typeof getAppAppLockRuntime>>);
for (const listener of lockListeners) listener({ locked: true });
await waitFor(() => counts.aborted === 2 && service!.aiContextService.broker.turns.size === 0);
assert.equal(aiBridge._getActiveStreamCountForTests(), 0);
assert.doesNotMatch(JSON.stringify(trustedPayloads), /fixture-only|apiKey|privateOwner|permissionMode|mcp/);
assert.doesNotMatch(JSON.stringify(trustedPayloads), /fixture-only|secondary-fixture-marker|apiKey|privateOwner|permissionMode|mcp/);
assert.deepEqual(sdkErrorNames, []);
} finally {
console.error = originalConsoleError;
panel?.window.close();
await act(async () => root.unmount());
await service?.manager.shutdown(); aiBridge.cleanup();
@@ -109,6 +109,7 @@ test('installed sample entrypoint uses real SDK, source authority, signed host d
const archive = path.join(directory, 'fixture.ncpkg');
await buildPluginPackage(packageRoot, archive);
await service.manager.install(archive, { enable: true });
service.database.setPermissionMode('com.netcatty.host-actions', 'ui.interact', 'ask');
service.interactionService.setReady(sender, true);
await act(async () => root.render(<I18nProvider locale="en"><PluginHostActionHost /></I18nProvider>));
@@ -192,8 +193,8 @@ test('installed sample entrypoint uses real SDK, source authority, signed host d
const run = await begin('edit'); await chooseGroup();
await waitFor(() => button('Save Host') !== undefined); await click(button('Save Host'));
await waitFor(() => preparing);
await act(async () => { service.permissionEngine.revokeApplication('com.netcatty.host-actions', 'vault.write'); release(); await settle(); });
await assert.rejects(run.promise, /revoked|cancelled/); assert.equal(saves, 1); beforeCommit = undefined;
await act(async () => { service.permissionEngine.setMode(service.database.getActivePlugin('com.netcatty.host-actions'), 'vault.write', 'deny'); release(); await settle(); });
await assert.rejects(run.promise, /revoked|cancelled/); assert.equal(saves, 1); beforeCommit = undefined; service.permissionEngine.setMode(service.database.getActivePlugin('com.netcatty.host-actions'), 'vault.write', 'allow');
});
await t.test('source replacement during review cannot use the old action authority', async () => {
@@ -272,13 +273,44 @@ test('installed sample entrypoint uses real SDK, source authority, signed host d
}
});
await t.test('Allow connects through the selected target without a confirmation dialog; Deny blocks every Host action', async () => {
const id = 'com.netcatty.host-actions';
const plugin = service.database.getActivePlugin(id);
const set = (permission: string, mode: string) => service.permissionEngine.setMode(plugin, permission, mode);
set('ui.interact', 'allow');
const allowed = await begin('connect'); await chooseGroup();
await act(async () => { await allowed.promise; await settle(); });
assert.equal(document.querySelector('[role="dialog"]'), null);
assert.equal(connections.length, 2);
for (const [permission, command] of [['vault.metadata', 'select'], ['vault.write', 'create']] as const) {
set(permission, 'deny'); requestClock += 60_001;
await assert.rejects(service.contributionService.executeCommand(`${id}.${command}`), /disabled/);
assert.equal(document.querySelector('[role="dialog"]'), null);
set(permission, 'allow');
}
set('ui.interact', 'deny');
const denied = await begin('connect'); await chooseGroup();
await assert.rejects(denied.promise, /disabled/);
assert.equal(connections.length, 2); assert.equal(saves, 1);
set('ui.interact', 'ask'); set('vault.write', 'ask');
const draft = await begin('create');
assert.equal(document.querySelectorAll('[role="dialog"]').length, 1);
assert.ok(button('Save Host')); await click(button('Cancel'));
assert.deepEqual(await draft.promise, { cancelled: true });
set('vault.write', 'allow'); set('vault.metadata', 'ask');
const selection = await begin('select'); await chooseGroup();
assert.ok('hosts' in await selection.promise);
assert.equal(document.querySelector('[role="dialog"]'), null);
set('vault.metadata', 'allow');
});
await t.test('runtime removal rejects old signed replies', async () => {
const run = await begin('create');
const old = prompts.at(-1)!;
await act(async () => { await service.manager.setEnabled('com.netcatty.host-actions', false); await settle(); });
await assert.rejects(run.promise);
assert.equal(await service.interactionService.respond(sender, { requestId: old.requestId, actionToken: old.actionToken, action: 'submit', draft: { hostname: 'late.invalid' } }), false);
assert.equal(saves, 1); assert.equal(connections.length, 1);
assert.equal(saves, 1); assert.equal(connections.length, 2);
});
} finally {
await act(async () => { root.unmount(); await settle(); });
+6 -13
View File
@@ -3,7 +3,7 @@ import test from 'node:test';
import { EventEmitter } from 'node:events';
import { JSDOM } from 'jsdom';
test('host dialog drives choice/input/copy and the two-phase clipboard share using real service action tokens', async () => {
test('host dialog drives choice/input/copy and a single scoped clipboard share using real service action tokens', 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) => {
@@ -80,9 +80,6 @@ test('host dialog drives choice/input/copy and the two-phase clipboard share usi
assert.deepEqual(await copy.promise, { cancelled: false, value: true });
assert.deepEqual(writes, ['synthetic output']);
const share = await begin({ kind: 'clipboard.read', title: 'Share clipboard' });
assert.equal(reads, 0);
assert.equal(document.querySelector('textarea'), null);
await click(button('Preview clipboard'));
assert.equal(reads, 1);
assert.equal(document.querySelector('textarea')?.value, 'synthetic private text');
await click(button('Share with plugin'));
@@ -105,17 +102,15 @@ test('host dialog drives choice/input/copy and the two-phase clipboard share usi
assert.match(document.querySelector('[role="dialog"]')?.textContent ?? '', /Synthetic selected terminal/);
await click(button('Cancel'));
assert.deepEqual(await noShare.promise, { cancelled: true });
assert.equal(selectionReads, 0);
const selected = await begin({ kind: 'terminal.selection.read', title: 'Synthetic terminal share' });
assert.equal(selectionReads, 0);
await click(button('Preview terminal selection'));
assert.equal(selectionReads, 1);
const selected = await begin({ kind: 'terminal.selection.read', title: 'Synthetic terminal share' });
assert.equal(selectionReads, 2);
assert.equal(document.querySelector('textarea')?.value, selectionText);
selectionText = 'changed after preview';
await click(button('Share with plugin'));
const result = await selected.promise as { cancelled: false; value: { text: string; handle: string } };
assert.equal(result.value.text, 'synthetic terminal selection\nsecond line');
assert.equal(selectionReads, 1);
assert.equal(selectionReads, 2);
const draft = await begin({ kind: 'terminal.input.propose', handle: result.value.handle, title: 'Synthetic editable review', text: 'first\nsecond\r\u0003\u001b[31m\u0000' });
assert.match(document.querySelector('[role="dialog"]')?.textContent ?? '', /sends no terminal input or Enter/);
const textarea = document.querySelector('textarea')!;
@@ -135,11 +130,9 @@ test('host dialog drives choice/input/copy and the two-phase clipboard share usi
assert.deepEqual(writes, ['synthetic output']);
selectionState.visible = false;
const hidden = await begin({ kind: 'terminal.selection.read', title: 'Hidden terminal' });
await click(button('Preview terminal selection'));
assert.ok(document.querySelector('[role="alert"]'));
assert.equal(selectionReads, 1);
await click(button('Cancel'));
assert.deepEqual(await hidden.promise, { cancelled: true });
assert.equal(selectionReads, 2);
assert.equal(document.querySelector('[role="dialog"]'), null);
} finally { cleanupSelection(); terminalElement.remove(); }
const cancelled = await begin({ kind: 'clipboard.write', title: 'Cancelled copy', text: 'must not copy' });
await click(button('Cancel'));
+107
View File
@@ -0,0 +1,107 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { EventEmitter } from 'node:events';
import { JSDOM } from 'jsdom';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
test('registered Ask uses one in-app dialog; policy controls apply Allow and Deny with no hidden prompt', 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', 'HTMLInputElement', 'Element', 'Node', 'NodeFilter', 'MutationObserver', 'CustomEvent', 'Event', 'KeyboardEvent', 'MouseEvent', 'DocumentFragment']) {
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
}
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window));
install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window));
install('IS_REACT_ACT_ENVIRONMENT', true);
dom.window.HTMLElement.prototype.scrollIntoView = () => {};
const { default: React, act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { I18nProvider } = await import('../application/i18n/I18nProvider');
const { PluginPermissionHost } = await import('./plugins/PluginPermissionHost');
const { PluginPermissionPanel } = await import('./settings/tabs/PluginPermissionPanel');
const { observePluginHostSecurityVisibility } = await import('../application/state/pluginHostSecurityVisibility');
const { PluginPermissionDecisionHost } = require('../electron/plugins/permissionDecisionHost.cjs');
const { PluginPermissionEngine } = require('../electron/plugins/permissionEngine.cjs');
const { PluginHostRpcRegistry } = require('../electron/plugins/hostRpcRegistry.cjs');
const listeners = new Set<(event: unknown) => void>();
const sender = Object.assign(new EventEmitter(), { isDestroyed: () => false, send: (_channel: string, event: unknown) => { for (const listener of listeners) listener(event); } });
const owner = Object.assign(new EventEmitter(), { webContents: sender, isDestroyed: () => false, isFocused: () => true, isVisible: () => true });
const host = new PluginPermissionDecisionHost({ getWindow: () => owner, isLocked: () => false });
let mode = 'allow', effects = 0;
const plugin = { id: 'com.example.permission-ui', activeVersion: '1.0.0', manifest: { id: 'com.example.permission-ui', publisher: 'example', permissions: { optional: [{ permission: 'network', resources: ['https://example.com'] }] } } };
const engine = new PluginPermissionEngine({ database: { getPermissionMode: () => mode, privateOwner: () => 'synthetic-source-owner',
setPermissionMode: (_id: string, _permission: string, value: string) => { mode = value; }, recordSecurityAudit() {}, deleteAllPermissionGrants() {}, listPermissionGrants: () => [] },
requestDecision: (...args: unknown[]) => host.request(...args) });
const registry = new PluginHostRpcRegistry(); registry.use(engine.createMiddleware());
registry.registerRequest('network.fixture', async () => { effects++; return 'synthetic result'; }, { authorization: { permission: 'network', resources: ['https://example.com'] } });
const route = registry.createRoutes({ pluginId: plugin.id, pluginVersion: '1.0.0', runtimeId: 'runtime-ui', runtimeKind: 'browser', manifest: plugin.manifest }).requestHandlers['network.fixture'];
Object.assign(dom.window, { netcatty: {
onPluginPermission(callback: (event: unknown) => void) { listeners.add(callback); return () => listeners.delete(callback); },
setPluginPermissionReady: async (ready: boolean) => host.setReady(sender, ready),
respondPluginPermission: async (response: unknown) => host.respond(sender, response),
getPluginPermissions: async () => ({ grants: [], audit: [], policies: engine.describePolicies(plugin), policyRevision: engine.getPolicyRevision(plugin) }),
setPluginPermissionMode: async (_id: string, permission: string, value: string, revision: string) => {
assert.equal(revision, engine.getPolicyRevision(plugin)); engine.setMode(plugin, permission, value); return true;
},
} });
const root = createRoot(document.getElementById('root')!);
const nativeMount = document.createElement('div'); document.body.append(nativeMount);
const nativeVisibility: boolean[] = [];
const stopVisibility = observePluginHostSecurityVisibility(nativeMount, (visible) => nativeVisibility.push(visible));
const settle = () => new Promise((resolve) => setTimeout(resolve, 20));
const button = (text: string) => Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find((element) => element.textContent === text)!;
const choose = async (text: string) => {
await act(async () => { document.querySelector('[role="combobox"]')!.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })); await settle(); });
const option = Array.from(document.querySelectorAll<HTMLElement>('[role="option"]')).find((element) => element.textContent === text)!;
assert.ok(option);
await act(async () => { option.click(); await settle(); });
};
try {
await act(async () => root.render(<I18nProvider locale="en"><PluginPermissionPanel pluginId={plugin.id} onChanged={async () => {}} /><PluginPermissionHost /></I18nProvider>));
await route({}, {}); assert.equal(effects, 1); assert.equal(document.querySelector('[role="dialog"]'), null);
await choose('Ask'); assert.equal(mode, 'ask');
let operation!: Promise<string>;
await act(async () => { operation = route({}, {}); await settle(); });
assert.equal(document.querySelectorAll('[role="dialog"]').length, 1);
assert.ok(document.querySelector('[role="dialog"][data-host-security-surface]'));
assert.equal(nativeVisibility.at(-1), false, 'the existing native-view lifecycle must yield to the trusted Ask');
assert.match(document.querySelector('[role="dialog"]')!.textContent!, /https:\/\/example.com/);
assert.equal(effects, 1);
await act(async () => { button('Allow this operation').click(); await operation; await settle(); });
assert.equal(effects, 2); assert.equal(document.querySelector('[role="dialog"]'), null);
await new Promise<void>((resolve) => dom.window.queueMicrotask(resolve));
assert.equal(nativeVisibility.at(-1), false, 'visible permission settings remain a security surface after Ask closes');
await choose('Deny'); assert.equal(mode, 'deny');
await assert.rejects(route({}, {}), /disabled/); assert.equal(effects, 2); assert.equal(document.querySelector('[role="dialog"]'), null);
await choose('Allow'); assert.equal(mode, 'allow');
await route({}, {}); assert.equal(effects, 3); assert.equal(document.querySelector('[role="dialog"]'), null);
// Model the settings editor closing before interacting with a native view.
document.querySelector('section[data-host-security-surface]')!.setAttribute('hidden', '');
await new Promise<void>((resolve) => dom.window.queueMicrotask(resolve));
assert.equal(nativeVisibility.at(-1), true);
let displayed!: Promise<unknown>;
const opaque = 'selected:0cfc16d6-3448-4333-82ef-dd4ffbddfdab:v1';
await act(async () => {
displayed = host.request({ requestId: 'host-display-fixture', pluginId: plugin.id, permission: 'ai.invoke', resources: ['*'], reason: 'Host model invocation',
relatedPermissions: [{ permission: 'context.selected.read', resources: [opaque] }],
displayContext: { modelLabel: 'QA fixture · deterministic-fixture', selections: [{ title: 'Synthetic retry plan', scope: 'note', version: 'bf304994-039a-4884-a707-3a1a40a5d3a9' }] },
}); await settle();
});
const text = document.querySelector('[role="dialog"]')!.textContent!;
assert.equal(nativeVisibility.at(-1), false, 'Ask alone must hide the attached plugin view');
assert.match(text, /QA fixture · deterministic-fixture/); assert.match(text, /Synthetic retry plan/);
assert.doesNotMatch(text, /selected:|0cfc16d6|bf304994/);
await act(async () => { button('Deny').click(); await displayed; await settle(); });
await new Promise<void>((resolve) => dom.window.queueMicrotask(resolve));
assert.equal(nativeVisibility.at(-1), true, 'dismissing Ask restores the existing view without closing it');
} finally {
await act(async () => root.unmount()); stopVisibility(); host.shutdown(); engine.shutdown(); dom.window.close();
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
}
});
@@ -0,0 +1,115 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { EventEmitter } from 'node:events';
import { createRequire } from 'node:module';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { JSDOM } from 'jsdom';
const require = createRequire(import.meta.url);
test('registered selected-summary Ask is one host chooser; Allow still selects and Deny releases nothing', { timeout: 45_000 }, 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', 'HTMLInputElement', 'HTMLSelectElement', 'Element', 'Node', 'NodeFilter', 'MutationObserver', 'CustomEvent', 'Event', 'KeyboardEvent', 'MouseEvent']) install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window));
install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window));
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 { PluginAIContextHost } = await import('./plugins/PluginAIContextHost');
const { PluginPermissionHost } = await import('./plugins/PluginPermissionHost');
const { publishNotesSnapshot, getNotesSnapshot } = await import('../application/state/notesStore');
const { registerAppAppLockRuntime, getAppAppLockRuntime } = await import('../application/state/appRuntimeBridge');
const { createPluginHostService } = require('../electron/plugins/hostService.cjs');
const { inProcessBrowserRuntime } = require('../electron/plugins/fixtures/inProcessBrowserRuntime.cjs');
const { registerPluginBridge } = require('../electron/plugins/pluginBridge.cjs');
const { createPreloadApi } = require('../electron/preload/api.cjs');
const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'netcatty-selected-policy-'));
const oldNotes = getNotesSnapshot(); const oldLock = getAppAppLockRuntime();
const handlers = new Map<string, (...args: unknown[]) => unknown>();
const ipcMain = Object.assign(new EventEmitter(), { handle: (channel: string, handler: (...args: unknown[]) => unknown) => handlers.set(channel, handler), removeHandler: (channel: string) => handlers.delete(channel) });
const ipcRenderer = Object.assign(new EventEmitter(), { invoke: async (channel: string, payload: unknown) => {
const handler = handlers.get(channel); assert.ok(handler, channel); return handler({ sender }, structuredClone(payload));
} });
const prompts: Array<{ channel: string; kind?: string; closed?: boolean }> = [];
const sender = Object.assign(new EventEmitter(), { id: 42, isDestroyed: () => false, send: (channel: string, payload: { kind?: string; closed?: boolean }) => {
prompts.push({ channel, kind: payload.kind, closed: payload.closed }); ipcRenderer.emit(channel, {}, structuredClone(payload));
} });
const owner = Object.assign(new EventEmitter(), { webContents: sender, isFocused: () => true, isVisible: () => true, isDestroyed: () => false });
const service = createPluginHostService({ app: { getAppPath: () => process.cwd(), getPath: () => fixtureRoot, getVersion: () => '0.0.0' },
electron: { ipcMain }, env: {}, getInteractionWindow: () => owner, isAppLocked: () => false });
service.runtimeSupervisor.runtimeFactories.browser = inProcessBrowserRuntime;
registerPluginBridge(ipcMain, { ...service, isTrustedSender: (event: { sender: unknown }) => event.sender === sender });
Object.assign(dom.window, { netcatty: createPreloadApi({ ipcRenderer, webUtils: {} }) });
const note = { id: 'synthetic-selected-note', title: 'Synthetic selection', content: 'BODY MUST NOT BE SHARED', createdAt: 1, updatedAt: 1 };
publishNotesSnapshot({ notes: [note], noteGroups: [] }); registerAppAppLockRuntime({ locked: false } as never);
const root = createRoot(document.getElementById('root')!);
const settle = () => new Promise((resolve) => setTimeout(resolve, 20));
const waitForDialog = async () => {
const deadline = Date.now() + 5_000;
while (!document.querySelector('[role="dialog"]')) {
assert.ok(Date.now() < deadline, 'registered route did not present a host interaction');
await act(async () => { await settle(); });
}
};
const button = (label: string) => Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find((element) => element.textContent === label)!;
const begin = () => {
const result = service.contributionService.executeCommand('com.netcatty.assistant.contexts') as Promise<Array<{ handle: string; version: string; title: string }>>;
void result.catch(() => {});
return result;
};
try {
await service.manager.initialize();
const stage = path.join(fixtureRoot, 'package'); fs.mkdirSync(path.join(stage, 'dist'), { recursive: true });
const sample = path.resolve('examples/plugins/assistant');
for (const file of ['netcatty.plugin.json', 'panel.html', 'panel.css', 'panel.js', 'README.md']) fs.copyFileSync(path.join(sample, file), path.join(stage, file));
fs.copyFileSync(path.join(sample, 'src/index.js'), path.join(stage, 'dist/index.js'));
const { buildPluginPackage } = await import('@netcatty/plugin-cli');
const archive = path.join(fixtureRoot, 'assistant.ncpkg'); await buildPluginPackage(stage, archive); await service.manager.install(archive, { enable: true });
await act(async () => root.render(<I18nProvider locale="en"><PluginPermissionHost /><PluginAIContextHost sessions={[]} workspaces={[]} /></I18nProvider>));
const plugin = service.database.getActivePlugin('com.netcatty.assistant');
for (const mode of ['ask', 'allow']) {
service.permissionEngine.setMode(plugin, 'context.selected.list', mode);
let result!: ReturnType<typeof begin>;
await act(async () => { result = begin(); await settle(); });
await waitForDialog();
assert.ok(document.getElementById('plugin-ai-note'), 'the first interaction must be the real host chooser');
assert.equal(document.querySelectorAll('[role="dialog"]').length, 1);
assert.equal(prompts.filter((prompt) => prompt.channel === 'netcatty:plugins:permission-prompt' && !prompt.closed).length, 0, 'no capability dialog before the chooser');
await act(async () => {
const select = document.getElementById('plugin-ai-note') as HTMLSelectElement; select.value = note.id; select.dispatchEvent(new dom.window.Event('change', { bubbles: true })); await settle();
});
await act(async () => { button('Share selected summaries').click(); await settle(); });
const summaries = await result;
assert.ok(summaries.some((item) => item.title === note.title));
assert.doesNotMatch(JSON.stringify(summaries), /BODY MUST NOT BE SHARED/);
assert.equal(document.querySelector('[role="dialog"]'), null);
}
service.permissionEngine.setMode(plugin, 'context.selected.list', 'deny');
const count = prompts.filter((prompt) => prompt.kind === 'context.select').length;
await assert.rejects(service.contributionService.executeCommand('com.netcatty.assistant.contexts'), /disabled/);
assert.equal(prompts.filter((prompt) => prompt.kind === 'context.select').length, count); assert.equal(document.querySelector('[role="dialog"]'), null);
service.permissionEngine.setMode(plugin, 'context.selected.list', 'ask');
let cancelled!: ReturnType<typeof begin>;
await act(async () => { cancelled = begin(); await settle(); });
await waitForDialog();
await act(async () => { button('Cancel').click(); await settle(); });
await assert.rejects(cancelled); assert.equal(service.aiContextService.selected.handles.size, 0);
let revoked!: ReturnType<typeof begin>;
await act(async () => { revoked = begin(); await settle(); });
await waitForDialog();
await act(async () => { service.permissionEngine.setMode(plugin, 'context.selected.list', 'deny'); await settle(); });
await assert.rejects(revoked); assert.equal(document.querySelector('[role="dialog"]'), null); assert.equal(service.aiContextService.selected.handles.size, 0);
} finally {
await act(async () => root.unmount()); await service.manager.shutdown();
publishNotesSnapshot(oldNotes); registerAppAppLockRuntime(oldLock); dom.window.close(); fs.rmSync(fixtureRoot, { recursive: true, force: true });
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
}
});
+4
View File
@@ -27,6 +27,7 @@ import { useExternalMcpGrantPersister } from "./ai/useExternalMcpGrantPersister"
import { setupMcpApprovalBridge } from "../infrastructure/ai/shared/approvalGate";
import { usePluginContributions } from "../application/state/usePluginContributions";
import { PluginContributionHost } from "./plugins/PluginContributionHost";
import { PluginPermissionHost } from "./plugins/PluginPermissionHost";
import { matchesKeyBinding } from "../domain/models";
import { isPrimaryModifierWBinding } from "../application/state/windowCommandClose";
@@ -575,6 +576,8 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
setShowHostTreeSidebar={settings.setShowHostTreeSidebar}
windowOpacity={settings.windowOpacity}
setWindowOpacity={settings.setWindowOpacity}
windowBackgroundBlur={settings.windowBackgroundBlur}
setWindowBackgroundBlur={settings.setWindowBackgroundBlur}
appIconVariant={settings.appIconVariant}
setAppIconVariant={settings.setAppIconVariant}
/>
@@ -720,6 +723,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
</Tabs>
</div>
<ExternalMcpApprovalsHost />
<PluginPermissionHost />
<PluginContributionHost locale={settings.uiLanguage} theme={settings.resolvedTheme} themeTokens={pluginThemeTokens} />
</>
);
+6 -3
View File
@@ -64,6 +64,8 @@ interface TextEditorModalProps {
onClose: () => void;
fileName: string;
initialContent: string;
/** Full path for language detection; the title still uses fileName. */
filePath?: string;
onSave: (content: string) => Promise<void>;
editorWordWrap: boolean;
onToggleWordWrap: () => void;
@@ -79,6 +81,7 @@ const TextEditorModal: React.FC<TextEditorModalProps> = ({
open,
onClose,
fileName,
filePath,
initialContent,
onSave,
editorWordWrap,
@@ -94,7 +97,7 @@ const TextEditorModal: React.FC<TextEditorModalProps> = ({
const [baselineContent, setBaselineContent] = useState(initialContent);
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const [languageId, setLanguageId] = useState(() => getLanguageId(fileName));
const [languageId, setLanguageId] = useState(() => getLanguageId(filePath ?? fileName));
const contentRef = useRef(initialContent);
const baselineContentRef = useRef(initialContent);
const savingRef = useRef(false);
@@ -149,13 +152,13 @@ const TextEditorModal: React.FC<TextEditorModalProps> = ({
setBaselineContent(initialContent);
setSaveError(null);
setSaving(false);
setLanguageId(getLanguageId(fileName));
setLanguageId(getLanguageId(filePath ?? fileName));
contentRef.current = initialContent;
baselineContentRef.current = initialContent;
savingRef.current = false;
closePromptRef.current = null;
viewStateRef.current = null;
}, [initialContent, fileName]);
}, [initialContent, fileName, filePath]);
const saveContent = useCallback(async (contentToSave = contentRef.current): Promise<boolean> => {
return saveCoordinatorRef.current?.save(contentToSave) ?? false;
@@ -8,6 +8,7 @@ import {
getTextEditorContentStats,
isTextEditorCommandWEnabled,
isTextEditorReadOnly,
languageIdToMonaco,
TextEditorPromoteButton,
} from "./TextEditorPane.tsx";
import { TooltipProvider } from "../ui/tooltip.tsx";
@@ -16,6 +17,11 @@ import { DEFAULT_KEY_BINDINGS } from "../../domain/models/keyBindings.ts";
const wrap = (child: React.ReactElement) =>
React.createElement(TooltipProvider, null, child);
test("maps manual Nginx selection to the registered language", () => {
assert.equal(languageIdToMonaco('nginx'), 'nginx');
assert.equal(languageIdToMonaco('ini'), 'ini');
});
test("disables promoting a modal editor to a tab while a save is running", () => {
assert.equal(canPromoteTextEditor({ saving: true }), false);
assert.equal(canPromoteTextEditor({ saving: false }), true);
+4 -1
View File
@@ -30,6 +30,7 @@ import { useClipboardBackend } from '../../application/state/useClipboardBackend
import { isPrimaryModifierWBinding } from '../../application/state/windowCommandClose';
import { HotkeyScheme, KeyBinding, matchesKeyBinding } from '../../domain/models';
import { pasteForMonacoEditorCommand } from '../../infrastructure/monaco/monacoClipboardPaste';
import { registerNginxLanguage } from '../../infrastructure/monaco/nginxLanguage';
import { useNetcattyMonacoTheme } from '../../infrastructure/monaco/useNetcattyMonacoTheme';
import { getLanguageName, getSupportedLanguages } from '../../lib/sftpFileUtils';
import { Button } from '../ui/button';
@@ -37,7 +38,7 @@ import { Combobox } from '../ui/combobox';
import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip';
// Map our language IDs to Monaco language IDs
const languageIdToMonaco = (langId: string): string => {
export const languageIdToMonaco = (langId: string): string => {
const mapping: Record<string, string> = {
'javascript': 'javascript',
'typescript': 'typescript',
@@ -73,6 +74,7 @@ const languageIdToMonaco = (langId: string): string => {
'yaml': 'yaml',
'toml': 'ini',
'ini': 'ini',
'nginx': 'nginx',
'sql': 'sql',
'graphql': 'graphql',
'markdown': 'markdown',
@@ -512,6 +514,7 @@ const TextEditorPaneInner: React.FC<TextEditorPaneProps> = ({
language={monacoLanguage}
value={content}
onChange={handleEditorChange}
beforeMount={registerNginxLanguage}
onMount={handleEditorMount}
theme={customThemeName}
loading={
+1 -1
View File
@@ -9,7 +9,7 @@ export function PluginAIContextHost({ sessions, workspaces }: { sessions: Termin
return <Dialog open={choice !== null} onOpenChange={(open) => { if (!open) choice?.cancel(); }}>
<DialogContent data-host-security-surface="">
<DialogHeader><DialogTitle>Choose a reference for the plugin</DialogTitle>
<DialogDescription>Share a Note summary and the current selected workspace, tab, session, and host summaries. Reading content requires a separate permission and text review.</DialogDescription></DialogHeader>
<DialogDescription>Share a Note summary and the current selected workspace, tab, session, and host summaries. Content access follows this plugin's Allow / Ask / Deny settings; this chooser shares summaries only.</DialogDescription></DialogHeader>
<label className="text-sm" htmlFor="plugin-ai-note">Note</label>
<select id="plugin-ai-note" value={noteId} onChange={(event) => setNoteId(event.target.value)} className="rounded border border-border bg-background p-2 text-foreground">
<option value="">No Note</option>
+26
View File
@@ -0,0 +1,26 @@
import React, { useState } from 'react';
import { UserRound } from 'lucide-react';
import { usePluginAuthorIdentity } from '../../application/state/usePluginAuthorIdentity';
import { useI18n } from '../../application/i18n/I18nProvider';
import { Badge } from '../ui/badge';
export function PluginAuthorRow({ entry, plugin, sourceId }: {
entry?: NetcattyPluginCatalogEntry; plugin?: NetcattyInstalledPlugin; sourceId?: string;
}) {
const { t } = useI18n();
const { ref, identity } = usePluginAuthorIdentity({ entry, plugin, sourceId });
const [failed, setFailed] = useState<string | null>(null);
const author = identity?.author ?? entry?.author ?? plugin?.manifest?.publisher ?? '';
const imageKey = JSON.stringify([entry?.id, entry?.selectionToken, plugin?.id, plugin?.activeVersion, plugin?.archiveSha256, sourceId, identity?.avatar]);
const avatar = identity?.avatar;
const showImage = avatar && avatar.length <= 700_000 && /^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(avatar) && failed !== imageKey;
return <div ref={ref} className="flex min-w-0 items-center gap-2 text-xs text-muted-foreground" data-plugin-author-row>
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted/60" aria-hidden="true">
{showImage ? <img src={avatar} alt="" width={20} height={20} className="h-full w-full object-cover" onError={() => setFailed(imageKey)} />
: <UserRound size={13} data-plugin-author-placeholder />}
</span>
<span className="min-w-0 truncate" title={author}>{author}</span>
{identity?.officialMaintained === true && <Badge className="shrink-0 whitespace-nowrap border-0 bg-amber-500/15 px-2 py-0.5 text-[10px] font-medium text-amber-800 hover:bg-amber-500/15 dark:bg-amber-400/15 dark:text-amber-300 dark:hover:bg-amber-400/15"
title={t('settings.plugins.author.officialMeaning')} data-plugin-official-maintainer>{t('settings.plugins.author.official')}</Badge>}
</div>;
}
@@ -0,0 +1,38 @@
import { usePluginPermissionPrompt } from '../../application/state/usePluginPermissionPrompt';
import { useI18n } from '../../application/i18n/I18nProvider';
import { describePluginPermission } from '@/domain/pluginPermissionDescriptions.cjs';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '../ui/dialog';
import { Button } from '../ui/button';
/** Rendered only by the trusted app, never inside a plugin view. */
export function PluginPermissionHost() {
const { resolvedLocale } = useI18n();
const zh = resolvedLocale.startsWith('zh');
const { prompt, busy, respond } = usePluginPermissionPrompt();
if (!prompt) return null;
const description = describePluginPermission(prompt.permission, resolvedLocale);
const resources = prompt.resources.filter((resource) => resource !== '*' && !resource.startsWith('selected:'));
return <Dialog open onOpenChange={(open) => { if (!open) void respond('cancel'); }}>
<DialogContent data-host-security-surface="" className="max-h-[85vh] overflow-y-auto sm:max-w-[480px]">
<DialogHeader>
<DialogTitle>{description.label}</DialogTitle>
<DialogDescription className="break-words">{prompt.pluginName ?? prompt.pluginId} · {prompt.pluginVersion}</DialogDescription>
</DialogHeader>
<p className="text-sm">{description.description}</p>
{prompt.displayContext?.modelLabel && <p className="text-sm break-words">{zh ? '模型' : 'Model'}: {prompt.displayContext.modelLabel}</p>}
{(prompt.displayContext?.selections ?? []).map((item, index) => <p key={index} className="text-sm break-words">
{item.title} <span className="text-xs text-muted-foreground">· {item.scope}</span>
</p>)}
{(prompt.relatedPermissions ?? []).filter((item, index, items) => items.findIndex((other) => other.permission === item.permission) === index).map((item, index) => <div key={index} className="space-y-1 text-sm">
<p>{describePluginPermission(item.permission, resolvedLocale).description}</p>
<p className="text-xs text-muted-foreground break-all">{item.resources.filter((resource) => !resource.startsWith('selected:')).join(', ')}</p>
</div>)}
<p className="text-xs text-muted-foreground break-all">{prompt.pluginId}</p>
{resources.length > 0 && <ul className="max-h-44 overflow-auto space-y-1 text-xs text-muted-foreground">{resources.map((resource) => <li key={resource} className="break-all">{resource}</li>)}</ul>}
<DialogFooter>
<Button variant="outline" disabled={busy} onClick={() => void respond('deny')}>{zh ? '拒绝' : 'Deny'}</Button>
<Button disabled={busy} onClick={() => void respond('allow')}>{prompt.sessionId && prompt.allowedScopes && !prompt.allowedScopes.includes('once') ? zh ? '允许此会话' : 'Allow for this session' : zh ? '允许此次操作' : 'Allow this operation'}</Button>
</DialogFooter>
</DialogContent>
</Dialog>;
}
@@ -0,0 +1,125 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { JSDOM } from 'jsdom';
import { EventEmitter } from 'node:events';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createRequire } from 'node:module';
import { usePluginAuthorIdentity } from '../../../application/state/usePluginAuthorIdentity';
import { checkPluginUpdates } from '../../../infrastructure/services/pluginUpdateCheck';
const require = createRequire(import.meta.url);
const { PluginDatabase } = require('../../../electron/plugins/database.cjs');
const { MarketSourcesService } = require('../../../electron/plugins/marketSourcesService.cjs');
const { OFFICIAL_SOURCE } = require('../../../electron/plugins/sourceIdentity.cjs');
const { registerPluginBridge, CHANNELS } = require('../../../electron/plugins/pluginBridge.cjs');
const { createPreloadApi } = require('../../../electron/preload/api.cjs');
const { catalog, delivery, makeFiles, read, digest } = require('../../../electron/plugins/fixtures/staticDistributionFixture.cjs');
test('mounted installed authors follow actual catalog/update/source entrypoints without changing package identity', async () => {
const rootPath = mkdtempSync(join(tmpdir(), 'netcatty-author-refresh-'));
const database = new PluginDatabase(join(rootPath, 'plugins.sqlite'));
const dom = new JSDOM('<!doctype html><div id="root"></div>', { pretendToBeVisual: true });
const previous = new Map<string, PropertyDescriptor | undefined>();
for (const [key, value] of Object.entries({ window: dom.window, document: dom.window.document,
navigator: dom.window.navigator, HTMLElement: dom.window.HTMLElement, Element: dom.window.Element,
Node: dom.window.Node, IntersectionObserver: undefined, IS_REACT_ACT_ENVIRONMENT: true })) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
const entry = structuredClone(catalog[0]);
entry.artifact = { sha256: 'a'.repeat(64), url: `${OFFICIAL_SOURCE.origin}/assets/${'a'.repeat(64)}.ncpkg` };
const bytes = read(delivery.plugins[0].iconLight.path.slice(1));
const avatar = { path: `/assets/${digest(bytes)}.png`, sha256: digest(bytes), size: bytes.length };
const filesFor = (entries = [entry], image = true) => {
const files = makeFiles(entries, (index: { plugins: Array<{ id: string; versions: Array<{ distribution: string }> }> }, sidecar: { schemaVersion: number; plugins: Array<{ id: string; avatar: typeof avatar | null; artifact: { path: string; sha256: string; size: number } }> }) => {
sidecar.schemaVersion = 2;
for (const item of sidecar.plugins) {
item.avatar = image ? avatar : null;
item.artifact = { path: `/assets/${entry.artifact.sha256}.ncpkg`, sha256: entry.artifact.sha256, size: 1 };
index.plugins.find((plugin) => plugin.id === item.id).versions[0].distribution = 'release';
}
});
files.set(avatar.path, bytes); return files;
};
let files = filesFor();
database.installVersion({ pluginId: entry.id, version: entry.version, runtimeKind: "browser", apiVersion: "0.1.0-internal.1", manifest: entry.manifest, archiveSha256: entry.artifact.sha256,
packageRelativePath: 'packages/synthetic', source: OFFICIAL_SOURCE }, { enable: true });
const manager = { initialize: async () => {}, list: async () => database.listPlugins(),
changeMarketSource: async (change: () => unknown) => change() };
let avatarReads = 0;
const service = new MarketSourcesService({ database, manager,
fetch: async (url: string) => { assert.equal(new URL(url).origin, OFFICIAL_SOURCE.origin); assert.ok(!new URL(url).pathname.endsWith('.ncpkg'), 'rejected selection never downloads a package'); return new Response(files.get(new URL(url).pathname)); },
createSourceFetch: (origin: string) => async (url: string) => { assert.equal(new URL(url).origin, origin); return new Response(files.get(new URL(url).pathname)); },
resolveAvatar: async () => { avatarReads++; return 'data:image/png;base64,eA=='; } });
const ipcMain = { handlers: new Map(), handle(channel: string, handler: unknown) { this.handlers.set(channel, handler); }, on() {} };
const events = new EventEmitter();
registerPluginBridge(ipcMain, { manager, catalogService: service, isTrustedSender: () => true,
broadcast: (channel: string, payload: unknown) => events.emit(channel, {}, payload) });
const api = createPreloadApi({ ipcRenderer: { on: events.on.bind(events), removeListener: events.removeListener.bind(events),
invoke: (channel: string, payload: unknown) => ipcMain.handlers.get(channel)({}, payload) } });
let authorCalls = 0;
const original = api.getPluginAuthorPresentation;
api.getPluginAuthorPresentation = (request: NetcattyPluginAuthorRequest) => { authorCalls++; return original(request); };
Object.assign(window, { netcatty: api });
let plugin = database.getActivePlugin(entry.id) as NetcattyInstalledPlugin;
function Row() {
const { ref, identity } = usePluginAuthorIdentity({ plugin });
return <div ref={ref} data-author={identity?.author} data-avatar={identity?.avatar} data-official={identity?.officialMaintained ?? false} />;
}
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const root = createRoot(document.getElementById('root')!);
const row = () => document.querySelector<HTMLElement>('[data-official]')!;
try {
await act(async () => root.render(<><Row /><Row /></>));
assert.equal(row().dataset.author, entry.manifest.publisher); assert.equal(row().dataset.official, 'false');
assert.equal(avatarReads, 0, 'opening installed rows never fetches a catalog/avatar');
await act(async () => { await checkPluginUpdates(api); });
assert.equal(row().dataset.author, entry.author); assert.equal(row().dataset.official, 'true');
assert.match(row().dataset.avatar!, /^data:image\/png/);
assert.equal(events.listenerCount(CHANNELS.catalogChanged), 1, 'rows share one preload subscription');
const count = authorCalls;
await act(async () => { await api.listPluginCatalog('official'); root.render(<><Row /><Row /></>); });
assert.equal(authorCalls, count, 'equivalent catalog and installation retain request dedupe');
files = filesFor([{ ...entry, author: 'Updated project name' }], false);
await act(async () => { await api.listPluginCatalog('official'); });
assert.equal(row().dataset.author, 'Updated project name'); assert.equal(row().dataset.avatar, undefined);
const beforeWithdrawal = (await api.listPluginCatalog('official')).entries[0];
files = filesFor([]);
await act(async () => {
await assert.rejects(api.installCatalogPlugin(entry.id, beforeWithdrawal.selectionToken, 'official'), /not in the curated catalog|changed/);
});
assert.equal(row().dataset.author, entry.manifest.publisher); assert.equal(row().dataset.official, 'false');
assert.equal(row().dataset.avatar, undefined, 'rejected install refresh removes withdrawn enrichment without another list or remount');
const source = await api.addPluginSource({ name: 'Community', address: 'https://community.example.com' });
const community = structuredClone(entry);
community.id = community.manifest.id = 'com.community.identity';
community.artifact.url = `${source.origin}/assets/${community.artifact.sha256}.ncpkg`;
files = filesFor([community]);
database.installVersion({ pluginId: community.id, version: community.version, manifest: community.manifest,
archiveSha256: community.artifact.sha256, packageRelativePath: 'packages/community', source }, { enable: true });
await act(async () => { await api.listPluginCatalog(source.id); });
assert.equal(authorCalls, count + 4, 'unrelated source changes do not reload official rows');
plugin = database.getActivePlugin(community.id);
await act(async () => root.render(<><Row /><Row /></>));
assert.equal(row().dataset.author, community.author); assert.match(row().dataset.avatar!, /^data:image\/png/);
assert.equal(row().dataset.official, 'false', 'copied catalog never gains official maintenance authority');
await act(async () => { await api.updatePluginSource({ id: source.id, name: 'Renamed', enabled: false }); });
assert.equal(row().dataset.author, community.manifest.publisher); assert.equal(row().dataset.avatar, undefined);
await act(async () => { await api.updatePluginSource({ id: source.id, name: 'Renamed', enabled: true }); });
assert.equal(row().dataset.author, community.author);
await act(async () => { await api.removePluginSource(source.id, false); });
assert.equal(row().dataset.author, community.manifest.publisher); assert.equal(row().dataset.avatar, undefined);
await act(async () => root.unmount());
assert.equal(events.listenerCount(CHANNELS.catalogChanged), 0, 'last row releases the shared IPC listener');
} finally {
database.close(); dom.window.close(); rmSync(rootPath, { recursive: true, force: true });
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key);
}
}
});
@@ -0,0 +1,116 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { JSDOM } from 'jsdom';
import { PluginAuthorRow } from '../../plugins/PluginAuthorRow';
import { I18nProvider } from '../../../application/i18n/I18nProvider';
const entry = { id: 'com.netcatty.starter', name: 'Starter', author: 'Netcatty', version: '0.1.2',
repository: 'binaricat/Netcatty', commit: 'a'.repeat(40), selectionToken: 'b'.repeat(64),
manifest: { publisher: 'netcatty' } } as NetcattyPluginCatalogEntry;
const identity = { author: 'Netcatty', avatar: 'data:image/png;base64,eA==', officialMaintained: true,
sourceId: 'official', version: entry.version, archiveSha256: null };
test('untrusted entry strings and absent imagery produce a compact placeholder without an official badge', () => {
const claimed = { ...entry, author: '<img src="https://avatars.githubusercontent.com/u/1">',
officialMaintained: true, avatar: 'https://avatars.githubusercontent.com/u/1' };
const html = renderToStaticMarkup(<I18nProvider locale="en"><PluginAuthorRow entry={claimed} /></I18nProvider>);
assert.match(html, /data-plugin-author-placeholder/);
assert.doesNotMatch(html, /<img|data-plugin-official-maintainer/);
assert.match(html, /&lt;img/);
assert.match(html, /items-center/);
});
test('mounted author rows load only when visible, retain fallbacks, cancel stale results and show a borderless themed maintainer pill', async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { pretendToBeVisual: true });
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 });
};
const observers: Array<{ target: Element | null; callback: IntersectionObserverCallback }> = [];
class VisibilityObserver {
record: typeof observers[number];
constructor(callback: IntersectionObserverCallback) { this.record = { callback, target: null }; observers.push(this.record); }
observe(target: Element) { this.record.target = target; }
disconnect() { this.record.target = null; }
}
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event']) {
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
}
install('IntersectionObserver', VisibilityObserver);
install('IS_REACT_ACT_ENVIRONMENT', true);
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const root = createRoot(document.getElementById('root')!);
const calls: NetcattyPluginAuthorRequest[] = [];
const pending: Array<(value: NetcattyPluginAuthorPresentation | null) => void> = [];
Object.assign(window, { netcatty: { getPluginAuthorPresentation: (request: NetcattyPluginAuthorRequest) => {
calls.push(request); return new Promise((resolve) => pending.push(resolve));
} } });
const render = async (value = entry, sourceId = 'official') => {
await act(async () => root.render(<I18nProvider locale="en"><PluginAuthorRow entry={value} sourceId={sourceId} /></I18nProvider>));
};
const visible = async () => {
await act(async () => {
for (const observer of [...observers]) if (observer.target) observer.callback([{ target: observer.target, isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver);
});
};
try {
await render(); assert.equal(calls.length, 0); assert.ok(document.querySelector('[data-plugin-author-placeholder]'));
await visible(); assert.deepEqual(calls[0], { kind: 'catalog', pluginId: entry.id, selectionToken: entry.selectionToken, sourceId: 'official' });
assert.ok(document.querySelector('[data-plugin-author-placeholder]'), 'loading uses the default placeholder');
await act(async () => pending.shift()!(identity));
const image = document.querySelector('img')!;
assert.equal(image.getAttribute('src'), identity.avatar); assert.equal(image.width, 20); assert.equal(image.height, 20);
const badge = document.querySelector<HTMLElement>('[data-plugin-official-maintainer]')!;
assert.equal(badge.textContent, 'Official maintainer'); assert.match(badge.title, /not a safety certification/);
assert.ok(badge.classList.contains('border-0'));
assert.ok(badge.classList.contains('bg-amber-500/15')); assert.ok(badge.classList.contains('dark:bg-amber-400/15'));
assert.ok(badge.classList.contains('text-amber-800')); assert.ok(badge.classList.contains('dark:text-amber-300'));
document.documentElement.classList.add('dark');
assert.ok(document.querySelector('[data-plugin-author-row]')?.classList.contains('items-center'));
await act(async () => image.dispatchEvent(new Event('error')));
assert.equal(document.querySelector('img'), null); assert.ok(document.querySelector('[data-plugin-author-placeholder]'));
assert.ok(document.querySelector('[data-plugin-official-maintainer]'), 'image failure does not alter maintenance identity');
const next = { ...entry, selectionToken: 'c'.repeat(64) };
await render(next); assert.equal(document.querySelector('[data-plugin-official-maintainer]'), null);
await visible(); const stale = pending.shift()!;
const copied = { ...entry, author: 'Community author', selectionToken: 'd'.repeat(64) };
await render(copied, 'third-party:copy'); await visible();
await act(async () => stale(identity));
assert.equal(document.querySelector('[data-plugin-official-maintainer]'), null);
assert.match(document.querySelector('[data-plugin-author-row]')!.textContent!, /Community author/);
await act(async () => pending.shift()!({ ...identity, author: copied.author, sourceId: 'third-party:copy', officialMaintained: false, avatar: 'https://avatars.githubusercontent.com/u/1' }));
assert.equal(document.querySelector('img'), null, 'renderer never uses a remote avatar URL');
assert.equal(document.querySelector('[data-plugin-official-maintainer]'), null);
await render({ ...entry, selectionToken: 'f'.repeat(64) }); await visible();
await act(async () => pending.shift()!({ ...identity, avatar: null, officialMaintained: false }));
assert.ok(document.querySelector('[data-plugin-author-placeholder]'));
const installed = { id: entry.id, activeVersion: entry.version, archiveSha256: 'a'.repeat(64),
source: { id: 'official', kind: 'official', origin: 'https://plugins.netcatty.app', name: 'Official' },
manifest: entry.manifest, runtime: {} } as NetcattyInstalledPlugin;
await act(async () => root.render(<I18nProvider locale="en"><PluginAuthorRow plugin={installed} /></I18nProvider>));
await visible(); assert.deepEqual(calls.at(-1), { kind: 'installed', pluginId: installed.id });
await act(async () => pending.shift()!({ ...identity, version: '9.0.0', archiveSha256: installed.archiveSha256! }));
assert.equal(document.querySelector('[data-plugin-official-maintainer]'), null, 'a stale installed version cannot gain a badge');
const count = calls.length;
await act(async () => root.render(<I18nProvider locale="en"><PluginAuthorRow plugin={{ ...installed }} /></I18nProvider>));
await visible(); assert.equal(calls.length, count, 'unchanged installed identity does not reload on a new object reference');
await render({ ...entry, selectionToken: 'e'.repeat(64) }); await visible();
const late = pending.shift()!;
await act(async () => root.unmount());
await act(async () => late(identity));
assert.equal(document.querySelector('[data-plugin-author-row]'), null);
assert.ok(observers.every((observer) => observer.target === null));
} finally {
dom.window.close();
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key);
}
}
});
@@ -32,7 +32,9 @@ test('installed grid filters, opens one detail and restores search, scroll and c
assert.equal(cards().length, 2);
const alphaCard = renderer.root.findAllByType('article')[0];
assert.match(JSON.stringify(renderer.toJSON()), /Alpha safely formats synthetic greetings/);
assert.ok(alphaCard.findAllByType('p').some((node) => node.children.includes('Example')), 'author has its own line');
const authorRow = alphaCard.findByProps({ 'data-plugin-author-row': true });
assert.ok(authorRow.findAllByType('span').some((node) => node.children.includes('Example')), 'author has its own compact row');
assert.ok(authorRow.findByProps({ 'data-plugin-author-placeholder': true }), 'an unverified installed publisher has a default avatar');
assert.ok(alphaCard.findAllByType('p').some((node) => node.props.className?.includes('line-clamp-3')), 'card description is bounded');
assert.match(JSON.stringify(renderer.toJSON()), /MIT/);
assert.match(JSON.stringify(renderer.toJSON()), /Incompatible version/);
@@ -19,7 +19,7 @@ export function PluginLogSettings() {
const disclosure = zh
? '插件编写的日志文字可能包含敏感数据。截断和字段过滤不能保证任意文字安全。只为排查问题临时开启,导出前请检查。重启应用后自动关闭详细日志。'
: 'Plugin-authored text may contain sensitive data. Truncation and field filtering cannot make arbitrary text safe. Enable temporarily for troubleshooting and review files before sharing. Verbose diagnostics turn off after app restart.';
return <div data-host-security-surface="">
return <div>
<Dialog open={open} onOpenChange={setOpen}>
<SettingRow label={title} description={zh ? '选择是否在此设备保存审计记录和诊断日志。' : 'Choose whether to keep audit records and diagnostics on this device.'}>
<div className="flex items-center gap-3">
@@ -53,6 +53,6 @@ export function PluginLogSettings() {
</DialogFooter>
</DialogContent>
</Dialog>
<ConfirmDialog open={confirmVerbose} title={zh ? '开启插件详细诊断?' : 'Enable verbose plugin diagnostics?'} message={disclosure} confirmLabel={zh ? '临时开启' : 'Enable temporarily'} onOpenChange={setConfirmVerbose} onConfirm={() => { setConfirmVerbose(false); void run('configure', { saveToDisk: true, verbose: true }); }} />
<ConfirmDialog hostSecuritySurface open={confirmVerbose} title={zh ? '开启插件详细诊断?' : 'Enable verbose plugin diagnostics?'} message={disclosure} confirmLabel={zh ? '临时开启' : 'Enable temporarily'} onOpenChange={setConfirmVerbose} onConfirm={() => { setConfirmVerbose(false); void run('configure', { saveToDisk: true, verbose: true }); }} />
</div>;
}
@@ -88,7 +88,11 @@ test('README failure leaves the permissions and source visible, before the failu
selected={entries[0].id} onSelect={() => {}} installed={[]} /></I18nProvider>);
assert.match(html, /Compatibility and permissions/);
assert.match(html, /settings.read/);
assert.match(html, /not a grant/);
assert.match(html, /Declared supported capabilities default to Allow/);
assert.match(html, /Ask or Deny/);
assert.match(html, /Host validation and resource scope always apply/);
assert.match(html, /Host validation and the selected permission mode still apply/);
assert.doesNotMatch(html, /Check the actual scope in the permission prompt/);
assert.match(html, /Source example/);
assert.ok(html.indexOf('settings.read') < html.indexOf('Network unavailable'));
assert.match(html, /Retry/);
@@ -4,6 +4,7 @@ import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../../ui/
import { PluginInfo } from './PluginInfo';
import React, { useRef, useState } from 'react';
import { PluginBrandIcon } from '../../plugins/PluginBrandIcon';
import { PluginAuthorRow } from '../../plugins/PluginAuthorRow';
import { ArrowLeft } from 'lucide-react';
import { useI18n } from '../../../application/i18n/I18nProvider';
import { usePluginCatalog } from '../../../application/state/usePluginCatalog';
@@ -82,7 +83,7 @@ export function PluginMarketplaceContent({ catalog, installed, selected, onSelec
return <button key={item.id} type="button" data-plugin-id={item.id} aria-current={selected === item.id ? 'true' : undefined} onClick={() => choose(item.id)}
className="plugin-card min-w-0 flex min-h-[200px] flex-col gap-3 rounded-lg bg-card p-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<div className="flex items-center gap-3"><span className="flex h-8 w-8 shrink-0 items-center justify-center"><PluginBrandIcon entry={item} size={32} className="text-muted-foreground" /></span><span className="min-w-0 break-words text-sm font-semibold leading-5">{item.name}</span></div>
<p className="break-words text-xs text-muted-foreground">{item.author}</p>
<PluginAuthorRow entry={item} sourceId={sourceId} />
<p className="line-clamp-3 break-words text-sm leading-5 text-muted-foreground">{item.description}</p>
<div className="mt-auto flex flex-wrap items-center justify-between gap-2 pt-1 text-xs text-muted-foreground"><span>{item.version} · {item.license}</span><span className="text-foreground">{t('settings.plugins.manager.details')}</span></div>
<div className="flex flex-wrap gap-2 text-xs text-muted-foreground">{isInstalled && <span className="rounded bg-muted px-2 py-0.5 text-foreground">{t('settings.plugins.market.installed')}</span>}{!item.artifact && <span className="rounded bg-muted/40 px-2 py-0.5">{t('settings.plugins.market.sourceBadge')}</span>}</div>
@@ -91,7 +92,7 @@ export function PluginMarketplaceContent({ catalog, installed, selected, onSelec
</div>}
{entry && <article key={entry.id} aria-label={entry.name} className="plugin-marketplace-detail mx-auto w-full max-w-[920px] min-w-0 space-y-6 focus:outline-none">
<Button variant="ghost" size="sm" onClick={back}><ArrowLeft size={14} className="mr-2" />{t('settings.plugins.market.back')}</Button>
<div className="space-y-2"><div className="flex items-center gap-3"><PluginBrandIcon entry={entry} size={48} /><h4 ref={detailRef} tabIndex={-1} className="break-words text-xl font-semibold focus:outline-none">{entry.name}</h4></div><p className="text-xs text-muted-foreground">{entry.author} · {entry.version} · {entry.license}</p>
<div className="space-y-2"><div className="flex items-center gap-3"><PluginBrandIcon entry={entry} size={48} /><h4 ref={detailRef} tabIndex={-1} className="break-words text-xl font-semibold focus:outline-none">{entry.name}</h4></div><PluginAuthorRow entry={entry} sourceId={sourceId} /><p className="text-xs text-muted-foreground">{entry.version} · {entry.license}</p>
{installedEntry && <p className="text-xs text-muted-foreground">{t('settings.plugins.market.installed')} · {installedEntry.activeVersion} · {t(installedEntry.enabled ? 'settings.plugins.manager.enabled' : 'settings.plugins.manager.disabled')}</p>}
</div>
{installedEntry?.runtime?.lastError && <p role="status" className="break-words text-xs text-destructive">{t('settings.plugins.manager.lastError')}: {installedEntry.runtime.lastError}</p>}
@@ -19,9 +19,16 @@ test('package detail renders manifest resources as text and explains advanced au
} as NetcattyInstalledPlugin;
const html = renderToStaticMarkup(<I18nProvider locale="en"><PluginPackageDetails plugin={plugin} /></I18nProvider>);
assert.match(html, /full Node filesystem and network authority/);
assert.match(html, /Broker permissions cannot restrict this access/);
assert.match(html, /Development preview only/);
assert.match(html, /https:\/\/example.com/);
assert.match(html, /&lt;script&gt;/);
assert.doesNotMatch(html, /<script>/);
assert.match(html, /not a grant/);
assert.match(html, /Declared supported capabilities default to Allow/);
assert.match(html, /Ask or Deny/);
assert.match(html, /Host validation and resource scope always apply/);
assert.match(html, /this capability may expose private data/);
assert.match(html, /mode can be changed in permission settings/);
assert.doesNotMatch(html, /before granting/);
assert.match(html, /aaaaaaaaaaaaaaaa/);
});
@@ -3,6 +3,7 @@ import { describePluginRuntime } from '@/domain/pluginRuntimePolicy.cjs';
import React, { useRef, useState } from 'react';
import { PluginPermissionPanel } from './PluginPermissionPanel';
import { PluginBrandIcon } from '../../plugins/PluginBrandIcon';
import { PluginAuthorRow } from '../../plugins/PluginAuthorRow';
import { ArrowLeft } from 'lucide-react';
import { usePluginManager } from '../../../application/state/usePluginManager';
import { useI18n } from '../../../application/i18n/I18nProvider';
@@ -103,7 +104,7 @@ export function PluginPackageManager({ manager, onSelectionChange, initialSelect
</Button>
</div>
<p className="break-all text-xs text-muted-foreground">{t('settings.plugins.sources.source')}: {t(plugin.source?.kind === 'official' ? 'settings.plugins.sources.official' : plugin.source?.kind === 'third-party' ? 'settings.plugins.sources.thirdparty' : 'settings.plugins.sources.local')}{plugin.source?.origin ? ` · ${plugin.source.origin}` : ''}</p>
{plugin.manifest?.publisher && <p className="break-words text-xs text-muted-foreground">{plugin.manifest.publisher}</p>}
{plugin.manifest?.publisher && <PluginAuthorRow plugin={plugin} />}
<p className={`break-words text-sm leading-5 text-muted-foreground ${selectedPlugin ? 'whitespace-pre-wrap' : 'line-clamp-3'}`}>{descriptionOf(plugin) || t('settings.plugins.manager.noDescription')}</p>
{!selectedPlugin ? <div className="mt-auto flex flex-wrap items-center justify-between gap-2 pt-1">
<p className="break-words text-xs text-muted-foreground">{plugin.activeVersion}{plugin.manifest?.license ? ` · ${plugin.manifest.license}` : ''}</p>
@@ -3,6 +3,8 @@ import { netcattyBridge } from '../../../infrastructure/services/netcattyBridge'
import { useI18n } from '../../../application/i18n/I18nProvider';
import { describePluginPermission } from '@/domain/pluginPermissionDescriptions.cjs';
import { Button } from '../../ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { SettingRow } from '../settings-ui';
/** Host UI only. Plugin views cannot query or mutate this security state. */
export function PluginPermissionPanel({ pluginId, onChanged }: {
@@ -36,6 +38,17 @@ export function PluginPermissionPanel({ pluginId, onChanged }: {
void refresh();
return () => { requestGeneration.current++; };
}, [refresh]);
const changeMode = async (permission: string, mode: PluginPermissionMode) => {
if (pending.current) return;
pending.current = true; setBusy(true); setError(null);
try {
const bridge = netcattyBridge.require();
if (!bridge.setPluginPermissionMode || !snapshot?.policyRevision) throw new Error(t('settings.plugins.permissions.unavailable'));
await bridge.setPluginPermissionMode(pluginId, permission, mode, snapshot.policyRevision);
await onChanged();
} catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
finally { await refresh(true); pending.current = false; setBusy(false); }
};
const revoke = async () => {
if (pending.current) return;
pending.current = true;
@@ -61,9 +74,18 @@ export function PluginPermissionPanel({ pluginId, onChanged }: {
<h4 className="font-medium">{t('settings.plugins.permissions.title')}</h4>
<Button variant="ghost" size="sm" disabled={busy} onClick={() => void refresh()}>{t('settings.plugins.permissions.refresh')}</Button>
</div>
<p className="text-xs text-muted-foreground">{t('settings.plugins.permissions.note')}</p>
{error && <p role="alert" className="text-xs text-destructive">{error}</p>}
{!snapshot && !error && <p role="status">{t('settings.plugins.permissions.loading')}</p>}
{snapshot && <>
{(snapshot.policies ?? []).map((policy) => <SettingRow key={policy.permission}
label={describePluginPermission(policy.permission, resolvedLocale).label}
description={<span className="whitespace-pre-wrap break-all">{describePluginPermission(policy.permission, resolvedLocale).description}{' · '}{policy.resources.join(', ')}</span>}>
<Select value={policy.mode} disabled={busy} onValueChange={(mode) => void changeMode(policy.permission, mode as PluginPermissionMode)}>
<SelectTrigger className="w-28" aria-label={describePluginPermission(policy.permission, resolvedLocale).label}><SelectValue /></SelectTrigger>
<SelectContent>{(['allow', 'ask', 'deny'] as const).map((mode) => <SelectItem key={mode} value={mode}>{t(`settings.plugins.permissions.${mode}`)}</SelectItem>)}</SelectContent>
</Select>
</SettingRow>)}
{snapshot.grants.length === 0 && <p className="text-xs text-muted-foreground">{t('settings.plugins.permissions.empty')}</p>}
{snapshot.grants.map((grant, index) => <div key={index} className="rounded-md bg-muted/40 p-3 text-xs">
<p className="font-medium">{describePluginPermission(grant.permission, resolvedLocale).label}</p>
@@ -76,7 +98,7 @@ export function PluginPermissionPanel({ pluginId, onChanged }: {
<summary className="cursor-pointer">{t('settings.plugins.permissions.audit')}</summary>
<ol className="mt-2 space-y-1">{snapshot.audit.map((entry, index) => <li key={index} className="break-words">
<time dateTime={new Date(entry.createdAt).toISOString()}>{new Date(entry.createdAt).toLocaleString(resolvedLocale)}</time>{' · '}
{entry.event}{entry.permission ? ` · ${entry.permission}` : ''}{entry.scope ? ` · ${entry.scope}` : ''}
{entry.event}{entry.permission ? ` · ${entry.permission}` : ''}{entry.scope ? ` · ${entry.scope}` : ''}{entry.mode ? ` · ${t(`settings.plugins.permissions.${entry.mode}`)}` : ''}{entry.action ? ` · ${entry.action}` : ''}
</li>)}</ol>
</details>
<p className="text-xs text-muted-foreground">{t('settings.plugins.permissions.revokeNote')}</p>
@@ -6,6 +6,7 @@ import type { usePluginManager } from '../../../application/state/usePluginManag
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { PluginBrandIcon } from '../../plugins/PluginBrandIcon';
import { PluginAuthorRow } from '../../plugins/PluginAuthorRow';
import { SettingCard, SettingRow, SettingsSection, Toggle } from '../settings-ui';
import { PluginLogSettings } from './PluginLogSettings';
@@ -72,7 +73,8 @@ export function PluginSettingsLanding({ manager, settingsAvailable, settingsErro
<span className="truncate" title={name}>{name}</span>
{plugin.activeVersion && <span className="shrink-0 text-xs font-normal text-muted-foreground">{plugin.activeVersion}</span>}
</span>} description={<>
<span className="block break-words">{[plugin.manifest?.publisher, sourceOf(plugin), statusOf(plugin)].filter(Boolean).join(' · ')}</span>
{plugin.manifest?.publisher && <PluginAuthorRow plugin={plugin} />}
<span className="block break-words">{[sourceOf(plugin), statusOf(plugin)].filter(Boolean).join(' · ')}</span>
{availableUpdate && <span className="block text-primary">{t('settings.plugins.landing.updateAvailable').replace('{version}', availableUpdate.availableVersion)}</span>}
{description && <span className="line-clamp-2 break-words">{description}</span>}
</>}>
@@ -0,0 +1,88 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { EventEmitter } from 'node:events';
import { createRequire } from 'node:module';
import { JSDOM } from 'jsdom';
const require = createRequire(import.meta.url);
test('real Settings landing leaves views visible while idle; log and Ask dialogs suspend and restore them', async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div><div id="native-view-mount"></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', 'HTMLInputElement', 'Element', 'Node', 'NodeFilter', 'Event', 'MouseEvent', 'KeyboardEvent', 'MutationObserver', 'DocumentFragment', 'CustomEvent']) install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window));
install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window));
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 { PluginSettingsLanding } = await import('./PluginSettingsLanding');
const { PluginPermissionHost } = await import('../../plugins/PluginPermissionHost');
const { observePluginHostSecurityVisibility } = await import('../../../application/state/pluginHostSecurityVisibility');
const { PluginPermissionDecisionHost } = require('../../../electron/plugins/permissionDecisionHost.cjs');
type Prompt = NetcattyPluginPermissionPrompt | { requestId: string; closed: true };
const listeners = new Set<(event: Prompt) => void>();
const sender = Object.assign(new EventEmitter(), { isDestroyed: () => false, send: (_channel: string, event: Prompt) => { for (const listener of listeners) listener(event); } });
const owner = Object.assign(new EventEmitter(), { webContents: sender, isFocused: () => true, isVisible: () => true, isDestroyed: () => false });
const host = new PluginPermissionDecisionHost({ getWindows: () => [owner], isLocked: () => false });
let logStatus = { saveToDisk: false, verbose: false, droppedRecords: 0, writeErrors: 0, pendingBytes: 0, maxBytes: 3145728, retentionDays: 7 };
Object.assign(dom.window, { netcatty: {
async getPluginLogStatus() { return logStatus; },
async configurePluginLogs(value: { saveToDisk: boolean; verbose: boolean }) { logStatus = { ...logStatus, ...value }; return logStatus; },
onPluginPermission(listener: (event: Prompt) => void) { listeners.add(listener); return () => listeners.delete(listener); },
setPluginPermissionReady: async (ready: boolean) => host.setReady(sender, ready),
respondPluginPermission: async (response: unknown) => host.respond(sender, response),
} });
const manager = { plugins: [], available: true, statusKnown: true, busy: false, error: null, credentialStorageAvailable: true,
async refresh() {}, async setEnabled() {}, async importPackage() {}, async uninstall() {} };
let visible = true;
const transitions: boolean[] = [];
const stopVisibility = observePluginHostSecurityVisibility(document.getElementById('native-view-mount')!, (next) => { visible = next; transitions.push(next); });
const root = createRoot(document.getElementById('root')!);
const button = (label: string) => [...document.querySelectorAll<HTMLButtonElement>('button')].find((element) => element.textContent === label)!;
const flushVisibility = () => new Promise<void>((resolve) => dom.window.queueMicrotask(resolve));
try {
await act(async () => root.render(<I18nProvider locale="en"><PluginSettingsLanding manager={manager} settingsAvailable={new Set()} onManage={() => {}} /><PluginPermissionHost /></I18nProvider>));
await flushVisibility();
assert.equal(document.querySelector('[role="dialog"]'), null);
assert.ok(button('Configure'), 'real idle logging row is present');
assert.equal(visible, true, 'idle Settings landing must not hide the native child');
assert.deepEqual(transitions, []);
await act(async () => button('Configure').click());
await flushVisibility();
assert.ok(document.querySelector('[role="dialog"][data-host-security-surface]'));
assert.equal(visible, false, 'actual logging security dialog must hide the child');
await act(async () => document.querySelectorAll<HTMLButtonElement>('[role="switch"]')[0].click());
await act(async () => document.querySelectorAll<HTMLButtonElement>('[role="switch"]')[1].click());
await flushVisibility();
assert.equal(document.querySelectorAll('[role="dialog"]').length, 2);
assert.equal(visible, false, 'the verbose security confirmation must also keep the child hidden');
await act(async () => button('Cancel').click());
await flushVisibility();
assert.equal(visible, false, 'cancelling verbose returns to the protected logging dialog');
await act(async () => button('Close').click());
await flushVisibility();
assert.equal(document.querySelector('[role="dialog"]'), null);
assert.equal(visible, true, 'closing logs must restore the child while its idle row remains');
let pending!: Promise<{ decision: string }>;
await act(async () => {
pending = host.request({ requestId: 'settings-visibility-ask', pluginId: 'com.example.settings-visibility', pluginName: 'Settings visibility fixture', pluginVersion: '1.0.0',
permission: 'settings.read', resources: ['*'], reason: 'Read own synthetic setting' });
});
await flushVisibility();
assert.ok(document.querySelector('[role="dialog"][data-host-security-surface]'));
assert.equal(visible, false, 'Ask must still hide the child above the real landing');
await act(async () => { button('Deny').click(); await pending; });
await flushVisibility();
assert.equal((await pending).decision, 'deny');
assert.equal(visible, true, 'dismissing Ask must restore the same child');
assert.deepEqual(transitions, [false, true, false, true]);
} finally {
await act(async () => root.unmount()); stopVisibility(); host.shutdown(); dom.window.close();
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
}
});
@@ -23,7 +23,7 @@ import {
import { resolveAppIconVariant, type AppIconVariant } from "../../../domain/appIconVariant";
import { resolveNoteFontSelectionFamily, resolveNoteFontSelectionId } from "../../../domain/noteFonts";
import { DEFAULT_AUTO_IMPORT_SYSTEM_KNOWN_HOSTS } from "../../../domain/systemKnownHostsAutoImport";
import { cn } from "../../../lib/utils";
import { cn, isMacPlatform } from "../../../lib/utils";
import { SectionHeader, SettingsAnchor, SettingsTabContent, SettingRow, Toggle, Select } from "../settings-ui";
import { FontSelect } from "../FontSelect";
import { TerminalFontSelect } from "../TerminalFontSelect";
@@ -69,6 +69,8 @@ function SettingsAppearanceTab(props: {
setShowHostTreeSidebar: (enabled: boolean) => void;
windowOpacity: number;
setWindowOpacity: (opacity: number) => void;
windowBackgroundBlur: boolean;
setWindowBackgroundBlur: (enabled: boolean) => void;
appIconVariant: AppIconVariant;
setAppIconVariant: (variant: AppIconVariant) => void;
}) {
@@ -140,10 +142,13 @@ function SettingsAppearanceTab(props: {
setShowHostTreeSidebar,
windowOpacity,
setWindowOpacity,
windowBackgroundBlur,
setWindowBackgroundBlur,
appIconVariant,
setAppIconVariant,
} = props;
const resolvedAppIconVariant = resolveAppIconVariant(appIconVariant);
const isMac = isMacPlatform();
const WINDOW_OPACITY_PRESETS = [
{ label: '100%', value: 1 },
@@ -315,6 +320,19 @@ function SettingsAppearanceTab(props: {
</div>
</div>
</SettingRow>
{isMac && (
<SettingRow
anchorId="appearance-window-background-blur"
label={t("settings.appearance.windowBackgroundBlur")}
description={t("settings.appearance.windowBackgroundBlur.desc")}
>
<Toggle
checked={windowBackgroundBlur}
onChange={setWindowBackgroundBlur}
ariaLabel={t("settings.appearance.windowBackgroundBlur")}
/>
</SettingRow>
)}
</div>
<SectionHeader title={t("settings.appearance.uiTheme")} />
+1
View File
@@ -264,6 +264,7 @@ export const SftpOverlays: React.FC<SftpOverlaysProps> = React.memo(({
open={showTextEditor}
onClose={closeTextEditor}
fileName={textEditorFileName}
filePath={textEditorTarget?.fullPath}
initialContent={textEditorContent}
onSave={handleSaveTextFile}
editorWordWrap={editorWordWrap}
+2 -2
View File
@@ -248,7 +248,7 @@ export const useSftpViewFileOps = ({
hostId: target.hostId,
remotePath: target.fullPath,
fileName: target.file.name,
languageId: snapshot.languageId || getLanguageId(target.file.name),
languageId: snapshot.languageId || getLanguageId(target.fullPath),
content: snapshot.content,
baselineContent: snapshot.baselineContent,
wordWrap: snapshot.wordWrap,
@@ -284,7 +284,7 @@ export const useSftpViewFileOps = ({
hostId: target.hostId,
remotePath: target.fullPath,
fileName: target.file.name,
languageId: snapshot.languageId || getLanguageId(target.file.name),
languageId: snapshot.languageId || getLanguageId(target.fullPath),
content: snapshot.content,
baselineContent: snapshot.baselineContent,
wordWrap: snapshot.wordWrap,
+131
View File
@@ -0,0 +1,131 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import test from 'node:test';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import ts from 'typescript';
import type { TextEditorPaneProps } from '../editor/TextEditorPane';
import type { SftpStateApi } from '../../application/state/useSftpState';
import { editorTabStore } from '../../application/state/editorTabStore';
import { activeTabStore } from '../../application/state/activeTabStore';
import { useSftpViewFileOps } from './hooks/useSftpViewFileOps';
// Keep the real modal state/save flow; replace only Monaco and visual chrome.
function loadModal(pane: React.ComponentType<TextEditorPaneProps>) {
const url = new URL('../TextEditorModal.tsx', import.meta.url);
const compiled = ts.transpileModule(readFileSync(url, 'utf8'), { compilerOptions: {
module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX, esModuleInterop: true,
} }).outputText;
const require = createRequire(url);
const passthrough = ({ children }: { children: React.ReactNode }) => children;
const replacements: Record<string, unknown> = {
'./editor/TextEditorPane': { TextEditorPane: pane },
'./ui/dialog': { Dialog: passthrough, DialogContent: passthrough, DialogTitle: passthrough },
'./ui/toast': { toast: { success() {}, error() {} } },
'../application/state/windowInputFocus': { scheduleWindowInputFocus() {} },
};
const module = { exports: {} as { default: React.ComponentType<Record<string, unknown>> } };
new Function('require', 'module', 'exports', compiled)(
(id: string) => replacements[id] ?? require(id), module, module.exports,
);
return module.exports.default;
}
test('SFTP modal uses full paths, preserves manual selection and saves exact content', async () => {
const globals = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previousAct = globals.IS_REACT_ACT_ENVIRONMENT;
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
const previousActiveTab = activeTabStore.getActiveTabId();
const detached: Array<{ languageId: string; content: string; remotePath: string }> = [];
Object.defineProperty(globalThis, 'window', { configurable: true, value: {
setTimeout, clearTimeout,
netcatty: { openEditorWindow: async (snapshot: typeof detached[number]) => {
detached.push(snapshot);
return { success: true };
} },
} });
globals.IS_REACT_ACT_ENVIRONMENT = true;
let paneProps: TextEditorPaneProps | undefined;
const Modal = loadModal((props) => { paneProps = props; return null; });
let ops: ReturnType<typeof useSftpViewFileOps> | undefined;
const original = '# fixture\r\nserver { proxy_pass http://$host; }\r\n';
const writes: unknown[][] = [];
const connection = { id: 'nginx-fixture', hostId: 'nginx-host', currentPath: '/etc/nginx/conf.d' };
const sftpRef = { current: {
leftPane: { id: 'nginx-pane', connection }, rightPane: { id: 'nginx-pane', connection },
joinPath: (parent: string, name: string) => `${parent}/${name}`,
readTextFile: async () => original,
writeTextFile: async (...args: unknown[]) => { writes.push(args); },
} as unknown as SftpStateApi };
function Probe() {
ops = useSftpViewFileOps({
sftpRef, behaviorRef: { current: '' }, autoSyncRef: { current: false },
getOpenerForFileRef: { current: () => null }, setOpenerForExtension() {}, t: (key) => key,
});
return ops.showTextEditor ? React.createElement(Modal, {
open: true, onClose() {}, fileName: ops.textEditorTarget!.file.name,
filePath: ops.textEditorTarget!.fullPath, initialContent: ops.textEditorContent,
onSave: ops.handleSaveTextFile, editorWordWrap: false, onToggleWordWrap() {},
hotkeyScheme: 'pc', keyBindings: [], onPromoteToTab: ops.onPromoteToTab,
}) : null;
}
let renderer: ReactTestRenderer | undefined;
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
const file = { name: 'site.conf', size: original.length, type: 'file' as const, lastModified: 0, sizeFormatted: '', lastModifiedFormatted: '' };
await act(async () => { await ops!.onEditFileLeft(file); });
assert.equal(paneProps!.languageId, 'nginx');
assert.equal(paneProps!.fileName, 'site.conf');
// Keep the modal mounted: basename and content stay identical, only path changes.
await act(async () => { await ops!.onEditFileLeft(file, '/etc/other/site.conf'); });
assert.equal(paneProps!.languageId, 'ini');
await act(async () => { await ops!.onEditFileLeft(file, '/etc/nginx/conf.d/site.conf'); });
assert.equal(paneProps!.languageId, 'nginx');
await act(async () => { paneProps!.onLanguageChange('ini'); });
await act(async () => { paneProps!.onSave(); });
assert.deepEqual(writes, [['left', '/etc/nginx/conf.d/site.conf', original]]);
await act(async () => { paneProps!.onPromoteToTab!(); });
let tab = editorTabStore.getTabs().find(({ sessionId }) => sessionId === connection.id);
assert.equal(tab?.languageId, 'ini', 'promotion preserves a manual override');
assert.equal(tab?.content, original);
editorTabStore.close(tab!.id);
// A generic config can still be switched to Nginx manually.
await act(async () => { await ops!.onEditFileLeft(file, '/etc/other/site.conf'); });
assert.equal(paneProps!.languageId, 'ini');
await act(async () => { paneProps!.onLanguageChange('nginx'); });
assert.equal(paneProps!.languageId, 'nginx', 'arbitrary config supports manual Nginx selection');
await act(async () => { paneProps!.onPromoteToTab!(); });
tab = editorTabStore.getTabs().find(({ sessionId }) => sessionId === connection.id);
assert.equal(tab?.languageId, 'nginx');
// Legacy snapshots without language still infer from the full target path.
await act(async () => { await ops!.onEditFileLeft(file, '/etc/nginx/conf.d/fallback.conf'); });
await act(async () => { ops!.onPromoteToTab({ fileName: file.name, content: original,
baselineContent: original, languageId: '', wordWrap: false, viewState: null }); });
assert.equal(editorTabStore.getTabs().find(({ remotePath }) => remotePath.endsWith('/fallback.conf'))?.languageId, 'nginx');
await act(async () => { await ops!.onEditFileLeft(file, '/etc/nginx/sites-enabled/example.com'); });
await act(async () => { ops!.onPopOut({ fileName: file.name, content: original,
baselineContent: original, languageId: '', wordWrap: false, viewState: null }); });
assert.equal(detached.at(-1)?.languageId, 'nginx', 'pop-out fallback also uses the full path');
assert.equal(detached.at(-1)?.remotePath, '/etc/nginx/sites-enabled/example.com');
assert.equal(detached.at(-1)?.content, original);
} finally {
await act(async () => { renderer?.unmount(); });
for (const tab of editorTabStore.getTabs().filter(({ sessionId }) => sessionId === connection.id)) editorTabStore.close(tab.id);
activeTabStore.setActiveTabId(previousActiveTab);
await new Promise<void>((resolve) => setTimeout(resolve, 0));
globals.IS_REACT_ACT_ENVIRONMENT = previousAct;
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
else Reflect.deleteProperty(globalThis, 'window');
}
});
test('the SFTP overlay forwards path context to the lazy modal', () => {
const overlay = readFileSync(new URL('./SftpOverlays.tsx', import.meta.url), 'utf8');
assert.match(overlay, /<LazyTextEditorModal[\s\S]*?filePath=\{textEditorTarget\?\.fullPath\}/);
const pane = readFileSync(new URL('../editor/TextEditorPane.tsx', import.meta.url), 'utf8');
assert.match(pane, /beforeMount=\{registerNginxLanguage\}/);
});
+3 -1
View File
@@ -17,6 +17,7 @@ interface ConfirmDialogProps {
confirmLabel: string;
busy?: boolean;
destructive?: boolean;
hostSecuritySurface?: boolean;
onOpenChange: (open: boolean) => void;
onConfirm: () => void;
}
@@ -28,6 +29,7 @@ export const ConfirmDialog = memo(function ConfirmDialog({
confirmLabel,
busy = false,
destructive = false,
hostSecuritySurface = false,
onOpenChange,
onConfirm,
}: ConfirmDialogProps) {
@@ -35,7 +37,7 @@ export const ConfirmDialog = memo(function ConfirmDialog({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-[calc(100vw-2rem)] overflow-hidden sm:max-w-[380px]">
<DialogContent data-host-security-surface={hostSecuritySurface ? "" : undefined} className="max-w-[calc(100vw-2rem)] overflow-hidden sm:max-w-[380px]">
<DialogHeader className="min-w-0 pr-6">
<DialogTitle className="truncate">{title}</DialogTitle>
</DialogHeader>
@@ -1,5 +1,9 @@
# Unified plugin acceptance candidate
This file records the frozen 677 native baseline. For the subsequent permission
policy and AI candidate, use [the new integration record](policy-ai-integration.md)
and its package manifest. Historical consent flows below are not the revised UX.
The dedicated branch is `integration/plugin-native-acceptance`. Its Draft PR
records the exact current head and CI runs. Native AI, database, Host/Vault, and
settings/logging checks use this candidate rather than separate feature trees.
+108
View File
@@ -0,0 +1,108 @@
# Plugin model transport cold start
Commit `092438803bed96753bfe68cb78da9ca1137dee25` removes an independent startup
dependency on the internal AI sidebar. It does not establish the cause or outcome
of the original native failure; that still requires an authorized native retest.
## Reproduced boundary
At native candidate `677aac33b1eec9dbd4a367417a49c964cdea63e7`, the plugin model
selector reads the saved host provider, while main's provider registry starts
empty. The existing sidebar synchronizes that registry when visible or sending.
The plugin startup path did not. A nondefault configured loopback port can
therefore fail main's provider allowlist before HTTP transport starts.
The revised `components/PluginAIContextHost.test.tsx` installs the browser sample,
mounts the trusted host component, uses the real application preload, and routes
model requests through `registerProviderHandlers` and its actual allowlist. It
does not mount the internal sidebar or manually alter the allowlist. Credential
injection uses synthetic fixture markers; the HTTP edge and deterministic local
fixture use the existing transport. No paid service, real key, Note, or host is
used. This remains DOM/in-process evidence, not native sandbox acceptance.
Failed-before evidence is `/tmp/netcatty-ai-cold-provider-before-final.log`:
```text
ok: false
allowlistRejected: true
statusCode: undefined
```
The corrected regression passes and preserves both the selected fixture provider
and a second host-configured synthetic provider. It checks that provider markers
and configuration do not enter plugin-facing model/context envelopes. Expected
SDK error output is suppressed during this diagnostic so request payloads and
headers are not logged.
## Correction
Before publishing a selected model handle, the trusted renderer synchronizes the
current host-owned provider settings through the existing `aiSyncProviders`
application API. It checks that the selected model revision matches the snapshot
being synchronized. The runtime rechecks activity, cancellation, model revision,
and pending-selection ownership after the await. Pending selections count toward
the model-handle cap; release and shutdown invalidate late results.
Plugin requests supply no URL, credential, or provider configuration. The existing
main sender validation, endpoint allowlist, source binding, and model invocation
budgets are unchanged. No new schema feature, plugin permission, or consent
dialog is added. The assistant package is unchanged and retains SHA-256
`c7d784d5c3bd2feb463afd58eae3a9594615395b168174cb8a3d0677584ae395`.
Production integration touches `configuredModel.ts`, `trustedHostRuntime.ts`, and
`usePluginAIContextHost.ts`. The hook's import and `prepareModel` option may
overlap host-selection work; preserve both when integrating the separate policy
task. Permission-engine, consent-dialog, and sample-UI changes are outside this
correction.
## Native and policy status
The native open/close sidebar comparison was incomplete. Execution auto-review
denied the Application-scope `context.selected.list` grant; that action did not
execute. No post-sidebar inference was performed, the prompt expired, and the
sample was disabled while the worker cleaned up. This is not native confirmation
of the startup cause. The original `677aac33` app remains frozen for comparison;
this fix does not authorize retrying the denied execution action.
In the earlier permission engine, **Application** grants are memory-only for the
application lifetime; **Always** grants are persisted. An explicitly authorized
Application grant can fit bounded temporary QA. A one-use prompt on every stream
read is not an unavoidable target UX. The separate policy task implements the
new direction: default Allow for declared supported capabilities, per-plugin
Allow/Ask/Deny settings, audit, and in-app Ask dialogs. That product change is
separate from execution-tool authorization and must not be used to evade a tool
denial. This transport correction does not redesign that policy.
Native outcome, independent verification, and the sample's light-theme appearance
follow-up remain separate acceptance work. No GUI launch, sandbox bypass, paid
model invocation, main merge, or release was performed for this correction.
## Node 22 CI observer correction
The new cold-start test failed on exact head `9ca70f329` in test run
`40436198585`, Linux job `121965743101`: 15,206 passed, 1 failed, 50 skipped.
The sole failure was the empty SDK/renderer-error assertion receiving one
`SDK_OR_RENDERER_ERROR` marker. This red result is retained as evidence; it is
not an unrelated baseline failure.
The CI runtime was Node `22.23.3`; local validation had used Node `24.19.0`.
Reproduction on the exact CI version identified the safe category
`setup:node-sqlite-experimental`, before any model operation. The existing
`node:sqlite` import schedules its ExperimentalWarning on the next tick via
`console.error`. The newly added observer was installed before that warning
drained. The same test passed on Node 24, which did not emit that warning.
The test now lets pending module warnings reach normal stderr before installing
the SDK/renderer observer. The warning remains visible, and the zero-runtime-error
assertion is unchanged. Safe phase/error categories make future failures
diagnosable without request payloads or headers. No production behavior, timeout,
permission, or cancellation assertion changed. Both Node versions pass the
focused test; the Node 22 parallel fixture/UI/provider/preload group passes all
16 tests with concurrency 4.
Diagnostic evidence: `/tmp/netcatty-ai-cold-ci-node22-sqlite-category.log` fails
before correction, `/tmp/netcatty-ai-cold-ci-node22-after.log` passes with the
SQLite warning still visible, and `/tmp/netcatty-ai-cold-ci-node22-parallel.log`
records the parallel check. The appearance-only sample change is independently
published as `e325742abf9fd329f1f7858eda66367e7a62357c`; its package hash is
`7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274`.
@@ -0,0 +1,125 @@
# Managed-window Ask acceptance candidate
The dedicated branch is `integration/plugin-ask-routing-acceptance`. Its Draft
PR records the exact frozen integration head, CI and private renderer artifact
handoff. It starts from frozen #4001 at
`02049102b6732778adcd0f33b0a0ade6b4752327`; the old source checkout, QA workspace,
profile and renderer artifact remain unchanged.
## Exact inputs and ownership
The only new input is policy owner's reviewed Ask correction
`89beeb93749c751f255beb6d0e0f95d23bdd9a7b`, imported by ordinary merge
`1b21c41fa26c0173084c7ae75e640ef3274285dd`. There were no merge conflicts or
manual production edits. These seven production files exactly match that input:
| File | Owned production delta |
| --- | --- |
| `electron/bridges/windowManager.cjs` | Enumerate managed app windows, including Settings |
| `electron/main/registerBridges.cjs` | Supply the managed permission-window getter |
| `electron/plugins/hostService.cjs` | Pass that getter to the existing decision host |
| `electron/plugins/permissionDecisionHost.cjs` | Bind ready/focused/visible/unlocked managed renderer selection and request lifecycle to the chosen receiver |
| `electron/plugins/pluginBridge.cjs` | Guard permission readiness/replies by managed app window and main frame; reject plugin/foreign/subframe senders |
| `components/SettingsPage.tsx` | Mount the existing permission host for standalone Settings |
| `components/plugins/PluginPermissionHost.tsx` | Mark Ask with the existing host-security surface so attached native views yield |
The input also owns the Settings-installed-entrypoint regression, renderer test
updates and policy/security documentation. AI d33 startup wiring, sample assets,
the combined cold-start assertions and all earlier policy/transport history are
preserved from 020. `ModelSelector.tsx` is unchanged from 020; the separate
model-selector failure-loop repair is not imported. Diagnostic #3999 remains
excluded. No broker resource/source rules, stream restrictions, package/lock
inputs, native dependencies or sandbox configuration change in this integration.
## Frozen 020 native evidence
The parent closed that QA session and released the GUI. Its partial outcome is:
| Native case on 020 | Result |
| --- | --- |
| Default Allow cold Send and completion | Passed |
| Stop, AI Deny, restore without automatic replay | Passed |
| Themes in new views | Passed |
| Ask visible dialog | Failed: no visible dialog, timeout, zero new model requests |
| Ask acceptance/cancel and content-read matrix | Not run; remain pending |
The input's independent source-only delta review is scoped clean. Its installed
SDK/registered IPC test reproduces the old Settings-owned failure and passes with
the correction using represented Electron objects. That is not native Ask
success. No new native acceptance is claimed by this coding executor.
Earlier terminal solo/split core passes with corrected fixtures, unreliable/
unverified Focus and one QA Enter in A during a palette attempt remain historical
evidence. There is no global zero-input or full terminal native-pass claim. The
old Rfam run failed socket transport before connect resolved, without reaching
authentication/SELECT; its cause and auth/TLS compatibility remain unverified.
The next native priority is the new Ask path, not more old-baseline loops.
## Checks and retained CI history
| Local check | Result |
| --- | --- |
| Registered runtime | 696 tests: 695 passed, one native skip, zero failed/cancelled |
| Contract/SDK/CLI | 91 passed |
| Offline examples | Five passed, one Docker opt-in skip |
| Mounted cold-start AI/permission/selected-summary/Host group | 21 passed |
| Settings and security-surface visibility group | 37 passed |
| Contract/capability/Codex generation and drift | Clean |
| Lint | Zero errors, seven existing warnings |
| Five sample archives | Validated; two builds each are identical and match frozen 020 |
The exact integration production build, renderer inventory and final CI are
recorded in the Draft PR and artifact provenance. Local native packaging and
unpackaged GUI acceptance are not claimed. This environment uses locked
dependencies and standard patches; the official pinned Electron binary uses its
documented cache/proxy support. No header workaround, native shim, HOME change
or sandbox change is introduced.
Input89 [test CI 40453446775](https://github.com/binaricat/Netcatty/actions/runs/40453446775)
succeeded on the parent's single infrastructure-only rerun: 15,342 passed, 50
skipped, zero failed/cancelled. The original runner interruption remains evidence;
this worker did not duplicate its retry. Input89
[four-platform packages](https://github.com/binaricat/Netcatty/actions/runs/40453446781)
passed with release jobs skipped. Frozen 020's successful full/platform CI and
all earlier diagnosed/unexplained failures remain separate predecessor evidence.
The [sample manifest](ask-routing-packages.json) records exact IDs, versions,
features, permissions/resources and archive/content hashes. All five archives
are byte-identical to 020, including Assistant
`7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274`.
No archive was activated by this executor. Its unchanged owner README retains
old review wording; the current Allow/Ask/Deny procedure governs acceptance.
## Production-renderer preparation and native Ask recipe
1. Create a new isolated checkout at this Draft's exact head and a separate
disposable synthetic QA profile. Keep the old 020 workspace/profile intact.
2. Match `package.json` and `package-lock.json` hashes to the renderer artifact's
provenance and the independently normally rebuilt native dependencies. They
are unchanged from 020. Prepare matching host workspace packages normally.
**The complete backend checkout must match the new head:** the frontend-only
bundle does not include the new CJS window-routing code or native binaries.
3. Materialize the exact private Library file/version in the consumer's own
environment. Verify its archive SHA-256 and every dist file with the supplied
inventory/verification script. Producer-local paths are not portable.
4. Use those verified production assets as a whole `dist/` in the matching
checkout, with the ordinary Electron entrypoint, no Vite environment and
normal sandbox/helper settings. This is native **unpackaged production-
renderer QA**, not packaged-binary certification. Process-loss causality
remains unclassified; no native build/header workaround is supplied.
5. Recreate only the synthetic provider/Note/sample setup. Verify Default Allow
remains functional; then set the plugin operation to Ask in the active main
or standalone Settings window. Keep the selected receiver visible, focused,
ready and unlocked; opening Ask must not force focus back to main.
6. Record visible readable Ask and native-view yielding. Check cancellation and
acceptance as separate explicit operations: cancel must send no model request;
accept must authorize only the current bounded operation. Complete the
content-read Allow/Ask/Deny matrix and lifecycle invalidation cases. Do not
treat the earlier zero-request timeout as an Ask pass.
7. Record exact head, archive/sample hashes, request counters, prompt ownership,
screenshots/video and any unrun cases. Report a model-selector failure
separately rather than folding its other owner's repair into this candidate.
Hosting/distribution/deployment and remaining DB/terminal acceptance gates stay
parent-coordinated. No main merge, Ready transition or release is part of this
handoff.
@@ -0,0 +1,197 @@
[
{
"name": "assistant",
"id": "com.netcatty.assistant",
"version": "0.1.0",
"fileCount": 6,
"bytes": 17214,
"sha256": "7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274",
"contentSha256": "c3e31e9613422bf9a05ccaa5b6f234304208f1a8298b1c1ee19262ba88af6cd0",
"features": {
"required": [
"ai.model-invocation",
"context.selected-read"
]
},
"permissions": {
"required": [
"commands",
"views"
],
"optional": [
"ai.invoke",
"context.selected.list",
"context.selected.read"
]
},
"package": "assistant.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "c7d784d5c3bd2feb463afd58eae3a9594615395b168174cb8a3d0677584ae395",
"changedEntriesFromFrozen677": [
"README.md",
"panel.css",
"panel.js"
],
"previous7856Sha256": "7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "89beeb93749c751f255beb6d0e0f95d23bdd9a7b",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef",
"previous020Sha256": "7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274",
"changedEntriesFrom020": []
},
{
"name": "database-owned",
"id": "com.netcatty.database-minimal",
"version": "0.1.0",
"fileCount": 5,
"bytes": 11660,
"sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"contentSha256": "4d628c41c7a231e31cd56dacb822acaaa37f61e1e98b285b0086a4f783be199d",
"features": {
"required": [
"network.byte-streams"
]
},
"permissions": {
"required": [
"commands",
"views"
],
"optional": [
{
"permission": "network.stream",
"resources": [
"tcp://10.77.0.20:3306"
],
"reason": "Connect only to the prepared disposable fixture."
}
]
},
"package": "database-owned.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"changedEntriesFromFrozen677": [],
"previous7856Sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "89beeb93749c751f255beb6d0e0f95d23bdd9a7b",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef",
"previous020Sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"changedEntriesFrom020": []
},
{
"name": "database-rfam-readonly",
"id": "com.netcatty.database-rfam-readonly",
"version": "0.1.0",
"fileCount": 5,
"bytes": 11003,
"sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"contentSha256": "f542ca7b8e821d684cf7f71f0930458bd3ad97bc94bf654c88b0f353111e9162",
"features": {
"required": [
"network.byte-streams"
]
},
"permissions": {
"required": [
"commands",
"views"
],
"optional": [
{
"permission": "network.stream",
"resources": [
"tcp://mysql-rfam-public.ebi.ac.uk:4497"
],
"reason": "Run the fixed public Rfam acceptance query only after explicit authorization."
}
]
},
"package": "database-rfam-readonly.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"changedEntriesFromFrozen677": [],
"previous7856Sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "89beeb93749c751f255beb6d0e0f95d23bdd9a7b",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef",
"previous020Sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"changedEntriesFrom020": []
},
{
"name": "host-actions",
"id": "com.netcatty.host-actions",
"version": "0.1.0",
"fileCount": 3,
"bytes": 4633,
"sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"contentSha256": "d6f8bf3ae9dc417ea838f673966f2e1075fc8f9ef1d939ca85b476b1bb007e6c",
"features": {
"required": [
"vault.host-actions",
"commands.interactive"
]
},
"permissions": {
"required": [
"commands",
"menus"
],
"optional": [
"vault.metadata",
"vault.write",
"ui.interact"
]
},
"package": "host-actions.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"changedEntriesFromFrozen677": [],
"previous7856Sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "89beeb93749c751f255beb6d0e0f95d23bdd9a7b",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef",
"previous020Sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"changedEntriesFrom020": []
},
{
"name": "terminal-selection-draft",
"id": "com.netcatty.terminal-selection-draft",
"version": "0.1.0",
"fileCount": 2,
"bytes": 2954,
"sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"contentSha256": "99797d8679f34b96580076f922cbec067e511adc0f4ccf396ed129206acb6c4c",
"features": {
"required": [
"terminal.selection-sharing",
"terminal.input-drafts",
"commands.interactive"
]
},
"permissions": {
"required": [
"commands",
"menus"
],
"optional": [
"terminal.selection.read",
"terminal.input.propose"
]
},
"package": "terminal-selection-draft.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"changedEntriesFromFrozen677": [],
"previous7856Sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "89beeb93749c751f255beb6d0e0f95d23bdd9a7b",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef",
"previous020Sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"changedEntriesFrom020": []
}
]
+13 -3
View File
@@ -1,5 +1,10 @@
# Test the selected Note assistant on an isolated desktop
For the permission-policy/AI acceptance candidate, first use
[its integration record](policy-ai-integration.md) and exact package manifest.
The older permission-dialog sequence below is historical baseline evidence;
apply the current Allow/Ask/Deny semantics when testing the new candidate.
This recipe tests a sandbox plugin against a deterministic loopback provider.
The provider does not run a model or contact a paid service. The profile contains
only synthetic data. The parent owns native screenshots and video on the working
@@ -29,9 +34,9 @@ browser runtime entry. It has no Node entry, networking, filesystem, secrets,
storage, terminal, or command-execution permission. Its `commands` permission
registers its own view callbacks. It cannot execute terminal commands.
The six-file artifact at this checkpoint has SHA-256
`c7d784d5c3bd2feb463afd58eae3a9594615395b168174cb8a3d0677584ae395`.
This replaces the earlier `c0f73369...` artifact after the selected-Note expiry
recovery repair.
`7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274`.
This replaces the earlier `c7d784d5...` artifact with the sample-only appearance
update. The host provider cold-start correction remains a separate app change.
## Start the deterministic fixture
@@ -119,6 +124,11 @@ Synthetic retry plan: add a retry button and show a connection status label.
in the dropdown, and click Send yourself. Deny the fresh content permission
once and cancel text review once before allowing a successful fixture run.
The draft must survive all steps, and no request may be silently retried.
14. With the sample idle, switch the host between light and dark and change its
accent. The page, controls, muted surfaces, text, focus ring, and Send button
must follow the existing view environment tokens without model requests or
new permission prompts. Capture both appearances on the same host window.
This check does not change or bypass the separately owned permission policy.
The expiry regression in `scripts/plugin-assistant-panel.test.cjs` controls the
panel and actual host service/selected-context authority clocks and advances past
+58
View File
@@ -0,0 +1,58 @@
# Plugin author presentation
The marketplace displays the catalog's author next to a small avatar. Installed
views reuse the author row. Missing, loading, unavailable, or invalid imagery
uses a bundled placeholder. An avatar is presentation metadata, not proof of an
authenticated GitHub publisher.
The registry binds an image to its reviewed displayed-author subject. Repository
ownership alone does not establish that subject. The current first-party author
is the Netcatty project, not an assumed personal GitHub identity. Until an image
pin is reviewed, its avatar remains null.
## Avatar delivery
Delivery v2 extends the reserved `avatar` field to null or
`{path, sha256, size}`. The path is exactly `/assets/<sha256>.png` or `.webp`.
Size is a positive integer no greater than 256KiB. The delivery digest and existing
id/version/repository/commit tuple bind the reference. Catalog and index identity
fields do not change. Source-only delivery v1 remains supported.
Only the main process fetches the selected source's same-origin asset. Existing
URL, credential, redirect, timeout, byte-count, and SHA-256 checks apply. The host
rechecks the source and selection after asynchronous work. The existing isolated
icon rasterizer validates and converts PNG or WebP to a bounded PNG data URI,
using its current queue, pending-work map, and cache. No renderer URL, arbitrary
file path, GitHub API, or GitHub avatar URL is accepted. Visible rows load lazily.
Installed presentation uses already validated catalog metadata only when source,
version, package digest, and manifest match the active installation. It does not
fetch a catalog just because the installed list opens. Without an exact match,
the declared publisher and placeholder remain visible, without a maintenance
badge. No installed-data migration or persistent identity cache is added.
## Official maintenance
The borderless gold pill means that the Netcatty project maintains the plugin.
It does not certify the plugin's safety or grant permissions. It is separate
from the official marketplace source label.
The main process requires the built-in official source and one of these explicit
first-party ID and repository pairs:
- `com.netcatty.starter`, `binaricat/Netcatty`
- `com.netcatty.hello`, `binaricat/Netcatty`
A local import, a third-party copy, an ID prefix, author text, manifest publisher,
README, or membership in the official marketplace cannot create this badge.
The renderer consumes the host result through the existing trusted-app IPC
boundary. No new plugin permission or plugin RPC is introduced.
## Validation scope
Focused registered tests cover source spoofing, exact installed identity,
hash-bound images, invalid metadata and decoding, redirects, source removal,
selection changes, cache reuse, lazy loading, stale UI cleanup, placeholders,
and borderless light/dark theme classes. These tests do not establish native
layout, actual account identity, live CDN deployment, or successful network access.
Actual app screenshots and native acceptance remain separately scheduled.
+7
View File
@@ -450,6 +450,13 @@ new child to an opened parent directory without a path race.
`readDirectory()` likewise keeps its stable SDK/RPC method but fails closed
unless the main process supplies a native adapter whose inode checks and entry
enumeration are bound to the same directory handle.
The host advertises `filesystem.directory-enumeration` only when it supplies that
adapter. Declare the feature as required, or optional and check
`context.enabledFeatures.has(PLUGIN_FILESYSTEM_DIRECTORY_ENUMERATION_FEATURE)`.
The default host supplies no adapter and does not enable this feature. Both the
SDK and direct RPC return `unsupported` before a permission request or path probe.
An enabled feature still requires the declared `filesystem.read` directory
resource and the normal permission, root, symlink and same-handle checks.
Permission names already use the phase-3 enforcement boundaries: clipboard
read/write, terminal metadata/output/input and input/output interception, Vault
Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

+121
View File
@@ -0,0 +1,121 @@
# Plugin foundation landing candidate
Draft #4011 is the single landing vehicle for the accumulated plugin foundation.
Earlier integration records describe frozen evidence, not the current acceptance
status. This candidate preserves their source history through ordinary merges.
The user cancelled the reference-driven row redesign. Installed grid and Settings
quick-toggle layout are restored exactly to b14, while author presentation and all
functional/security corrections remain. Cancelled visual commits stay in history
with attributable reverts; they are not effective changes in the landing tree.
It does not include global Agent/custom Chat #4006/#4012, model-picker #4002,
or terminal diagnostic #3999. No older source PR is closed by this preparation.
## Included commits
| Input | Exact input | Ordinary integration |
| --- | --- | --- |
| Prior #4011 | `d40b0d3c25ed00a33679e83be948fd1a5aa10bfa` | Starting point; all inherited contributions retained |
| Current main | `2796d1113a6310fae1779931f242e208a69b95a5` | `db1223d16`; Nginx #4010, macOS appearance #4013, closed-socket MCP reconnect #4016 |
| Author metadata and preserved visual history | `e4eb33856b335fe0b1d302827b1325ddfc23bdde` | `b3895a477`; preserves original avatar/badge, canonical v2 schema, b14 invalidation, visual-worker patch subsequently reverted |
| Directory availability | `a36a906292cbe8033bc19b596dcaf7f853a804c7` | `d035cbea3`; no native adapter or expanded permission |
| Two-profile sync composition | `14ed19d2ed7cd1ecc201c9c910b112e97cc098ff` | `fc37ac48e`; tests only |
| Restore pre-row layout | `7e7b05620ff800ae459d0bf007bbace6aaebbdbc` | Normal revert of e4 row commit; all six layout paths match parent `b14b65679ffd9c617bb0aa1215d8653c53430243` |
| Rejected-install catalog refresh | `50fda91424c915c1497e53a87a210e3943cb1e39` | Separate correction after bounded review; service and mounted-row regression only |
The separately published icon branch first reverted its outline correction
(`530ff0318`), then the e4 row commit (`6e4465f47`). Neither outline correction nor
those isolated reverts are imported here; foundation never included the outline.
The e4 and 1f renderer artifacts are historical pre-cancellation evidence, not
accepted final UI. No further cancelled-design build or screenshot is requested.
The only manual merge conflict was the end of `index.css`. Resolution retains
both the prior host-security theme block and main's window-background-blur block,
with their declarations unchanged. Automatic combinations retain main appearance
wiring alongside plugin settings/theme wiring, all five locales, preload methods,
the host services and SDK exports. No permission, source, endpoint, sandbox or
selected-resource restriction is relaxed. Package and lock inputs are unchanged.
`50fda9142` reuses the same selection-token comparison after an install-triggered
catalog refresh, including an install rejected for a changed/withdrawn selection.
The rejection is preserved; mounted authors no longer retain withdrawn enrichment.
The regression makes no package download or execution. It also preserves the
original synchronous unavailable-source rejection in `list()`: the first aggregate
runtime run caught that b14 changed it into a Promise rejection. The assertion was
not weakened. Corrected aggregate runtime: 711 pass, one native skip, zero failures
or cancellations. The original failed run and fail-before regression are retained.
## Checks and packages
Registered runtime, SDK/contract, Settings and actual connected host entrypoints,
changed-main MCP/appearance/editor regressions, example preparation, code generation,
lint and the normal production renderer build are run on this candidate. Exact
head, commands, counts and CI links are recorded in #4011. Package provenance is
in [the bounded sample manifest](foundation-packages.json): each archive is built
twice and whole-byte compared. Assistant is byte-identical to d40; Host changes
only README wording, with manifest/entrypoint unchanged. Database-owned, Rfam and
terminal archives change only `browser.js` minified bound identifier spelling.
Rebuilding the same sources with d40's generated SDK/contract artifacts reproduces
the exact old archive hashes. Parsing and normalizing lexical bindings yields
identical ASTs for all three bundles; manifests, protocol and permissions do not
change. Preparation does not connect, activate or query.
Local checks at pre-restoration1f: runtime 711 pass/one existing native skip; SDK91; Settings and
connected host/security78; changed-main MCP/appearance/editor71; examples five
pass/one Docker opt-in skip. Contract/capability/Codex generation has no drift;
lint zero errors/seven existing warnings; normal production build36.13s. These
checks do not claim native UI, packaging or encrypted transport acceptance.
Restoration-focused layout/author tests: six pass; changed-file lint and diff
checks clean. Two broader Settings runs each had38pass/one PluginLogSettings
file-entry failure, without a detailed assertion; that file alone passed. Their
cause remains unclassified and both failed runs are retained. No production log
change or baseline attribution is made. Every one of the six layout paths exactly matches b14; fourteen functional
paths (identity/provenance, permissions, directory availability and sync included)
remain byte-identical to1f. The five sample records remain unchanged. Pre-restoration1f exact CI completed:
[test40505644082](https://github.com/binaricat/Netcatty/actions/runs/40505644082)
records15,372pass/50skip/zero failures or cancellations on its successful retry;
[packages40505644200](https://github.com/binaricat/Netcatty/actions/runs/40505644200)
passed all four platforms with release skipped. Its original runner shutdown is
retained. These results do not certify the restored head.
An earlier coding-executor full suite timed out after 15 minutes: 31 failures and
482 cancellations. Seven failures reproduced on unchanged d40; 24 were not probed
on that baseline. They remain unresolved evidence, not assumed baseline failures.
No additional long local full suite is used to conceal them. Clean-run exact-head
CI is a separate aggregate check and does not diagnose that historical run.
## Acceptance and landing order
1. Foundation: keep #4011 Draft until integrated CI/review and affected native UI
acceptance settle. d40 Settings, Host/Vault policy, terminal A/B selection and
inert multiline draft isolation, and native chat split/drag ownership passes
are historical evidence at their stated heads. They do not certify this new
current-main merge tree. The e4/07b reference-driven row design is cancelled;
stop its native visual work. Restored layout retains author/avatar presentation.
Avatar/catalog behavior and the final install-refresh correction still require
their scoped review/acceptance; cancellation does not erase functional gates.
2. Marketplace distribution: retain static-source identity and v2 delivery checks,
but track reviewed registry data, actual hosting/CDN and install/update/source
replacement/withdrawal acceptance separately. Current live source-only viewing
is not installation or deployment acceptance. Never weaken admitted-source or
destination guards to manufacture a pass.
3. Global Agent: #4006/#4012 remain a separate later increment, with their own
scope, review, CI and actual sample smoke. #4002 is also separate.
Historical integration vehicles #3967/#3989/#3993/#3997/#4001/#4004 are superseded
as landing vehicles, not discarded contributions. Their ancestors and native
receipts stay available. Unique source PRs remain intact; no premature closures.
Directory enumeration is intentionally unavailable in the default production
composition until a same-handle adapter exists. The advertised feature now tells
SDK callers the truth; filesystem permission alone does not enable it. The new
sync composition test proves local collect/apply/hydrate with real databases, not
encrypted cloud transport or native cloud-account sync. A native compatibility
transition needs two properly versioned builds; two 0.0.0 checkouts do not qualify.
Public database acceptance remains blocked by the retained TCP refusal before
protocol payload; the separately owned local fixture is pending. Source-policy,
compatibility and database gates must be explicitly reconciled by the parent,
not silently removed from requirements. Nested log-dialog overlap has source
coverage but no normal native route in the tested UI. This is code-readiness work,
not a claim that deployment, every original requirement or the whole project is
complete. No main merge, Ready transition, release or live metadata publication.
@@ -0,0 +1,177 @@
[
{
"name": "assistant",
"id": "com.netcatty.assistant",
"version": "0.1.0",
"sha256": "7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274",
"bytes": 17214,
"fileCount": 6,
"permissions": {
"required": [
"commands",
"views"
],
"optional": [
"ai.invoke",
"context.selected.list",
"context.selected.read"
]
},
"features": {
"required": [
"ai.model-invocation",
"context.selected-read"
]
},
"repeatIdentical": true,
"previousD40Sha256": "7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274",
"preparedOnly": true,
"noConnectionOrActivation": true,
"changedEntriesFromD40": [],
"delta": "Archive byte-identical."
},
{
"name": "database-owned",
"id": "com.netcatty.database-minimal",
"version": "0.1.0",
"sha256": "3c67f529cd5d2843dbf74a62d237b7b7d50d24a466ade85cce76b3adfff919a2",
"bytes": 11660,
"fileCount": 5,
"permissions": {
"required": [
"commands",
"views"
],
"optional": [
{
"permission": "network.stream",
"resources": [
"tcp://10.77.0.20:3306"
],
"reason": "Connect only to the prepared disposable fixture."
}
]
},
"features": {
"required": [
"network.byte-streams"
]
},
"repeatIdentical": true,
"previousD40Sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"preparedOnly": true,
"noConnectionOrActivation": true,
"changedEntriesFromD40": [
"browser.js"
],
"delta": "Generated SDK export changes alter only minified bound identifier spelling; scope-aware normalized AST is identical.",
"oldGeneratedRebuildSha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"boundIdentifierAlphaEquivalent": true
},
{
"name": "database-rfam-readonly",
"id": "com.netcatty.database-rfam-readonly",
"version": "0.1.0",
"sha256": "554407c067ced0a6634599b7eccc7c6dbb4f2ff7c523d0bacbbbd4fb78c04612",
"bytes": 11003,
"fileCount": 5,
"permissions": {
"required": [
"commands",
"views"
],
"optional": [
{
"permission": "network.stream",
"resources": [
"tcp://mysql-rfam-public.ebi.ac.uk:4497"
],
"reason": "Run the fixed public Rfam acceptance query only after explicit authorization."
}
]
},
"features": {
"required": [
"network.byte-streams"
]
},
"repeatIdentical": true,
"previousD40Sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"preparedOnly": true,
"noConnectionOrActivation": true,
"changedEntriesFromD40": [
"browser.js"
],
"delta": "Generated SDK export changes alter only minified bound identifier spelling; scope-aware normalized AST is identical.",
"oldGeneratedRebuildSha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"boundIdentifierAlphaEquivalent": true
},
{
"name": "host-actions",
"id": "com.netcatty.host-actions",
"version": "0.1.0",
"sha256": "9713f001449b0c749f518d42f013fa72ead6dd43f8e7ddd7843cc6ecc03027f9",
"bytes": 4789,
"fileCount": 3,
"permissions": {
"required": [
"commands",
"menus"
],
"optional": [
"vault.metadata",
"vault.write",
"ui.interact"
]
},
"features": {
"required": [
"vault.host-actions",
"commands.interactive"
]
},
"repeatIdentical": true,
"previousD40Sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"preparedOnly": true,
"noConnectionOrActivation": true,
"changedEntriesFromD40": [
"README.md"
],
"delta": "README wording follows permission policy. Manifest and browser entrypoint are byte-identical."
},
{
"name": "terminal-selection-draft",
"id": "com.netcatty.terminal-selection-draft",
"version": "0.1.0",
"sha256": "aaadd8687b1af1d6e1f9a56c52760ac0d19e7ed4e8212fb7c8775ed052ed74f1",
"bytes": 2954,
"fileCount": 2,
"permissions": {
"required": [
"commands",
"menus"
],
"optional": [
"terminal.selection.read",
"terminal.input.propose"
]
},
"features": {
"required": [
"terminal.selection-sharing",
"terminal.input-drafts",
"commands.interactive"
]
},
"repeatIdentical": true,
"previousD40Sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"preparedOnly": true,
"noConnectionOrActivation": true,
"changedEntriesFromD40": [
"browser.js"
],
"delta": "Generated SDK export changes alter only minified bound identifier spelling; scope-aware normalized AST is identical.",
"oldGeneratedRebuildSha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"boundIdentifierAlphaEquivalent": true
}
]
@@ -1,8 +1,8 @@
# Host and Vault actions
Feature: `vault.host-actions`. The SDK registers three methods under
`context.vault`. Netcatty owns the picker, field-diff review, and connection
confirmation. Plugin business logic stays in the offline browser sandbox.
`context.vault`. Netcatty owns the picker, field-diff review, permission routing,
and normal connection dispatch. Plugin business logic stays in the offline browser sandbox.
Base: source integration #3981 at
`4213d8e6726c44e7a479418ece3adf16ea494782`.
@@ -36,10 +36,12 @@ remain behind the typed target reference; its revision is the expected revision.
Group metadata describes the explicitly selected current member handles. The
grant never expands when another host joins a group.
Selection grants metadata access only. Each draft save and each connection
requires its own host-owned confirmation. A connection confirmation displays the
saved target and whether saved scripts can run. It does not grant terminal input,
terminal output, or session access.
Selection shares the chosen metadata only. Later edit and connection requests
follow the plugin's Allow, Ask, or Deny settings. Draft saves retain the mandatory
host editor. Connection Ask displays the saved target and whether saved scripts
can run; Allow can dispatch without that permission-only dialog. Normal SSH
authentication remains unchanged. These actions grant no terminal input, output,
or session access.
All requests are bounded and cancel on runtime stop, source replacement, revoke,
Vault lock, owner window replacement, expiry, or user cancellation. The host
@@ -47,7 +49,7 @@ revalidates authority and expected revision after asynchronous work and before
the Vault write or connection dispatch.
Bounds reuse `HostInteractionLimits`: one pending request per runtime,
eight total, ten per minute, a 60-second confirmation deadline, and a 64-KiB
eight total, ten per minute, a 60-second host-interaction deadline, and a 64-KiB
request ceiling. Selection adds a maximum of 50 current hosts. Titles use the
existing 128-character single-line limit. Draft field lengths use
`ImporterHostDraft`. Unknown properties are rejected by the shared schema.
@@ -86,15 +88,16 @@ It revalidates after asynchronous authentication. AI selected-context handles ar
text-disclosure handles and cannot target these actions.
The permission engine gates selection with `vault.metadata`, drafts with
`vault.write`, and connection requests with `ui.interact`. Every save or connection
also requires a separate host-owned confirmation and a signed one-use action
claim. A stored permission grant cannot bypass this review.
`vault.write`, and connection requests with `ui.interact`. Each committed save or
connection uses a signed one-use action claim. Permission settings control the
permission-only prompt; an Allow setting does not bypass the draft editor or
normal SSH authentication.
After review, the renderer prepares the existing transaction or connection
request. It claims action authority after the final asynchronous preparation,
immediately before persistence or dispatch. This claim is the action's commit
point. Completion only acknowledges the committed action. Automation changes
during connection review require fresh confirmation.
during an Ask connection review require fresh confirmation.
The connection label uses the same `resolveEffectiveTerminalProtocol` helper as
the launcher, including Mosh/ET flags and implicit localhost shells. Local
execution displays an explicit on-device shell notice and omits the remote SSH
+13 -7
View File
@@ -3,8 +3,10 @@
The plugin manager has Installed, Official marketplace and Third-party marketplace
pages. Listing a plugin in the official market does not certify it or establish
that Netcatty maintains it. Remote manifests, publisher names, source names and
README content cannot create a host-issued official badge. This revision does not
issue maintainer badges. README text and images remain author content.
README content cannot create a host-issued official badge. The separate gold
maintainer badge requires the built-in official source and an exact host-curated
first-party ID/repository pair. It describes maintenance, not safety certification.
README text and images remain author content.
## Add a source
@@ -33,20 +35,24 @@ manifest, compatibility, browser-runtime admission and archive validation still
apply. Third-party source consent is not permission consent.
Delivery v1 is unchanged and source-only. Delivery **v2** has the same fields and
strict schema as v1, with `schemaVersion: 2` and one extension: each plugin's
`artifact` can be null or a package reference:
strict schema as v1, with `schemaVersion: 2`. Each plugin's `artifact` can be null
or a package reference:
```json
{"path":"/assets/<64-lowercase-hex-sha256>.ncpkg","sha256":"<same-sha256>","size":12345}
```
Packages are at most 32 MiB. The catalog entry must contain
V2 delivery packages are at most 16 MiB. The catalog entry must contain
`artifact: {url: "https://plugins.example.com/assets/<same-sha256>.ncpkg", sha256}`.
The index's current, non-withdrawn version must exactly equal the catalog entry
and use `distribution: "release"`. Source-only entries retain null delivery
artifacts and `distribution: "source-only"`. Avatars remain null; remote README
embeds are not loaded. README and PNG/WebP references retain the v1 bounds.
artifacts and `distribution: "source-only"`. The reserved `avatar` can also be
null or a same-origin `/assets/<sha256>.png` or `.webp` reference, with a positive
size no greater than 256KiB. The host verifies and rasterizes its bytes through
the existing image infrastructure. Missing or invalid imagery uses a placeholder.
Remote README embeds are not loaded. README and PNG/WebP references retain the v1 bounds.
Existing official bootstrap entries are not changed or made installable.
See [author presentation](author-identity.md) for subject and maintenance authority.
Before every install, refresh and validate the entire snapshot again. A changed
selection, withdrawal, unavailable source, altered hash or size prevents install;
@@ -0,0 +1,286 @@
# Plugin Allow / Ask / Deny handoff
This change is stacked on frozen PR #3997 at
`677aac33b1eec9dbd4a367417a49c964cdea63e7`. Its source checkout and native QA
checkout were not changed. No merge, release, live database connection, native
activation or real user configuration change was performed here.
## Behavior and storage
- Declared supported capabilities default to Allow, with no installation
checklist or required-permission preflight dialogs.
- Settings uses existing `SettingRow` and Select components. It shows each
declaration's resource scope and effective Allow / Ask / Deny mode.
- Policies use `plugin_host_preferences`, keyed by host source owner and
capability. They survive restart and updates within the same source, including
reintroduced capabilities. New capabilities default to Allow. Existing grants
still use the original package/declaration principal; they were not widened.
- Explicit source reset clears that source's policies and private plugin data.
Another source receives independent defaults. Unrelated Vault, host, settings
and user data are preserved. No plugin-policy migration was added.
- Policy edits clear grants, cancel pending/in-flight work and invalidate
handles. Settings edits require the exact host-issued source/version/policy
revision, so stale controls cannot change a replacement source or override a
newer Deny.
- Ask decisions use the existing in-app Dialog/Button components, reached only
through trusted managed-app-window preload IPC. A one-use response token binds the
request; close, cancel, lock, blur/hide, reload, renderer crash and shutdown
invalidate it. Plugin DOM clicks confer no host gesture authority.
- Host selection, model/context selection and draft editing remain workflows.
Ask is integrated into their existing host UI where applicable. Allow removes
permission-only sharing and connection confirmations while retaining exact
target validation and action tokens. Terminal drafts never send PTY input.
- AI start combines model permission and exact selected-content scopes into one
Ask decision. Its receipt cannot cross an RPC operation. Broker-bound stream
reads/stop/close do not ask per chunk. Same-origin network redirects reuse the
current operation decision; different origins still require declared bounds
and their own authorization.
- Policy edits, decisions, use/revoke and operation outcomes remain auditable.
Audit records omit note/terminal bodies, model payloads, credentials and tokens.
Optional local log persistence remains user-controlled.
See [the security boundary](security-and-permissions.md) for the storage and
update rules. The separate AI cold-start provider-sync fix is not included;
`configuredModel.ts`, `trustedHostRuntime.ts` and `usePluginAIContextHost.ts`
were left untouched for parent integration.
## Review corrections after the initial 643e71b checkpoint
The initial commit and its screenshots remain in history. Registered regressions
reproduce three concrete issues on that exact tree and pass with these repairs:
- Selected-summary Ask now delegates its decision to the existing host chooser.
The first and only interaction is target selection; Allow uses that same
necessary chooser, while Deny opens none and releases no summaries.
- The registry creates a fresh host-only operation identity for every RPC.
Internal model contexts retain it when replacing a cancellation signal, so a
combined model/content Ask receipt survives that derivation. Receipts also
bind plugin, runtime, source, principal and policy revision, and cannot cross
operations. Current declaration, policy and selection checks still run.
- Changing the privileged development-only `runtime.advanced` policy to Ask or
Deny disables/stops the activation through the existing manager mutation queue
before the policy IPC completes. A source-owner check inside that queue prevents
an old source's teardown from disabling a replacement. Browser sandbox policy
and development admission guards remain unchanged.
Ask now presents the current host-selected model label and Note title/scope.
Exact versions remain bound internally. Labels come from the checked broker chat
and owned selected summaries;
plugins cannot supply operation identities or display fields through RPC params.
Opaque selected handles remain internal, and display metadata is not added to
audit records. The chooser copy reflects Allow / Ask / Deny without claiming a
mandatory second text review. Spanish keys preserve the existing locale parity
contract. The quota and expiry regression now uses independent requests to avoid
its former 20ms timer race.
Updated component previews use a realistic opaque selected handle internally:
| Light Ask | Dark Ask |
| --- | --- |
| ![Model and Note labels in light Ask](evidence/permission-modes/plugin-permission-model-ask-light.png) | ![Model and Note labels in dark Ask](evidence/permission-modes/plugin-permission-model-ask-dark.png) |
These remain synthetic Chromium component previews, not native QA or a recording.
No Library item was created. The original four screenshots below are retained as
initial-checkpoint evidence.
## Latest checks and remaining environment blockers
- The native candidate `2433cf0130d1c3274c56c39e5765349c2945de01` retains the
same idle logging-row marker as `89beeb9` (source blob
`4dd5a7cea4ae5a6addc5db5c162038d8fa44075c`). Actual Settings landing plus the
existing observer reproduces native-child suppression with no dialog open.
This source defect is separate from the worker's earlier GPU exit and does
not alone establish the cause of the recorded blank native body.
- The scoped correction removes only the idle-row marker. Actual logging and
Ask dialogs remain marked. A real nested verbose confirmation test also
reproduced premature restoration when its parent became accessibility-hidden;
that confirmation now opts into the existing marker on its own dialog content.
The observer, window trust, permissions and data access are unchanged. The real
landing regression verifies idle visible, each security dialog hidden, and
restored on dismissal. Focused group **six passed**; Settings boundary group
**36 passed**. Both pre-fix failures are retained outside the source tree.
Production build and full lint pass (zero lint errors/seven existing warnings).
Full TypeScript remains baseline-equivalent at 774 diagnostics with zero
added/removed. Exact-head CI and the next frozen native recheck are separate
gates; neither is inferred from these local tests.
- QA-only **Settings Ask QA 0.1.0** uses its supported `location: settings` entry
and public SDK to read only its synthetic own setting after an explicit click.
Exact archive SHA-256:
`9502a58a4804862e4b13de9fc0d1baf6ad8c2bc681c08b5c0664b552ef0aafc4`.
Its HTML/CSS/JS each return 200 with proper MIME/CSP through the actual plugin
protocol. It contains no raw IPC/test hook or external access. No GUI or running
app was changed by this correction; parent will build a new frozen candidate
after current cleanup and repeat native Settings acceptance.
- A registered regression reproduces `Plugin permission decision provider failed`
on exact `79a9bd6` when a Settings-owned view activates a real `settings.get`
API configured Ask while main is unfocused. The follow-up uses the existing
managed-window registry (including Settings), per-renderer readiness and the
same in-app component. It does not focus main or expand plugin-frame trust.
The actual Settings factory, installed package/SDK activation, view command
IPC and permission IPC now pass main/Settings/foreign/background, subframe,
independent readiness and hide/close/stale-token checks. Native Electron
objects are represented in this regression; this is not native GUI acceptance.
Focused boundary group: **67 passed**; renderer/native-view visibility group:
**three passed**; runtime aggregate: **695 passed/one native skip**. The initial
renderer assertion incorrectly expected a view to reappear while the separate
permission-settings security surface remained visible; the corrected test
checks both overlapping surfaces and restoration after both close.
Production build passed (69 seconds). Full lint passes with the same seven
warnings after moving a leftover screenshot harness out of the source tree;
its initial lint failure is retained. TypeScript remains baseline-equivalent
at 774 diagnostics, with zero added/removed after path normalization.
- Subsequent exact `da4e809` workflows **40444934631** (tests) and
**40444934738** (packages) passed. The full suite reports **15,392 tests:
15,342 passed, 50 skipped, zero failures/cancellations**. The runtime group
reports 694 passed/one native skip, and package settings 35 passed. All four
platform package jobs passed; release jobs were skipped. This does not replace
manual plugin native acceptance or erase the local failures below.
- A focused wording follow-up removes the implication of mandatory prompts from
the package detail's sensitive/unbounded scope text in English, Spanish,
Russian and both Chinese locales. The Russian declaration note now also
reflects default Allow instead of pre-activation permission ceremonies.
The complete local CI boundary command passes after this copy change:
contract generation is current, runtime 694 passed/one skip, examples five
passed/one skip, and package settings 35 passed. Locale parity six passed;
changed-file lint has no errors/warnings.
- Exact `2eee561` packaging workflow **40443396402 passed** on Linux x64,
Linux arm64, macOS and Windows; release jobs were skipped. Its first Linux
test job **121988800130** stopped on a runner shutdown signal, with no observed
assertion failure. Parent requested one retry. Fresh job **121992430185**
passed the 694-test runtime aggregate (one native skip) and failed two
package-detail assertions still expecting the superseded "not a grant" copy.
The full suite was skipped. Those assertions now verify default Allow,
adjustable Ask/Deny and retained host/resource validation; development-runtime
disclosure and HTML escaping remain checked. No production behavior changes
accompany this test correction. Original interruption/failure logs are kept.
- Registered runtime recheck: **695 tests, 694 passed, zero failed/cancelled, one
native skip**. Separate final registered receipt/authority group: **21 passed**.
- Serial mounted renderer/Host/selected-summary/panel/locale group: **35 passed**.
A preceding concurrent run timed out during build/lint load; its failure log is
retained. No timeout result is reclassified as a pass.
- Advanced-runtime manager/source lifecycle and AI group: **35 passed**.
Receipt/declaration group: **32 passed**. Final engine/registry/manager/host
boundary group: **71 passed**. Final registered AI audit/receipt check: **one
passed**; an earlier 15-second timeout while the preview was active is retained.
The serial rerun passed in five seconds. Contract/SDK/CLI: **91 passed**.
- Final production build passed in **45 seconds**. Full lint has zero errors/seven
existing warnings. Full TypeScript remains **774 diagnostics**, identical to
frozen 677 after path normalization, with zero added/removed diagnostics.
- The normal official Electron installer succeeded using its documented proxy
support and a task-local cache. Exact **42.11.12** executes in Node mode; no
shared libraries are missing. This is not native GUI acceptance.
- Exact-header setup via the installed node-gyp 12.4.0 and the unchanged rebuild
tool's official URL failed. The proxy returns **403 Forbidden** for
`https://www.electronjs.org/headers/v42.11.12/node-v42.11.12-headers.tar.gz`.
That download stopped; no mirror, alternate host, checksum bypass, dependency
shim, native-rebuild skip, HOME change or sandbox change was used. Normal
postinstall/native rebuild and desktop packaging remain incomplete.
- A private task-local `TMPDIR` uses Netcatty's existing safe-temp resolution to
its normal `Netcatty` subdirectory; HOME remains unchanged. This fixes the
earlier fallback-to-unwritable-home prerequisite without changing app code.
- A **diagnostic full-suite run on the evolving worktree**, after those environment
repairs, reported **15,059 tests: 14,922 passed, 92 failed, two cancelled, 43
skipped**. A stuck FIDO child was terminated after its timeout; this is not a
successful completed exact-head aggregate. Frozen-baseline focused runs
reproduce its FIDO timeout and **28 failures** across native imports, Cursor
fixtures and repository postinstall patch checks, plus the earlier six
Markdown comparison assertions. Other failures remain unclassified. The
permission locale parity and obsolete forced-review expectations found by that
run were corrected and pass focused checks. Original failed/incomplete runs
below are preserved.
The independent AI cold-start production files remain untouched. This branch
updates only policy expectations in `components/PluginAIContextHost.test.tsx`;
parent integration must retain the AI owner's actual-main-allowlist and provider
sync assertions when merging that test file.
## Local evidence
These are local code/test results, not native acceptance:
| Check | Result |
| --- | --- |
| Registered runtime aggregate, concurrency 2 | 693 tests: 691 passed, one failed, one native skip; no cancellations. Sole failure imports the missing Electron binary on real worker reconnect. |
| Engine, policy matrix, trusted prompt and policy IPC group | 79 passed; subsequent shutdown guard test: 9 passed. |
| Mounted in-app permission controls and Host/terminal workflows | 22 passed. Includes Host Allow/Ask/Deny, policy change during save preparation, exact targets and stale replies. |
| Registered AI/context + policy group | 7 passed, including normal Allow, combined Ask, Deny and revocation. |
| Source/version/revision edit guards and registered byte-stream group | 47 passed. |
| Contract/SDK/CLI suite | 91 passed. Four prepared sample archives validate. |
| Lint | Zero errors, seven existing warnings. |
| Production build | Passed; final `pack:dir` build also passed in 76 seconds. |
| Contract/capability/Codex generation | Regenerated/checks clean; no capability-tool diff. |
| Full TypeScript check | Frozen baseline and implementation each have 774 diagnostics; zero added/removed after normalizing worktree paths. |
| Full `npm test` | Incomplete: stopped after three unchanged bridge child processes remained pending. Reported 9,891 tests, 9,359 passed, 40 failed, 478 cancelled, 14 skipped. This is not a passing aggregate. |
| Desktop `pack:dir` | Unpassed: native rebuild attempts `/home/agent/.electron-gyp`, outside this workspace's writable roots. Earlier pinned Electron installation failed with `fetch failed`. No shim, alternate runtime or sandbox change was used. |
Frozen-baseline focused runs reproduce the two large-history SFTP recovery
failures, six Markdown comparison failures, and missing-Electron adapter/serial
failures observed in the broad run. Other broad-run failures remain unclassified;
unchanged code alone does not prove a baseline failure. One earlier runtime
aggregate hit the existing 15-second byte-stream fixture timeout during concurrent
builds; its focused run and the final aggregate above pass that case.
Logs and archives are in `/workspace/permission-evidence/` in this execution
environment. The final task report identifies any remaining blockers and checks.
Exact-head CI and native acceptance remain pending parent coordination.
## Component screenshots
Chromium rendered the actual React components with built-in light/dark tokens
and synthetic host bridge data. These images demonstrate layout and state only;
they do not certify Electron behavior.
| Controls | Ask |
| --- | --- |
| ![Light controls](evidence/permission-modes/plugin-permission-controls-light.png) | ![Light Ask](evidence/permission-modes/plugin-permission-ask-light.png) |
| ![Dark controls](evidence/permission-modes/plugin-permission-controls-dark.png) | ![Dark Ask](evidence/permission-modes/plugin-permission-ask-dark.png) |
## Prepared sample packages
All packages were built locally; none was activated in a native app. No owned or
public database service was contacted. The owned database package is scoped to
the previously specified disposable fixture endpoint `tcp://10.77.0.20:3306`.
| Archive | SHA-256 |
| --- | --- |
| assistant.ncpkg | `c7d784d5c3bd2feb463afd58eae3a9594615395b168174cb8a3d0677584ae395` |
| host-actions.ncpkg | `cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2` |
| terminal-selection-draft.ncpkg | `4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e` |
| database-owned.ncpkg | `f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874` |
Reproduction uses the unchanged sample build tools:
```sh
node examples/plugins/assistant/build.mjs
node packages/plugin-cli/dist/cli.js pack examples/plugins/assistant/.package --out /tmp/assistant.ncpkg
node packages/plugin-cli/dist/cli.js pack examples/plugins/host-actions --out /tmp/host-actions.ncpkg
node examples/plugins/terminal-selection-draft/prepare.mjs /tmp/terminal-selection-draft.ncpkg
node examples/plugins/database-minimal/prepare.mjs tcp://10.77.0.20:3306 /tmp/database-owned.ncpkg
```
## Parent-serialized native recheck
1. Use a fresh isolated app profile and the exact next integrated head. Import and
enable a sample: no installation permission ceremony should appear.
2. In Allow, select hosts in the host chooser, create/edit via the normal draft
editor, and connect using a current selected reference without a separate
plugin confirmation. Ordinary SSH authentication and host-key checks remain.
3. Select a Note/context and model, start and read a turn in Allow. Then switch
AI/content to Ask: one scoped decision covers the turn and exact references,
with no per-chunk or second content-sharing dialog.
4. Check terminal Allow sharing and the editable inert draft; Ask shows one share
preview; Deny releases no selection and cannot reopen old handles.
5. Check network Allow/Ask/Deny at the declared endpoint. Preserve all endpoint,
DNS, redirect, private-network and control-plane rejection checks.
6. Flip policy while a chooser, draft, model read or network operation awaits.
Old results/tokens must fail. Switch back to Allow and start a fresh operation.
7. Restart/update the same source with an explicit Deny; it must remain Deny.
Check distinct plugins and sources, stale settings edits and explicit source
reset. Review bounded audit events and optional local logging for redaction.
8. Open a plugin view from standalone Settings and exercise an Ask-gated API
during activation and from its own view command. Ask must be reachable in
Settings without focusing main or losing the view. Close/hide/reload that
window, switch to an unrelated window, and try a stale response: old authority
must be cancelled, with no background-window fallback or plugin-frame reply.
No merge, release or native acceptance is authorized by this handoff.
@@ -0,0 +1,189 @@
# Permission-policy and AI acceptance candidate
This records frozen 020 and its predecessor evidence. For the later managed-
window Ask correction, use [the isolated Ask integration record](ask-routing-integration.md).
020 native Default Allow/Stop/Deny/restore/themes passed; Ask had no visible
dialog and timed out with zero new model requests. Ask acceptance/cancel and
the content-read matrix remain unrun until that new candidate is checked.
Use the dedicated `integration/plugin-policy-ai-acceptance` branch. Its Draft PR
records the exact published head and aggregate CI. Frozen #3997 at
`677aac33b1eec9dbd4a367417a49c964cdea63e7` remains the historical native baseline;
neither that branch nor main is changed by this integration.
This is a candidate for parent-coordinated acceptance. It is not a claim of
completed native acceptance, deployment readiness or permission activation.
## Preserved inputs
| Input | Exact checkpoint | Integration |
| --- | --- | --- |
| Frozen integration | `677aac33b1eec9dbd4a367417a49c964cdea63e7` | Starting point; includes stream/source/Host/settings and prior terminal history |
| Permission policy #4000 | `79a9bd6df1c17fd8a5238aba31d7a8b4cda184b9` | Initial ordinary merge `9aa899059` preserved 2eee561; follow-up ordinary merge `cfa13680e` preserves the authoritative scope/sensitivity copy and tests |
| AI #3986 | `d33c0193ccaedc1a10aed9da495f040250121bef` | Ordinary merge `5d2ff1cb8`; cold-start wiring, themed sample and Node 22 warning-drain test correction |
| Terminal production | #3996 `8e7c28fe1bdbcdd76816d33ec926ba8e60eefe64` | Preserve the prior renderer eligibility/publication path; policy-owned interaction changes remain from #4000 |
Diagnostic #3999 and its tests/docs-only `3fdaa357` continuation are not merged.
No terminal runtime fix is required by the fixture-classification finding.
Database protocol and fixed SQL remain solely in the minimal examples.
## Direct integration decisions
The initial merge conflict was `components/PluginAIContextHost.test.tsx`. The
combined test keeps policy's absence of a second native content-sharing review
and AI's actual main allowlist, two-provider synchronization, streamed result,
Stop/lock cleanup and empty SDK-error assertion. The Node 22 warning drain is
retained. The obsolete forced-review cancellation branch is superseded by the
current in-app Ask/cancellation tests; no transport assertion is dropped.
No production file needed a manual conflict resolution. Policy production files
remain identical to the policy input; the three AI startup wiring files and
sample assets remain identical to d33c0193. The stream service/router and prior
terminal renderer eligibility/publication files are unchanged from frozen 677.
Integration commit `7d8a354404d68071d0924532ffe74c713ace6cb9` updates two stale
disclosure assertions in `PluginPackageManager.test.tsx` and
`PluginMarketplace.interaction.test.tsx`. They expected the old words
`not a grant`; the new assertions require default Allow, Ask/Deny controls and
retained host validation/resource scope. Existing escaping, advanced-authority,
source and README-failure assertions remain intact. Production copy is unchanged.
The later authoritative 79a9bd6 policy merge overlapped those two tests. Their
final contents are byte-identical to 79a9bd6: all three earlier policy assertions
remain, together with the owner's additional unbounded-resource, sensitivity,
escaping/source-order and advanced-authority checks. No assertion was dropped.
This follow-up imports the owner's five-locale wording changes; it makes no
manual production conflict edit and leaves the shared AI test intact.
## Checks and retained failures
| Local check | Result |
| --- | --- |
| Registered runtime | 695 tests: 694 passed, one native skip, zero failed/cancelled |
| Contract/SDK/CLI | 91 passed |
| Offline examples | Five passed, one explicit Docker opt-in skip |
| Serial mounted AI/permission/selected-summary/Host/provider/panel group at 7856 | 31 passed |
| Final settings, terminal interaction, cold-start host and locale group | 90 passed |
| Contract/capability/Codex generation and drift | Passed |
| Full lint | Zero errors, seven existing warnings |
| Production build | Passed; Vite 35.50 seconds |
| Five sample archives | Validated; repeat builds byte-identical |
The initial settings group records 34 passes and two failures on the stale copy
assertions. That run is retained separately from the corrected 36/36 result.
Policy input [test CI 40443396430](https://github.com/binaricat/Netcatty/actions/runs/40443396430)
first received an explicit runner shutdown. The parent requested one retry;
this integration task did not duplicate it. Retry Linux job `121992430185`
passed registered runtime (694/one skip) and examples (five/one skip), then
failed those same two `not a grant` assertions: settings group 33 passed/two
failed. It did not reach the full suite. The candidate includes the isolated
test correction above; do not relabel the input CI as passing. Both input Windows
jobs and [policy package CI](https://github.com/binaricat/Netcatty/actions/runs/40443396402)
passed. Parent reports the independent policy correction reviews scoped clean,
including both P2s and the three UI findings, with 71 focused/synthetic checks.
The policy owner subsequently corrected these tests in predecessor
`da4e80946d2f3fb48f205aae2a732252b2f51fca`. Its
[test CI](https://github.com/binaricat/Netcatty/actions/runs/40444934631) passed
15,342 cases with 50 skipped and no failures/cancellations, and its
[four-platform package CI](https://github.com/binaricat/Netcatty/actions/runs/40444934738)
passed. The final 79a9bd6 wording head's
[test CI](https://github.com/binaricat/Netcatty/actions/runs/40446529092) passed;
its [package workflow](https://github.com/binaricat/Netcatty/actions/runs/40446529100)
is tracked separately in the Draft PR. No input retry was duplicated here.
Integration predecessor `7856c664c3c2255a21badef2758bb29311b27a01` passed its
[test CI](https://github.com/binaricat/Netcatty/actions/runs/40445809589): 15,344
passed, 50 skipped, zero failed/cancelled, plus both Windows jobs and native
automated checks. Its [four-platform packages](https://github.com/binaricat/Netcatty/actions/runs/40445809590)
also passed. These are retained predecessor results; the new exact head needs
its own aggregate CI.
AI input [test CI](https://github.com/binaricat/Netcatty/actions/runs/40439111241)
and [package CI](https://github.com/binaricat/Netcatty/actions/runs/40439111215)
passed. Parent reports its three isolated changes scoped clean. Its prior 9ca
Node 22 warning-observer failure remains documented in `ai-provider-startup.md`;
the warning drain does not ignore errors or remove the empty-error assertion.
Frozen 677's earlier unexplained MCP assertion remains separate history.
This executor used locked dependencies with install scripts disabled, then the
standard repository dependency patches. The official pinned Electron binary
installed through its documented proxy support and executes in Node mode.
No native-header download, alternate mirror, native shim, HOME change or
sandbox change was used. Normal native postinstall/rebuild, local full-suite
success and local desktop packaging are not claimed. Exact candidate CI is the
aggregate full-suite and platform-packaging verification surface.
## Exact packages and provenance
The machine-readable [package record](policy-ai-packages.json) contains complete
IDs, versions, required features, permission/resource declarations, archive and
content hashes, and frozen-baseline comparisons. All five versions are 0.1.0.
| Sample | SHA-256 | Comparison with frozen 677 |
| --- | --- | --- |
| Assistant | `7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274` | Matches the AI owner's new themed archive; only README.md, panel.css and panel.js differ from 677 |
| Owned database | `f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874` | Byte-identical |
| Rfam | `aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3` | Byte-identical |
| Host actions | `cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2` | Byte-identical |
| Terminal draft | `4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e` | Byte-identical |
After the authoritative 79 follow-up, all five archives were rebuilt twice,
validated and compared byte for byte with the 7856 candidate: all five remain
identical. No sample permission/resource declaration changed. The host's new policy changes
effective authorization behavior; identical package bytes do not certify that
new host behavior. The old Assistant c7d784d5 archive remains historical evidence,
not the themed archive. No handoff archive was activated by this coding executor.
The owner-identical Assistant README retains earlier permission-review wording;
use this candidate's Allow/Ask/Deny procedure below for acceptance. That packaged
copy is a documentation limitation, not a requirement for repeated dialogs.
## Native preparation and remaining gates
Use the exact candidate head from its Draft PR in a separate disposable native
checkout/profile. Keep normal platform sandbox/helper settings. Build and hash:
```sh
npm ci
npm run build
node examples/plugins/assistant/build.mjs
node packages/plugin-cli/dist/cli.js pack examples/plugins/assistant/.package --out /tmp/assistant.ncpkg
node examples/plugins/database-minimal/prepare.mjs tcp://10.77.0.20:3306 /tmp/database-owned.ncpkg
node examples/plugins/database-rfam-readonly/prepare.mjs tcp://mysql-rfam-public.ebi.ac.uk:4497 /tmp/database-rfam-readonly.ncpkg
node packages/plugin-cli/dist/cli.js pack examples/plugins/host-actions --out /tmp/host-actions.ncpkg
node examples/plugins/terminal-selection-draft/prepare.mjs /tmp/terminal-selection-draft.ncpkg
```
Validate each archive with the plugin CLI and compare against the machine record.
The owned DB address is packaging-only. A different approved fixture endpoint
requires a new archive and hash. Preparation does not dial either endpoint.
- Verify default Allow for declared supported capabilities without a mandatory
first-install permission checklist or repeated permission-only dialogs. Verify
per-plugin Ask/Deny, one scoped Ask receipt, readable host-selected labels,
lifecycle invalidation and redacted audit. Preserve necessary target selection
and inert draft editing, exact resources, source isolation and sandboxing.
- Verify the assistant's cold startup through the normal host without opening
the AI sidebar. Native inference on frozen 677 returned unavailable; the
independent startup regression did not establish that native error's cause.
Use only the deterministic synthetic provider and Note recipe, with current
policy semantics. Native success is not claimed before that recheck.
- Frozen 677 Host core passed per parent; old consent recordings describe the
prior policy. They do not certify the new permission implementation.
- Terminal's source-level finding is fixture-sensitive-input fail-closed:
`fixture-A> ` is untrusted; `fixture@owned-A:~$ ` is confirmed shell. Parent
reports corrected-fixture solo/split core passed on unmodified 677. Focus
remained unreliable/unverified, and QA sent one Enter in A during a palette
attempt. Do not claim global zero input or full terminal native acceptance.
Keep the inert draft's no-PTY-dispatch property distinct from that QA action.
Exclude diagnostic instrumentation. Prior-policy results do not certify the
new policy; the next native priority is final-policy and cold-start AI QA.
- Native Rfam's single baseline run failed with sanitized -32014 socket error
before connect resolved. Auth/SELECT were not reached; transport causality and
auth/TLS compatibility remain unverified. No probe/fallback or restriction
change is authorized by this coding task. Owned DB fixture prerequisites and
parent coordination remain separate.
- Record exact head, hashes, ordered prompt/operation outcomes, screenshots and
video for the new candidate. Hosting/distribution/deployment remain pending;
no main merge, Ready transition or release is part of this handoff.
@@ -0,0 +1,187 @@
[
{
"name": "assistant",
"id": "com.netcatty.assistant",
"version": "0.1.0",
"fileCount": 6,
"bytes": 17214,
"sha256": "7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274",
"contentSha256": "c3e31e9613422bf9a05ccaa5b6f234304208f1a8298b1c1ee19262ba88af6cd0",
"features": {
"required": [
"ai.model-invocation",
"context.selected-read"
]
},
"permissions": {
"required": [
"commands",
"views"
],
"optional": [
"ai.invoke",
"context.selected.list",
"context.selected.read"
]
},
"package": "assistant.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "c7d784d5c3bd2feb463afd58eae3a9594615395b168174cb8a3d0677584ae395",
"changedEntriesFromFrozen677": [
"README.md",
"panel.css",
"panel.js"
],
"previous7856Sha256": "7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "79a9bd6df1c17fd8a5238aba31d7a8b4cda184b9",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef"
},
{
"name": "database-owned",
"id": "com.netcatty.database-minimal",
"version": "0.1.0",
"fileCount": 5,
"bytes": 11660,
"sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"contentSha256": "4d628c41c7a231e31cd56dacb822acaaa37f61e1e98b285b0086a4f783be199d",
"features": {
"required": [
"network.byte-streams"
]
},
"permissions": {
"required": [
"commands",
"views"
],
"optional": [
{
"permission": "network.stream",
"resources": [
"tcp://10.77.0.20:3306"
],
"reason": "Connect only to the prepared disposable fixture."
}
]
},
"package": "database-owned.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"changedEntriesFromFrozen677": [],
"previous7856Sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "79a9bd6df1c17fd8a5238aba31d7a8b4cda184b9",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef"
},
{
"name": "database-rfam-readonly",
"id": "com.netcatty.database-rfam-readonly",
"version": "0.1.0",
"fileCount": 5,
"bytes": 11003,
"sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"contentSha256": "f542ca7b8e821d684cf7f71f0930458bd3ad97bc94bf654c88b0f353111e9162",
"features": {
"required": [
"network.byte-streams"
]
},
"permissions": {
"required": [
"commands",
"views"
],
"optional": [
{
"permission": "network.stream",
"resources": [
"tcp://mysql-rfam-public.ebi.ac.uk:4497"
],
"reason": "Run the fixed public Rfam acceptance query only after explicit authorization."
}
]
},
"package": "database-rfam-readonly.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"changedEntriesFromFrozen677": [],
"previous7856Sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "79a9bd6df1c17fd8a5238aba31d7a8b4cda184b9",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef"
},
{
"name": "host-actions",
"id": "com.netcatty.host-actions",
"version": "0.1.0",
"fileCount": 3,
"bytes": 4633,
"sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"contentSha256": "d6f8bf3ae9dc417ea838f673966f2e1075fc8f9ef1d939ca85b476b1bb007e6c",
"features": {
"required": [
"vault.host-actions",
"commands.interactive"
]
},
"permissions": {
"required": [
"commands",
"menus"
],
"optional": [
"vault.metadata",
"vault.write",
"ui.interact"
]
},
"package": "host-actions.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"changedEntriesFromFrozen677": [],
"previous7856Sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "79a9bd6df1c17fd8a5238aba31d7a8b4cda184b9",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef"
},
{
"name": "terminal-selection-draft",
"id": "com.netcatty.terminal-selection-draft",
"version": "0.1.0",
"fileCount": 2,
"bytes": 2954,
"sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"contentSha256": "99797d8679f34b96580076f922cbec067e511adc0f4ccf396ed129206acb6c4c",
"features": {
"required": [
"terminal.selection-sharing",
"terminal.input-drafts",
"commands.interactive"
]
},
"permissions": {
"required": [
"commands",
"menus"
],
"optional": [
"terminal.selection.read",
"terminal.input.propose"
]
},
"package": "terminal-selection-draft.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"changedEntriesFromFrozen677": [],
"previous7856Sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "79a9bd6df1c17fd8a5238aba31d7a8b4cda184b9",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef"
}
]
+8 -1
View File
@@ -29,6 +29,13 @@ for brand icons. This v1 publishing schema requires **avatar and artifact to
be null**. The client rejects unsupported delivery metadata rather than
inventing installable packages or deriving a GitHub avatar URL.
Delivery v2 retains those fields and admits hash-bound packages plus the reserved
avatar as null or a positive-size PNG/WebP asset reference of at most 256KiB.
The host fetches only the selected source's same-origin asset, verifies bytes,
and reuses its bounded icon rasterizer and cache. The renderer receives a PNG
data URI. Author imagery does not verify a GitHub account, and no GitHub avatar
URL is derived. See [author presentation](author-identity.md).
Index is validated with its pinned schema. Plugin/version identities must be
unique; each catalog entry must exactly equal the index's current, non-withdrawn,
source-only entry. Withdrawal does not disable, uninstall or delete any existing
@@ -73,7 +80,7 @@ exact SHA-256 bytes; it does not relax those future gates or auto-enable code.
| README details | Exact delivery `/assets/<hash>.md` | Visible error/Retry, no upstream fallback |
| Uninstalled brand icons | Existing reviewed bundled previews | Default icon; delivery icon metadata validated but not fetched by UI |
| Installed brand icons | Host-owned local package decoder | Default icon; no activation/network request |
| Author avatars | Not implemented; delivery v1 requires null | Existing local presentation; no avatar lookup |
| Author avatars | Visible-row host fetch of a validated v2 same-origin resource; v1 remains null | Default placeholder; no GitHub lookup or renderer URL fetch |
| Package artifacts | Not published or admitted by delivery v1 | Source-only; no download action fabricated |
| Source/README links | Explicit user-opened external HTTPS link | May open GitHub; no background dependency |
@@ -1,12 +1,67 @@
# Plugin security and permission boundary
Status: phase 3 internal preview (`0.1.0-internal`)
Status: unreleased plugin platform; browser plugins remain sandboxed. Advanced
utility packages remain restricted to developer mode.
This phase is available only with `NETCATTY_PLUGIN_DEV=1`. It is deliberately
usable by later contribution and Provider phases, but it is not a public plugin
release. There is no renderer permission UI yet. The first-party development
bootstrap injects a native Electron confirmation dialog; embedders that do not
inject a decision provider still fail closed.
Declared capabilities that the platform exposes default to **Allow**. Installing
or enabling a plugin does not open a permission checklist. In Settings, each
plugin has host-owned **Allow / Ask / Deny** controls with its declared resource
scope. Allow skips permission dialogs; Ask requests one scoped decision; Deny
rejects before side effects or content release. Target selection, model selection,
and editing/saving drafts remain normal host workflows. SSH authentication and
host-key checks are unchanged.
## Policy storage, updates and source changes
Policies live in `plugin_host_preferences`, separate from plugin-writable
settings, under `permission:<host source owner>:<capability>`. Missing entries mean
Allow. No historical plugin-policy migration or unrelated user-data reset runs.
Policies survive restart, disable/re-enable, uninstall/reinstall from the same
source, and package/version/publisher/declaration changes within that source.
An explicit Deny therefore survives an update, including removal and later
reintroduction of that capability. New declared capabilities default to Allow;
existing Ask/Deny modes apply to the current declared scope. Undeclared
permissions, unsupported methods and out-of-scope resources still fail closed.
Changing a source requires the existing explicit uninstall/private-data reset.
That reset removes only the old source's plugin policies and private records.
A different source receives independent defaults. Policies never come from a
manifest, plugin setting, RPC payload or imported grant. Existing grant hashes
still include the immutable package principal and declaration boundaries; this
change does not turn an old package grant into a cross-version grant.
Every policy edit clears saved grants, cancels pending decisions and active RPCs,
and invalidates host resource handles and model/stream state. Guards bind the
source and policy revision before asynchronous authorization resolution, recheck
before commits and content delivery, and remain invalid after a Deny-to-Allow
flip. A late prompt reply cannot revive old work. The user must start a fresh
operation after changing policy.
Ask uses Netcatty's existing in-app Dialog, typography and theme. Its recipient
must be a ready, focused, visible, unlocked top-level app renderer in the managed
window registry, including the standalone Settings window. Arbitrary windows,
plugin view contents and subframes cannot register or respond. Each single-use
token and cancellation lifecycle remains bound to the receiving window; another
renderer's readiness changes cannot cancel or inherit that request. No main-window
focus handoff is needed. Close, cancel, timeout, lock, hide/blur, reload, crash
and stale runtime/source fail closed. The dialog uses the existing host security
surface marker so attached native plugin views yield while it is visible and
restore through their existing lifecycle on dismissal.
Ordinary landing rows do not suspend native views. The logging dialog and its
verbose confirmation are marked security surfaces; the confirmation opts into
the existing marker because it temporarily accessibility-hides its parent dialog.
A plugin DOM click never becomes a host gesture. Choosers, drafts, terminal and
clipboard sharing use their existing host-owned action tokens. Ask integrates
with that workflow instead of opening a second capability dialog. Allow skips
sharing and connection permission confirmations while retaining validation and
operation/resource binding. AI start combines model access and exact selected
context handles into one Ask decision; its receipt is limited to that operation.
Stream reads, stop and close validate broker handles without prompting per chunk. The receipt uses a host-created RPC operation identity retained by derived
model contexts, with source/runtime/principal/revision binding. It is never a
plugin-provided field. The selected-summary chooser owns its Ask interaction;
there is no preceding generic capability prompt. Ask displays checked host
model/selection labels rather than opaque selected handles.
Selected-context reads remain selected-only and never enumerate the whole Vault.
## Authority model
@@ -40,9 +95,9 @@ Permission prompts use the canonical contract directly: absent operation and
session IDs are omitted, long host-generated operation IDs become stable
SHA-256 identifiers, reasons are bounded, and no request can carry more than
128 canonical resources.
Runtime trust/placement resolves before permission prompts. The special
`runtime.advanced` permission is excluded from generic required-permission
preflight and requested exactly once only when the host actually selects the
Runtime trust/placement resolves before advanced-runtime authorization. Required
preflight validates declarations without asking for capability grants. The
`runtime.advanced` policy is checked only if the host selects the developer-only
utility runtime.
## Grant lifetimes
@@ -62,19 +117,25 @@ identical prompts coalesce. Prompt timeout, runtime abort,
cancel, denial, absence of a decision provider, and stale activation all fail
closed. Grant/use/deny/revoke events enter the bounded security audit.
`PermissionRequest` is part of the canonical Schema and carries plugin display
identity, version, runtime placement, permission, canonical resources and their
aligned resource kinds, reason, operation and optional host session. This is
the complete PR-4 UI handoff; the renderer must return the same request ID and
one canonical lifetime decision. The native fallback visibly escapes control,
line-separator, and bidirectional-control characters in every plugin-controlled
display field so untrusted text cannot forge labels or resource lines.
`PermissionRequest` remains part of the canonical schema. It carries host-bound
identity, capability, canonical resource scope and optional related capabilities
for one combined operation. The trusted host UI renders text, never plugin HTML
or body payloads. A response must match its request and action token. Ordinary
Ask decisions apply once; long-lived stream attachment may use a host session.
The older grant lifetimes remain supported by the engine, not exposed as a
mandatory install flow.
Changing `runtime.advanced` to Ask or Deny disables and stops the privileged
development activation through the existing manager queue. Policy IPC awaits
that teardown. Queued lifecycle updates check the original source owner, so a
replacement source cannot be stopped by a stale edit. Ordinary browser sandboxes
are unchanged.
## Host-mediated capabilities
These brokers are the only authority path for ordinary browser plugins. An
advanced utility entrypoint is intentionally different: `runtime.advanced`
means explicit consent to ambient Node, filesystem and network APIs in its
exposes ambient Node, filesystem and network APIs in its
contained process. Fine-grained broker grants do not sandbox that ambient Node
authority. Phase 9 must also require a verified publisher principal before the
advanced path can be publicly enabled.
@@ -83,8 +144,7 @@ Required resource-scoped permissions (`network`, filesystem read/write, and
companion execution) must declare non-empty activation-time resource bounds;
the all-resources `*` wildcard is not a valid bound.
The string shorthand remains available only for optional declarations, whose
concrete resource is approved on first use. A package update therefore cannot
activate first and defer a newly required resource decision until later.
concrete resource is checked against its policy and scope on use.
Native companions are an advanced-runtime capability. Their manifests require
a Node utility entrypoint plus `runtime.advanced`, and `companion.start` rejects
@@ -229,8 +289,8 @@ after durable user data can exist.
## Inspect and revoke actual grants
The installed package detail separates declared permissions from **Saved
grants**. The host-only panel lists resource, scope, session (when applicable),
The installed package detail shows declared capabilities, resources and effective
Allow / Ask / Deny modes alongside any saved grants. The host-only panel lists resource, scope, session (when applicable),
and grant time. Each row indicates whether its declaration hash and security
principal match the host-owned current activation. Saved grants from an older
package or a stopped/disabled activation remain visible as inactive. One-use decisions do not appear as retained grants. Refresh
@@ -244,7 +304,7 @@ persists disabled state before revoking grants, invalidates contributions, and
waits for runtime shutdown. Existing runtime teardown cancels RPC, streams,
leases, providers, and companions. Every cleanup stage is attempted if grant deletion, audit persistence, or
contribution invalidation fails. Multiple errors are aggregated and reported;
the UI never claims successful revocation when persistence or cleanup failed. Explicit enable requests fresh access.
the UI never claims successful revocation when persistence or cleanup failed. Explicit enable retains the saved policy; Deny remains in force.
This management bridge is available only to the trusted app renderer. It is
not a plugin RPC method and grants no plugin authority over another package.
@@ -0,0 +1,140 @@
# Settings visibility and current-main acceptance candidate
This isolated branch, `integration/plugin-settings-main-acceptance`, starts at
frozen #4004 `2433cf0130d1c3274c56c39e5765349c2945de01`. Its Draft PR and private
renderer provenance record the final exact head and CI. Frozen2433 source,
artifact, QA workspace/profile and earlier evidence remain intact.
## Inputs and production ownership
Both inputs were ordinarily merged, without conflicts or manual production edits:
| Input | Import | Production files and behavior |
| --- | --- | --- |
| Current main `a0cf2b487c9ff0b0472d622e66bc5ee20de32c71` | Merge `c4aedfa9ed8c9f2647ac26f0e6e144edab341c2d` | `domain/workspaceAiScopeHandoff.ts` keeps inherited AI chat on a surviving owner when a workspace dissolves (#4003/e3e2dcfe); `electron/bridges/ai/shellUtils.cjs` narrowly recognizes Oh My Zsh ys two-line idle prompts (#4008/a0cf2b48) |
| Policy `1551fa8355021b5a811d737d16f81e8070f99f5d` | Merge `714e2397a43dc6c083dce8afeeb7a0475de11384` | `PluginLogSettings.tsx` removes the idle-row security marker and opts the nested verbose confirmation into it; `confirm-dialog.tsx` adds the optional host-only marker with default false |
All four production files exactly match their respective owners. Main has only
those two new commits since common base f0897c3c. Neither changed file overlaps
the prior plugin changes. The new prompt utility is not imported by plugin
production modules; plugin sensitive-input, selection and source guards remain
unchanged. Existing prompt and live-PTY-byte suffix tests still reject bare
markers and pending input. These are synthetic tests, not a new native SSH pass.
The input also owns its real Settings landing regression and documentation.
The existing observer, Ask marker, IPC/window authority, sandbox, resource/source
controls, AI d33 wiring, schemas, sample bytes and package/lock inputs are
unchanged. `ModelSelector.tsx` equals2433: separate #4002 is not included. Global
Agent/custom Chat #4006 and terminal diagnostic #3999 are excluded. No main merge,
Ready transition, original-PR closure or release is part of this handoff.
The parent reports the1551-vs89 independent delta review scoped clean: idle
Settings no longer requests suspension, the real logging dialog remains marked,
its nested verbose portal protects itself while the parent is accessibility-
hidden, closing the nested dialog leaves the parent protected, and closing all
dialogs permits restoration. This source-only result is not native resolution
of the recorded Settings blank body.
## Frozen2433 native results
The parent supplied these results; this coding executor did not run the GUI:
| Case | Result on2433 |
| --- | --- |
| Main Ask visible | Passed |
| Cancel | Passed; zero provider POSTs |
| Accept | Passed; one provider POST |
| Stream chunks | Passed; no repeated permission prompts |
| Content Deny | Passed |
| Real five-minute chat expiry | Passed |
| Settings sample body | Blank; not accepted |
The idle-row suppression defect is source-confirmed. The correction requires a
new native Settings recheck; no native success is inferred from the DOM regression.
A later GPU exit9 and incomplete cleanup were reported separately. Its cause is
unclassified; no source hotpatch or sandbox/GPU workaround was used here.
Consumer verification of2433's Library renderer is complete: the parent checked
the matching full source/backend and all1001 renderer hashes, with native inputs
unchanged. The earlier producer download failure remains historical evidence,
not an outstanding consumer transfer blocker. That verified artifact still
certifies2433 only; it does not include1551 or the new main renderer behavior.
Earlier020 Default Allow cold Send/completion, Stop/Deny/restore and themes,
677 Host core, and corrected-fixture terminal solo/split results remain scoped
historical evidence. Terminal Focus is unreliable/unverified and QA sent one
Enter inA during a palette attempt: no global zero-input/full-terminal-pass claim.
The historical Rfam attempt failed socket transport before connect resolved;
authentication/SELECT were not reached and cause/auth/TLS compatibility remain
unverified. Final source-policy, DB, placement/lifecycle and actual hosting/CDN
gates remain separately reconciled by the parent.
## Local checks and sample provenance
| Check | Result |
| --- | --- |
| Registered plugin runtime | 695 passed, one native skip; zero failed/cancelled |
| Contract/SDK/CLI | 91 passed |
| Offline examples | Five passed, one Docker opt-in skip |
| Changed main owner/scope/prompt/suffix and terminal lifecycle group | 139 passed |
| Actual mounted AI/permission/selected-context/Host group | 21 passed |
| Settings boundary and security visibility group | 38 passed |
| Contract/capability/Codex generation and committed drift | Clean |
| Lint | Zero errors, seven existing warnings |
| Five sample archives | Validated, built twice and byte-identical to2433 |
The final exact-head normal production build, renderer inventory, bounded
credential check, CI and Codex review are recorded in the Draft PR/artifact
handoff. Local full-suite, native packaging and GUI success are not claimed.
Locked dependencies, standard patches and the official pinned Electron binary
were prepared normally; no header, HOME, sandbox or native shim workaround.
[Exact sample IDs, permissions/resources and hashes](settings-main-packages.json)
preserve all prior provenance, including Assistant7943d4c3, ownedDBf01c6a24,
Rfamaaca5866, Hostcf04f82d and terminal4c9c2388. Whole archive equality was
asserted, rather than inferred from unchanged source. The owned10.77.0.20 endpoint
is packaging-only, not a running fixture. No package was activated or service
queried by this executor.
The owner's separate QA-only Settings Ask sample has reported SHA-256
`9502a58a4804862e4b13de9fc0d1baf6ad8c2bc681c08b5c0664b552ef0aafc4`.
It is not one of these five repository examples and was not rebuilt here. The
native owner must retain its exact verified manifest/source/permissions and
fixture provenance; no package ID, permission expansion or hash equivalence is
invented by this integration.
## Native preparation and bounded recheck
1. After the parent's GUI/Nginx slot is released, use a NEW isolated checkout of
the final exact head and a separate synthetic QA profile. Preserve the old2433
workspace/profile and recordings. Materialize the new private Library artifact
in the consumer's own workspace and verify archive and every renderer hash.
2. Use the complete matching backend checkout: frontend-only dist does not carry
the CJS prompt helper or native dependencies. Match package/lock hashes to
independently normally rebuilt native inputs and prepare workspace packages
normally. Install dist as a whole; use the ordinary Electron launch without
Vite and with normal sandbox/helper settings. This is unpackaged native
production-renderer QA, not packaged-binary certification.
3. Open the verified Settings sample through its existing supported settings
entry. Check the idle body is visible/clickable with the logging row present.
Open logging and the nested verbose confirmation separately; native content
must yield to each, remain hidden after cancelling the nested confirmation,
and restore only after the parent closes. Do not enable real verbose logging
or collect real content for this check.
4. In the ready/focused/visible/unlocked Settings owner, exercise its synthetic
own-setting Ask operation. Record visible Ask, explicit cancel/accept, exact
current operation outcome and restoration. Recheck main Ask briefly. Preserve
the2433 main/content/expiry counters and any unrun matrix cases separately.
5. Use owned synthetic A/B AI chats: form a workspace, prefer B, dissolve while A
survives and confirm both histories stay with their owners. Remove A and
check bounded fallback to B. Confirm handoff alone does not invoke a model or
re-share content. Exercise selected-target invalidation across the transition
with inert drafts and no PTY input. Do not treat earlier Focus uncertainty as
resolved by this main domain fix.
6. Record exact source/artifact/sample identities, screenshots/video, request
counters, cleanup and unrun cases. No fallback endpoint/probe, real credentials,
paid API, security relaxation or unrecognized installation is authorized here.
If main advances after this pinned a0cf snapshot, compare the new delta and assess
its affected checks before landing. The current candidate deliberately does not
chase unrelated changes while native preparation is in progress.
@@ -0,0 +1,217 @@
[
{
"name": "assistant",
"id": "com.netcatty.assistant",
"version": "0.1.0",
"fileCount": 6,
"bytes": 17214,
"sha256": "7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274",
"contentSha256": "c3e31e9613422bf9a05ccaa5b6f234304208f1a8298b1c1ee19262ba88af6cd0",
"features": {
"required": [
"ai.model-invocation",
"context.selected-read"
]
},
"permissions": {
"required": [
"commands",
"views"
],
"optional": [
"ai.invoke",
"context.selected.list",
"context.selected.read"
]
},
"package": "assistant.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "c7d784d5c3bd2feb463afd58eae3a9594615395b168174cb8a3d0677584ae395",
"changedEntriesFromFrozen677": [
"README.md",
"panel.css",
"panel.js"
],
"previous7856Sha256": "7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "1551fa8355021b5a811d737d16f81e8070f99f5d",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef",
"previous020Sha256": "7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274",
"changedEntriesFrom020": [],
"rebuiltAgainstMain": "a0cf2b487c9ff0b0472d622e66bc5ee20de32c71",
"productionMerge": "714e2397a43dc6c083dce8afeeb7a0475de11384",
"previous2433Sha256": "7943d4c3800914fe0acd3d0f3a3d7f7c1910c212a5dc58a044871a6a82485274",
"changedEntriesFrom2433": []
},
{
"name": "database-owned",
"id": "com.netcatty.database-minimal",
"version": "0.1.0",
"fileCount": 5,
"bytes": 11660,
"sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"contentSha256": "4d628c41c7a231e31cd56dacb822acaaa37f61e1e98b285b0086a4f783be199d",
"features": {
"required": [
"network.byte-streams"
]
},
"permissions": {
"required": [
"commands",
"views"
],
"optional": [
{
"permission": "network.stream",
"resources": [
"tcp://10.77.0.20:3306"
],
"reason": "Connect only to the prepared disposable fixture."
}
]
},
"package": "database-owned.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"changedEntriesFromFrozen677": [],
"previous7856Sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "1551fa8355021b5a811d737d16f81e8070f99f5d",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef",
"previous020Sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"changedEntriesFrom020": [],
"rebuiltAgainstMain": "a0cf2b487c9ff0b0472d622e66bc5ee20de32c71",
"productionMerge": "714e2397a43dc6c083dce8afeeb7a0475de11384",
"previous2433Sha256": "f01c6a24382897d4b0bf4130941274abacb9a9a963f9b56ecaceb2c020f36874",
"changedEntriesFrom2433": []
},
{
"name": "database-rfam-readonly",
"id": "com.netcatty.database-rfam-readonly",
"version": "0.1.0",
"fileCount": 5,
"bytes": 11003,
"sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"contentSha256": "f542ca7b8e821d684cf7f71f0930458bd3ad97bc94bf654c88b0f353111e9162",
"features": {
"required": [
"network.byte-streams"
]
},
"permissions": {
"required": [
"commands",
"views"
],
"optional": [
{
"permission": "network.stream",
"resources": [
"tcp://mysql-rfam-public.ebi.ac.uk:4497"
],
"reason": "Run the fixed public Rfam acceptance query only after explicit authorization."
}
]
},
"package": "database-rfam-readonly.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"changedEntriesFromFrozen677": [],
"previous7856Sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "1551fa8355021b5a811d737d16f81e8070f99f5d",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef",
"previous020Sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"changedEntriesFrom020": [],
"rebuiltAgainstMain": "a0cf2b487c9ff0b0472d622e66bc5ee20de32c71",
"productionMerge": "714e2397a43dc6c083dce8afeeb7a0475de11384",
"previous2433Sha256": "aaca586669db454e91d61487e576ed524d1b7190eed182bc2cd0035e59caa0d3",
"changedEntriesFrom2433": []
},
{
"name": "host-actions",
"id": "com.netcatty.host-actions",
"version": "0.1.0",
"fileCount": 3,
"bytes": 4633,
"sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"contentSha256": "d6f8bf3ae9dc417ea838f673966f2e1075fc8f9ef1d939ca85b476b1bb007e6c",
"features": {
"required": [
"vault.host-actions",
"commands.interactive"
]
},
"permissions": {
"required": [
"commands",
"menus"
],
"optional": [
"vault.metadata",
"vault.write",
"ui.interact"
]
},
"package": "host-actions.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"changedEntriesFromFrozen677": [],
"previous7856Sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "1551fa8355021b5a811d737d16f81e8070f99f5d",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef",
"previous020Sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"changedEntriesFrom020": [],
"rebuiltAgainstMain": "a0cf2b487c9ff0b0472d622e66bc5ee20de32c71",
"productionMerge": "714e2397a43dc6c083dce8afeeb7a0475de11384",
"previous2433Sha256": "cf04f82dfe25ab5cda6f5f3dad0a8fb06c37bedf9924f556bee2b8402e542ef2",
"changedEntriesFrom2433": []
},
{
"name": "terminal-selection-draft",
"id": "com.netcatty.terminal-selection-draft",
"version": "0.1.0",
"fileCount": 2,
"bytes": 2954,
"sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"contentSha256": "99797d8679f34b96580076f922cbec067e511adc0f4ccf396ed129206acb6c4c",
"features": {
"required": [
"terminal.selection-sharing",
"terminal.input-drafts",
"commands.interactive"
]
},
"permissions": {
"required": [
"commands",
"menus"
],
"optional": [
"terminal.selection.read",
"terminal.input.propose"
]
},
"package": "terminal-selection-draft.ncpkg",
"repeatIdentical": true,
"preparedOnlyInThisExecutor": true,
"previousFrozen677Sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"changedEntriesFromFrozen677": [],
"previous7856Sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"changedEntriesFrom7856": [],
"rebuiltAgainstPolicy": "1551fa8355021b5a811d737d16f81e8070f99f5d",
"rebuiltAgainstAI": "d33c0193ccaedc1a10aed9da495f040250121bef",
"previous020Sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"changedEntriesFrom020": [],
"rebuiltAgainstMain": "a0cf2b487c9ff0b0472d622e66bc5ee20de32c71",
"productionMerge": "714e2397a43dc6c083dce8afeeb7a0475de11384",
"previous2433Sha256": "4c9c2388b7f891156192a0b5ab7b23291beba3555e7ec8cf24fbe2dfe1242d5e",
"changedEntriesFrom2433": []
}
]
+3 -3
View File
@@ -11,12 +11,12 @@ const PERMISSION_DESCRIPTIONS = {
menus: [false, "Menu entries", "Add this plugin's actions to host menus.", "菜单入口", "将此插件的操作加入应用菜单。"],
"ui.interact": [false, "Host prompts", "Ask the host to show bounded input and choice dialogs.", "宿主交互", "请求宿主显示有界的输入和选择对话框。"],
views: [false, "Plugin panels", "Display plugin-owned panels inside the app.", "插件面板", "在应用中显示插件自己的面板。"],
"ai.invoke": [true, "Use configured AI model", "Send plugin prompts and separately approved selected text to the configured model. Provider charges may apply. Does not grant tools or host actions.", "使用已配置的 AI 模型", "向已配置的模型发送插件提示和另行批准的所选文本。模型提供商可能收费。此权限不授予工具或宿主操作权限。"],
"ai.invoke": [true, "Use configured AI model", "Send plugin prompts and permitted selected text to the configured model. Provider charges may apply. Does not grant tools or host actions.", "使用已配置的 AI 模型", "向已配置的模型发送插件提示和权限允许的所选文本。模型提供商可能收费。此权限不授予工具或宿主操作权限。"],
"context.selected.list": [true, "Selected context summaries", "Ask you to share summaries of selected workspace, tab, session, host, or Note references. Does not read their text.", "所选上下文摘要", "请求你分享所选工作区、标签页、会话、主机或笔记引用的摘要。此权限不会读取其文本。"],
"context.selected.read": [true, "Read selected context", "Read text from references you explicitly select and approve. It may contain private data.", "读取所选上下文", "读取你明确选择并批准的引用中的文本,其中可能包含隐私信息。"],
"context.selected.read": [true, "Read selected context", "Read text from host-selected references under this plugin's permission setting. It may contain private data.", "读取所选上下文", "根据插件权限设置读取宿主所选引用中的文本,其中可能包含隐私信息。"],
"clipboard.read": [true, "Read clipboard", "Read copied text, which may contain passwords or other sensitive data.", "读取剪贴板", "读取复制的文本,其中可能包含密码或其他敏感数据。"],
"clipboard.write": [true, "Write clipboard", "Replace clipboard content that you may paste elsewhere.", "写入剪贴板", "替换剪贴板内容,可能影响你随后粘贴的数据。"],
"terminal.selection.read": [true, "Share terminal selection", "Read only text explicitly previewed and shared from the selected live terminal. It may contain secrets. Each action requires approval.", "分享终端选区", "仅读取用户从当前活跃终端明确预览并分享的文本,可能包含秘密;每次操作均需确认。"],
"terminal.selection.read": [true, "Share terminal selection", "Read only the current selection from the host-selected live terminal. It may contain secrets. Ask mode shows one sharing preview.", "分享终端选区", "仅读取宿主所选活跃终端的当前选区,可能包含秘密;询问模式显示一次分享预览。"],
"terminal.input.propose": [true, "Review terminal input draft", "Open an editable host draft for one selected terminal. Does not send input or Enter.", "审阅终端输入草稿", "打开所选终端的可编辑宿主草稿,不发送输入或回车。"],
"terminal.metadata": [true, "Terminal metadata", "Read terminal/session details that may identify hosts and activity.", "终端元数据", "读取终端和会话信息,可能暴露主机及操作活动。"],
"terminal.output": [true, "Read terminal output", "Receive terminal output through supported providers; it may contain credentials or private data.", "读取终端输出", "通过支持的提供器接收终端输出,其中可能包含凭据或隐私信息。"],
+35
View File
@@ -5,6 +5,7 @@ import en from "../application/i18n/locales/en.ts";
import zhCN from "../application/i18n/locales/zh-CN.ts";
import zhTW from "../application/i18n/locales/zh-TW.ts";
import { filterSettingsSearchCatalog } from "./settingsSearch.ts";
import { resolveSettingsPlatform } from "./settingsSearchCatalog.ts";
import { SETTINGS_SEARCH_CATALOG } from "./settingsSearchCatalog.ts";
const EN: Record<string, string> = {
@@ -152,3 +153,37 @@ test("Sync status entries retain syncSubTab for navigation", () => {
assert.ok(backups);
assert.equal(backups?.entry.syncSubTab, "status");
});
test("macOS-only settings stay out of search on other platforms", () => {
const blurId = "appearance-window-background-blur";
// Both a targeted query and the default (empty query) list must skip it,
// otherwise selecting the hit jumps to a tab with no anchor to focus.
const macHits = filterSettingsSearchCatalog("", tEn, { platform: "mac", limit: 500 });
assert.ok(macHits.some((hit) => hit.entry.id === blurId));
for (const platform of ["win", "linux"] as const) {
const searched = filterSettingsSearchCatalog("frosted glass", tEn, { platform });
assert.equal(searched.some((hit) => hit.entry.id === blurId), false);
const defaults = filterSettingsSearchCatalog("", tEn, { platform, limit: 500 });
assert.equal(defaults.some((hit) => hit.entry.id === blurId), false);
}
});
test("platform-gated entries never hide cross-platform settings", () => {
for (const platform of ["mac", "win", "linux"] as const) {
const hits = filterSettingsSearchCatalog("opacity", tEn, { platform });
assert.ok(
hits.some((hit) => hit.entry.id === "appearance-window-opacity"),
`window opacity must stay searchable on ${platform}`,
);
}
});
test("resolveSettingsPlatform maps Electron-style platform strings", () => {
assert.equal(resolveSettingsPlatform("MacIntel"), "mac");
assert.equal(resolveSettingsPlatform("Win32"), "win");
assert.equal(resolveSettingsPlatform("Linux x86_64"), "linux");
assert.equal(resolveSettingsPlatform(""), "linux");
});
+9
View File
@@ -1,6 +1,9 @@
import { matchesSearchQuery } from "../lib/searchMatcher";
import {
SETTINGS_SEARCH_CATALOG,
isSettingsEntryAvailableOn,
resolveSettingsPlatform,
type SettingsPlatform,
type SettingsSearchEntry,
type SettingsTabId,
} from "./settingsSearchCatalog";
@@ -61,16 +64,22 @@ export function filterSettingsSearchCatalog(
catalog?: readonly SettingsSearchEntry[];
includePlugins?: boolean;
limit?: number;
/** Platform whose settings UI will receive the jump; defaults to the host. */
platform?: SettingsPlatform;
},
): SettingsSearchHit[] {
const catalog = options?.catalog ?? SETTINGS_SEARCH_CATALOG;
const includePlugins = options?.includePlugins ?? true;
const limit = options?.limit ?? 40;
const platform = options?.platform ?? resolveSettingsPlatform();
const trimmed = query.trim();
const hits: SettingsSearchHit[] = [];
for (const entry of catalog) {
if (!includePlugins && entry.tab === "plugins") continue;
// Platform-gated settings are hidden from search where their anchor is not
// rendered, so a hit always has a real control to focus.
if (!isSettingsEntryAvailableOn(entry, platform)) continue;
const hit = buildSettingsSearchHit(entry, t);
if (!trimmed) {
hits.push(hit);
+35
View File
@@ -31,6 +31,8 @@ export const SYNC_SETTINGS_SUB_TAB_IDS = ["providers", "status"] as const;
export type SyncSettingsSubTabId = (typeof SYNC_SETTINGS_SUB_TAB_IDS)[number];
export type SettingsPlatform = "mac" | "win" | "linux";
export type SettingsSearchEntry = {
/** Stable id; also used as `data-settings-anchor` on the target element. */
id: string;
@@ -47,8 +49,33 @@ export type SettingsSearchEntry = {
sectionKey?: string;
/** Extra English/Chinese aliases that are not full i18n strings. */
keywords?: readonly string[];
/**
* Platforms where the destination actually renders. Omit for cross-platform
* entries. Entries must not be offered on a platform whose settings UI hides
* the anchor, otherwise search jumps to a tab with nothing to highlight.
*/
platforms?: readonly SettingsPlatform[];
};
/** Resolve the host platform in the same terms the settings UI branches on. */
export function resolveSettingsPlatform(
platform?: string,
): SettingsPlatform {
const value = platform
?? (typeof navigator !== "undefined" ? navigator.platform : "");
if (/mac|iphone|ipad/i.test(value)) return "mac";
if (/win/i.test(value)) return "win";
return "linux";
}
export function isSettingsEntryAvailableOn(
entry: SettingsSearchEntry,
platform: SettingsPlatform,
): boolean {
if (!entry.platforms?.length) return true;
return entry.platforms.includes(platform);
}
export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
// Application
{
@@ -108,6 +135,14 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.appearance.windowOpacity.desc",
keywords: ["transparency", "透明"],
},
{
id: "appearance-window-background-blur",
tab: "appearance",
labelKey: "settings.appearance.windowBackgroundBlur",
descriptionKey: "settings.appearance.windowBackgroundBlur.desc",
keywords: ["blur", "frosted glass", "vibrancy", "模糊", "毛玻璃"],
platforms: ["mac"],
},
{
id: "appearance-theme",
tab: "appearance",
+19
View File
@@ -0,0 +1,19 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
isWindowBackgroundBlurActive,
} from './windowBackgroundBlur';
test('window background blur is visible only with a translucent surface', () => {
assert.equal(isWindowBackgroundBlurActive(true, 1), false);
assert.equal(isWindowBackgroundBlurActive(true, 0.99), true);
assert.equal(isWindowBackgroundBlurActive(true, 0.5), true);
assert.equal(isWindowBackgroundBlurActive(true, Number.NaN), false);
});
test('window background blur becomes inactive without losing the request state', () => {
assert.equal(isWindowBackgroundBlurActive(true, 0.85), true);
assert.equal(isWindowBackgroundBlurActive(true, 1), false);
assert.equal(isWindowBackgroundBlurActive(false, 0.85), false);
});
+6
View File
@@ -0,0 +1,6 @@
export function isWindowBackgroundBlurActive(
requested: boolean,
windowOpacity: number,
): boolean {
return requested && Number.isFinite(windowOpacity) && windowOpacity < 1;
}
+46 -6
View File
@@ -108,7 +108,7 @@ test('handoffDissolvedWorkspaceAIScope retargets inherited chat when its pane is
});
});
test('handoffDissolvedWorkspaceAIScope retargets inherited chat when original pane also survives', () => {
test('handoffDissolvedWorkspaceAIScope keeps inherited chat on its surviving owner pane', () => {
const result = handoffDissolvedWorkspaceAIScope({
activeSessionIdMap: {
'workspace:ws-1': 'chat-a',
@@ -132,12 +132,52 @@ test('handoffDissolvedWorkspaceAIScope retargets inherited chat when original pa
preferredTerminalId: 'term-b',
});
assert.equal(result.changed, true);
assert.equal(result.activeSessionIdMap['terminal:term-b'], 'chat-a');
assert.equal(result.activeSessionIdMap['terminal:term-a'], null);
assert.equal(result.sessions[0]?.scope.targetId, 'term-b');
assert.equal(result.activeSessionIdMap['terminal:term-a'], 'chat-a');
assert.equal(result.activeSessionIdMap['terminal:term-b'], 'chat-b');
assert.equal(result.sessions[0]?.scope.type, 'terminal');
assert.equal(result.sessions[0]?.scope.targetId, 'term-a');
assert.equal(result.sessions[0]?.updatedAt, 1);
assert.equal(result.sessions[1]?.scope.targetId, 'term-b');
assert.deepEqual(result.panelViewByScope['terminal:term-b'], {
assert.deepEqual(result.panelViewByScope['terminal:term-a'], {
mode: 'session',
sessionId: 'chat-a',
});
assert.equal(result.panelViewByScope['terminal:term-b'], undefined);
});
test('handoffDissolvedWorkspaceAIScope keeps owner history when the other pane is preferred', () => {
const result = handoffDissolvedWorkspaceAIScope({
activeSessionIdMap: {
'workspace:ws-1': 'chat-a',
'terminal:term-b': 'chat-b',
},
sessions: [
{
id: 'chat-a',
scope: { type: 'terminal', targetId: 'term-a', hostIds: ['host-a'] },
updatedAt: 1,
},
{
id: 'chat-b',
scope: { type: 'terminal', targetId: 'term-b', hostIds: ['host-b'] },
updatedAt: 1,
},
],
workspaceId: 'ws-1',
terminalIds: ['term-a', 'term-b'],
preferredTerminalId: 'term-b',
panelViewByScope: {
'workspace:ws-1': { mode: 'session', sessionId: 'chat-a' },
},
});
assert.equal(result.changed, true);
assert.equal(result.activeSessionIdMap['terminal:term-a'], 'chat-a');
assert.equal(result.activeSessionIdMap['terminal:term-b'], 'chat-b');
assert.equal(result.sessions[0]?.scope.targetId, 'term-a');
assert.equal(result.sessions[1]?.id, 'chat-b');
assert.equal(result.sessions[1]?.scope.targetId, 'term-b');
assert.deepEqual(result.panelViewByScope['terminal:term-a'], {
mode: 'session',
sessionId: 'chat-a',
});
+31 -19
View File
@@ -78,13 +78,15 @@ export function seedWorkspaceAIActiveSessionFromMembers(input: {
}
/**
* When a workspace tab dissolves, copy its active chat onto the preferred
* surviving terminal before the workspace scope key is pruned. Also remint
* workspace-scoped chats and the handed-off active chat when it still lives
* under a different terminal (including one that also survives dissolve),
* clear that previous terminal selection so ownership filters do not hide the
* chat, and seed a session panel view so terminal scopes do not fall back to
* a blank draft.
* When a workspace tab dissolves, copy its active chat onto a surviving
* terminal before the workspace scope key is pruned. An inherited chat that
* is already terminal-scoped to a pane still in `terminalIds` stays on that
* owner, even when focus/preferred is a different survivor. Otherwise the
* target is the preferred survivor, or the first remaining terminal when the
* original pane is gone. Workspace-scoped chats are reminted onto that
* target, duplicate terminal map entries for the same chat are cleared, and
* a session panel view is seeded so terminal scopes do not fall back to a
* blank draft.
*/
export function handoffDissolvedWorkspaceAIScope<T extends AISessionScopeHandoffLike>(input: {
activeSessionIdMap: AIActiveSessionIdMap;
@@ -99,7 +101,7 @@ export function handoffDissolvedWorkspaceAIScope<T extends AISessionScopeHandoff
panelViewByScope: Record<string, AIPanelViewHandoffLike>;
changed: boolean;
} {
const preferredTerminalId = (
const fallbackTerminalId = (
input.preferredTerminalId
&& input.terminalIds.includes(input.preferredTerminalId)
? input.preferredTerminalId
@@ -109,6 +111,17 @@ export function handoffDissolvedWorkspaceAIScope<T extends AISessionScopeHandoff
const workspaceKey = buildAIScopeKey('workspace', input.workspaceId);
const workspaceActive = input.activeSessionIdMap[workspaceKey];
const hasWorkspaceActive = typeof workspaceActive === 'string' && workspaceActive.length > 0;
const activeSession = hasWorkspaceActive
? input.sessions.find((session) => session.id === workspaceActive)
: undefined;
const survivingOwnerTerminalId = (
activeSession?.scope.type === 'terminal'
&& activeSession.scope.targetId
&& input.terminalIds.includes(activeSession.scope.targetId)
? activeSession.scope.targetId
: null
);
const handoffTargetTerminalId = survivingOwnerTerminalId ?? fallbackTerminalId;
const previousPanelViewByScope = (
input.panelViewByScope as Record<string, AIPanelViewHandoffLike> | undefined
) ?? {};
@@ -118,8 +131,8 @@ export function handoffDissolvedWorkspaceAIScope<T extends AISessionScopeHandoff
};
let mapChanged = false;
if (preferredTerminalId && hasWorkspaceActive) {
const terminalKey = buildAIScopeKey('terminal', preferredTerminalId);
if (handoffTargetTerminalId && hasWorkspaceActive) {
const terminalKey = buildAIScopeKey('terminal', handoffTargetTerminalId);
let map = nextMap;
let changed = false;
if (map[terminalKey] !== workspaceActive) {
@@ -145,24 +158,23 @@ export function handoffDissolvedWorkspaceAIScope<T extends AISessionScopeHandoff
let sessionsChanged = false;
const nextSessions = input.sessions.map((session) => {
if (!preferredTerminalId) return session;
if (!handoffTargetTerminalId) return session;
const isWorkspaceScoped = (
session.scope.type === 'workspace'
&& session.scope.targetId === input.workspaceId
);
// Inherited member chats stay terminal-scoped under the original pane.
// Prefer the focused survivor even when that original pane also survives
// dissolve, otherwise B's history ownership filter excludes A's chat.
// Keep an inherited chat on its owner when that pane survives. Remint
// only when the handoff target is a different terminal (original pane gone).
const isInheritedActiveChatOnOtherTerminal = (
hasWorkspaceActive
&& session.id === workspaceActive
&& session.scope.type === 'terminal'
&& Boolean(session.scope.targetId)
&& session.scope.targetId !== preferredTerminalId
&& session.scope.targetId !== handoffTargetTerminalId
);
if (!isWorkspaceScoped && !isInheritedActiveChatOnOtherTerminal) return session;
if (session.scope.type === 'terminal' && session.scope.targetId === preferredTerminalId) {
if (session.scope.type === 'terminal' && session.scope.targetId === handoffTargetTerminalId) {
return session;
}
@@ -172,7 +184,7 @@ export function handoffDissolvedWorkspaceAIScope<T extends AISessionScopeHandoff
scope: {
...session.scope,
type: 'terminal',
targetId: preferredTerminalId,
targetId: handoffTargetTerminalId,
},
updatedAt: Date.now(),
};
@@ -182,8 +194,8 @@ export function handoffDissolvedWorkspaceAIScope<T extends AISessionScopeHandoff
const nextPanelViewByScope: Record<string, AIPanelViewHandoffLike> = {
...previousPanelViewByScope,
};
if (preferredTerminalId && hasWorkspaceActive) {
const terminalKey = buildAIScopeKey('terminal', preferredTerminalId);
if (handoffTargetTerminalId && hasWorkspaceActive) {
const terminalKey = buildAIScopeKey('terminal', handoffTargetTerminalId);
const workspacePanelView = previousPanelViewByScope[workspaceKey];
const terminalPanelView = previousPanelViewByScope[terminalKey];
const nextView: AIPanelViewHandoffLike = (
+28 -10
View File
@@ -71,9 +71,17 @@ const POSIX_PROMPT_PATTERN = /^(?:[^\s@]+@[^\s:]+(?::[^\n\r]*)?|\[[^\s@\]]+@[^\s
// Host line of a two-line bash PS1 (`\u@\h: \w` then a following `$` or `#`).
// Same user@host[:path] class as POSIX_PROMPT_PATTERN's first alternative,
// without a prompt marker on this line. A bare `$`/`#` alone is not a prompt.
// without a prompt marker on this line. Oh My Zsh `ys` uses a different host
// line (`# user @ host ...`), matched separately below. A bare `$`/`#` alone
// is not a prompt.
const POSIX_PROMPT_HOST_LINE_PATTERN = /^[^\s@]+@[^\s:]+(?::[^\n\r]*)?$/;
// Oh My Zsh `ys` status line: a decorative `#`, then `user @ host` with
// spaces around `@`, then an optional remainder (directory, git, venv, time,
// exit code). Example: `# user @ host in ~ [12:34:56]`. Arbitrary text before
// a bare `$`/`#` still does not match.
const OH_MY_ZSH_YS_HOST_LINE_PATTERN = /^#\s+[^\s@]+\s+@\s+[^\s]+(?:\s+[^\n\r]+)?$/;
// Alpine's default ash PS1 omits the username: `\h:\w\$ ` -> `localhost:~# `.
// Require a hostname and a home/absolute path, excluding prompt delimiters
// within the path so partially entered commands do not count as idle prompts.
@@ -124,12 +132,15 @@ function extractTrailingIdlePrompt(output) {
return lastLine;
}
// Two-line PS1 (`export PS1="\u@\h: \w\n$ "`). Bash emits the newline as
// CR and the PTY's ONLCR adds another, so the bytes are `\r\r\n`. The
// CR-to-LF normalize above turns that into blank lines between the host
// line and `$`/`#`. Keep those blanks in the cache: getFreshIdlePrompt
// uses the same normalize, and hasExpectedPromptSuffix compares this
// CR-as-LF form against live PTY bytes. A lone `$` must not satisfy endsWith.
// Two-line PS1. Classic bash is `export PS1="\u@\h: \w\n$ "`. Oh My Zsh
// `ys` paints `# user @ host ...` and then a bare `$` or `#`. Bash emits
// the newline as CR and the PTY's ONLCR adds another, so the bytes are
// `\r\r\n`. The CR-to-LF normalize above turns that into blank lines
// between the host line and `$`/`#`. Keep those blanks in the cache:
// getFreshIdlePrompt uses the same normalize, and hasExpectedPromptSuffix
// compares this CR-as-LF form against live PTY bytes. A lone `$`/`#` must
// not satisfy endsWith; the previous non-empty line has to be a recognized
// host line (classic `user@host[:path]` or Oh My Zsh `ys`).
if (rightTrimmed === "$" || rightTrimmed === "#") {
let hostIndex = lines.length - 1;
while (hostIndex >= 0 && lines[hostIndex].replace(/\s+$/, "") === "") {
@@ -137,7 +148,13 @@ function extractTrailingIdlePrompt(output) {
}
const previousLine = hostIndex >= 0 ? lines[hostIndex] : "";
const previousRightTrimmed = previousLine.replace(/\s+$/, "");
if (POSIX_PROMPT_HOST_LINE_PATTERN.test(previousRightTrimmed)) {
// Same optional "(name) " env prefix as isDefaultPosixPromptLine (#3947).
// Recognition only; the returned prompt keeps the visible prefix.
const previousHostLine = previousRightTrimmed.replace(/^\([^()\n\r]+\)\s+/, "");
if (
POSIX_PROMPT_HOST_LINE_PATTERN.test(previousHostLine)
|| OH_MY_ZSH_YS_HOST_LINE_PATTERN.test(previousHostLine)
) {
return `${lines.slice(hostIndex).join("\n")}\n${lastLine}`;
}
}
@@ -202,8 +219,9 @@ function trackSessionIdlePrompt(session, chunk) {
// Return `session.lastIdlePrompt` only if the PTY's recent rolling tail
// still ends with it. The cached prompt is updated only when
// extractTrailingIdlePrompt recognizes a known shape (PowerShell, cmd.exe,
// `user@host[:path][#$]`, two-line `user@host[:path]` + `$`/`#`,
// RHEL `[user@host path][#$]`, or Alpine `host:path[#$]`);
// `user@host[:path][#$]`, two-line classic `user@host[:path]` or Oh My Zsh
// `ys` (`# user @ host ...`) + `$`/`#`, RHEL `[user@host path][#$]`, or
// Alpine `host:path[#$]`);
// a remote shell switch into another shell, an oh-my-posh / starship / custom
// PS1, or any unrecognized prompt would
// otherwise leave a stale value behind, which `resolveEffectiveShellKind`
+77
View File
@@ -262,6 +262,83 @@ test("trackSessionIdlePrompt and getFreshIdlePrompt accept a two-line user@host
assert.equal(getFreshIdlePrompt(ptySession), "user@host: /home/foo\n\n\n$ ");
});
test("extractTrailingIdlePrompt recognizes an Oh My Zsh ys two-line idle prompt", () => {
// ys paints `# user @ host ...` then a bare `$` or `#`. Spaces around `@`
// and the leading decorative `#` are required; a lone marker is not a prompt.
assert.equal(
extractTrailingIdlePrompt("# user @ host in ~ [12:34:56]\n$ "),
"# user @ host in ~ [12:34:56]\n$ ",
);
assert.equal(
extractTrailingIdlePrompt("welcome\r\n# user @ host in ~ [12:34:56]\n# "),
"# user @ host in ~ [12:34:56]\n# ",
);
assert.equal(
extractTrailingIdlePrompt("# user @ host in ~/proj on git:main [12:34:56]\n$ "),
"# user @ host in ~/proj on git:main [12:34:56]\n$ ",
);
assert.equal(
extractTrailingIdlePrompt("welcome\r\n# ys @ ys-mbp in ~/.oh-my-zsh on git:master x [21:47:42] C:127\n$ "),
"# ys @ ys-mbp in ~/.oh-my-zsh on git:master x [21:47:42] C:127\n$ ",
);
// Same CR / CRLF blank lines as the classic two-line PS1.
assert.equal(
extractTrailingIdlePrompt("# user @ host in ~ [12:34:56]\r\r\n$ "),
"# user @ host in ~ [12:34:56]\n\n\n$ ",
);
assert.equal(
extractTrailingIdlePrompt("# user @ host in ~ [12:34:56]\r\n# "),
"# user @ host in ~ [12:34:56]\n\n# ",
);
// Optional "(name) " env prefix is stripped only for recognition (#3947).
assert.equal(
extractTrailingIdlePrompt("(venv) # user @ host in ~ [12:34:56]\n$ "),
"(venv) # user @ host in ~ [12:34:56]\n$ ",
);
assert.equal(
extractTrailingIdlePrompt("(venv) user@host: /home/foo\n$ "),
"(venv) user@host: /home/foo\n$ ",
);
assert.equal(extractTrailingIdlePrompt("$ "), "");
assert.equal(extractTrailingIdlePrompt("# "), "");
assert.equal(extractTrailingIdlePrompt("welcome\r\n$ "), "");
assert.equal(extractTrailingIdlePrompt("not a host line\n$ "), "");
assert.equal(extractTrailingIdlePrompt("user @ host in ~\n$ "), "");
assert.equal(extractTrailingIdlePrompt("# user host in ~ [12:34:56]\n$ "), "");
assert.equal(extractTrailingIdlePrompt("# user@host in ~ [12:34:56]\n$ "), "");
assert.equal(extractTrailingIdlePrompt("copied output\n# "), "");
assert.equal(extractTrailingIdlePrompt("# user @ host in ~ [12:34:56]\n$ ls"), "");
assert.equal(extractTrailingIdlePrompt("# user @ host in ~ [12:34:56] $"), "");
assert.equal(extractTrailingIdlePrompt("echo $"), "");
assert.equal(extractTrailingIdlePrompt("price is 5$"), "");
assert.equal(extractTrailingIdlePrompt("(venv) not a host line\n$ "), "");
});
test("trackSessionIdlePrompt and getFreshIdlePrompt accept an Oh My Zsh ys two-line prompt", () => {
const session = {};
const prompt = "# user @ host in ~ [12:34:56]\n$ ";
trackSessionIdlePrompt(session, `welcome\r\n${prompt}`);
assert.equal(getFreshIdlePrompt(session), prompt);
const extra = {};
trackSessionIdlePrompt(extra, "# user @ host in ~/proj on git:main [12:34:56]\r\r\n$ ");
assert.equal(
getFreshIdlePrompt(extra),
"# user @ host in ~/proj on git:main [12:34:56]\n\n\n$ ",
);
const root = {};
trackSessionIdlePrompt(root, "# user @ host in ~ [12:34:56]\n# ");
assert.equal(getFreshIdlePrompt(root), "# user @ host in ~ [12:34:56]\n# ");
const bare = {};
assert.equal(trackSessionIdlePrompt(bare, "$ "), "");
assert.equal(getFreshIdlePrompt(bare), "");
assert.equal(trackSessionIdlePrompt(bare, "not a host line\n$ "), "");
assert.equal(getFreshIdlePrompt(bare), "");
});
test("extractTrailingIdlePrompt still recognizes a classic single-line POSIX prompt", () => {
assert.equal(extractTrailingIdlePrompt("welcome\r\nuser@host:~$ "), "user@host:~$ ");
});
+90 -14
View File
@@ -39,6 +39,10 @@ let settingsWindow = null;
let currentTheme = "light";
let currentLanguage = "en";
let currentWindowOpacity = 1;
let currentWindowBackgroundBlurRequested = false;
let currentWindowBackgroundColor = null;
/** Windows this module switched to a transparent backing, so restore is safe. */
const transparentChromeWindows = new WeakSet();
let cachedNativeTheme = null;
let handlersRegistered = false; // Prevent duplicate IPC handler registration
@@ -342,6 +346,12 @@ function getAppContentWindowList() {
return Array.from(appContentWindows).filter((win) => isWindowUsable(win));
}
// Settings has its own reusable window lifecycle, outside app-content editors.
// Enumerate only managed app renderers; remote/pop-up/plugin contents are absent.
function getManagedAppWindowList() {
return [...new Set([...getAppContentWindowList(), getSettingsWindow()])].filter((win) => isWindowUsable(win));
}
function getDirtyEditorWindowList() {
pruneAppContentWindows();
return Array.from(dirtyEditorWindows).filter((win) => isWindowUsable(win));
@@ -357,6 +367,7 @@ function registerAppContentWindow(win, options = {}) {
if (!win || win.isDestroyed?.()) return;
appContentWindows.add(win);
if (options.queryDirtyEditors === true) dirtyEditorWindows.add(win);
applyWindowBackgroundChromeToWindow(win, { applyBackgroundColor: true });
}
function unregisterAppContentWindow(win) {
@@ -406,21 +417,84 @@ function clampWindowOpacity(opacity) {
function applyWindowOpacityToWindow(win) {
if (!win || win.isDestroyed?.()) return;
try {
win.setOpacity?.(currentWindowOpacity);
win.setOpacity?.(isWindowBackgroundBlurActive() ? 1 : currentWindowOpacity);
} catch {
// ignore
}
applyWindowBackgroundChromeToWindow(win, { applyBackgroundColor: true });
}
function applyWindowOpacity(opacity) {
currentWindowOpacity = clampWindowOpacity(opacity);
for (const win of getAppContentWindowList()) applyWindowOpacityToWindow(win);
for (const win of getAppContentWindowList()) {
applyWindowOpacityToWindow(win);
}
if (settingsWindow && !settingsWindow.isDestroyed()) {
applyWindowOpacityToWindow(settingsWindow);
}
return currentWindowOpacity;
}
function isWindowBackgroundBlurActive() {
return process.platform === "darwin"
&& currentWindowBackgroundBlurRequested
&& currentWindowOpacity < 1;
}
function applyWindowBackgroundChromeToWindow(win, options = {}) {
if (!win || win.isDestroyed?.()) return;
try {
if (isWindowBackgroundBlurActive()) {
win.setVibrancy?.("hud");
win.setBackgroundColor?.("#00000000");
transparentChromeWindows.add(win);
return;
}
if (process.platform === "darwin") win.setVibrancy?.(null);
if (options.applyBackgroundColor !== true) return;
// An explicit theme/background-color push must always repaint, otherwise
// the native backing goes stale after theme changes. Registration-time
// chrome setup is different: it must not clobber the color the window was
// created with before any theme color has been pushed.
const wasTransparent = transparentChromeWindows.delete(win);
if (options.forceBackgroundColor === true || wasTransparent) {
// A window can be asked to drop vibrancy before any theme color has been
// pushed (cold start with blur already saved). Falling back to the active
// theme keeps the window from staying transparent.
const restoreColor = currentWindowBackgroundColor
|| THEME_COLORS[currentTheme]?.background;
if (restoreColor) win.setBackgroundColor?.(restoreColor);
}
} catch {
// ignore platform-specific chrome failures
}
}
function applyWindowBackgroundColor(color) {
const normalized = normalizeBackgroundColor(color);
if (!normalized) return false;
currentWindowBackgroundColor = normalized;
for (const win of getAppContentWindowList()) {
applyWindowBackgroundChromeToWindow(win, { applyBackgroundColor: true, forceBackgroundColor: true });
}
if (settingsWindow && !settingsWindow.isDestroyed()) {
applyWindowBackgroundChromeToWindow(settingsWindow, { applyBackgroundColor: true, forceBackgroundColor: true });
}
return true;
}
function applyWindowBackgroundBlur(enabled) {
const supported = process.platform === "darwin";
currentWindowBackgroundBlurRequested = supported && enabled === true;
for (const win of getAppContentWindowList()) {
applyWindowOpacityToWindow(win);
}
if (settingsWindow && !settingsWindow.isDestroyed()) {
applyWindowOpacityToWindow(settingsWindow);
}
return supported;
}
function getMainWindowCount() {
return getMainWindowList().length;
}
@@ -992,7 +1066,12 @@ const { createWindow } = mainWindowApi;
const { createSettingsWindowApi } = require("./windowManager/settingsWindow.cjs");
const settingsWindowApi = createSettingsWindowApi({
get settingsWindow() { return settingsWindow; },
set settingsWindow(value) { settingsWindow = value; },
set settingsWindow(value) {
settingsWindow = value;
if (value) {
applyWindowBackgroundChromeToWindow(value, { applyBackgroundColor: true });
}
},
get mainWindow() { return mainWindow; },
get currentTheme() { return currentTheme; },
get isQuitting() { return isQuitting; },
@@ -1181,21 +1260,12 @@ function registerWindowHandlers(ipcMain, nativeTheme) {
? (nativeTheme?.shouldUseDarkColors ? "dark" : "light")
: theme;
const themeConfig = THEME_COLORS[effectiveTheme] || THEME_COLORS.light;
forEachMainWindow((win) => win.setBackgroundColor(themeConfig.background));
if (settingsWindow && !settingsWindow.isDestroyed()) {
settingsWindow.setBackgroundColor(themeConfig.background);
}
applyWindowBackgroundColor(themeConfig.background);
return true;
});
ipcMain.handle("netcatty:setBackgroundColor", (_event, color) => {
const normalized = normalizeBackgroundColor(color);
if (!normalized) return false;
forEachMainWindow((win) => win.setBackgroundColor(normalized));
if (settingsWindow && !settingsWindow.isDestroyed()) {
settingsWindow.setBackgroundColor(normalized);
}
return true;
return applyWindowBackgroundColor(color);
});
ipcMain.handle("netcatty:setWindowOpacity", (_event, opacity) => {
@@ -1203,6 +1273,10 @@ function registerWindowHandlers(ipcMain, nativeTheme) {
return true;
});
ipcMain.handle("netcatty:setWindowBackgroundBlur", (_event, enabled) => {
return applyWindowBackgroundBlur(enabled);
});
ipcMain.handle("netcatty:setAppIconVariant", (_event, variant) => {
const { app, BrowserWindow, nativeImage } = require("electron");
const appIconManager = require("./appIconManager.cjs");
@@ -1284,6 +1358,7 @@ function registerWindowHandlers(ipcMain, nativeTheme) {
try {
const sharedWindowSetting = [
"netcatty_window_opacity_v1",
"netcatty_window_background_blur_v1",
"netcatty_hotkey_scheme_v1",
"netcatty_custom_key_bindings_v1",
"netcatty_hotkey_recording_v1",
@@ -1555,6 +1630,7 @@ module.exports = {
getMainWindow,
getMainWindows: getMainWindowList,
getAppContentWindows: getAppContentWindowList,
getManagedAppWindows: getManagedAppWindowList,
getDirtyEditorWindows: getDirtyEditorWindowList,
getMainWindowCount,
isMainWindow,
@@ -263,11 +263,13 @@ function createMainWindowApi(ctx) {
minWidth: windowMinimumSize.width,
minHeight: windowMinimumSize.height,
backgroundColor,
transparent: isMac,
icon: appIcon,
show: false,
frame: isMac,
titleBarStyle: isMac ? "hiddenInset" : undefined,
trafficLightPosition: isMac ? { x: 12, y: 12 } : undefined,
...(isMac ? { visualEffectState: "active" } : {}),
...windowsChrome,
webPreferences: {
preload,
@@ -139,6 +139,7 @@ function createSettingsWindowApi(ctx) {
minWidth: 820,
minHeight: 600,
backgroundColor,
transparent: isMac,
icon: appIcon,
fullscreenable: !isMac,
// NOTE: Do NOT set parent - on macOS this causes rendering issues when dragging
@@ -150,6 +151,7 @@ function createSettingsWindowApi(ctx) {
frame: isMac,
titleBarStyle: isMac ? "hiddenInset" : undefined,
trafficLightPosition: isMac ? { x: 12, y: 12 } : undefined,
...(isMac ? { visualEffectState: "active" } : {}),
...windowsChrome,
webPreferences: {
preload,
@@ -0,0 +1,111 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { createRequire } = require('node:module');
const vm = require('node:vm');
const test = require('node:test');
function loadWindowManager(platform) {
const filename = path.resolve(__dirname, '../windowManager.cjs');
const loadedModule = { exports: {} };
const context = vm.createContext({
process: { ...process, platform },
console,
URL,
setTimeout,
clearTimeout,
});
const load = vm.runInContext(
`(function(exports, require, module, __filename, __dirname) { ${fs.readFileSync(filename, 'utf8')}\n})`,
context,
);
load(loadedModule.exports, createRequire(filename), loadedModule, filename, path.dirname(filename));
const handlers = new Map();
loadedModule.exports.registerWindowHandlers({
handle: (channel, handler) => handlers.set(channel, handler),
on: (channel, handler) => handlers.set(channel, handler),
}, {});
const state = { opacity: 1, vibrancy: null, background: '#123456' };
const win = {
isDestroyed: () => false,
setOpacity: (value) => { state.opacity = value; },
setVibrancy: (value) => { state.vibrancy = value; },
setBackgroundColor: (value) => { state.background = value; },
webContents: { id: 1, isDestroyed: () => false },
};
loadedModule.exports.registerMainWindow(win);
const invoke = (name, value) => handlers.get(`netcatty:${name}`)({}, value);
return { invoke, state };
}
test('macOS blur keeps native opacity at one and restores normal opacity on disable', () => {
const { invoke, state } = loadWindowManager('darwin');
assert.equal(state.background, '#123456');
invoke('setBackgroundColor', '#123456');
invoke('setWindowBackgroundBlur', true);
assert.equal(state.vibrancy, null);
invoke('setWindowOpacity', 0.7);
assert.equal(state.opacity, 1);
assert.equal(state.vibrancy, 'hud');
assert.equal(state.background, '#00000000');
invoke('setWindowOpacity', 0.85);
assert.equal(state.opacity, 1);
invoke('setWindowBackgroundBlur', false);
assert.equal(state.opacity, 0.85);
assert.equal(state.vibrancy, null);
assert.equal(state.background, '#123456');
});
test('restoring 100% removes native vibrancy and restores the theme background', () => {
const { invoke, state } = loadWindowManager('darwin');
invoke('setWindowOpacity', 0.7);
invoke('setWindowBackgroundBlur', true);
invoke('setBackgroundColor', '#abcdef');
assert.equal(state.background, '#00000000');
invoke('setWindowOpacity', 1);
assert.equal(state.opacity, 1);
assert.equal(state.vibrancy, null);
assert.equal(state.background, '#abcdef');
invoke('setWindowOpacity', 0.7);
assert.equal(state.opacity, 1);
assert.equal(state.vibrancy, 'hud');
});
test('unsupported platforms retain the existing opacity behavior', () => {
for (const platform of ['win32', 'linux']) {
const { invoke, state } = loadWindowManager(platform);
invoke('setWindowOpacity', 0.7);
assert.equal(invoke('setWindowBackgroundBlur', true), false);
assert.equal(state.opacity, 0.7);
assert.equal(state.vibrancy, null);
}
});
test('disabling blur before any theme color push restores the current theme background', () => {
const { invoke, state } = loadWindowManager('darwin');
// No setBackgroundColor / setTheme call yet: currentWindowBackgroundColor is
// still null, so the fallback must come from the active theme.
invoke('setWindowOpacity', 0.7);
invoke('setWindowBackgroundBlur', true);
assert.equal(state.background, '#00000000');
invoke('setWindowBackgroundBlur', false);
assert.equal(state.vibrancy, null);
assert.notEqual(state.background, '#00000000');
assert.match(String(state.background), /^#[0-9a-fA-F]{6}$/);
});
test('explicit theme and background-color pushes repaint windows that never used blur', () => {
for (const platform of ['darwin', 'win32', 'linux']) {
const { invoke, state } = loadWindowManager(platform);
assert.equal(state.background, '#123456');
// Registration-time chrome setup must leave the creation-time color alone...
invoke('setWindowBackgroundBlur', false);
assert.equal(state.background, '#123456');
// ...but an explicit theme color must always land.
invoke('setBackgroundColor', '#abcdef');
assert.equal(state.background, '#abcdef');
invoke('setTheme', 'dark');
assert.match(String(state.background), /^#[0-9a-fA-F]{6}$/);
assert.notEqual(state.background, '#abcdef');
}
});
+2 -14
View File
@@ -153,9 +153,6 @@ function createBridgeRegistrar(context) {
env: process.env,
createService: () => {
const { createPluginHostService } = require("../plugins/hostService.cjs");
const {
createNativePermissionDecisionProvider,
} = require("../plugins/nativePermissionDecision.cjs");
const {
terminalInterceptorChoiceLabel,
terminalInterceptorIdentifier,
@@ -166,20 +163,10 @@ function createBridgeRegistrar(context) {
electron: electronModule,
safeStorage,
getInteractionWindow: () => win,
getPermissionWindows: () => getWindowManager().getManagedAppWindows(),
getTerminalWorkerManager: () => terminalWorkerManager,
isAppLocked: () => getAppLockController?.()?.getRuntimeState?.()?.locked !== false,
subscribeAppLock: (listener) => getAppLockController?.()?.subscribe?.(listener),
requestPermissionDecision: createNativePermissionDecisionProvider({
getLocale: () => getWindowManager().getCurrentLanguage?.() ?? "en",
dialog: electronModule.dialog,
window: win,
getWindow: () => {
const settingsWindow = getWindowManager().getSettingsWindow?.();
return settingsWindow && !settingsWindow.isDestroyed() && settingsWindow.isFocused()
? settingsWindow
: win;
},
}),
getLocale: () => getWindowManager().getCurrentLanguage?.() ?? "en",
requestTerminalInterceptorSelection: async ({ direction, providers }) => {
const messages = terminalInterceptorMessages(getWindowManager().getCurrentLanguage?.() ?? "en");
@@ -223,6 +210,7 @@ function createBridgeRegistrar(context) {
manager: pluginHostService?.manager,
interactionService: pluginHostService?.interactionService,
permissionEngine: pluginHostService?.permissionEngine,
permissionDecisionHost: pluginHostService?.permissionDecisionHost,
runtimeSupervisor: pluginHostService?.runtimeSupervisor,
database: pluginHostService?.database,
catalogService: pluginHostService?.catalogService,
+22 -5
View File
@@ -37,7 +37,12 @@ function startBridge({ token, authDelayMs = 0, onGetContext = null }) {
sockets.add(socket);
socket.on("close", () => sockets.delete(socket));
let buffer = "";
let authenticated = false;
socket.setEncoding("utf8");
const writeLine = (payload) => {
if (socket.destroyed) return;
socket.write(`${JSON.stringify(payload)}\n`);
};
socket.on("data", (chunk) => {
buffer += chunk;
let newlineIdx;
@@ -52,17 +57,29 @@ function startBridge({ token, authDelayMs = 0, onGetContext = null }) {
token: msg.params?.token,
});
const respond = () => {
if (socket.destroyed) return;
if (msg.method === "auth/verify") {
if (msg.params?.token !== token) {
socket.write(`${JSON.stringify({
writeLine({
jsonrpc: "2.0",
id: msg.id,
error: { code: -32001, message: "Authentication required. Send auth/verify with valid token first." },
})}\n`);
});
socket.destroy();
return;
}
socket.write(`${JSON.stringify({ jsonrpc: "2.0", id: msg.id, result: { ok: true } })}\n`);
authenticated = true;
writeLine({ jsonrpc: "2.0", id: msg.id, result: { ok: true } });
return;
}
// Match the app bridge: a call before auth/verify closes the socket.
if (!authenticated) {
writeLine({
jsonrpc: "2.0",
id: msg.id,
error: { code: -32001, message: "Authentication required. Send auth/verify with valid token first." },
});
socket.destroy();
return;
}
if (msg.method === "netcatty/getContext" && onGetContext) {
@@ -72,11 +89,11 @@ function startBridge({ token, authDelayMs = 0, onGetContext = null }) {
return;
}
}
socket.write(`${JSON.stringify({
writeLine({
jsonrpc: "2.0",
id: msg.id,
result: { ok: true, marker: token },
})}\n`);
});
};
if (msg.method === "auth/verify" && authDelayMs > 0) {
setTimeout(respond, authDelayMs);
+33 -10
View File
@@ -122,19 +122,33 @@ function guardWriteOperation(command, { skipBlocklist = false } = {}) {
}
let tcpSocket = null;
let pendingRequests = new Map(); // id -> { resolve, reject }
let pendingRequests = new Map(); // id -> { resolve, reject, sock }
let nextRpcId = 1;
let tcpBuffer = "";
// `destroyed` stays false after the peer FIN has already moved readyState to
// "closed". Writing in that window hits writeAfterFIN and rejects the call
// with "TCP connection lost" instead of reconnecting.
function isLiveSocket(sock) {
return Boolean(
sock
&& !sock.destroyed
&& sock.readyState === "open"
&& sock.writable
&& !sock.readableEnded
&& !sock.writableEnded
);
}
function rejectPendingOnSocket(sock, externalMessage) {
if (tcpSocket && tcpSocket !== sock) return;
const managed = !externalDiscoveryPath;
if (managed && tcpSocket === sock) tcpSocket = null;
const message = managed ? "Not connected to Netcatty" : externalMessage;
for (const { reject: rej } of pendingRequests.values()) {
rej(new Error(message));
for (const [id, pending] of pendingRequests) {
if (pending.sock !== sock) continue;
pendingRequests.delete(id);
pending.reject(new Error(message));
}
pendingRequests.clear();
}
function connectTcp() {
@@ -198,15 +212,16 @@ function connectTcp() {
function sendRpc(method, params) {
return new Promise((resolve, reject) => {
if (!tcpSocket || tcpSocket.destroyed) {
if (!isLiveSocket(tcpSocket)) {
reject(new Error("Not connected to Netcatty"));
return;
}
const sock = tcpSocket;
const id = nextRpcId++;
pendingRequests.set(id, { resolve, reject });
pendingRequests.set(id, { resolve, reject, sock });
const msg = JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n";
debugLog("rpcCall", { id, method });
tcpSocket.write(msg);
sock.write(msg);
});
}
@@ -246,7 +261,12 @@ function dropActiveSocket() {
let connecting = null;
async function connectAndAuth() {
if (tcpSocket?.destroyed) tcpSocket = null;
// Drop the reference only. In-flight requests stay bound to the old socket
// and are rejected when that socket closes; they are not replayed.
if (!isLiveSocket(tcpSocket)) {
tcpSocket = null;
tcpBuffer = "";
}
refreshExternalEndpoint();
tcpBuffer = "";
try {
@@ -263,8 +283,11 @@ async function connectAndAuth() {
}
function ensureConnected() {
if (tcpSocket && !tcpSocket.destroyed) return Promise.resolve();
// Join an in-flight reconnect before trusting tcpSocket. connectTcp assigns
// the socket before auth/verify returns; a second caller must wait for that
// re-auth instead of sending on an unauthenticated socket.
if (connecting) return connecting;
if (isLiveSocket(tcpSocket)) return Promise.resolve();
connecting = connectAndAuth().finally(() => {
connecting = null;
});
@@ -15,6 +15,7 @@ if (!schema.$defs.PluginAIChatResult) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "netcatty-assistant-entry-"));
let service; let contentAllowed = false; let modelAllowed = true; let reviewed = true; let invoked = 0; let versionCurrent = true;
const decisions = [];
let holdDecision = false, decisionOpened, completeDecision;
t.after(async () => { await service?.manager.shutdown(); await fs.rm(root, { recursive: true, force: true }); });
service = createPluginHostService({
app: { getAppPath: () => path.resolve(__dirname, "../../.."), getPath: () => root, getVersion: () => "0.0.0" }, electron: {}, env: {},
@@ -28,7 +29,11 @@ if (!schema.$defs.PluginAIChatResult) {
},
requestPermissionDecision: async (request) => {
decisions.push(request);
if ((request.permission === "context.selected.read" && !contentAllowed) || (request.permission === "ai.invoke" && !modelAllowed)) return { requestId: request.requestId, decision: "deny" };
if (holdDecision) {
decisionOpened();
return new Promise((resolve) => { completeDecision = () => resolve({ requestId: request.requestId, decision: "allow", scope: "once" }); });
}
if (((request.permission === "context.selected.read" || request.relatedPermissions?.some((item) => item.permission === "context.selected.read")) && !contentAllowed) || (request.permission === "ai.invoke" && !modelAllowed)) return { requestId: request.requestId, decision: "deny" };
return { requestId: request.requestId, decision: "allow", scope: request.permission === "context.selected.read" ? "once" : "application" };
},
});
@@ -45,26 +50,61 @@ if (!schema.$defs.PluginAIChatResult) {
await service.manager.install(archive, { enable: true });
const id = "com.netcatty.assistant";
const run = (name, args) => service.contributionService.executeCommand(`${id}.${name}`, args);
modelAllowed = false; await assert.rejects(run("open")); assert.equal(invoked, 0);
modelAllowed = true;
// Normal installed Allow flow has only host model/context selection, with
// no permission or body-sharing ceremony at any stream stage.
const defaultChat = await run("open"); const [defaultReference] = await run("contexts");
const defaultTurn = await run("send", { chatHandle: defaultChat.chatHandle, prompt: "Summarize", contexts: [{ handle: defaultReference.handle, version: defaultReference.version }] });
await run("read", { turnHandle: defaultTurn.turnHandle }); await run("read", { turnHandle: defaultTurn.turnHandle }); await run("read", { turnHandle: defaultTurn.turnHandle });
assert.equal(decisions.length, 0); assert.equal(invoked, 1);
invoked = 0;
service.permissionEngine.setMode({ id, manifest: service.database.getActivePlugin(id).manifest }, "ai.invoke", "deny");
await assert.rejects(run("open")); assert.equal(invoked, 0);
service.permissionEngine.setMode({ id, manifest: service.database.getActivePlugin(id).manifest }, "ai.invoke", "ask");
const chat = await run("open"); const references = await run("contexts"); assert.equal(references.length, 1);
assert.equal(references[0].scope, "note"); assert.equal(references[0].text, undefined);
const input = { chatHandle: chat.chatHandle, prompt: "Summarize", contexts: [{ handle: references[0].handle, version: references[0].version }] };
service.database.setPermissionMode(id, "context.selected.read", "ask");
await assert.rejects(run("send", input)); assert.equal(invoked, 0);
contentAllowed = true; reviewed = false; await assert.rejects(run("send", input)); assert.equal(invoked, 0);
reviewed = true;
contentAllowed = true; reviewed = false; // No separate body-sharing ceremony.
const beforeStart = decisions.length;
const turn = await run("send", input);
assert.equal(decisions.length, beforeStart + 1, "one registered AI turn must not lose its content receipt in a derived context");
assert.deepEqual(decisions.at(-1).displayContext, { modelLabel: "Synthetic fixture", selections: [{ title: "Synthetic retry plan", scope: "note", version: "v1" }] });
const { createDefinitionValidator } = require("../contractValidator.cjs");
assert.equal(createDefinitionValidator("PermissionRequest")(decisions.at(-1)), true);
const auditMetadata = JSON.stringify(service.database.listSecurityAudit(id, 1000));
assert.equal(auditMetadata.includes("Synthetic retry plan"), false);
assert.equal(auditMetadata.includes("Synthetic fixture"), false);
assert.deepEqual(await run("read", { turnHandle: turn.turnHandle }), { kind: "text", sequence: 0, text: "Synthetic summary" });
assert.deepEqual(await run("read", { turnHandle: turn.turnHandle }), { kind: "usage", sequence: 1, inputTokens: 12, outputTokens: 6, totalTokens: 18 });
assert.deepEqual(await run("read", { turnHandle: turn.turnHandle }), { kind: "end", sequence: 2 });
await assert.rejects(run("send", { ...input, privateOwner: "spoofed" }));
await assert.rejects(run("send", { ...input, permissionOperation: {} }));
await assert.rejects(run("send", { ...input, displayContext: { modelLabel: "Plugin spoof" } }));
await assert.rejects(run("send", { ...input, contexts: [null] }));
await assert.rejects(run("read", { turnHandle: turn.turnHandle, source: "spoofed" }));
const pending = await run("send", input);
service.permissionEngine.revokeApplication(id, "ai.invoke", "*");
assert.equal(service.aiContextService.broker.turns.size, 0);
await assert.rejects(run("read", { turnHandle: pending.turnHandle }));
assert.ok(decisions.some((decision) => decision.permission === "context.selected.read" && decision.resources[0].startsWith("selected:")));
assert.ok(decisions.some((decision) => decision.relatedPermissions?.some((item) => item.permission === "context.selected.read" && item.resources[0].startsWith("selected:"))));
const owned = { id, manifest: service.database.getActivePlugin(id).manifest };
const queuedChat = await run("open"); const [queuedReference] = await run("contexts");
holdDecision = true;
const promptOpened = new Promise((resolve) => { decisionOpened = resolve; });
const beforeRevocation = invoked;
const queued = run("send", { chatHandle: queuedChat.chatHandle, prompt: "Do not invoke", contexts: [{ handle: queuedReference.handle, version: queuedReference.version }] });
const rejected = assert.rejects(queued, /changed|revoked|cancel/);
await promptOpened;
service.permissionEngine.setMode(owned, "context.selected.read", "deny");
completeDecision(); await rejected;
assert.equal(invoked, beforeRevocation);
holdDecision = false;
const deniedChat = await run("open"); const [deniedReference] = await run("contexts");
const beforeDeny = decisions.length;
await assert.rejects(run("send", { chatHandle: deniedChat.chatHandle, prompt: "Still denied", contexts: [{ handle: deniedReference.handle, version: deniedReference.version }] }), /disabled/);
assert.equal(decisions.length, beforeDeny); assert.equal(invoked, beforeRevocation);
service.permissionEngine.setMode(owned, "context.selected.read", "allow");
const fresh = await run("open"); const [reference] = await run("contexts");
versionCurrent = false;
await assert.rejects(run("send", { chatHandle: fresh.chatHandle, prompt: "Hi", contexts: [{ handle: reference.handle, version: reference.version }] }));
+23 -4
View File
@@ -96,8 +96,27 @@ class PluginAIContextService {
},
authorization: async (params, context) => {
await this.#guard(context);
if (route.operation === "readSelected") await this.selected.assertCurrent(params, context);
return this.#authorization(route.permission, params);
const references = route.operation === "readSelected" ? [params] : route.operation === "start" ? params.contexts ?? [] : [];
let displayContext;
if (route.operation === "start" || references.length) {
for (const reference of references) await this.selected.assertCurrent(reference, context);
const summaries = references.length ? await this.selected.summaries(context) : [];
const selections = references.map((reference) => {
const summary = summaries.find((item) => item.handle === reference.handle && item.version === reference.version);
if (!summary) throw fail("permissionDenied", "Selected context changed");
return { title: summary.title, scope: summary.scope, version: summary.version };
});
displayContext = { ...(route.operation === "start" ? await this.broker.describeChat(params.chatHandle, context) : {}), selections };
}
return { ...this.#authorization(route.permission, params),
...(displayContext ? { displayContext } : {}),
...(route.operation === "start" && params.contexts?.length ? { relatedPermissions: params.contexts.map((reference) => (
this.#authorization("context.selected.read", reference)
)) } : {}),
// Open selects a model; start is the meaningful invocation. The
// broker's source-bound handles authorize subsequent stream work.
...(["open", "list", "read", "stop", "close"].includes(route.operation) ? { deferDecision: true } : {}),
};
},
}));
}
@@ -150,8 +169,8 @@ class PluginAIContextService {
await this.#guard(context);
const selected = await this.selected.read(reference, context);
await this.#guard(context);
if (!await this.host.reviewText({ scope: selected.scope, title: selected.title, version: selected.version,
text: selected.text, pluginId: context.pluginId }, context)) throw fail("cancelled", "Selected context sharing was cancelled");
// The selected handle and version are checked on both sides of the read.
// Permission middleware (or the model-turn content check above) owns Ask.
await this.#guard(context);
await this.selected.assertCurrent(reference, context);
return selected;
@@ -22,26 +22,23 @@ function fixture() {
allow: (v) => { allowed = v; }, review: (v) => { reviewed = v; }, current: (v) => { current = v; }, source: (v) => { sourceId = v; }, revoke: () => revoke({ pluginId: context.pluginId }) };
}
test("model invocation independently requests content permission and reviewed text", async (t) => {
test("model invocation independently checks content permission without a duplicate sharing prompt", async (t) => {
const f = fixture(); t.after(() => f.service.shutdown());
const { items: [reference] } = await f.service.list({}, f.context); assert.equal(f.reads(), 0);
const chat = await f.service.open({}, f.context);
f.allow(false);
await assert.rejects(f.service.start({ chatHandle: chat.chatHandle, prompt: "Hi", contexts: [{ handle: reference.handle, version: reference.version }] }, f.context));
assert.equal(f.reads(), 0); assert.equal(f.invoked(), 0);
f.allow(true); f.review(false);
await assert.rejects(f.service.start({ chatHandle: chat.chatHandle, prompt: "Hi", contexts: [{ handle: reference.handle, version: reference.version }] }, f.context));
assert.equal(f.invoked(), 0);
f.review(true);
f.allow(true); f.hostAdapter.reviewText = () => { throw new Error("Duplicate sharing prompt"); };
const turn = await f.service.start({ chatHandle: chat.chatHandle, prompt: "Hi", contexts: [{ handle: reference.handle, version: reference.version }] }, f.context);
assert.equal((await f.service.read(turn, f.context)).text, "Result");
assert.ok(f.authorizations.every((authorization) => authorization.permission === "context.selected.read" && authorization.allowedScopes[0] === "once"));
});
test("source change during host review suppresses text and inference", async (t) => {
test("source change during selected-content read suppresses text and inference", async (t) => {
const f = fixture(); t.after(() => f.service.shutdown());
const { items: [reference] } = await f.service.list({}, f.context); const chat = await f.service.open({}, f.context);
f.hostAdapter.reviewText = async () => { f.source("source-b"); return true; };
f.service.selected.handles.get(reference.handle).readText = async () => { f.source("source-b"); return "Never release"; };
await assert.rejects(f.service.start({ chatHandle: chat.chatHandle, prompt: "Hi", contexts: [{ handle: reference.handle, version: reference.version }] }, f.context));
assert.equal(f.invoked(), 0);
});
@@ -120,6 +120,13 @@ class ModelInvocationBroker {
} finally { this.openings.delete(opening); }
}
async describeChat(chatHandle, context) {
const chat = this.chats.get(chatHandle);
if (!chat) throw fail("permissionDenied", "Plugin chat is unavailable");
await this.#check(chat, context);
return { modelLabel: chat.model.label };
}
async start({ chatHandle, prompt, contexts = [] }, context) {
assertPluginJsonValue({ chatHandle, prompt, contexts }, { maxBytes: this.limits.inputBytes + 2048 });
if (typeof prompt !== "string" || !prompt.trim() || prompt.includes("\0") || !Array.isArray(contexts)
@@ -0,0 +1,162 @@
"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const { RegistryCatalogService } = require("./registryCatalogService.cjs");
const { PluginContributionIconService } = require("./contributionIconService.cjs");
const { MarketSourcesService } = require("./marketSourcesService.cjs");
const { OFFICIAL_SOURCE, LOCAL_SOURCE, thirdPartySource } = require("./sourceIdentity.cjs");
const { catalog, delivery, digest, makeFiles, read } = require("./fixtures/staticDistributionFixture.cjs");
const sourcePng = read(delivery.plugins[0].iconLight.path.slice(1));
const avatar = { path: `/assets/${digest(sourcePng)}.png`, sha256: digest(sourcePng), size: sourcePng.length };
function filesFor(entries = catalog, change = () => {}) {
const files = makeFiles(entries, (index, sidecar) => {
sidecar.schemaVersion = 2;
for (const item of sidecar.plugins) {
item.avatar = structuredClone(avatar);
const entry = entries.find((entry) => entry.id === item.id);
if (entry.artifact) {
item.artifact = { path: `/assets/${entry.artifact.sha256}.ncpkg`, sha256: entry.artifact.sha256, size: 1 };
index.plugins.find((plugin) => plugin.id === item.id).versions[0].distribution = "release";
}
}
change(index, sidecar);
});
files.set(avatar.path, sourcePng);
return files;
}
function imageService(rasterizeIcon) {
return new PluginContributionIconService({ rasterizeIcon: rasterizeIcon ?? (async () => {
const png = Buffer.alloc(24); Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(png);
png.write("IHDR", 12); png.writeUInt32BE(32, 16); png.writeUInt32BE(32, 20); return png;
}) });
}
function registry(options = {}) {
const requests = [];
let files = options.files ?? filesFor();
const service = new RegistryCatalogService({ ...options,
fetch: options.fetch ?? (async (url, init) => {
requests.push(url);
assert.equal(new URL(url).origin, options.source?.origin ?? OFFICIAL_SOURCE.origin);
assert.equal(init.redirect, "manual"); assert.equal(init.credentials, "omit");
return files.has(new URL(url).pathname) ? new Response(files.get(new URL(url).pathname)) : new Response(null, { status: 404 });
}),
resolveAvatar: options.resolveAvatar ?? ((request) => imageServiceSingleton.resolveCatalogAvatar(request)),
});
const imageServiceSingleton = imageService();
return { service, requests, setFiles(value) { files = value; } };
}
test("v2 avatars use verified same-origin bytes and the shared image cache without GitHub", async () => {
const r = registry(); const snapshot = await r.service.list(); assert.equal(snapshot.error, null);
const entry = snapshot.entries[0];
const values = await Promise.all([r.service.author(entry.id, entry.selectionToken), r.service.author(entry.id, entry.selectionToken)]);
assert.deepEqual(values[0], values[1]); assert.match(values[0].avatar, /^data:image\/png;base64,/);
assert.equal(values[0].officialMaintained, true); assert.equal(values[0].author, "Netcatty");
assert.equal(r.requests.filter((url) => new URL(url).pathname === avatar.path).length, 1);
assert.ok(r.requests.every((url) => new URL(url).origin === OFFICIAL_SOURCE.origin));
await r.service.author(entry.id, entry.selectionToken);
assert.equal(r.requests.length, 5, "cached raster avoids another download");
});
test("third-party copies, community entries and local imports cannot acquire maintenance authority", async () => {
const copied = registry({ source: thirdPartySource("Netcatty official", "https://community.example.com") });
const entry = (await copied.service.list()).entries[0];
assert.equal((await copied.service.author(entry.id, entry.selectionToken)).officialMaintained, false);
const community = structuredClone(catalog[0]); community.id = "com.community.official";
community.manifest.id = community.id; community.author = "Netcatty official"; community.manifest.publisher = "netcatty";
const r = registry({ files: filesFor([community]) }); const listed = (await r.service.list()).entries[0];
assert.equal((await r.service.author(listed.id, listed.selectionToken)).officialMaintained, false);
const local = new MarketSourcesService({ database: { getActivePlugin: () => ({ id: catalog[0].id, activeVersion: catalog[0].version,
source: LOCAL_SOURCE, archiveSha256: "a".repeat(64), manifest: catalog[0].manifest, runtime: {} }) } });
assert.equal((await local.author({ kind: "installed", pluginId: catalog[0].id })).officialMaintained, false);
await assert.rejects(local.author({ kind: "installed", pluginId: catalog[0].id, officialMaintained: true }), /Invalid/);
});
test("avatar failure, redirects and mismatched bytes yield a placeholder without another origin", async () => {
for (const kind of ["missing", "hash", "format", "redirect"]) {
const files = filesFor(); const requests = [];
const r = registry({ files, fetch: async (url) => {
requests.push(url); const p = new URL(url).pathname;
if (p === avatar.path) {
if (kind === "redirect") return new Response(null, { status: 302, headers: { location: "https://avatars.githubusercontent.com/u/1" } });
if (kind === "missing") return new Response(null, { status: 404 });
if (kind === "hash") return new Response(Buffer.alloc(sourcePng.length));
}
return new Response(files.get(p));
}, ...(kind === "format" ? { resolveAvatar: async () => { throw new Error("Invalid PNG"); } } : {}) });
const entry = (await r.service.list()).entries[0]; const value = await r.service.author(entry.id, entry.selectionToken);
assert.equal(value.avatar, null, kind); assert.equal(value.officialMaintained, true);
assert.ok(requests.every((url) => new URL(url).origin === OFFICIAL_SOURCE.origin));
}
});
test("avatar schema rejects foreign paths, non-raster formats and invalid sizes before fetching", async () => {
for (const ref of [
{ ...avatar, path: "https://avatars.githubusercontent.com/u/1" },
{ ...avatar, path: `/assets/${avatar.sha256}.svg` },
{ ...avatar, path: `/assets/${"a".repeat(64)}.png` },
{ ...avatar, size: 0 }, { ...avatar, size: 256 * 1024 + 1 }, { ...avatar, size: 1.5 },
]) {
const r = registry({ files: filesFor(catalog, (_index, delivery) => { delivery.plugins[0].avatar = ref; }) });
const result = await r.service.list(); assert.ok(result.error, JSON.stringify(ref));
assert.equal(r.requests.length, 4, "invalid delivery cannot cause an avatar request");
}
});
test("v2 package references enforce the publisher's positive 16MiB bound without installing", async () => {
const entry = structuredClone(catalog[0]);
entry.artifact = { sha256: "a".repeat(64), url: `${OFFICIAL_SOURCE.origin}/assets/${"a".repeat(64)}.ncpkg` };
for (const size of [0, 16 * 1024 * 1024, 16 * 1024 * 1024 + 1]) {
const r = registry({ files: filesFor([entry], (_index, sidecar) => { sidecar.plugins[0].artifact.size = size; }) });
const snapshot = await r.service.list();
assert.equal(Boolean(snapshot.error), size !== 16 * 1024 * 1024);
assert.equal(r.requests.length, 4, "catalog validation never downloads or installs the package");
}
});
test("a changed selection or removed source cannot publish an in-flight avatar result", async () => {
for (const change of ["selection", "source"]) {
let release; let entered; let enabled = true;
const started = new Promise((resolve) => { entered = resolve; });
const gate = new Promise((resolve) => { release = resolve; });
const r = registry({ sourceGuard() { if (!enabled) throw new Error("Source removed"); }, resolveAvatar: async () => { entered(); await gate; return "data:image/png;base64,eA=="; } });
const entry = (await r.service.list()).entries[0]; const pending = r.service.author(entry.id, entry.selectionToken); await started;
if (change === "selection") { r.setFiles(filesFor(catalog, (_i, sidecar) => { sidecar.plugins[0].avatar = null; })); await r.service.refresh(); }
else enabled = false;
release(); await assert.rejects(pending, /changed|removed/);
}
});
test("installed presentation requires exact source/version/package/manifest and rejects replacement during load", async () => {
const entry = structuredClone(catalog[0]); entry.artifact = { sha256: "a".repeat(64), url: `${OFFICIAL_SOURCE.origin}/assets/${"a".repeat(64)}.ncpkg` };
let plugin = { id: entry.id, activeVersion: entry.version, archiveSha256: entry.artifact.sha256, source: OFFICIAL_SOURCE, manifest: entry.manifest, runtime: {} };
const requests = []; const files = filesFor([entry]);
const database = { getActivePlugin: () => plugin, db: { prepare: () => ({ get: () => undefined }) } };
const service = new MarketSourcesService({ database, fetch: async (url) => { requests.push(url); return new Response(files.get(new URL(url).pathname)); } });
const query = { kind: "installed", pluginId: entry.id };
assert.equal((await service.author(query)).officialMaintained, false); assert.equal(requests.length, 0);
await service.list(); assert.equal((await service.author(query)).officialMaintained, true);
for (const patch of [{ activeVersion: "9.0.0" }, { archiveSha256: "b".repeat(64) }, { manifest: { ...entry.manifest, publisher: "other" } }, { source: LOCAL_SOURCE }]) {
const saved = plugin; plugin = { ...plugin, ...patch };
assert.equal((await service.author(query)).officialMaintained, false); plugin = saved;
}
let release; let entered;
const started = new Promise((resolve) => { entered = resolve; });
service.catalogs.get("official").resolveAvatar = async () => { entered(); await new Promise((resolve) => { release = resolve; }); return null; };
const pending = service.author(query); await started; plugin = { ...plugin, archiveSha256: "b".repeat(64) }; release();
await assert.rejects(pending, /Installed plugin changed/);
});
test("avatar decoding validates bytes and uses the existing bounded rasterizer", async () => {
let calls = 0;
const service = imageService(async () => { calls++; throw new Error("Decode failed"); });
const request = { sourceId: "official", reference: avatar, read: async () => sourcePng };
await assert.rejects(service.resolveCatalogAvatar(request), /Decode failed/); assert.equal(calls, 1);
await assert.rejects(service.resolveCatalogAvatar({ ...request, read: async () => Buffer.alloc(sourcePng.length) }), /bytes/); assert.equal(calls, 1);
await assert.rejects(service.resolveCatalogAvatar({ ...request, reference: { ...avatar, path: `/assets/${avatar.sha256}.webp` } }), /format|signature/); assert.equal(calls, 1);
const cached = imageService();
await cached.resolveCatalogAvatar(request);
await assert.rejects(cached.resolveCatalogAvatar({ ...request, reference: { ...avatar, size: avatar.size + 1 } }), /bytes/);
await assert.rejects(cached.resolveCatalogAvatar({ ...request, reference: { ...avatar, path: `/assets/${avatar.sha256}.webp` } }), /format|signature/);
});
@@ -110,6 +110,7 @@ export default { activate(context) {
await buildPluginPackage(packageRoot, archive);
await service.manager.install(archive, { enable: true });
const run = (name) => service.contributionService.executeCommand(`${id}.${name}`);
service.permissionEngine.setMode({ id, manifest }, "network.stream", "ask");
await assert.rejects(run("run"), /denied/u);
assert.equal(service.byteStreamService.broker.connections.size, 0);
allow = true;
@@ -1,6 +1,7 @@
"use strict";
const path = require("node:path");
const { createHash } = require("node:crypto");
const { readContainedFile } = require("./pluginProtocol.cjs");
const { createIsolatedContributionIconRasterizer } = require("./contributionIconRasterizer.cjs");
@@ -214,6 +215,35 @@ class PluginContributionIconService {
return pending;
}
// Called only with a host-selected, hash-bound registry reference. It shares
// the existing decoder, queue, cache and pending work with package icons.
async resolveCatalogAvatar({ sourceId, reference, read }) {
const key = JSON.stringify(["catalog-avatar", sourceId, reference.path, reference.sha256, reference.size]);
if (this.cache.has(key)) return this.cache.get(key);
if (this.pending.has(key)) return this.pending.get(key);
if (this.pending.size >= MAX_QUEUED_ICON_RASTERIZATIONS + MAX_CONCURRENT_ICON_RASTERIZATIONS) {
throw new Error("Plugin image queue is full");
}
const pending = (async () => {
const body = await read();
if (!Buffer.isBuffer(body) || body.length !== reference.size || body.length > 256 * 1024
|| createHash("sha256").update(body).digest("hex") !== reference.sha256) throw new Error("Invalid plugin avatar bytes");
const extension = path.extname(reference.path);
if (![".png", ".webp"].includes(extension)) throw new Error("Invalid plugin avatar format");
const inspected = inspectContributionIconSource(body, extension);
if (inspected.mimeType !== (extension === ".png" ? "image/png" : "image/webp")) throw new Error("Plugin avatar format mismatch");
const png = await this.rasterizeIcon({ body, ...inspected, maxEdge: MAX_ICON_EDGE });
if (!png.length || png.length > MAX_ICON_PNG_BYTES) throw new Error("Plugin avatar output is too large");
inspectContributionIconSource(png, ".png", MAX_ICON_EDGE);
const value = `data:image/png;base64,${png.toString("base64")}`;
if (this.cache.size >= 256) this.cache.clear();
this.cache.set(key, value);
return value;
})().finally(() => this.pending.delete(key));
this.pending.set(key, pending);
return pending;
}
async #resolveUncached({ pluginId, plugin, icon, cacheKey }) {
const packageRoot = await this.packageStore.preparePackageRoot(plugin);
const result = Object.freeze({
+20
View File
@@ -335,6 +335,7 @@ class PluginDatabase {
for (const table of ["plugin_settings", "plugin_view_state", "plugin_permission_grants", "plugin_secrets", "plugin_sync_sidecars", "plugin_sync_provider_bindings"]) {
this.db.prepare(`DELETE FROM ${table} WHERE plugin_id = ? OR plugin_id = ?`).run(owner, pluginId);
}
this.db.prepare("DELETE FROM plugin_host_preferences WHERE key LIKE ?").run(`permission:${owner}:%`);
this.db.prepare("DELETE FROM plugin_source_bindings WHERE plugin_id = ?").run(pluginId);
});
}
@@ -1170,6 +1171,25 @@ class PluginDatabase {
`).run(pluginId, pluginId);
}
// Host-owned policy preferences are deliberately separate from plugin-writable
// settings. Source ownership is stable across package versions; grants are not.
getPermissionMode(pluginId, permission) {
const key = `permission:${this.privateOwner(pluginId)}:${permission}`;
const row = this.db.prepare("SELECT value_json FROM plugin_host_preferences WHERE key = ?").get(key);
const mode = row ? parseJson(row.value_json, "permission mode") : "allow";
if (!["allow", "ask", "deny"].includes(mode)) throw new Error("Corrupt plugin permission mode");
return mode;
}
setPermissionMode(pluginId, permission, mode) {
const key = `permission:${this.privateOwner(pluginId)}:${permission}`;
this.transaction(() => {
this.db.prepare("INSERT INTO plugin_host_preferences(key,value_json,updated_at) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET value_json=excluded.value_json,updated_at=excluded.updated_at")
.run(key, JSON.stringify(mode), this.clock());
this.#appendSecurityAudit(pluginId, "permission.policy-edited", JSON.stringify({ permission, mode, sourceOwner: this.privateOwner(pluginId) }));
});
}
getHostThemeSelection() {
const row = this.db.prepare("SELECT value_json FROM plugin_host_preferences WHERE key = 'theme'").get();
return row ? parseJson(row.value_json, "host theme selection") : {formatVersion: 1, revision: 0, light: null, dark: null};
+9
View File
@@ -14,3 +14,12 @@ The fixture includes no executable plugin package, avatar or credentials.
Schema revisions must be coordinated with the registry publisher. In particular,
artifact/avatar are deliberately null in v1; do not expand this consumer alone.
`delivery-v2.schema.json` is vendored without changes from
`binaricat/netcatty-plugins@2ffed31ad6a430e3711a63a902305063bd2504f8`,
`schema/delivery-v2.schema.json` (Git blob
`7a57504fbea272ca0e873725e050d1f15352cb5b`). The v2 consumer retains the pinned v1
schema and permits positive-size package references up to 16MiB and PNG/WebP avatar references.
Avatar references require positive size up to 256KiB and exact content-addressed
paths. No v3 path is added. The original bootstrap bytes remain unchanged, and
client support does not publish or activate live metadata.
@@ -0,0 +1,222 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Netcatty static delivery v2 (reviewed avatars and packages)",
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"registryCommit",
"plugins",
"catalogSha256",
"indexSha256",
"sourceLockSha256",
"builderSha256"
],
"properties": {
"schemaVersion": {
"const": 2
},
"registryCommit": {
"type": "string",
"pattern": "^[a-f0-9]{40}$"
},
"plugins": {
"type": "array",
"maxItems": 1000,
"items": {
"type": "object",
"additionalProperties": false,
"required": [
"id",
"version",
"repository",
"commit",
"readme",
"iconLight",
"iconDark",
"avatar",
"artifact"
],
"properties": {
"id": {
"type": "string"
},
"version": {
"type": "string"
},
"repository": {
"type": "string"
},
"commit": {
"type": "string",
"pattern": "^[a-f0-9]{40}$"
},
"readme": {
"type": "object",
"additionalProperties": false,
"required": [
"path",
"sha256",
"size"
],
"properties": {
"path": {
"type": "string",
"pattern": "^/assets/[a-f0-9]{64}\\.(md|png|webp|ncpkg)$"
},
"sha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"size": {
"type": "integer",
"minimum": 0,
"maximum": 262144
}
}
},
"iconLight": {
"oneOf": [
{
"type": "null"
},
{
"type": "object",
"additionalProperties": false,
"required": [
"path",
"sha256",
"size"
],
"properties": {
"path": {
"type": "string",
"pattern": "^/assets/[a-f0-9]{64}\\.(md|png|webp|ncpkg)$"
},
"sha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"size": {
"type": "integer",
"minimum": 0,
"maximum": 262144
}
}
}
]
},
"iconDark": {
"oneOf": [
{
"type": "null"
},
{
"type": "object",
"additionalProperties": false,
"required": [
"path",
"sha256",
"size"
],
"properties": {
"path": {
"type": "string",
"pattern": "^/assets/[a-f0-9]{64}\\.(md|png|webp|ncpkg)$"
},
"sha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"size": {
"type": "integer",
"minimum": 0,
"maximum": 262144
}
}
}
]
},
"avatar": {
"oneOf": [
{
"type": "null"
},
{
"type": "object",
"additionalProperties": false,
"required": [
"path",
"sha256",
"size"
],
"properties": {
"path": {
"type": "string",
"pattern": "^/assets/[a-f0-9]{64}\\.(png|webp)$"
},
"sha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"size": {
"type": "integer",
"minimum": 1,
"maximum": 262144
}
}
}
]
},
"artifact": {
"oneOf": [
{
"type": "null"
},
{
"type": "object",
"additionalProperties": false,
"required": [
"path",
"sha256",
"size"
],
"properties": {
"path": {
"type": "string",
"pattern": "^/assets/[a-f0-9]{64}\\.ncpkg$"
},
"sha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"size": {
"type": "integer",
"minimum": 1,
"maximum": 16777216
}
}
}
]
}
}
}
},
"catalogSha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"indexSha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"sourceLockSha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"builderSha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
}
}
}
+3 -9
View File
@@ -16,14 +16,7 @@ ajv.addSchema(require("./generated/plugin-contract.schema.json"));
const validateIndex = ajv.compile(require("./distribution/index.schema.json"));
const deliverySchema = require("./distribution/delivery.schema.json");
const validateDelivery = ajv.compile(deliverySchema);
const deliveryV2 = structuredClone(deliverySchema);
deliveryV2.title = "Netcatty static delivery v2 (hash-bound packages)";
deliveryV2.properties.schemaVersion.const = 2;
const packageRef = structuredClone(deliveryV2.properties.plugins.items.properties.readme);
packageRef.properties.path.pattern = "^/assets/[a-f0-9]{64}\\.ncpkg$";
packageRef.properties.size.maximum = 32 * 1024 * 1024;
deliveryV2.properties.plugins.items.properties.artifact = { oneOf: [{ type: "null" }, packageRef] };
const validateDeliveryV2 = ajv.compile(deliveryV2);
const validateDeliveryV2 = ajv.compile(require("./distribution/delivery-v2.schema.json"));
const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
const tuple = (entry) => JSON.stringify([entry.id, entry.version, entry.repository, entry.commit]);
@@ -101,9 +94,10 @@ function validateSet(pointer, entries, index, delivery, origin = DISTRIBUTION_OR
if (!catalogTuples.has(key) || resources.has(key)) throw new Error("Delivery identity does not match catalog tuple");
assertAsset(plugin.readme, ["md"]);
for (const icon of [plugin.iconLight, plugin.iconDark]) if (icon !== null) assertAsset(icon, ["png", "webp"]);
if (plugin.avatar !== null) assertAsset(plugin.avatar, ["png", "webp"]);
const entry = entries.find((item) => tuple(item) === key);
if (plugin.artifact !== null) {
assertReference(plugin.artifact, `/assets/${plugin.artifact.sha256}.ncpkg`, 32 * 1024 * 1024);
assertReference(plugin.artifact, `/assets/${plugin.artifact.sha256}.ncpkg`, 16 * 1024 * 1024);
if (!entry.artifact || entry.artifact.sha256 !== plugin.artifact.sha256 || entry.artifact.url !== `${origin}${plugin.artifact.path}`) throw new Error("Package delivery does not match catalog hash and source");
} else if (entry.artifact) throw new Error("Catalog package has no delivery resource");
resources.set(key, plugin);
+7 -7
View File
@@ -207,6 +207,12 @@ class PluginFilesystemBroker {
};
}
validatePath(params) { return assertPathParams(params); }
validateDirectory(params) {
if (typeof this.openDirectoryHandle !== "function") {
throw new PluginRpcError(RPC_ERRORS.unsupported, "Secure plugin directory enumeration is unavailable on this runtime");
}
return assertPathParams(params);
}
describeReadAuthorization(params, resourceKind = "exact") {
const value = assertPathParams(params);
@@ -329,17 +335,11 @@ class PluginFilesystemBroker {
}
async readDirectory(params, context) {
const value = assertPathParams(params);
const value = this.validateDirectory(params);
assertAuthorizedPath(context, "filesystem.read", value.path);
const { canonical, stats } = await resolveExistingPath(value.path, this.fileSystem);
assertAuthorizedPath(context, "filesystem.read", canonical);
if (!stats.isDirectory()) throw invalidArgument("Plugin filesystem directory target is not a directory");
if (!this.openDirectoryHandle) {
throw new PluginRpcError(
RPC_ERRORS.unsupported,
"Secure plugin directory enumeration is unavailable on this runtime",
);
}
const directory = await this.openDirectoryHandle(canonical, { signal: context.signal });
if (
!directory
@@ -1099,6 +1099,13 @@
"request"
],
"properties": {
"permissionMode": {
"enum": [
"allow",
"ask",
"deny"
]
},
"requestId": {
"type": "string",
"maxLength": 128
@@ -5774,6 +5781,76 @@
"$ref": "#/$defs/PermissionResourceKind"
}
},
"displayContext": {
"type": "object",
"additionalProperties": false,
"properties": {
"modelLabel": {
"type": "string",
"minLength": 1,
"maxLength": 160
},
"selections": {
"type": "array",
"maxItems": 5,
"items": {
"type": "object",
"required": [
"title",
"scope",
"version"
],
"additionalProperties": false,
"properties": {
"title": {
"type": "string",
"maxLength": 160
},
"scope": {
"enum": [
"workspace",
"tab",
"session",
"host",
"note"
]
},
"version": {
"type": "string",
"minLength": 1,
"maxLength": 128
}
}
}
}
}
},
"relatedPermissions": {
"type": "array",
"maxItems": 5,
"items": {
"type": "object",
"required": [
"permission",
"resources"
],
"properties": {
"permission": {
"$ref": "#/$defs/PluginPermission"
},
"resources": {
"type": "array",
"minItems": 1,
"maxItems": 128,
"uniqueItems": true,
"items": {
"$ref": "#/$defs/PermissionResource"
}
}
},
"additionalProperties": false
}
},
"reason": {
"type": "string",
"minLength": 1,
@@ -7081,6 +7158,9 @@
"TerminalInputDraftFeature": {
"const": "terminal.input-drafts"
},
"FilesystemDirectoryEnumerationFeature": {
"const": "filesystem.directory-enumeration"
},
"HostTerminalInputProposalRequest": {
"type": "object",
"required": [
@@ -57,8 +57,7 @@ for (const source of ["compose", "share"]) test(`normal browser example complete
const output = source === "compose" ? "synthetic output" : "SYNTHETIC PRIVATE TEXT";
assert.deepEqual(result, { copied: true, characters: output.length });
assert.deepEqual(copied, [output]); assert.equal(reads, source === "share" ? 1 : 0);
assert.ok(requests.includes("ui.interact")); assert.ok(requests.includes("clipboard.write"));
assert.equal(requests.includes("clipboard.read"), source === "share");
assert.deepEqual(requests, [], "Allow mode has only the real choice/input workflows");
assert.equal(JSON.stringify(audit).includes("synthetic private text"), false);
assert.equal(JSON.stringify(audit).includes("synthetic output"), false);
assert.equal(service.pending.size, 0);
@@ -71,7 +70,7 @@ test("outer command deadline closes its real browser clipboard confirmation and
const manifest = JSON.parse(await readFile(new URL("../../examples/plugins/host-interactions/netcatty.plugin.json", pathToFileURL(__filename)), "utf8"));
const identity = { pluginId: manifest.id, pluginVersion: manifest.version, runtimeId: "runtime-deadline", runtimeKind: "browser" };
const writes = [], messages = [];
const database = { listPermissionGrants: () => [], recordSecurityAudit() {},
const database = { getPermissionMode: () => "ask", listPermissionGrants: () => [], recordSecurityAudit() {},
listPlugins: () => [{ id: manifest.id, activeVersion: manifest.version, manifest, enabled: true, runtime: { status: "running" } }],
};
const engine = new PluginPermissionEngine({ database, requestDecision: async (request) => ({ requestId: request.requestId, decision: "allow", scope: "once" }) });
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more