mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-10-30 18:32:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4eb33856b | ||
|
|
b14b65679f | ||
|
|
0c05a96fa1 | ||
|
|
da16b90e9e | ||
|
|
d40b0d3c25 | ||
|
|
714e2397a4 | ||
|
|
c4aedfa9ed | ||
|
|
1551fa8355 | ||
|
|
a0cf2b487c | ||
|
|
e3e2dcfe02 |
No files matched your search
@@ -27,7 +27,6 @@ import { AppHostTreeLayer } from './AppHostTreeLayer';
|
||||
import { AppHostEditorLayer } from './AppHostEditorLayer';
|
||||
import { AppPluginKeybindingHost } from './AppPluginKeybindingHost';
|
||||
import { PluginAIContextHost } from '../../components/plugins/PluginAIContextHost';
|
||||
import { PluginAgentHost } from '../../components/plugins/PluginAgentHost';
|
||||
import { shouldOpenHostEditOnWorkSurface } from './workTabSurface';
|
||||
import { useConnectionLogsStore } from '../state/connectionLogsStore';
|
||||
import {
|
||||
@@ -859,7 +858,6 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
workspaces={workspaces}
|
||||
/>
|
||||
<PluginAIContextHost sessions={sessions} workspaces={workspaces} />
|
||||
<PluginAgentHost sessions={sessions} />
|
||||
</div>
|
||||
|
||||
{/* Global "quick add / edit snippet" modal, triggered by the
|
||||
|
||||
@@ -1262,6 +1262,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.",
|
||||
@@ -1419,7 +1421,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',
|
||||
|
||||
@@ -1261,6 +1261,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.",
|
||||
@@ -1419,7 +1421,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',
|
||||
|
||||
@@ -1130,6 +1130,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": "Импортированные пакеты отключены до проверки и включения.",
|
||||
@@ -1284,7 +1286,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
|
||||
|
||||
@@ -1177,6 +1177,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": "导入本地插件包以开始使用。",
|
||||
@@ -1334,7 +1336,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': '确认连接',
|
||||
|
||||
@@ -1179,6 +1179,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": "導入的插件保持停用,請檢查後再啟用。",
|
||||
@@ -1337,7 +1339,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': '確認連線',
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { TerminalSession } from '../../domain/models';
|
||||
import type { PluginAgentHostTerminal } from '@netcatty/plugin-contract';
|
||||
import { createTrustedPluginAgentRuntime } from '../../infrastructure/ai/pluginAgent/trustedAgentRuntime';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { getAppAppLockRuntime } from './appRuntimeBridge';
|
||||
import { LOCAL_STORAGE_ADAPTER_CHANGED_EVENT } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import { STORAGE_KEY_AI_PROVIDERS, STORAGE_KEY_AI_ACTIVE_PROVIDER, STORAGE_KEY_AI_ACTIVE_MODEL, STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP, STORAGE_KEY_AI_EXTERNAL_AGENTS } from '../../infrastructure/config/storageKeys';
|
||||
|
||||
type Choice = { items: PluginAgentHostTerminal[]; confirm: (ids: string[]) => void; cancel: () => void };
|
||||
|
||||
// All inventory remains in trusted application UI. Only confirmed metadata is
|
||||
// passed to the main-owned worker bindings; focus never determines a target.
|
||||
export function usePluginAgentHost(sessions: TerminalSession[]) {
|
||||
const latest = useRef(sessions); latest.current = sessions;
|
||||
const [choice, setChoice] = useState<Choice | null>(null);
|
||||
useEffect(() => {
|
||||
const api = netcattyBridge.get();
|
||||
if (!api?.onPluginAgentHostRequest || !api.setPluginAgentHostReady || !api.respondPluginAgentHost) return;
|
||||
const bridge = { subscribe: api.onPluginAgentHostRequest.bind(api), ready: api.setPluginAgentHostReady.bind(api), respond: api.respondPluginAgentHost.bind(api) };
|
||||
let mounted = true;
|
||||
let chooser: { runtimeId: string; cancel: () => void } | null = null;
|
||||
const requests = new Map<string, { runtimeId: string; controller: AbortController }>();
|
||||
const runtime = createTrustedPluginAgentRuntime({
|
||||
isActive: () => mounted && document.visibilityState === 'visible' && getAppAppLockRuntime()?.locked === false,
|
||||
chooseTargets: (signal, runtimeId) => new Promise((resolve, reject) => {
|
||||
if (chooser) { reject(Error('A target selection is already pending')); return; }
|
||||
const items = latest.current.filter((item) => item.status === 'connected').map((item) => ({
|
||||
sessionId: item.id, hostId: item.hostId, hostname: (item.hostname || '').slice(0, 253),
|
||||
label: (item.customName || item.hostLabel || item.id).slice(0, 160),
|
||||
...(item.protocol ? { protocol: item.protocol } : {}), ...(item.username ? { username: item.username.slice(0, 160) } : {}), connected: true,
|
||||
}));
|
||||
const finish = (ids: string[] | null) => {
|
||||
if (chooser?.cancel !== cancel) return;
|
||||
chooser = null; signal.removeEventListener('abort', cancel); setChoice(null);
|
||||
if (ids === null || signal.aborted || ids.length > 32 || new Set(ids).size !== ids.length) { reject(Error('Target selection cancelled')); return; }
|
||||
const selected = ids.map((id) => items.find((item) => item.sessionId === id));
|
||||
if (selected.some((item) => !item || !latest.current.some((session) => session.id === item.sessionId && session.status === 'connected'))) {
|
||||
reject(Error('Selected terminal is no longer connected')); return;
|
||||
}
|
||||
resolve(selected as PluginAgentHostTerminal[]);
|
||||
};
|
||||
const cancel = () => finish(null);
|
||||
chooser = { runtimeId, cancel }; signal.addEventListener('abort', cancel, { once: true });
|
||||
setChoice({ items, confirm: finish, cancel });
|
||||
if (signal.aborted) cancel();
|
||||
}),
|
||||
});
|
||||
const unsubscribe = bridge.subscribe((request) => {
|
||||
if (request.kind === 'request.cancel') {
|
||||
const pending = requests.get(request.payload.requestId);
|
||||
if (pending?.runtimeId === request.runtimeId) pending.controller.abort();
|
||||
runtime.cancelRequest(request.payload.requestId, request.runtimeId); return;
|
||||
}
|
||||
if (request.kind === 'runtime.release') {
|
||||
for (const item of requests.values()) if (item.runtimeId === request.runtimeId) item.controller.abort();
|
||||
if (chooser?.runtimeId === request.runtimeId) chooser.cancel();
|
||||
runtime.releaseRuntime(request.runtimeId); return;
|
||||
}
|
||||
if (request.kind === 'agent.close') { runtime.releaseChat(request.payload.chatSessionId, request.runtimeId); return; }
|
||||
if (requests.has(request.requestId) || requests.size >= 64) return;
|
||||
const controller = new AbortController(); requests.set(request.requestId, { runtimeId: request.runtimeId, controller });
|
||||
void runtime.handle(request, controller.signal).then(
|
||||
(result) => bridge.respond({ requestId: request.requestId, actionToken: request.actionToken, result }).catch(() =>
|
||||
bridge.respond({ requestId: request.requestId, actionToken: request.actionToken, error: true })),
|
||||
() => bridge.respond({ requestId: request.requestId, actionToken: request.actionToken, error: true }),
|
||||
).catch(() => {}).finally(() => requests.delete(request.requestId));
|
||||
});
|
||||
const pageHide = () => { runtime.shutdown(); for (const item of requests.values()) item.controller.abort(); };
|
||||
const configurationKeys = new Set([STORAGE_KEY_AI_PROVIDERS, STORAGE_KEY_AI_ACTIVE_PROVIDER, STORAGE_KEY_AI_ACTIVE_MODEL,
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP, STORAGE_KEY_AI_AGENT_PROVIDER_MAP, STORAGE_KEY_AI_EXTERNAL_AGENTS]);
|
||||
const configurationChanged = (event: Event) => {
|
||||
const key = event.type === 'storage' ? (event as StorageEvent).key : (event as CustomEvent<{ key: string }>).detail?.key;
|
||||
if (key === null || (key && configurationKeys.has(key))) runtime.invalidateConfiguration();
|
||||
};
|
||||
window.addEventListener('pagehide', pageHide);
|
||||
window.addEventListener('storage', configurationChanged); window.addEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, configurationChanged);
|
||||
void bridge.ready(true).catch(() => {});
|
||||
return () => {
|
||||
mounted = false; chooser?.cancel(); unsubscribe(); window.removeEventListener('pagehide', pageHide);
|
||||
window.removeEventListener('storage', configurationChanged); window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, configurationChanged);
|
||||
for (const item of requests.values()) item.controller.abort(); requests.clear(); runtime.shutdown();
|
||||
void bridge.ready(false).catch(() => {});
|
||||
};
|
||||
}, []);
|
||||
return { choice };
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { createRequire } from 'node:module';
|
||||
import { EventEmitter, once } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
test('installed global Chat UI reuses actual Catty runtime, configured HTTP transport and selected worker dispatch', { timeout: 30_000 }, async () => {
|
||||
// This Node/JSDOM harness proves installed app wiring, not a native sandbox or
|
||||
// real model/Claude acceptance. No real shell, remote host or credentials.
|
||||
const rootPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'netcatty-global-agent-ui-'));
|
||||
const oldTmp = process.env.TMPDIR; process.env.TMPDIR = directory;
|
||||
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', 'DocumentFragment']) install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
install('localStorage', dom.window.localStorage); 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 { PluginAgentHost } = await import('./plugins/PluginAgentHost');
|
||||
const { I18nProvider } = await import('../application/i18n/I18nProvider');
|
||||
const { registerAppAppLockRuntime, getAppAppLockRuntime } = await import('../application/state/appRuntimeBridge');
|
||||
const keys = await import('../infrastructure/config/storageKeys');
|
||||
const { createGlobalAgentProviderFixture } = await import('../scripts/plugin-global-agent-provider-fixture.mjs');
|
||||
const { createPluginHostService } = require('../electron/plugins/hostService.cjs');
|
||||
const { inProcessBrowserRuntime } = require('../electron/plugins/fixtures/inProcessBrowserRuntime.cjs');
|
||||
const { createPreloadApi } = require('../electron/preload/api.cjs');
|
||||
const { registerProviderHandlers } = require('../electron/bridges/aiBridge/providerHandlers.cjs');
|
||||
const { registerCattyExecHandlers } = require('../electron/bridges/aiBridge/cattyExecHandlers.cjs');
|
||||
const { registerAgentProcessHandlers } = require('../electron/bridges/aiBridge/agentProcessHandlers.cjs');
|
||||
const { registerPrivacyHandlers } = require('../electron/bridges/aiBridge/privacyHandlers.cjs');
|
||||
const aiBridge = require('../electron/bridges/aiBridge.cjs'); const mcp = require('../electron/bridges/mcpServerBridge.cjs');
|
||||
const privacy = require('../electron/shared/aiPrivacyService.cjs');
|
||||
const { server, counts } = createGlobalAgentProviderFixture({ delayMs: 30 });
|
||||
const oldLock = getAppAppLockRuntime(); const root = createRoot(document.getElementById('root')!);
|
||||
let service: ReturnType<typeof createPluginHostService> | undefined; let panel: JSDOM | undefined;
|
||||
const errors: string[] = []; const originalError = console.error;
|
||||
let phase = 'setup';
|
||||
// Flush the known Node sqlite import warning before observing safe categories.
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
console.error = (value: unknown) => { errors.push(`${phase}:${typeof value === 'string' && value === '[Plugin Agent] Turn unavailable' ? 'DELEGATED_TURN_UNAVAILABLE' : typeof value === 'string' && /not wrapped in act/.test(value) ? 'REACT_ACT_WARNING' : 'SDK_OR_RENDERER_ERROR'}`); };
|
||||
try {
|
||||
privacy.configure({ enabled: false }); server.listen(0, '127.0.0.1'); await once(server, 'listening');
|
||||
const address = server.address(); assert.ok(address && typeof address !== 'string'); const endpoint = `http://127.0.0.1:${address.port}/v1`;
|
||||
const handlers = new Map<string, (...args: unknown[]) => unknown>();
|
||||
const ipcMain = { handle: (name: string, handler: (...args: unknown[]) => unknown) => handlers.set(name, handler), removeHandler: (name: string) => handlers.delete(name) };
|
||||
const ipcRenderer = new EventEmitter() as EventEmitter & { invoke: (channel: string, payload: unknown) => Promise<unknown> };
|
||||
const trustedReplies: unknown[] = []; const pluginReplies: unknown[] = []; const workerCalls: string[] = [];
|
||||
const sender = Object.assign(new EventEmitter(), { id: 7, isDestroyed: () => false, send: (channel: string, payload: unknown) => ipcRenderer.emit(channel, {}, structuredClone(payload)) });
|
||||
const mainWindow = Object.assign(new EventEmitter(), { webContents: sender, isDestroyed: () => false, isVisible: () => true, isFocused: () => true });
|
||||
const owner = (id: string) => id === 'synthetic-a' ? 7 : id === 'synthetic-b' ? 8 : null;
|
||||
const worker = { getSessionOwnerWebContentsId: owner, getPluginSessionBinding: (id: string, actual: number) => actual === owner(id) ? { epoch: 'fixture-worker', generation: id === 'synthetic-a' ? 1 : 2 } : null,
|
||||
send: () => {}, request: async (method: string, payload: { sessionId: string }, options?: { beforeExecute?: () => void }) => {
|
||||
options?.beforeExecute?.(); if (method === 'netcatty:ai:exec') { workerCalls.push(payload.sessionId); return { ok: true, stdout: 'Synthetic worker output', stderr: '', exitCode: 0 }; } return [];
|
||||
} };
|
||||
mcp.init({ sessions: new Map(), terminalWorkerManager: worker, cliDiscoveryFilePath: path.join(directory, 'discovery.json') }); mcp.setPermissionMode('observer');
|
||||
const common = { ipcMain, validateSender: (event: { sender: unknown }) => event.sender === sender,
|
||||
validateSenderOrSettings: (event: { sender: unknown }) => event.sender === sender, mcpServerBridge: mcp, aiPrivacyService: privacy };
|
||||
const providerContext = { ...common, require: createRequire(path.join(rootPath, 'electron/bridges/aiBridge.cjs')),
|
||||
providerConfigs: [] as Array<{ id: string; baseURL?: string; apiKey?: string }>, webSearchApiHost: null,
|
||||
injectApiKeyIntoRequest: (url: string, headers: Record<string, string>, providerId: string) => {
|
||||
const provider = providerContext.providerConfigs.find((entry) => entry.id === providerId);
|
||||
return { url, headers: Object.fromEntries(Object.entries(headers).map(([key, value]) => [key, value.replace('__IPC_SECURED__', provider?.apiKey ?? '')])) };
|
||||
}, shouldSkipTLSVerify: () => false, streamRequest: aiBridge._streamRequestForTests,
|
||||
// The production stream function owns this map. Turn release below uses
|
||||
// its actual main lease; direct SDK abort still calls the ordinary route.
|
||||
activeStreams: new Map() };
|
||||
registerProviderHandlers(providerContext); registerCattyExecHandlers(common); registerAgentProcessHandlers(common); registerPrivacyHandlers(common);
|
||||
ipcRenderer.invoke = async (channel, payload) => {
|
||||
if (channel === 'netcatty:ai:chat:stream') {
|
||||
const request = payload as { requestId: string; url: string }; assert.equal(new URL(request.url).origin, new URL(endpoint).origin);
|
||||
assert.match(request.requestId, /^agent-model_/);
|
||||
}
|
||||
const handler = handlers.get(channel); assert.ok(handler, `Unexpected trusted IPC: ${channel}`);
|
||||
const result = await handler({ sender }, structuredClone(payload));
|
||||
if (channel === 'netcatty:plugins:agent-host-response') trustedReplies.push(payload);
|
||||
return result;
|
||||
};
|
||||
const api = createPreloadApi({ ipcRenderer, webUtils: {} }); Object.defineProperty(dom.window, 'netcatty', { value: api });
|
||||
registerAppAppLockRuntime({ locked: false } as NonNullable<ReturnType<typeof getAppAppLockRuntime>>);
|
||||
dom.window.localStorage.setItem(keys.STORAGE_KEY_AI_PROVIDERS, JSON.stringify([{ id: 'fixture-provider', name: 'Synthetic fixture', providerId: 'custom', enabled: true,
|
||||
baseURL: endpoint, defaultModel: 'global-agent-fixture', apiKey: 'FIXTURE_ONLY_API_MARKER' }]));
|
||||
dom.window.localStorage.setItem(keys.STORAGE_KEY_AI_ACTIVE_PROVIDER, 'fixture-provider');
|
||||
service = createPluginHostService({ app: { getAppPath: () => rootPath, getPath: () => directory, getVersion: () => '0.0.0' }, env: {},
|
||||
electron: { ipcMain }, getInteractionWindow: () => mainWindow, isAppLocked: () => false, getTerminalWorkerManager: () => worker });
|
||||
service.runtimeSupervisor.runtimeFactories.browser = inProcessBrowserRuntime; await service.manager.initialize();
|
||||
const sample = path.join(rootPath, 'examples/plugins/global-agent'); const staging = path.join(directory, 'package'); fs.mkdirSync(path.join(staging, 'dist'), { recursive: true });
|
||||
for (const file of ['netcatty.plugin.json', 'panel.html', 'panel.css', 'panel.js', 'README.md']) fs.copyFileSync(path.join(sample, file), path.join(staging, file));
|
||||
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(directory, 'global-agent.ncpkg'); await buildPluginPackage(staging, archive);
|
||||
await service.manager.install(archive, { enable: true });
|
||||
await act(async () => root.render(<I18nProvider locale="en"><PluginAgentHost sessions={[
|
||||
{ id: 'synthetic-a', hostId: 'host-a', hostLabel: 'Workspace A fixture', hostname: 'a.invalid', username: 'fixture', status: 'connected' },
|
||||
{ id: 'synthetic-b', hostId: 'host-b', hostLabel: 'Workspace B fixture', hostname: 'b.invalid', username: 'fixture', status: 'connected' },
|
||||
]} /></I18nProvider>));
|
||||
const waitFor = async (condition: () => boolean) => { const until = Date.now() + 8_000; while (!condition()) {
|
||||
if (Date.now() >= until) throw Error(`Global Agent UI fixture timed out; accepted=${counts.requests}, rejected=${counts.rejected}, effects=${workerCalls.length}, status=${panel?.window.document.getElementById('status')?.textContent}`);
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 5)); });
|
||||
} };
|
||||
panel = new JSDOM(fs.readFileSync(path.join(sample, 'panel.html'), 'utf8'), { runScripts: 'outside-only' });
|
||||
Object.defineProperty(panel.window, 'netcattyView', { value: { executeCommand: async (name: string, params: unknown) => {
|
||||
const result = structuredClone(await service!.contributionService.executeCommand(name, structuredClone(params))); pluginReplies.push(result); return result;
|
||||
}, onDidReceiveMessage: () => ({ dispose() {} }), onDidChangeEnvironment: () => ({ dispose() {} }) } });
|
||||
await act(async () => panel!.window.eval(fs.readFileSync(path.join(sample, 'panel.js'), 'utf8')));
|
||||
const element = (id: string) => panel!.window.document.getElementById(id)!;
|
||||
await waitFor(() => element('status').textContent!.startsWith('Choose terminals'));
|
||||
await act(async () => element('targets').click()); await waitFor(() => document.querySelectorAll('input[type="checkbox"]').length === 2);
|
||||
await act(async () => { for (const checkbox of document.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')) checkbox.click(); });
|
||||
await act(async () => { [...document.querySelectorAll('button')].find((button) => button.textContent === 'Use selected terminals')!.click(); });
|
||||
await waitFor(() => element('status').textContent!.startsWith('Targets selected'));
|
||||
await act(async () => element('open').click()); await waitFor(() => element('status').textContent!.startsWith('Ready'));
|
||||
const prompt = element('prompt') as HTMLTextAreaElement; prompt.value = 'Synthetic selected-target task';
|
||||
const send = () => element('compose').dispatchEvent(new panel!.window.Event('submit', { cancelable: true }));
|
||||
phase = 'complete'; await act(async () => { send(); }); await waitFor(() => element('status').textContent === 'Complete');
|
||||
assert.deepEqual(workerCalls, ['synthetic-b']); assert.match(element('transcript').textContent!, /Synthetic global Agent result/);
|
||||
assert.equal(mcp.getPermissionMode(), 'observer'); assert.equal(counts.requests, 2); assert.equal(counts.rejected, 0);
|
||||
assert.match(element('usage').textContent!, /input tokens/);
|
||||
phase = 'stop'; prompt.value = 'fixture:wait'; await act(async () => { send(); });
|
||||
await waitFor(() => element('transcript').textContent!.includes('Synthetic waiting output'));
|
||||
await act(async () => element('stop').click()); await waitFor(() => element('status').textContent === 'Stopped' && counts.aborted === 1);
|
||||
const stopped = element('transcript').textContent; await new Promise((resolve) => setTimeout(resolve, 75)); assert.equal(element('transcript').textContent, stopped);
|
||||
phase = 'deny'; const before = counts.requests; const plugin = service.database.getActivePlugin('com.netcatty.globalagent');
|
||||
service.permissionEngine.setMode(plugin, 'ai.agent.actions', 'deny', service.permissionEngine.getPolicyRevision(plugin));
|
||||
await act(async () => { send(); }); await waitFor(() => element('status').textContent!.startsWith('Request ended'));
|
||||
assert.equal(counts.requests, before); assert.deepEqual(workerCalls, ['synthetic-b']);
|
||||
phase = 'restart-history';
|
||||
const reference = pluginReplies.find((value) => value && typeof value === 'object' && 'conversationRef' in value && 'chatHandle' in value) as { conversationRef: string };
|
||||
await service.manager.setEnabled('com.netcatty.globalagent', false);
|
||||
await service.manager.setEnabled('com.netcatty.globalagent', true);
|
||||
await act(async () => element('refresh').click()); await waitFor(() => element('status').textContent!.startsWith('Choose terminals'));
|
||||
const conversation = element('conversation') as HTMLSelectElement; conversation.value = reference.conversationRef;
|
||||
await act(async () => conversation.dispatchEvent(new panel!.window.Event('change')));
|
||||
await act(async () => element('targets').click()); await waitFor(() => document.querySelectorAll('input[type="checkbox"]').length === 2);
|
||||
await act(async () => { [...document.querySelectorAll('button')].find((button) => button.textContent === 'Use selected terminals')!.click(); });
|
||||
await waitFor(() => element('status').textContent!.startsWith('Targets selected'));
|
||||
await act(async () => element('open').click()); await waitFor(() => element('status').textContent!.startsWith('Ready'));
|
||||
assert.match(element('transcript').textContent!, /Synthetic global Agent result/, 'owned core history survives runtime restart');
|
||||
prompt.value = 'Synthetic model-only continuation'; await act(async () => { send(); });
|
||||
await waitFor(() => element('status').textContent === 'Complete');
|
||||
assert.equal(counts.requests, before + 1, 'Actions Deny allows a tool-free configured model turn after reopening');
|
||||
assert.deepEqual(workerCalls, ['synthetic-b']);
|
||||
assert.doesNotMatch(JSON.stringify(pluginReplies), /FIXTURE_ONLY_API_MARKER|apiKey|externalSessionId|plugin-agent:|opaque-owner|mcpServers|permissionMode/);
|
||||
assert.doesNotMatch(JSON.stringify(trustedReplies), /FIXTURE_ONLY_API_MARKER|apiKey/);
|
||||
assert.deepEqual(errors, []);
|
||||
} finally {
|
||||
console.error = originalError;
|
||||
if (panel) { panel.window.dispatchEvent(new panel.window.Event('pagehide')); panel.window.close(); }
|
||||
await act(async () => root.unmount()); await service?.manager.shutdown();
|
||||
mcp.setPermissionMode('confirm'); mcp.cleanup(); aiBridge.cleanup(); privacy.configure({ enabled: false }); registerAppAppLockRuntime(oldLock);
|
||||
server.closeAllConnections(); await new Promise<void>((resolve) => server.close(() => resolve())); dom.window.close();
|
||||
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
|
||||
if (oldTmp === undefined) delete process.env.TMPDIR; else process.env.TMPDIR = oldTmp;
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import type { TerminalSession } from '../../domain/models';
|
||||
import { usePluginAgentHost } from '../../application/state/usePluginAgentHost';
|
||||
import { Button } from '../ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '../ui/dialog';
|
||||
|
||||
export function PluginAgentHost({ sessions }: { sessions: TerminalSession[] }) {
|
||||
const { choice } = usePluginAgentHost(sessions);
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
return <Dialog open={choice !== null} onOpenChange={(open) => { if (!open) choice?.cancel(); }}>
|
||||
<DialogContent data-host-security-surface="" onOpenAutoFocus={() => setSelected([])}>
|
||||
<DialogHeader><DialogTitle>Choose terminals for this Agent conversation</DialogTitle>
|
||||
<DialogDescription>The conversation is independent of the active tab or workspace. Only the terminals selected here are eligible targets. Tool actions follow this plugin's Allow / Ask / Deny setting.</DialogDescription></DialogHeader>
|
||||
<div className="max-h-72 space-y-2 overflow-y-auto">
|
||||
{choice?.items.map((item) => <label key={item.sessionId} className="flex gap-2 text-sm">
|
||||
<input type="checkbox" checked={selected.includes(item.sessionId)} disabled={selected.length >= 32 && !selected.includes(item.sessionId)}
|
||||
onChange={(event) => setSelected((ids) => event.target.checked ? [...ids, item.sessionId] : ids.filter((id) => id !== item.sessionId))} />
|
||||
<span>{item.label} <span className="text-muted-foreground">{item.hostname}</span></span>
|
||||
</label>)}
|
||||
{choice?.items.length === 0 && <p className="text-sm text-muted-foreground">No connected terminals. You can continue without targets.</p>}
|
||||
</div>
|
||||
<DialogFooter><Button variant="outline" onClick={() => choice?.cancel()}>Cancel</Button>
|
||||
<Button onClick={() => choice?.confirm(selected)}>Use selected terminals</Button></DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>;
|
||||
}
|
||||
@@ -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,31 @@
|
||||
import React from 'react';
|
||||
import { ChevronRight } from 'lucide-react';
|
||||
import { PluginBrandIcon } from './PluginBrandIcon';
|
||||
|
||||
/** Shared installed-plugin composition; navigation never wraps the quick actions. */
|
||||
export function PluginListRow({ plugin, name, description, metadata, actions, openLabel, onOpen }: {
|
||||
plugin: NetcattyInstalledPlugin;
|
||||
name: string;
|
||||
description: string;
|
||||
metadata?: React.ReactNode;
|
||||
actions: React.ReactNode;
|
||||
openLabel?: string;
|
||||
onOpen?: () => void;
|
||||
}) {
|
||||
const heading = <span className="flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-1">
|
||||
<span className="min-w-0 max-w-full text-sm font-medium leading-5 [overflow-wrap:anywhere]">{name}</span>
|
||||
{plugin.activeVersion && <span className="inline-flex max-w-full items-center rounded-full border-0 bg-muted/60 px-2 py-0 text-[11px] font-normal leading-5 text-muted-foreground hover:bg-muted/60 [overflow-wrap:anywhere]" data-plugin-row-tag>{plugin.activeVersion}</span>}
|
||||
</span>;
|
||||
return <article aria-label={name} data-plugin-row={plugin.id} className="grid min-w-0 grid-cols-[3rem_minmax(0,1fr)_auto] items-start gap-x-3 rounded-lg py-4 sm:gap-x-4">
|
||||
<div data-plugin-icon-slot className="flex h-12 w-12 shrink-0 items-center justify-center text-muted-foreground"><PluginBrandIcon plugin={plugin} size={32} /></div>
|
||||
<div className="min-w-0 space-y-1.5">
|
||||
{onOpen ? <button type="button" data-plugin-card={plugin.id} aria-label={openLabel} aria-expanded={false} onClick={onOpen}
|
||||
className="group block w-full min-w-0 rounded-md text-left transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background">
|
||||
<span className="flex min-w-0 items-center gap-2"><span className="min-w-0 flex-1">{heading}</span><ChevronRight size={14} className="shrink-0 text-muted-foreground transition-colors group-hover:text-foreground" aria-hidden="true" /></span>
|
||||
<span className="mt-1 block line-clamp-2 text-sm leading-5 text-muted-foreground [overflow-wrap:anywhere]" title={description}>{description}</span>
|
||||
</button> : <div>{heading}<p className="mt-1 line-clamp-2 text-sm leading-5 text-muted-foreground [overflow-wrap:anywhere]" title={description}>{description}</p></div>}
|
||||
{metadata && <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs leading-5 text-muted-foreground [&>*]:min-w-0 [&>*]:max-w-full [overflow-wrap:anywhere]">{metadata}</div>}
|
||||
</div>
|
||||
<div className="flex min-h-12 shrink-0 items-center justify-end gap-2 self-center" data-plugin-row-actions>{actions}</div>
|
||||
</article>;
|
||||
}
|
||||
@@ -20,10 +20,6 @@ export function PluginPermissionHost() {
|
||||
</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?.action && <div className="space-y-1">
|
||||
<p className="text-sm">{zh ? '请求内容(控制字符以转义形式显示)' : 'Requested action (control characters shown as escapes)'}</p>
|
||||
<pre className="max-h-48 overflow-auto whitespace-pre-wrap break-words rounded border border-border p-2 text-xs">{prompt.displayContext.action.text}</pre>
|
||||
</div>}
|
||||
{(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>)}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
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); 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);
|
||||
files = filesFor([]);
|
||||
await act(async () => { await api.listPluginCatalog('official'); });
|
||||
assert.equal(row().dataset.author, entry.manifest.publisher); assert.equal(row().dataset.official, 'false');
|
||||
assert.equal(row().dataset.avatar, undefined, 'withdrawal removes enriched identity without a 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, /<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);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,12 +1,16 @@
|
||||
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 { PluginListRow } from '../../plugins/PluginListRow';
|
||||
import { Toggle } from '../settings-ui';
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
import { I18nProvider } from '../../../application/i18n/I18nProvider';
|
||||
import { PluginPackageManager } from './PluginPackageManager';
|
||||
import type { usePluginManager } from '../../../application/state/usePluginManager';
|
||||
|
||||
test('installed grid filters, opens one detail and restores search, scroll and card focus without pill navigation', async () => {
|
||||
test('installed rows filter, open one detail and restore search, scroll and row focus without toggle navigation', async () => {
|
||||
const globals = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previous = globals.IS_REACT_ACT_ENVIRONMENT; globals.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const raf = globalThis.requestAnimationFrame;
|
||||
@@ -32,12 +36,17 @@ 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');
|
||||
assert.ok(alphaCard.findAllByType('p').some((node) => node.props.className?.includes('line-clamp-3')), 'card description is bounded');
|
||||
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('span').some((node) => node.props.className?.includes('line-clamp-2')), 'row description is bounded');
|
||||
assert.ok(alphaCard.props['data-plugin-row'], 'installed entries use the shared row composition');
|
||||
assert.match(alphaCard.findByProps({ 'data-plugin-row-tag': true }).props.className, /border-0/);
|
||||
assert.doesNotMatch(alphaCard.props.className, /bg-card|border|divide/);
|
||||
assert.match(JSON.stringify(renderer.toJSON()), /MIT/);
|
||||
assert.match(JSON.stringify(renderer.toJSON()), /Incompatible version/);
|
||||
assert.ok(renderer.root.findAllByType('div').some((node) => node.props.className?.includes('repeat(auto-fill')));
|
||||
const pill = renderer.root.findAllByType('button').find((node) => node.props['aria-pressed'] !== undefined)!;
|
||||
assert.equal(renderer.root.findAllByType('div').some((node) => node.props.className?.includes('repeat(auto-fill')), false, 'installed rows no longer inherit the marketplace grid');
|
||||
const pill = renderer.root.findAllByType('button').find((node) => node.props.role === 'switch')!;
|
||||
await act(async () => pill.props.onClick());
|
||||
assert.deepEqual(toggles, [[plugins[0].id, true]]); assert.deepEqual(selections, []);
|
||||
await act(async () => renderer.root.findByType('input').props.onChange({ target: { value: 'Alpha' } }));
|
||||
@@ -55,9 +64,39 @@ test('installed grid filters, opens one detail and restores search, scroll and c
|
||||
assert.equal(cards().length, 0);
|
||||
await act(async () => renderer.root.findByType('input').props.onChange({ target: { value: '' } }));
|
||||
await act(async () => renderer.update(<I18nProvider locale="en"><PluginPackageManager manager={{ ...manager, statusKnown: false, error: 'synthetic state unavailable' }} onSelectionChange={(id) => selections.push(id)} /></I18nProvider>));
|
||||
const unknown = renderer.root.findAllByType('button').filter((node) => node.children.includes('Status unknown'));
|
||||
const unknown = renderer.root.findAllByType('button').filter((node) => node.props.role === 'switch');
|
||||
assert.equal(unknown.length, 2);
|
||||
assert.ok(unknown.every((node) => node.props.disabled === true && node.props['aria-pressed'] === undefined));
|
||||
assert.ok(unknown.every((node) => node.props.disabled === true && node.props['aria-label'].startsWith('Status unknown')));
|
||||
await act(async () => renderer.unmount());
|
||||
} finally { globals.IS_REACT_ACT_ENVIRONMENT = previous; globalThis.requestAnimationFrame = raf; }
|
||||
});
|
||||
|
||||
|
||||
test('long installed-row text keeps baseline tags and independent native-button actions', () => {
|
||||
const name = `Long plugin ${'unbroken'.repeat(30)}`;
|
||||
const description = `Description ${'long description '.repeat(30)}`;
|
||||
const plugin = { id: 'com.test.long', activeVersion: '1.2.3-preview.4', enabled: false, runtime: {} } as NetcattyInstalledPlugin;
|
||||
const html = renderToStaticMarkup(<PluginListRow plugin={plugin} name={name} description={description}
|
||||
metadata={<span>{'https://source.example/'.repeat(20)}</span>} openLabel={`Details ${name}`} onOpen={() => {}}
|
||||
actions={<Toggle checked={false} ariaLabel={`Enable ${name}`} onChange={() => {}} />} />);
|
||||
const dom = new JSDOM(html);
|
||||
try {
|
||||
const row = dom.window.document.querySelector('[data-plugin-row]')!;
|
||||
const navigation = row.querySelector<HTMLButtonElement>('[data-plugin-card]')!;
|
||||
const toggle = row.querySelector<HTMLButtonElement>('[role=switch]')!;
|
||||
const tag = row.querySelector('[data-plugin-row-tag]')!;
|
||||
assert.equal(navigation.type, 'button');
|
||||
assert.equal(toggle.type, 'button');
|
||||
assert.equal(navigation.contains(toggle), false, 'Enter/Space on the switch cannot invoke row navigation');
|
||||
assert.match(navigation.className, /focus-visible:ring-2/);
|
||||
assert.match(toggle.className, /focus-visible:ring-2/);
|
||||
assert.match(tag.parentElement!.className, /items-baseline/);
|
||||
assert.equal(tag.previousElementSibling!.textContent, name, 'long names stay available without title truncation');
|
||||
assert.match(tag.previousElementSibling!.className, /overflow-wrap:anywhere/);
|
||||
assert.match(tag.className, /border-0/);
|
||||
assert.equal(navigation.querySelector('[title]')!.getAttribute('title'), description, 'clamped descriptions retain the full text');
|
||||
assert.match(row.className, /minmax\(0,1fr\)/);
|
||||
assert.doesNotMatch(row.querySelector('[data-plugin-icon-slot]')!.className, /border|ring|bg-/);
|
||||
assert.equal(row.querySelector('button button'), null);
|
||||
} finally { dom.window.close(); }
|
||||
});
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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>}
|
||||
|
||||
@@ -3,6 +3,9 @@ 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 { PluginListRow } from '../../plugins/PluginListRow';
|
||||
import { Toggle } from '../settings-ui';
|
||||
import { ArrowLeft } from 'lucide-react';
|
||||
import { usePluginManager } from '../../../application/state/usePluginManager';
|
||||
import { useI18n } from '../../../application/i18n/I18nProvider';
|
||||
@@ -79,13 +82,25 @@ export function PluginPackageManager({ manager, onSelectionChange, initialSelect
|
||||
if (!manager.available) return null;
|
||||
return <section ref={rootRef} className="space-y-4" aria-label={t('settings.plugins.manager.installed')}>
|
||||
{selectedPlugin && <Button variant="ghost" size="sm" onClick={() => choose(null)}><ArrowLeft size={14} className="mr-2" />{t('settings.plugins.manager.installed')}</Button>}
|
||||
{!selectedPlugin && manager.plugins.length > 0 && <select aria-label={t('settings.plugins.sources.source')} value={sourceFilter} onChange={(event) => setSourceFilter(event.target.value)} className="h-9 rounded-md border border-input bg-background px-3 text-sm"><option value="">{t('settings.plugins.sources.all')}</option>{[...new Map(manager.plugins.map((plugin) => [plugin.source?.id ?? 'local', plugin.source])).entries()].map(([id, source]) => <option key={id} value={id}>{source?.origin ?? t('settings.plugins.sources.local')}</option>)}</select>}
|
||||
{!selectedPlugin && manager.plugins.length > 0 && <select aria-label={t('settings.plugins.sources.source')} value={sourceFilter} onChange={(event) => setSourceFilter(event.target.value)} className="h-9 max-w-full rounded-md border border-input bg-background px-3 text-sm"><option value="">{t('settings.plugins.sources.all')}</option>{[...new Map(manager.plugins.map((plugin) => [plugin.source?.id ?? 'local', plugin.source])).entries()].map(([id, source]) => <option key={id} value={id}>{source?.origin ?? t('settings.plugins.sources.local')}</option>)}</select>}
|
||||
{!selectedPlugin && manager.plugins.length > 0 && <Input value={search} onChange={(event) => setSearch(event.target.value)} placeholder={t('settings.plugins.market.search')} aria-label={t('settings.plugins.market.search')} />}
|
||||
{!selectedPlugin && manager.plugins.length > 0 && visible.length === 0 && <p className="p-6 text-center text-sm text-muted-foreground">{t('settings.plugins.market.noResults')}</p>}
|
||||
{manager.error && <p role="alert" className="text-sm text-destructive">{manager.error}</p>}
|
||||
{!manager.plugins.length && <div className="rounded-xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground">{t('settings.plugins.manager.empty')}</div>}
|
||||
<div className={selectedPlugin ? 'space-y-4' : 'grid grid-cols-[repeat(auto-fill,minmax(min(100%,280px),1fr))] gap-3'}>
|
||||
{visible.map((plugin) => <article key={plugin.id} data-plugin-detail={selectedPlugin ? true : undefined} tabIndex={selectedPlugin ? -1 : undefined} aria-label={nameOf(plugin)} className={`min-w-0 rounded-lg focus:outline-none ${selectedPlugin ? 'space-y-4' : 'plugin-card flex min-h-[200px] flex-col gap-3 bg-card p-4'}`}>
|
||||
<div className={selectedPlugin ? 'space-y-4' : 'space-y-1'} data-plugin-row-list={!selectedPlugin || undefined}>
|
||||
{visible.map((plugin) => !selectedPlugin ? <PluginListRow key={plugin.id} plugin={plugin} name={nameOf(plugin)} description={descriptionOf(plugin) || t('settings.plugins.manager.noDescription')}
|
||||
openLabel={`${t('settings.plugins.manager.details')} ${nameOf(plugin)}`} onOpen={() => choose(plugin.id)}
|
||||
metadata={<>
|
||||
{plugin.manifest?.publisher && <PluginAuthorRow plugin={plugin} />}
|
||||
<span>{plugin.source ? `${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}` : ''}` : t('settings.plugins.landing.sourceUnknown')}</span>
|
||||
{plugin.manifest?.license && <span>{plugin.manifest.license}</span>}
|
||||
{manager.statusKnown === false && <span>{t('settings.plugins.permissions.statusUnknown')}</span>}
|
||||
{plugin.runtime.lastError && <span role="status" className="w-full text-destructive">{t('settings.plugins.manager.lastError')}: {plugin.runtime.lastError}</span>}
|
||||
</>}
|
||||
actions={<Toggle checked={plugin.enabled} disabled={manager.busy || manager.statusKnown === false}
|
||||
ariaLabel={`${t(manager.statusKnown === false ? 'settings.plugins.permissions.statusUnknown' : plugin.enabled ? 'settings.plugins.manager.disable' : 'settings.plugins.manager.enable')} ${nameOf(plugin)}`}
|
||||
onChange={(enabled) => void manager.setEnabled(plugin.id, enabled)} />}
|
||||
/> : <article key={plugin.id} data-plugin-detail={selectedPlugin ? true : undefined} tabIndex={selectedPlugin ? -1 : undefined} aria-label={nameOf(plugin)} className="min-w-0 space-y-4 rounded-lg focus:outline-none">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="flex h-12 w-12 shrink-0 items-center justify-center"><PluginBrandIcon plugin={plugin} size={32} /></div>
|
||||
<button type="button" data-plugin-card={plugin.id} className="min-w-0 flex-1 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-expanded={selected === plugin.id} onClick={() => choose(selected === plugin.id ? null : plugin.id)}>
|
||||
@@ -103,12 +118,9 @@ 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>
|
||||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs" onClick={() => choose(plugin.id)} aria-label={`${t('settings.plugins.manager.details')} ${nameOf(plugin)}`}>{t('settings.plugins.manager.details')}</Button>
|
||||
</div> : <p className="text-xs text-muted-foreground">{plugin.activeVersion}{plugin.manifest?.license ? ` · ${plugin.manifest.license}` : ''}</p>}
|
||||
<p className="text-xs text-muted-foreground">{plugin.activeVersion}{plugin.manifest?.license ? ` · ${plugin.manifest.license}` : ''}</p>
|
||||
{plugin.runtime.lastError && <p role="status" className="break-words text-xs text-destructive">{t('settings.plugins.manager.lastError')}: {plugin.runtime.lastError}</p>}
|
||||
{selected === plugin.id && <>
|
||||
<PluginPackageDetails plugin={plugin} />
|
||||
|
||||
@@ -41,6 +41,13 @@ test('landing rows expose real sources/status/settings and quick toggles preserv
|
||||
await render();
|
||||
assert.equal(document.querySelector('[role=dialog]'), null);
|
||||
assert.equal(document.querySelector('input[type=checkbox]'), null);
|
||||
assert.equal(document.querySelectorAll('[data-plugin-row]').length, 2);
|
||||
assert.equal(document.querySelectorAll('[data-plugin-icon-slot]').length, 2);
|
||||
assert.equal(document.querySelector('[data-plugin-row-list]')!.className.includes('border'), false);
|
||||
const alphaRow = document.querySelector('[data-plugin-row="com.example.alpha"]')!;
|
||||
assert.ok(alphaRow.querySelector('[data-plugin-row-tag]'));
|
||||
assert.equal(alphaRow.querySelector('[data-plugin-row-actions] [role=switch]')?.getAttribute('aria-label'), 'Disable Alpha');
|
||||
assert.equal(alphaRow.querySelector('button button'), null, 'quick actions are never nested inside navigation');
|
||||
assert.equal(document.querySelectorAll('[role=switch]').length, 2, 'only real plugin toggles appear on landing');
|
||||
assert.match(document.body.textContent!, /Running/);
|
||||
assert.match(document.body.textContent!, /Source: Official/);
|
||||
|
||||
@@ -5,7 +5,8 @@ import type { usePluginUpdateCheck } from '../../../application/state/usePluginU
|
||||
import type { usePluginManager } from '../../../application/state/usePluginManager';
|
||||
import { Button } from '../../ui/button';
|
||||
import { Input } from '../../ui/input';
|
||||
import { PluginBrandIcon } from '../../plugins/PluginBrandIcon';
|
||||
import { PluginListRow } from '../../plugins/PluginListRow';
|
||||
import { PluginAuthorRow } from '../../plugins/PluginAuthorRow';
|
||||
import { SettingCard, SettingRow, SettingsSection, Toggle } from '../settings-ui';
|
||||
import { PluginLogSettings } from './PluginLogSettings';
|
||||
|
||||
@@ -62,27 +63,24 @@ export function PluginSettingsLanding({ manager, settingsAvailable, settingsErro
|
||||
{manager.statusKnown && manager.available && manager.plugins.length === 0 && <p className="text-sm text-muted-foreground">{t('settings.plugins.landing.empty')}</p>}
|
||||
{manager.plugins.length > 0 && <>
|
||||
<Input aria-label={t('settings.plugins.landing.search')} placeholder={t('settings.plugins.landing.search')} value={search} onChange={(event) => setSearch(event.target.value)} />
|
||||
{visible.length === 0 ? <p role="status" className="text-sm text-muted-foreground">{t('settings.plugins.market.noResults')}</p> : <SettingCard divided>
|
||||
{visible.length === 0 ? <p role="status" className="text-sm text-muted-foreground">{t('settings.plugins.market.noResults')}</p> : <div className="space-y-1" data-plugin-row-list>
|
||||
{visible.map((plugin) => {
|
||||
const name = nameOf(plugin);
|
||||
const description = localized(plugin.manifest?.description);
|
||||
const availableUpdate = updates?.result?.updates.find((item) => item.pluginId === plugin.id && item.sourceId === plugin.source?.id);
|
||||
const declaredSettings = Boolean(plugin.manifest?.contributes?.settings?.length || plugin.manifest?.contributes?.views?.some((view) => view.location === 'settings'));
|
||||
return <SettingRow key={plugin.id} leading={<PluginBrandIcon plugin={plugin} size={24} />} label={<span className="flex min-w-0 items-baseline gap-2">
|
||||
<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>
|
||||
{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>}
|
||||
</>}>
|
||||
return <PluginListRow key={plugin.id} plugin={plugin} name={name} description={description || t('settings.plugins.manager.noDescription')} metadata={<>
|
||||
{plugin.manifest?.publisher && <PluginAuthorRow plugin={plugin} />}
|
||||
<span>{[sourceOf(plugin), statusOf(plugin)].filter(Boolean).join(' · ')}</span>
|
||||
{availableUpdate && <span className="text-primary">{t('settings.plugins.landing.updateAvailable').replace('{version}', availableUpdate.availableVersion)}</span>}
|
||||
</>} actions={
|
||||
<div className="flex items-center gap-3">
|
||||
{declaredSettings && <Button className="focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2" variant="ghost" size="icon" disabled={manager.busy || !manager.statusKnown || !settingsAvailable.has(plugin.id)} aria-label={t('settings.plugins.landing.settingsFor').replace('{name}', name)} title={t(settingsAvailable.has(plugin.id) ? 'common.settings' : !plugin.enabled ? 'settings.plugins.landing.enableSettings' : 'settings.plugins.landing.settingsUnavailable')} onClick={(event) => onManage(plugin.id, event.currentTarget)}><Settings2 size={16} /></Button>}
|
||||
<Toggle checked={plugin.enabled} disabled={manager.busy || !manager.available || !manager.statusKnown} ariaLabel={`${t(plugin.enabled ? 'settings.plugins.manager.disable' : 'settings.plugins.manager.enable')} ${name}`} onChange={(enabled) => void manager.setEnabled(plugin.id, enabled)} />
|
||||
</div>
|
||||
</SettingRow>;
|
||||
} />;
|
||||
})}
|
||||
</SettingCard>}
|
||||
</div>}
|
||||
</>}
|
||||
</SettingsSection>
|
||||
</>;
|
||||
|
||||
@@ -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); }
|
||||
}
|
||||
});
|
||||
@@ -6,14 +6,14 @@ import { I18nProvider } from '../../../application/i18n/I18nProvider';
|
||||
import { PluginPackageManager } from './PluginPackageManager';
|
||||
import type { usePluginManager } from '../../../application/state/usePluginManager';
|
||||
|
||||
test('state pill exposes actual state, opposite action, focus styling and pending disable without granting permissions', async () => {
|
||||
test('detail state pill exposes actual state, opposite action, focus styling and pending disable without granting permissions', async () => {
|
||||
const globals = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previous = globals.IS_REACT_ACT_ENVIRONMENT; globals.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const calls: unknown[] = [];
|
||||
const plugin = { id: 'com.test.pill', activeVersion: '1.0.0', enabled: true, manifest: { name: 'Pill' }, runtime: {} } as NetcattyInstalledPlugin;
|
||||
const plugin = { id: 'com.test.pill', activeVersion: '1.0.0', enabled: true, manifest: { name: 'Pill', main: { browser: 'index.js' }, engines: { api: '0.1.0-internal', netcatty: '*' } }, runtime: {} } as NetcattyInstalledPlugin;
|
||||
const manager = { available: true, plugins: [plugin], busy: false, setEnabled: async (...args: unknown[]) => { calls.push(args); } } as unknown as ReturnType<typeof usePluginManager>;
|
||||
let renderer: ReactTestRenderer;
|
||||
const render = (enabled: boolean, busy = false) => <I18nProvider locale="en"><PluginPackageManager manager={{ ...manager, busy, plugins: [{ ...plugin, enabled }] }} /></I18nProvider>;
|
||||
const render = (enabled: boolean, busy = false) => <I18nProvider locale="en"><PluginPackageManager initialSelectedId={plugin.id} manager={{ ...manager, busy, plugins: [{ ...plugin, enabled }] }} /></I18nProvider>;
|
||||
try {
|
||||
await act(async () => { renderer = create(render(true)); });
|
||||
const pill = () => renderer.root.findAllByType('button').find((node) => node.props['aria-pressed'] !== undefined)!;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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.
|
||||
@@ -1,74 +0,0 @@
|
||||
# Global Agent continuation: bounded QA recipe
|
||||
|
||||
This is a separate increment after the plugin platform foundation. The transport
|
||||
review checkpoint is #4012 at `ea619555`; its isolated correction is `63f0572e0`.
|
||||
The runtime continuation carries the correction through an ordinary feature-branch
|
||||
merge. It is not merged to main or accepted for release.
|
||||
|
||||
## Reproduce the installable sample
|
||||
|
||||
From the exact runtime head reported in the handoff:
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
npm run build:plugin-runtime-deps
|
||||
node examples/plugins/global-agent/build.mjs
|
||||
node packages/plugin-cli/dist/cli.js pack examples/plugins/global-agent/.package --out /tmp/netcatty-global-agent.ncpkg
|
||||
sha256sum /tmp/netcatty-global-agent.ncpkg
|
||||
```
|
||||
|
||||
The reproducible sample SHA-256 is
|
||||
`36993b1d566814d3b5304337fab73ff464e422d93ba52909e95e3ceedcad2a6a`.
|
||||
Two independent package builds matched. Build scripts and tests are excluded
|
||||
from the six-file installed package.
|
||||
|
||||
## Native fixture acceptance (parent-scheduled GUI only)
|
||||
|
||||
1. Use an isolated synthetic profile, no real Notes, hosts, histories or keys.
|
||||
Start `node scripts/plugin-global-agent-provider-fixture.mjs --port 9218`.
|
||||
It performs no inference or outbound request and logs no bodies/headers.
|
||||
2. Through normal host settings, configure an OpenAI-compatible Chat Completions
|
||||
provider at `http://127.0.0.1:9218/v1`, model `global-agent-fixture`, with the
|
||||
fixture-only literal `FIXTURE_ONLY_API_MARKER`. Do not use real credentials,
|
||||
paid services, allowlist edits, debugger injection or the builtin AI sidebar.
|
||||
3. Install the `.ncpkg` in Settings → Plugins and open its contributed Global
|
||||
Agent Chat view. Verify light/dark/accent updates using existing theme tokens.
|
||||
4. Choose Catty. Choose no targets, or only owned synthetic terminal fixtures,
|
||||
then Open conversation. The fixture's default tool is `get_environment`; it
|
||||
never requests a terminal command. Record Send → streamed result/usage and
|
||||
`GET /fixture/status` counters. This proves a deterministic pipeline, not
|
||||
real model inference.
|
||||
5. Send `fixture:wait`, wait for output, press Stop. Verify aborted count rises
|
||||
once and no late text appears. Capture screenshot/video with fixture labels.
|
||||
6. Exercise Actions Ask using the existing in-app policy dialog: approve and
|
||||
deny the scoped environment tool separately. Actions Deny permits model-only
|
||||
chat with no tools. Agent-use Deny prevents dispatch. A policy change revokes
|
||||
existing handles; reselect/reopen explicitly before another Send.
|
||||
7. Close/reopen and disable/re-enable only this synthetic plugin. Reselect its
|
||||
targets and reopen its owned conversation. History should survive, while the
|
||||
private per-open actor ID is fresh. At five-minute expiry, the sample asks for
|
||||
explicit reselection and keeps the draft, without resending or renewing scope.
|
||||
8. Revoke/disable or lock while streaming and verify cleanup/no late events.
|
||||
Disconnect/re-own a selected synthetic worker during selection and a turn;
|
||||
stale selections must fail instead of binding a replacement connection.
|
||||
|
||||
Do not activate a configured real Claude backend in this fixture recipe. Claude
|
||||
MCP's code/handler boundary is covered with synthetic tests; authenticated service
|
||||
and genuine CLI acceptance remain unverified and require separately approved
|
||||
access. Other backends are explicitly unsupported/unavailable. No background
|
||||
service, blanket OS/Vault access, merge or release is implied.
|
||||
|
||||
## Evidence and limits
|
||||
|
||||
- Installed Catty path uses actual `AgentRuntime`, driver, main provider admission,
|
||||
source policy and worker dispatcher, with JSDOM/in-process plugin transport and
|
||||
synthetic workers. It proves selected B dispatch, stream, Stop, revocation and
|
||||
history after runtime restart. This is not a native BrowserWindow sandbox test.
|
||||
- Main/core tests cover source/session/resource substitution, scope expiry,
|
||||
approval waits, worker lifecycle, cancellation, late completion, stable source
|
||||
budgets, source-isolated history and no key serialization. Filesystem API reads
|
||||
cannot access the core history root. Explicitly granted terminal commands still
|
||||
have that terminal's native OS authority.
|
||||
- No GUI ran in this executor. Native screenshots/video and independent runtime
|
||||
review remain parent-owned gates. The exact-head CI result must be reported
|
||||
separately from focused local evidence.
|
||||
@@ -1,309 +0,0 @@
|
||||
# Global Agent plugin bridge (work in progress)
|
||||
|
||||
This stack starts from `integration/plugin-ask-routing-acceptance` at
|
||||
`2433cf0130d1c3274c56c39e5765349c2945de01`. The parent confirmed this dependency;
|
||||
its native Ask acceptance and integrated CI are still pending. This branch does
|
||||
not modify the frozen candidate, #3986, #3998, or #4002.
|
||||
|
||||
The user approved a global conversation independent of a terminal or workspace,
|
||||
with a plugin-provided chat UI and selectable existing Agent backends. Core owns
|
||||
Agent execution, history, target authority, native approvals, credentials and
|
||||
audit. Global is not unrestricted inventory access or a background service.
|
||||
|
||||
## Stage 1: dispatch authority
|
||||
|
||||
`electron/plugins/agent/delegatedScope.cjs` is a host-only authority. It does not
|
||||
register plugin APIs, start an Agent or implement an orchestration loop.
|
||||
|
||||
- `issue(context, hostSnapshot)` authenticates with the existing source binding.
|
||||
Host snapshots contain backend identity/revision, target kind/id/owner/revision,
|
||||
synchronous current-owner checks, and a supported capability subset. The public
|
||||
result contains only an opaque handle and expiry. Plugin parameters must never
|
||||
be used as `hostSnapshot`.
|
||||
- `begin(handle, context)` returns an internal turn ticket and AbortController.
|
||||
- `dispatch(ticket, context, resolvedAction, execute)` runs the common host policy
|
||||
adapter once, checks current target revisions after any approval wait, invokes
|
||||
the real dispatcher, and rejects late results. `resolvedAction` must come from
|
||||
canonical host capability/argument resolution, not an unchecked plugin object.
|
||||
- `assertTurn` guards outgoing events. `finish` and `stop` invalidate the exact
|
||||
ticket. Runtime/plugin release, lock/hide invalidation and shutdown abort work.
|
||||
- Handles expire in five minutes. There are at most eight per runtime owner and
|
||||
64 overall, with at most 32 explicit resources per scope. Expiry never silently
|
||||
refreshes a selection or revives an old turn.
|
||||
|
||||
The focused tests use the actual `PluginAISourceBinding` with synthetic host
|
||||
registries, two terminal owners representing different workspaces, controlled
|
||||
time, and deferred approval/native completion. They cover source/runtime/target
|
||||
substitution, focus changes, revision changes across approval, policy denial,
|
||||
Stop, release, lock, late completion and bounds. They do not yet prove actual MCP
|
||||
or AgentRuntime dispatch; those remain integration gates.
|
||||
|
||||
Initial execution failed before test discovery because the new worktree has no
|
||||
dependencies (`ajv/dist/2020` missing). Running with the existing local worktree's
|
||||
read-only CommonJS dependency path passes all 12 cases. No provider, CLI Agent,
|
||||
paid credentials or GUI was used.
|
||||
|
||||
The adjacent run then passed 49 tests and failed one installed-entrypoint test
|
||||
because ESM could not resolve `@netcatty/plugin-cli` from the new worktree. Standard
|
||||
`npm ci --ignore-scripts` and `build:plugin-runtime-deps` repaired the setup. These
|
||||
failures are setup evidence, not failed-before product regressions.
|
||||
|
||||
The core conversation repository stores the existing global `AISession` document
|
||||
shape in a host-only directory, namespaced by the hash of source/private-owner.
|
||||
Native session identity and compaction remain private. Commits serialize a cloned
|
||||
snapshot, revalidate provenance before atomic rename, and retain previous history
|
||||
when that check fails. Files use mode 0600 and no-follow reads. The repository
|
||||
does not register a plugin storage API or change the source database schema.
|
||||
|
||||
The canonical schema and SDK now declare the proposed session interface and
|
||||
permissions. Runtime methods and the supported-feature advertisement are not yet
|
||||
registered. This stage must not be described as an installable working Agent
|
||||
bridge. Focused scope/history/wire and permission-copy tests pass 20 cases;
|
||||
contract/SDK/CLI tests pass 91. Focused lint and generated drift checks pass.
|
||||
|
||||
## Independent stage-1 correction
|
||||
|
||||
The independent review of exact `056164157f34ea779ed6cf51199909082345eca4`
|
||||
confirmed two helper defects before any runtime acceptance claim: source failure
|
||||
during the initial owner check rejected late work without aborting the active
|
||||
native signal; Stop could acquire a replacement turn after awaiting identity.
|
||||
|
||||
Both reproduce against that exact helper using the real `PluginAISourceBinding`:
|
||||
the focused before run is 13 passed / 2 failed. The correction revokes the captured
|
||||
scope when its own host-authenticated identity fails, and captures the intended
|
||||
turn before Stop's first await. A foreign runtime cannot use a failed lookup to
|
||||
revoke another caller's scope. Focused after: 15 passed / 0 failed. The complete
|
||||
foundation/permission group passes 23 on Node 24.19.0 and Node 22.23.3; focused lint
|
||||
and diff checks pass. Logs: `/tmp/netcatty-global-agent-review-before.log`,
|
||||
`/tmp/netcatty-global-agent-review-after.log`,
|
||||
`/tmp/netcatty-global-agent-review-node22.log`.
|
||||
|
||||
The first CI run at 0561641, test `40459522087`, Linux job `122040565759`, failed
|
||||
after an explicit runner shutdown and operation cancellation, with no assertion
|
||||
failure in its log and no complete repository test total. Package workflow
|
||||
`40459521971` and both Windows jobs passed. The parent authorized one job rerun;
|
||||
it was requested once, producing Linux job `122048349748`, still running at this
|
||||
checkpoint. Original runner failure remains historical evidence. Neither that
|
||||
rerun nor the helper fix establishes runtime, native or independent-review
|
||||
acceptance; the correction still needs reviewer recheck.
|
||||
|
||||
### Follow-up: cancellation is not source revocation
|
||||
|
||||
The independent recheck confirmed the first two repairs and found a remaining
|
||||
Stop race: an aborted Stop(A) RPC could enter the generic owner-failure cleanup
|
||||
after B had started, revoking B's scope. The same failure was reproduced at both
|
||||
owner-validation await paths using the actual source binding. Exact-18377 source
|
||||
with the new 18-case scope suite yields 16 passed / 2 failed; evidence is retained
|
||||
in `/tmp/netcatty-global-agent-stop-rpc-exact183-before.log`.
|
||||
|
||||
The minimal follow-up distinguishes this request's abort/deadline from verified
|
||||
owner or resource failure, rethrows the access failure, and leaves the existing
|
||||
turn-capture rule intact. Cancellation of Stop(A) cannot revoke B. A separate
|
||||
regression confirms that a verified source mismatch still aborts native work
|
||||
even when the RPC is concurrently cancelled. Foreign caller protections remain.
|
||||
The full foundation/permission group passes 26 tests on Node 22.23.3 and Node
|
||||
24.19.0; focused lint and diff checks pass. Logs:
|
||||
`/tmp/netcatty-global-agent-stop-rpc-final.log` and
|
||||
`/tmp/netcatty-global-agent-stop-rpc-node22.log`. Independent recheck is pending.
|
||||
|
||||
The authorized original-head Linux rerun `122048349748` ended cancelled, with an
|
||||
operation-cancelled log and no assertion failure. No second rerun was requested.
|
||||
At 18377, test workflow `40462595842`, Linux job `122050816182`, also received an
|
||||
explicit runner shutdown; `PluginLogSettings.test.tsx` was SIGKILLed immediately
|
||||
afterward. That interrupted stage reports 34 passed / 1 failed, not a complete
|
||||
repository total or an assertion failure. Both Windows jobs passed. No blind
|
||||
rerun of that job was made. Package workflow `40462595846` was still running when
|
||||
checked. These records are not substituted for exact-head green CI.
|
||||
|
||||
## Planned public contract and adapters
|
||||
|
||||
### Independent transport correction
|
||||
|
||||
The exact `ea619555` internal-handler reproductions fail all four targeted cases:
|
||||
both no-session and empty-selection environment reads serialize global tool hints;
|
||||
stale chat-wide cleanup cancels replacement B; and caller-supplied builtin chat
|
||||
text can downgrade cancellation of a main-owned delegated request. The outer
|
||||
sender gate still accepts only the current trusted main window. These are trusted
|
||||
application lifecycle defects, not arbitrary plugin IPC exposure or installed
|
||||
runtime exploit evidence.
|
||||
|
||||
Cancellation now resolves ownership from the main request map, rejects a
|
||||
conflicting caller chat, checks the recorded sender and current turn lease, and
|
||||
cancels only that native request. The legacy chat-wide cleanup IPC is unavailable
|
||||
for reserved delegated conversations; main-owned exact-turn release remains the
|
||||
cleanup authority. All delegated environment return paths omit global tool hints.
|
||||
|
||||
An additional Node 22 regression is independently reproduced: inline arrow
|
||||
properties at the beginning of `module.exports` prevent namespace detection of
|
||||
existing exports such as `init`, breaking the real Catty attachment harness.
|
||||
Identifier exports preserve that existing interface. Correction tests pass 94 on
|
||||
Node 22.23.3, including the actual Catty attachment consumer; focused lint passes.
|
||||
Failed-before logs are `/tmp/netcatty-global-agent-transport-review-four-failed-before.log`
|
||||
and `/tmp/netcatty-global-agent-ea619-namespace-before.log`. The transport PR's
|
||||
review checkpoint remains `ea619555` until the parent integrates/rechecks this
|
||||
separate correction. No native/backend/full-CI acceptance is implied.
|
||||
|
||||
### Stage 2A: trusted native dispatch boundary
|
||||
|
||||
The independent bounded recheck of foundation `ba4d3fc` passed all 20 reviewer
|
||||
cases. This resolves its reported helper findings; it does not establish full CI,
|
||||
runtime, backend or native acceptance.
|
||||
|
||||
The additive transport slice gives managed subprocesses a separate per-turn MCP
|
||||
credential, permanently binds their TCP connection to that turn, filters their
|
||||
tool list, and routes actual tool execution through the source-bound host policy
|
||||
adapter. Catty's trusted-app IPC enters the same dispatcher. Branded approval
|
||||
contexts skip the legacy Agent approval only after that host adapter grants the
|
||||
action; process-global permission mode is unchanged. Selected environment reads
|
||||
return the scoped session metadata without querying global tunnel inventory.
|
||||
|
||||
Managed Claude is restricted to its existing MCP mode with builtin tools disabled,
|
||||
strict MCP configuration and no inherited settings sources. The main native entry
|
||||
rejects unverified backends and Skills mode for reserved delegated conversations.
|
||||
Each model stream and native SDK request carries a main-owned turn tag; releasing
|
||||
that lease aborts its HTTP/native work. Old credentials, cancellation requests and
|
||||
disposers cannot acquire or cancel the next turn.
|
||||
|
||||
The focused boundary suite passes 116 cases, including an actual local TCP/main
|
||||
handler with synthetic workers, plus two new actual-HTTP/renderer-transport lease
|
||||
tests. These are deterministic transport tests, not real model inference or
|
||||
authenticated Claude service/CLI acceptance. Public runtime registration, core
|
||||
conversation integration and the custom chat sample are still separate work in
|
||||
progress; this transport slice alone is not a usable plugin Agent feature.
|
||||
|
||||
At exact `ba4d3fc`, package CI `40464058910` passed; test workflow `40464058908`
|
||||
is red. Linux job `122055141575` failed a real assertion in
|
||||
`PluginManagementDialog.interaction.test.tsx:71`: the external view handoff had
|
||||
not run when asserted. That stage reports 34 passed / 1 failed; earlier runtime
|
||||
and contract groups passed 720 and 5. Both Windows jobs passed. No blind rerun was
|
||||
requested. This unresolved assertion must not be classified as runner shutdown.
|
||||
|
||||
The wider initial local transport run reports 697 passed / 10 failed / 3 skipped.
|
||||
All ten failures are Cursor discovery expectations after `npm ci --ignore-scripts`
|
||||
left SQLite's native binding absent, making the bundled Cursor SDK import fail.
|
||||
The standard rebuild first failed using unwritable default caches; rebuilding
|
||||
with task-local npm/node-gyp cache paths succeeded. The failed totals are retained
|
||||
in `/tmp/netcatty-global-agent-transport-expanded.log`; the after-setup run is
|
||||
recorded separately. No GUI or provider credentials were used.
|
||||
|
||||
After the dependency repair, the expanded transport/native-handler/preload/SDK
|
||||
suite passes 709 tests, 0 failures, 3 skips. Log:
|
||||
`/tmp/netcatty-global-agent-transport-expanded-after-setup.log`. Focused lint passes.
|
||||
|
||||
The proposed feature is `ai.agent-sessions`, with `ai.agent.use` for conversation
|
||||
operations and `ai.agent.actions` for actual Agent tool actions. Permission mode
|
||||
comes from the existing source-bound Allow/Ask/Deny engine. These are additive
|
||||
names, separate from the existing tools-disabled `ai.invoke` broker.
|
||||
|
||||
The API will provide backend listing, explicit target selection, owned chat
|
||||
listing/opening, sending, bounded event reads, history, Stop and close. Backend
|
||||
references are opaque host-issued configuration revisions. Conversation references
|
||||
identify only histories owned by the calling source/private-owner; runtime handles
|
||||
are separate and cannot substitute builtin chat IDs or native SDK resume IDs.
|
||||
Messages cannot supply permissionMode, CLI/env/MCP configuration or owner fields.
|
||||
|
||||
Core will reuse `AISession`, `AgentRuntime`, both existing turn drivers, event and
|
||||
compaction handling, SDK resume identity validation, and `stopAgentTurn`. The first
|
||||
eligible backends are Catty and configured Claude Code in MCP mode. Other backend
|
||||
entries must return explicit unsupported/unconfigured status until their native
|
||||
tool and approval boundaries are verified. Codex SDK's current unrestricted native
|
||||
configuration must not be treated as eligible merely because it has a driver.
|
||||
|
||||
The terminal worker already exposes a suitable main-owned resource binding:
|
||||
`getPluginSessionBinding(sessionId, ownerWebContentsId)` returns worker epoch and
|
||||
session generation. Use this for dispatch-time targets; do not use menu IDs,
|
||||
focused tab, display labels, or a renderer-provided session ID as authority.
|
||||
|
||||
The MCP dispatcher and Catty direct execution route need the same delegated
|
||||
session guard. A delegated call must not update process-global permission mode,
|
||||
or request both an Agent approval and a plugin approval for the same action.
|
||||
Policy changes, disable/restart/source replacement, lock and host disconnection
|
||||
must cancel scoped native work and invalidate outgoing event tickets. Existing
|
||||
Agent trace and plugin audit/log facilities will receive redacted correlation
|
||||
metadata, not credentials, provider diagnostics or full unreviewed tool payloads.
|
||||
|
||||
## Remaining acceptance gates
|
||||
|
||||
### Separate runtime/sample implementation checkpoint
|
||||
|
||||
The runtime continuation wires the nine `context.agent` methods through the
|
||||
registered default host, dedicated trusted-app preload/IPC and `PluginAgentHost`
|
||||
mounted in `AppView`. It reuses the existing `AgentRuntime`, Catty/external turn
|
||||
drivers, core `AISession` documents, compaction, model/provider transport, native
|
||||
cancellation, selected worker epoch/generation checks and permission/audit engine.
|
||||
No source database, Vault history or builtin conversation ownership change is
|
||||
included. Plugin input cannot supply internal session IDs, source/owner, CLI/env,
|
||||
MCP configuration or permission mode.
|
||||
|
||||
The first eligible profiles are configured Catty and Claude MCP. Other known
|
||||
backends report unsupported/unavailable. Claude has builtin tools disabled,
|
||||
strict MCP, no inherited settings sources, at most 12 native turns and no native
|
||||
session persistence/resume; its existing driver rehydrates from core-owned history.
|
||||
This code path has handler/driver/MCP fixture coverage. Authenticated Claude
|
||||
service/native CLI acceptance has not run and must not be inferred from mocks.
|
||||
|
||||
Actions use one source-bound Allow / Ask / Deny decision path. Actions Deny permits
|
||||
model-only conversation with an empty tool profile; Agent-use Deny blocks host
|
||||
dispatch. Explicit target choice is independent of focus/workspace. Worker
|
||||
lifecycle changes cancel a pending chooser and revoke stale target leases;
|
||||
source/runtime/policy/lock invalidation aborts native work and rejects late events.
|
||||
Core history is source/private-owner namespaced and read/write protected through
|
||||
the plugin filesystem broker. A user-granted terminal command still has that
|
||||
terminal's native OS authority; this is not an OS filesystem sandbox.
|
||||
|
||||
Bounds include six sends/source/minute, eight scopes/runtime and 64 total, 256
|
||||
retained turn handles, 32 tool actions and 32 Catty HTTP calls per turn, 12 Catty
|
||||
iterations, a 120-second turn lifetime, 60-second model HTTP/15-second streaming
|
||||
idle deadlines, 128 KiB HTTP responses, 256 KiB projected turn output and 4 KiB
|
||||
text events. Usage is projected; no hard total native-Claude token budget is
|
||||
claimed. Handles expire after five minutes without silent target reselection.
|
||||
|
||||
The installable `examples/plugins/global-agent` sample provides backend/owned
|
||||
conversation choice, explicit targets, history, Send/Stop and existing host theme
|
||||
tokens. Its deterministic local provider fixture performs no model inference,
|
||||
paid API calls, real terminal execution or request/body/header logging. The
|
||||
installed Node/JSDOM pipeline test uses actual Catty orchestration, configured
|
||||
HTTP admission and main dispatch to synthetic workers. It proves one selected-B
|
||||
tool cycle, streamed result, Stop and revoked-handle denial; it is not native
|
||||
browser sandbox or real model acceptance. A failed-before JSON-snapshot regression
|
||||
is retained at `/tmp/netcatty-global-agent-snapshot-failed-before.log`.
|
||||
|
||||
Recorded validation: plugin runtime 732 passed/0 failed/1 skipped; affected group
|
||||
105 passed/0 failed/3 skipped; examples 6 passed/0 failed/1 skipped; repaired setup
|
||||
paths 284 passed. Build, codegen and lint passed before the final review corrections.
|
||||
Typecheck is still red: 774 diagnostics on both unchanged foundation and this
|
||||
continuation, with equal per-file/error-code counts; it is not a clean typecheck.
|
||||
The repaired Node 22 full run reports 15,354 passed/9 failed/46 skipped. Eight are
|
||||
missing xterm install patches, subsequently applied; the ninth is the transport
|
||||
CJS namespace regression fixed separately. Exact final-head validation is pending.
|
||||
|
||||
The earlier pre-setup full run remains pending after its timed-out unpatched FIDO
|
||||
test worker kept a socket open. Reading `/proc/319596/cwd` to confirm that worker's
|
||||
identity was denied (EACCES); no signal was sent and no alternate route attempted.
|
||||
Its log is retained without invented final totals. `pack:dir` first failed using
|
||||
the unwritable default npm cache; a standard task-local cache repaired that step,
|
||||
then native rebuild failed because installed `@electron/rebuild` hardcodes
|
||||
`/home/agent/.electron-gyp` outside writable roots. No home override or sandbox
|
||||
bypass was attempted. Native screenshots/video and independent runtime review
|
||||
remain parent-owned gates; nothing is merged or released.
|
||||
|
||||
Final focused Node 22 validation passes 205 cases, including all nine failure
|
||||
paths from the broad run after the documented setup/correction changes. The
|
||||
installed pipeline additionally proves disable/re-enable, owned history reopening
|
||||
and a fresh model-only turn under Actions Deny. `conversationRef` is durable;
|
||||
each open receives a fresh private runtime actor so revoked privacy/native/tool
|
||||
state cannot be revived. A typed, host-only close control clears its owned
|
||||
runtime caches after that actor settles. Build, lint (seven existing warnings)
|
||||
and generated drift checks pass. Typecheck still has the same 774 per-file/code
|
||||
diagnostic counts as the unchanged foundation. Logs:
|
||||
`/tmp/netcatty-global-agent-lifecycle-final-tests.log`,
|
||||
`/tmp/netcatty-global-agent-lifecycle-final-build.log`, and
|
||||
`/tmp/netcatty-global-agent-lifecycle-final-typecheck.log`.
|
||||
|
||||
The native recipe and reproducible package hash are in
|
||||
[`global-agent-qa.md`](global-agent-qa.md). Remaining gates are independent
|
||||
transport/runtime review, CI on the final integrated head, parent-scheduled native
|
||||
screenshots/video, genuine Claude compatibility acceptance with separately
|
||||
approved access, and native packaging on a machine with supported writable
|
||||
rebuild caches. The initial full-run pending worker and previous red totals above
|
||||
remain recorded. No GUI ownership, merge or release is granted to this executor.
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -85,6 +85,32 @@ 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
|
||||
|
||||
@@ -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 |
|
||||
|
||||
|
||||
@@ -47,6 +47,9 @@ 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
|
||||
|
||||
@@ -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,8 +3,6 @@
|
||||
// Presentation only. Admission and grants remain owned by the canonical schema
|
||||
// and permission engine. Tests require exact coverage of its permission enum.
|
||||
const PERMISSION_DESCRIPTIONS = {
|
||||
"ai.agent.use": [true, "Agent conversations", "Use configured host Agents and read this plugin's own chat history. Model or Agent service usage may incur costs.", "Agent 会话", "使用宿主已配置的 Agent,并读取此插件自己的聊天历史;模型或 Agent 服务可能产生费用。"],
|
||||
"ai.agent.actions": [true, "Agent actions", "Authorize Agent tools against explicitly selected targets under this plugin's policy. Commands can change remote systems.", "Agent 操作", "根据插件策略授权 Agent 工具操作明确选中的目标;命令可能更改远程系统。"],
|
||||
storage: [false, "Plugin storage", "Save and read this plugin's local data.", "插件存储", "保存和读取此插件自己的本地数据。"],
|
||||
"runtime.advanced": [true, "Full device access", "Run Node code with filesystem and network access outside broker restrictions. Developer mode only.", "完整设备访问", "运行 Node 代码,可直接访问文件系统和网络,不受代理权限限制。仅限开发者模式。"],
|
||||
"settings.read": [false, "Read plugin settings", "Read this plugin's configured preferences.", "读取插件设置", "读取此插件自己的设置。"],
|
||||
|
||||
@@ -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',
|
||||
});
|
||||
|
||||
@@ -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 = (
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -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:~$ ");
|
||||
});
|
||||
|
||||
@@ -611,22 +611,11 @@ function withContentLength(headers, body) {
|
||||
}
|
||||
|
||||
async function streamRequest(url, options, event, requestId, skipTLS) {
|
||||
if (requestId.startsWith("agent-model_") && !/^agent-model_[0-9a-f-]{36}_[0-9a-f-]{36}_sdk_/.test(requestId)) {
|
||||
throw new Error("Delegated model request identity invalid");
|
||||
}
|
||||
const parsedUrl = new URL(url);
|
||||
// Register cancellation before any await so Stop during PAC/proxy lookup works.
|
||||
const controller = new AbortController();
|
||||
const pluginRuntimeId = /^plugin-model_([A-Za-z0-9-]{1,128})_/.exec(requestId)?.[1];
|
||||
const delegatedMatch = /^agent-model_([0-9a-f-]{36})_([0-9a-f-]{36})_sdk_/.exec(requestId);
|
||||
const delegatedId = delegatedMatch?.[1];
|
||||
const delegationTag = delegatedMatch?.[2];
|
||||
const delegatedBridge = delegatedId ? require("./mcpServerBridge.cjs") : null;
|
||||
const assertDelegation = () => delegatedBridge?.assertPluginAgentCaller(`plugin-agent:${delegatedId}`, event.sender.id, delegationTag);
|
||||
assertDelegation();
|
||||
if (delegatedId) delegatedBridge.beginPluginAgentModelRequest(`plugin-agent:${delegatedId}`, event.sender.id, delegationTag);
|
||||
const detachDelegation = delegatedBridge?.onPluginAgentRelease(`plugin-agent:${delegatedId}`, delegationTag, () => controller.abort(createAbortError()));
|
||||
const { idleTimeoutMs, totalTimeoutMs } = pluginRuntimeId || delegatedId
|
||||
const { idleTimeoutMs, totalTimeoutMs } = pluginRuntimeId
|
||||
? { idleTimeoutMs: Math.min(15_000, Math.max(1, Number(options.idleTimeoutMs) || 15_000)),
|
||||
totalTimeoutMs: Math.min(60_000, Math.max(1, Number(options.totalTimeoutMs) || 60_000)) }
|
||||
: resolveAIStreamTimeouts(options);
|
||||
@@ -640,7 +629,6 @@ async function streamRequest(url, options, event, requestId, skipTLS) {
|
||||
clearTimeout(idleTimer);
|
||||
activeStreams.delete(requestId);
|
||||
pluginModelStreamOwners.delete(requestId);
|
||||
detachDelegation?.();
|
||||
};
|
||||
const noteStreamActivity = () => {
|
||||
if (lifecycleFinished) return;
|
||||
@@ -660,9 +648,6 @@ async function streamRequest(url, options, event, requestId, skipTLS) {
|
||||
throw controller.signal.reason instanceof Error ? controller.signal.reason : createAbortError();
|
||||
}
|
||||
|
||||
try { assertDelegation(); }
|
||||
catch (error) { finishLifecycle(); throw error; }
|
||||
|
||||
const { resolveOutboundHttpAgent } = require("./httpNetworkProxyAgent.cjs");
|
||||
let proxyAgent;
|
||||
try {
|
||||
@@ -746,7 +731,6 @@ async function streamRequest(url, options, event, requestId, skipTLS) {
|
||||
if (proxyAgent) reqOpts.agent = proxyAgent;
|
||||
|
||||
try {
|
||||
assertDelegation();
|
||||
req = lib.request(parsedUrl, reqOpts,
|
||||
(res) => {
|
||||
if (streamFinished) {
|
||||
@@ -811,7 +795,7 @@ async function streamRequest(url, options, event, requestId, skipTLS) {
|
||||
res.on("data", (chunk) => {
|
||||
if (streamFinished) return;
|
||||
noteStreamActivity();
|
||||
if (pluginRuntimeId || delegatedId) {
|
||||
if (pluginRuntimeId) {
|
||||
pluginResponseBytes += Buffer.byteLength(chunk);
|
||||
if (pluginResponseBytes > 131_072) {
|
||||
failStream(new Error("Plugin model stream byte budget exceeded"));
|
||||
|
||||
@@ -46,7 +46,6 @@ function loadBridgeWithMocks(options = {}) {
|
||||
clearPendingApprovals() {},
|
||||
cleanupScopedMetadata: async () => {},
|
||||
cleanup() {},
|
||||
...options.mcpServerBridge,
|
||||
},
|
||||
"../cli/discoveryPath.cjs": {
|
||||
getCliLauncherPath: () => "/tmp/netcatty-tool-cli",
|
||||
@@ -1726,61 +1725,6 @@ async function withCapturingServer(t, options, respond) {
|
||||
};
|
||||
}
|
||||
|
||||
test("delegated model stream release aborts its actual HTTP request and stale turns fail before HTTP", { timeout: 5_000 }, async (t) => {
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const id = randomUUID(); const tag = randomUUID(); const chatId = `plugin-agent:${id}`;
|
||||
let live = true; let release; let detached = 0; let requests = 0;
|
||||
let resolveAccepted; const accepted = new Promise((resolve) => { resolveAccepted = resolve; });
|
||||
const ctx = await withCapturingServer(t, { mcpServerBridge: {
|
||||
beginPluginAgentModelRequest: () => {},
|
||||
assertPluginAgentCaller: (actual, sender, actualTag) => {
|
||||
assert.equal(actual, chatId); assert.equal(sender, 1);
|
||||
if (!live || actualTag !== tag) throw Error("Agent turn unavailable");
|
||||
},
|
||||
onPluginAgentRelease: (_id, _tag, cancel) => { release = cancel; return () => detached++; },
|
||||
} }, (res) => {
|
||||
requests++; res.writeHead(200, { "content-type": "text/event-stream" });
|
||||
res.write('data: {"synthetic":true}\n\n'); resolveAccepted();
|
||||
});
|
||||
try {
|
||||
const invoke = (turnTag) => ctx.ipcMain.handlers.get("netcatty:ai:chat:stream")({ sender: ctx.sender }, {
|
||||
requestId: `agent-model_${id}_${turnTag}_sdk_fixture`, url: `${ctx.baseURL}/v1/chat/completions`,
|
||||
headers: { "content-type": "application/json" }, body: '{"stream":true}', providerId: "content-length",
|
||||
});
|
||||
const ended = new Promise((resolve) => ctx.onStreamEvent((channel) => {
|
||||
if (channel === "netcatty:ai:stream:error" || channel === "netcatty:ai:stream:end") resolve();
|
||||
}));
|
||||
const pending = invoke(tag); await accepted; live = false; release();
|
||||
await pending; await ended;
|
||||
assert.equal(detached, 1); assert.equal(requests, 1);
|
||||
const stale = await invoke(randomUUID());
|
||||
assert.equal(stale.ok, false); assert.equal(requests, 1);
|
||||
} finally { ctx.restore(); }
|
||||
});
|
||||
|
||||
test("delegated compaction fetch uses the same exact-turn cancellation", { timeout: 5_000 }, async (t) => {
|
||||
const { randomUUID } = require("node:crypto"); const id = randomUUID(); const tag = randomUUID();
|
||||
let live = true; let release; let detached = 0; let requests = 0;
|
||||
let accepted; const started = new Promise((resolve) => { accepted = resolve; });
|
||||
const ctx = await withCapturingServer(t, { mcpServerBridge: {
|
||||
beginPluginAgentModelRequest: () => {},
|
||||
assertPluginAgentCaller: (chatId, sender, actualTag) => {
|
||||
assert.equal(chatId, `plugin-agent:${id}`); assert.equal(sender, 1);
|
||||
if (!live || actualTag !== tag) throw Error("Agent unavailable");
|
||||
},
|
||||
onPluginAgentRelease: (_id, _tag, cancel) => { release = cancel; return () => detached++; },
|
||||
} }, (res) => { requests++; res.writeHead(200, { "content-type": "application/json" }); res.write('{"synthetic":'); accepted(); });
|
||||
try {
|
||||
const invoke = () => ctx.ipcMain.handlers.get("netcatty:ai:fetch")({ sender: ctx.sender }, {
|
||||
requestId: `agent-model_${id}_${tag}_fetch_fixture`, url: `${ctx.baseURL}/v1/chat/completions`, method: "POST",
|
||||
headers: { "content-type": "application/json" }, body: '{"messages":[]}', providerId: "content-length",
|
||||
});
|
||||
const pending = invoke(); await started; assert.equal(ctx.received.body.toString(), '{"messages":[]}');
|
||||
live = false; release(); assert.equal((await pending).ok, false); assert.equal(detached, 1);
|
||||
assert.equal((await invoke()).ok, false); assert.equal(requests, 1); assert.equal(ctx.ipcMain.handlers.has("netcatty:ai:chat:cancel"), true);
|
||||
} finally { ctx.restore(); }
|
||||
});
|
||||
|
||||
test("streaming AI requests send Content-Length instead of chunked encoding", { timeout: 5_000 }, async (t) => {
|
||||
const ctx = await withCapturingServer(t, {}, (res) => {
|
||||
res.writeHead(200, { "content-type": "text/event-stream" });
|
||||
|
||||
@@ -4,12 +4,8 @@ function registerAgentProcessHandlers(ctx) {
|
||||
const maxCommandTimeoutSeconds = 24 * 60 * 60;
|
||||
// ── MCP Server session metadata ──
|
||||
|
||||
ipcMain.handle("netcatty:ai:mcp:update-sessions", async (event, { sessions: sessionList, chatSessionId, delegationTag }) => {
|
||||
ipcMain.handle("netcatty:ai:mcp:update-sessions", async (event, { sessions: sessionList, chatSessionId }) => {
|
||||
if (!validateSenderOrSettings(event)) return { ok: false, error: "Unauthorized IPC sender" };
|
||||
if (mcpServerBridge.isPluginAgentConversation?.(chatSessionId)) {
|
||||
try { mcpServerBridge.assertPluginAgentCaller(chatSessionId, event.sender.id, delegationTag); }
|
||||
catch { return { ok: false, error: "Agent scope update unavailable" }; }
|
||||
}
|
||||
const list = Array.isArray(sessionList) ? sessionList : [];
|
||||
const externalId = mcpServerBridge.EXTERNAL_MCP_CHAT_SESSION_ID;
|
||||
if (chatSessionId === externalId) {
|
||||
|
||||
@@ -87,20 +87,11 @@ async function proxyCattyExecToWorker({
|
||||
function registerCattyExecHandlers(ctx) {
|
||||
const privacyService = ctx.aiPrivacyService || defaultAiPrivacyService;
|
||||
with (ctx) {
|
||||
ipcMain.handle("netcatty:ai:exec", async (event, { sessionId, command, chatSessionId, delegationTag }) => {
|
||||
ipcMain.handle("netcatty:ai:exec", async (event, { sessionId, command, chatSessionId }) => {
|
||||
// Validate IPC sender (Issue #17)
|
||||
if (!validateSender(event)) {
|
||||
return { ok: false, error: "Unauthorized IPC sender" };
|
||||
}
|
||||
if (mcpServerBridge.isPluginAgentConversation?.(chatSessionId)) {
|
||||
try {
|
||||
return await mcpServerBridge.dispatchBuiltinRpc("netcatty/exec", { sessionId, command, chatSessionId }, {
|
||||
trustedAgentSenderId: event.sender.id,
|
||||
trustedAgentTurnTag: delegationTag,
|
||||
beforeExecute: () => assertCattyPrivacySession(privacyService, chatSessionId),
|
||||
});
|
||||
} catch { return { ok: false, error: "Delegated Agent execution unavailable" }; }
|
||||
}
|
||||
// Block execution in observer mode (Issue #11)
|
||||
if (mcpServerBridge.getPermissionMode() === "observer") {
|
||||
return { ok: false, error: "Execution blocked: permission mode is 'observer'" };
|
||||
@@ -302,14 +293,10 @@ function registerCattyExecHandlers(ctx) {
|
||||
});
|
||||
|
||||
// Cancel in-flight Catty Agent command executions for a chat session
|
||||
ipcMain.handle("netcatty:ai:catty:cancel", async (event, { chatSessionId, delegationTag }) => {
|
||||
ipcMain.handle("netcatty:ai:catty:cancel", async (event, { chatSessionId }) => {
|
||||
if (!validateSender(event)) {
|
||||
return { ok: false, error: "Unauthorized IPC sender" };
|
||||
}
|
||||
if (mcpServerBridge.isPluginAgentConversation?.(chatSessionId)) {
|
||||
try { mcpServerBridge.assertPluginAgentCaller(chatSessionId, event.sender.id, delegationTag); }
|
||||
catch { return { ok: false, error: "Agent cancellation unavailable" }; }
|
||||
}
|
||||
mcpServerBridge.cancelPtyExecsForSession(chatSessionId);
|
||||
void mcpServerBridge.cancelSftpOpsForSession?.(chatSessionId);
|
||||
if (typeof mcpServerBridge.cancelWorkerBackgroundJobsForSession === "function") {
|
||||
@@ -326,7 +313,7 @@ function registerCattyExecHandlers(ctx) {
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
ipcMain.handle("netcatty:ai:chat-session:set-cancelled", async (event, { chatSessionId, cancelled, delegationTag }) => {
|
||||
ipcMain.handle("netcatty:ai:chat-session:set-cancelled", async (event, { chatSessionId, cancelled }) => {
|
||||
if (!validateSender(event)) {
|
||||
return { ok: false, error: "Unauthorized IPC sender" };
|
||||
}
|
||||
@@ -334,14 +321,13 @@ function registerCattyExecHandlers(ctx) {
|
||||
return { ok: false, error: "chatSessionId is required" };
|
||||
}
|
||||
try {
|
||||
if (mcpServerBridge.isPluginAgentConversation?.(chatSessionId)) mcpServerBridge.assertPluginAgentCaller(chatSessionId, event.sender.id, delegationTag);
|
||||
return await mcpServerBridge.applyChatSessionCancelled(chatSessionId, cancelled !== false);
|
||||
} catch (err) {
|
||||
return { ok: false, error: err?.message || String(err) };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle("netcatty:ai:capability", async (event, { rpcMethod, params, chatSessionId, delegationTag }) => {
|
||||
ipcMain.handle("netcatty:ai:capability", async (event, { rpcMethod, params, chatSessionId }) => {
|
||||
if (!validateSender(event)) {
|
||||
return { ok: false, error: "Unauthorized IPC sender" };
|
||||
}
|
||||
@@ -354,7 +340,7 @@ function registerCattyExecHandlers(ctx) {
|
||||
return await mcpServerBridge.dispatchBuiltinRpc(rpcMethod, {
|
||||
...(params || {}),
|
||||
chatSessionId,
|
||||
}, { beforeExecute, trustedAgentSenderId: event.sender.id, trustedAgentTurnTag: delegationTag });
|
||||
}, { beforeExecute });
|
||||
} catch (err) {
|
||||
return { ok: false, error: err?.message || "AI privacy protection is unavailable." };
|
||||
}
|
||||
|
||||
@@ -400,7 +400,7 @@ function registerProviderHandlers(ctx) {
|
||||
});
|
||||
|
||||
// Non-streaming request (for model listing, validation, etc.)
|
||||
ipcMain.handle("netcatty:ai:fetch", async (event, { url, method, headers, body, providerId, skipHostCheck, followRedirects, skipTLSVerify, requestId }) => {
|
||||
ipcMain.handle("netcatty:ai:fetch", async (event, { url, method, headers, body, providerId, skipHostCheck, followRedirects, skipTLSVerify }) => {
|
||||
// Validate IPC sender — settings window needs this for model listing
|
||||
if (!validateSenderOrSettings(event)) {
|
||||
return { ok: false, status: 0, data: "", error: "Unauthorized IPC sender" };
|
||||
@@ -428,25 +428,7 @@ function registerProviderHandlers(ctx) {
|
||||
return { ok: false, status: 0, data: "", error: "URL host is not in the allowed list" };
|
||||
}
|
||||
|
||||
const delegated = typeof requestId === "string" && /^agent-model_([0-9a-f-]{36})_([0-9a-f-]{36})_fetch_/.exec(requestId);
|
||||
if (requestId !== undefined && !delegated) return { ok: false, status: 0, data: "", error: "Delegated request identity invalid" };
|
||||
const controller = delegated ? new AbortController() : null;
|
||||
const delegatedBridge = delegated ? require("./mcpServerBridge.cjs") : null;
|
||||
const assertDelegation = () => {
|
||||
controller?.signal.throwIfAborted();
|
||||
if (delegated) delegatedBridge.assertPluginAgentCaller(`plugin-agent:${delegated[1]}`, event.sender.id, delegated[2]);
|
||||
};
|
||||
let detach; let totalTimer;
|
||||
if (delegated) {
|
||||
try {
|
||||
assertDelegation();
|
||||
delegatedBridge.beginPluginAgentModelRequest(`plugin-agent:${delegated[1]}`, event.sender.id, delegated[2]);
|
||||
detach = delegatedBridge.onPluginAgentRelease(`plugin-agent:${delegated[1]}`, delegated[2], () => controller.abort());
|
||||
activeStreams.set(requestId, controller);
|
||||
totalTimer = setTimeout(() => controller.abort(), 60_000);
|
||||
} catch { return { ok: false, status: 0, data: "", error: "Delegated Agent unavailable" }; }
|
||||
}
|
||||
const MAX_RESPONSE_SIZE = delegated ? 131_072 : 10 * 1024 * 1024;
|
||||
const MAX_RESPONSE_SIZE = 10 * 1024 * 1024; // 10MB safety limit
|
||||
const MAX_REDIRECTS = followRedirects ? 5 : 0;
|
||||
|
||||
async function doFetch(fetchUrl, redirectsLeft) {
|
||||
@@ -455,18 +437,14 @@ function registerProviderHandlers(ctx) {
|
||||
const skipTLS = Boolean(skipTLSVerify || shouldSkipTLSVerify(providerId));
|
||||
let proxyAgent;
|
||||
try {
|
||||
assertDelegation();
|
||||
proxyAgent = await resolveOutboundHttpAgent(fetchUrl, {
|
||||
session: electronModule?.session?.defaultSession,
|
||||
rejectUnauthorized: skipTLS ? false : undefined,
|
||||
});
|
||||
} catch (error) {
|
||||
if (delegated) throw error;
|
||||
} catch {
|
||||
proxyAgent = undefined;
|
||||
}
|
||||
|
||||
assertDelegation();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const parsedUrl = new URL(fetchUrl);
|
||||
const isHttps = parsedUrl.protocol === "https:";
|
||||
@@ -479,8 +457,6 @@ function registerProviderHandlers(ctx) {
|
||||
};
|
||||
if (skipTLS && isHttps) fetchOpts.rejectUnauthorized = false;
|
||||
if (proxyAgent) fetchOpts.agent = proxyAgent;
|
||||
if (controller) fetchOpts.signal = controller.signal;
|
||||
assertDelegation();
|
||||
const req = lib.request(parsedUrl, fetchOpts,
|
||||
(res) => {
|
||||
// Handle redirects
|
||||
@@ -529,9 +505,7 @@ function registerProviderHandlers(ctx) {
|
||||
});
|
||||
}
|
||||
|
||||
try { return await doFetch(resolvedUrl, MAX_REDIRECTS); }
|
||||
catch (error) { if (!delegated) throw error; return { ok: false, status: 0, data: "", error: "Delegated Agent unavailable" }; }
|
||||
finally { if (delegated) { clearTimeout(totalTimer); detach?.(); activeStreams.delete(requestId); } }
|
||||
return doFetch(resolvedUrl, MAX_REDIRECTS);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@@ -101,9 +101,7 @@ function mergeClaudeEffortSettings(settings, effort) {
|
||||
function buildClaudeQueryOptions({
|
||||
cwd, model, env, pathToClaudeCodeExecutable, abortController, injectedMcpServers, settings, resume,
|
||||
toolIntegrationMode,
|
||||
delegatedAgent = false,
|
||||
}) {
|
||||
if (delegatedAgent && toolIntegrationMode !== "mcp") throw Error("Delegated Claude requires MCP mode");
|
||||
const { model: resolvedModel, effort } = splitClaudeModelSelection(model);
|
||||
const options = {
|
||||
cwd,
|
||||
@@ -132,17 +130,8 @@ function buildClaudeQueryOptions({
|
||||
options.pathToClaudeCodeExecutable = pathToClaudeCodeExecutable;
|
||||
}
|
||||
// Optional settings.json path / inline object — additive to CLAUDE_CONFIG_DIR.
|
||||
const parsedSettings = mergeClaudeEffortSettings(delegatedAgent ? undefined : parseClaudeSettings(settings), effort);
|
||||
const parsedSettings = mergeClaudeEffortSettings(parseClaudeSettings(settings), effort);
|
||||
if (parsedSettings !== undefined) options.settings = parsedSettings;
|
||||
if (delegatedAgent) {
|
||||
options.strictMcpConfig = true;
|
||||
options.settingSources = [];
|
||||
options.maxTurns = 12;
|
||||
// Global plugin history belongs to core's source namespace. Rehydrate from
|
||||
// that history each turn instead of creating a second native history store.
|
||||
options.persistSession = false;
|
||||
delete options.resume;
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
|
||||
@@ -333,19 +333,3 @@ test("listClaudeModels aborts a hung SDK query and returns it for cleanup", asyn
|
||||
assert.equal(queryAbortSignal.aborted, true);
|
||||
assert.equal(returnCount, 1);
|
||||
});
|
||||
|
||||
test("delegated Claude uses only explicit MCP configuration and cannot inherit local settings/tool mode", () => {
|
||||
const options = buildClaudeQueryOptions({
|
||||
delegatedAgent: true, toolIntegrationMode: "mcp", settings: { mcpServers: { unwanted: {} } },
|
||||
injectedMcpServers: [{ name: "scoped-netcatty", command: "host-managed", args: [], env: [] }],
|
||||
});
|
||||
assert.equal(options.strictMcpConfig, true);
|
||||
assert.equal(options.maxTurns, 12);
|
||||
assert.equal(options.persistSession, false);
|
||||
assert.equal(options.resume, undefined);
|
||||
assert.deepEqual(options.settingSources, []);
|
||||
assert.deepEqual(options.tools, []);
|
||||
assert.equal(options.settings, undefined);
|
||||
assert.deepEqual(Object.keys(options.mcpServers), ["scoped-netcatty"]);
|
||||
assert.throws(() => buildClaudeQueryOptions({ delegatedAgent: true, toolIntegrationMode: "skills" }), /requires MCP/);
|
||||
});
|
||||
@@ -44,7 +44,6 @@ const DRIVER_REGISTRY = {
|
||||
settings: ctx.claudeSettings,
|
||||
resume: ctx.resumeSessionId,
|
||||
toolIntegrationMode: ctx.toolIntegrationMode,
|
||||
delegatedAgent: ctx.delegatedAgent === true,
|
||||
});
|
||||
return claude.runClaudeTurn({ prompt: ctx.prompt, attachments: ctx.attachments, options, emitter: ctx.emitter, assertSessionValid: ctx.assertSessionValid });
|
||||
},
|
||||
|
||||
@@ -13,7 +13,6 @@ async function buildInjectedMcpServers({
|
||||
mcpServerBridge,
|
||||
chatSessionId,
|
||||
toolIntegrationMode,
|
||||
delegationTag,
|
||||
}) {
|
||||
try {
|
||||
// Start the netcatty control host for BOTH modes. getOrCreateHost binds the
|
||||
@@ -31,22 +30,8 @@ async function buildInjectedMcpServers({
|
||||
scopedIds,
|
||||
chatSessionId,
|
||||
);
|
||||
if (mcpServerBridge.isPluginAgentConversation?.(chatSessionId)) {
|
||||
const delegated = mcpServerBridge.getPluginAgentMcpConfiguration(chatSessionId, delegationTag);
|
||||
// Replace, never append alongside, the app-wide credential. These values
|
||||
// stay in the managed subprocess configuration and never reach the plugin.
|
||||
netcattyMcpConfig.env = netcattyMcpConfig.env.filter((entry) => ![
|
||||
"NETCATTY_MCP_TOKEN", "NETCATTY_MCP_DEBUG", "NETCATTY_MCP_PERMISSION_MODE",
|
||||
].includes(entry.name));
|
||||
netcattyMcpConfig.env.push(
|
||||
{ name: "NETCATTY_MCP_TOKEN", value: delegated.token },
|
||||
{ name: "NETCATTY_MCP_PERMISSION_MODE", value: "confirm" },
|
||||
{ name: "NETCATTY_MCP_DELEGATED_TOOLS", value: JSON.stringify(delegated.tools) },
|
||||
);
|
||||
}
|
||||
return [netcattyMcpConfig];
|
||||
} catch (err) {
|
||||
if (mcpServerBridge.isPluginAgentConversation?.(chatSessionId)) throw Error("Delegated Agent MCP is unavailable");
|
||||
console.error("[sdk] Failed to ensure netcatty host / inject MCP server:", err?.message || err);
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -744,22 +744,6 @@ function registerSdkStreamHandlers(ctx) {
|
||||
} = payload;
|
||||
|
||||
const backendKey = resolveBackendKey(sdkBackend);
|
||||
const delegatedAgent = mcpServerBridge.isPluginAgentConversation?.(chatSessionId) === true;
|
||||
const delegationTag = delegatedAgent ? /^plugin-agent_([0-9a-f-]{36})_/.exec(requestId)?.[1] : undefined;
|
||||
if (delegatedAgent && (backendKey !== "claude" || toolIntegrationMode !== "mcp")) {
|
||||
throw Error("This backend is not eligible for delegated Agent sessions");
|
||||
}
|
||||
if (delegatedAgent) {
|
||||
mcpServerBridge.assertPluginAgentCaller(chatSessionId, event.sender.id, delegationTag);
|
||||
mcpServerBridge.getPluginAgentMcpConfiguration(chatSessionId, delegationTag);
|
||||
}
|
||||
let delegatedCwd;
|
||||
if (delegatedAgent) {
|
||||
const nativePath = require("node:path");
|
||||
const name = require("node:crypto").createHash("sha256").update(chatSessionId).digest("hex");
|
||||
delegatedCwd = nativePath.join(tempDirBridge.getTempDir(), "plugin-agent", name);
|
||||
require("node:fs").mkdirSync(delegatedCwd, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
if (!backendKey) {
|
||||
safeSend(event.sender, "netcatty:ai:sdk-agent:error", {
|
||||
requestId, error: `Unknown SDK backend: ${sdkBackend}`,
|
||||
@@ -768,11 +752,8 @@ function registerSdkStreamHandlers(ctx) {
|
||||
}
|
||||
|
||||
const abortController = new AbortController();
|
||||
const detachDelegatedCancellation = delegatedAgent
|
||||
? mcpServerBridge.onPluginAgentRelease(chatSessionId, delegationTag, () => abortController.abort()) : null;
|
||||
sdkActiveStreams.set(requestId, abortController);
|
||||
sdkRequestSessions.set(requestId, chatSessionId);
|
||||
if (delegatedAgent) sdkRequestRuntimes.set(requestId, { backendKey, delegationTag, senderId: event.sender.id });
|
||||
mcpServerBridge.setChatSessionCancelled?.(chatSessionId, false);
|
||||
|
||||
let privacyEnabled = false;
|
||||
@@ -795,7 +776,6 @@ function registerSdkStreamHandlers(ctx) {
|
||||
mcpServerBridge,
|
||||
chatSessionId,
|
||||
toolIntegrationMode: effectiveMode,
|
||||
delegationTag,
|
||||
});
|
||||
|
||||
// NETCATTY_CLAUDE_SETTINGS is a netcatty marker carrying the claude SDK
|
||||
@@ -870,7 +850,6 @@ function registerSdkStreamHandlers(ctx) {
|
||||
const sessionRuntime = backendKey === "grok" ? grokRuntime : codexRuntime;
|
||||
sdkRequestRuntimes.set(requestId, {
|
||||
backendKey,
|
||||
...(delegatedAgent ? { delegationTag, senderId: event.sender.id } : {}),
|
||||
codexRuntime,
|
||||
grokRuntime,
|
||||
sessionRuntime,
|
||||
@@ -1047,14 +1026,9 @@ function registerSdkStreamHandlers(ctx) {
|
||||
chatSessionId,
|
||||
// Drivers recheck after their own asynchronous startup, at the
|
||||
// final Netcatty-owned prompt handoff (including disabled turns).
|
||||
assertSessionValid: () => {
|
||||
if (delegatedAgent) mcpServerBridge.assertPluginAgentCaller(chatSessionId, event.sender.id, delegationTag);
|
||||
abortController.signal.throwIfAborted();
|
||||
return privacyService.checkSession(chatSessionId);
|
||||
},
|
||||
delegatedAgent,
|
||||
assertSessionValid: () => privacyService.checkSession(chatSessionId),
|
||||
...promptPlacement,
|
||||
cwd: delegatedCwd || cwd || process.cwd(),
|
||||
cwd: cwd || process.cwd(),
|
||||
model: model || undefined,
|
||||
permissionMode: permissionMode || "confirm",
|
||||
env,
|
||||
@@ -1112,7 +1086,6 @@ function registerSdkStreamHandlers(ctx) {
|
||||
emitter.emitError(err?.message || String(err));
|
||||
return { ok: false, error: err?.message || String(err) };
|
||||
} finally {
|
||||
detachDelegatedCancellation?.();
|
||||
sdkActiveStreams.delete(requestId);
|
||||
sdkRequestSessions.delete(requestId);
|
||||
sdkRequestRuntimes.delete(requestId);
|
||||
@@ -1415,19 +1388,7 @@ function registerSdkStreamHandlers(ctx) {
|
||||
|
||||
ipcMain.handle("netcatty:ai:sdk-agent:cancel", async (event, { requestId, chatSessionId }) => {
|
||||
if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" };
|
||||
const ownedChatSessionId = sdkRequestSessions.get(requestId);
|
||||
// Caller text cannot select the legacy route for a delegated request.
|
||||
if (ownedChatSessionId && chatSessionId && ownedChatSessionId !== chatSessionId) return { ok: false, error: "Agent request ownership mismatch" };
|
||||
const effectiveChatSessionId = ownedChatSessionId || chatSessionId;
|
||||
if (mcpServerBridge.isPluginAgentConversation?.(effectiveChatSessionId)) {
|
||||
const native = sdkRequestRuntimes.get(requestId);
|
||||
if (!native?.delegationTag || native.senderId !== event.sender.id
|
||||
|| sdkRequestSessions.get(requestId) !== effectiveChatSessionId) return { ok: false, error: "Agent turn unavailable" };
|
||||
try { mcpServerBridge.assertPluginAgentCaller(effectiveChatSessionId, event.sender.id, native.delegationTag); }
|
||||
catch { return { ok: false, error: "Agent turn unavailable" }; }
|
||||
sdkActiveStreams.get(requestId)?.abort();
|
||||
return { ok: true };
|
||||
}
|
||||
const effectiveChatSessionId = chatSessionId || sdkRequestSessions.get(requestId);
|
||||
mcpServerBridge.setChatSessionCancelled?.(effectiveChatSessionId, true);
|
||||
mcpServerBridge.cancelPtyExecsForSession(effectiveChatSessionId);
|
||||
mcpServerBridge.cancelWorkerBackgroundJobsForSession?.(effectiveChatSessionId);
|
||||
@@ -1444,9 +1405,6 @@ function registerSdkStreamHandlers(ctx) {
|
||||
|
||||
ipcMain.handle("netcatty:ai:sdk-agent:cleanup", async (event, { chatSessionId }) => {
|
||||
if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" };
|
||||
// This legacy route has no per-request identity. Delegated lifecycle is
|
||||
// owned by main's exact-turn lease, never a delayed chat-wide UI cleanup.
|
||||
if (mcpServerBridge.isPluginAgentConversation?.(chatSessionId)) return { ok: false, error: "Delegated Agent cleanup is main-owned" };
|
||||
mcpServerBridge.setChatSessionCancelled?.(chatSessionId, true);
|
||||
mcpServerBridge.cancelPtyExecsForSession(chatSessionId);
|
||||
mcpServerBridge.cancelWorkerBackgroundJobsForSession?.(chatSessionId);
|
||||
|
||||
@@ -2192,85 +2192,3 @@ test("SDK adapter passes a live privacy guard through asynchronous driver startu
|
||||
assert.equal(sent, false);
|
||||
assert.equal(h.ctx.sdkActiveStreams.size, 0);
|
||||
});
|
||||
|
||||
test("delegated Agent entry rejects unverified runtimes and Skills before native/environment work", async () => {
|
||||
let validated = 0;
|
||||
const { handlers } = registerWithStubbedCtx({
|
||||
mcpServerBridge: {
|
||||
isPluginAgentConversation: () => true,
|
||||
assertPluginAgentCaller: () => {},
|
||||
getPluginAgentMcpConfiguration: () => { validated++; throw Error("No current delegation"); },
|
||||
},
|
||||
});
|
||||
const handler = handlers.get("netcatty:ai:sdk-agent:stream");
|
||||
for (const sdkBackend of ["codex", "copilot", "cursor", "codebuddy", "opencode", "grok", "mimo", "arbitrary-cli"]) {
|
||||
await assert.rejects(handler({ sender: { id: 7 } }, {
|
||||
requestId: "synthetic", chatSessionId: "plugin-agent:synthetic", sdkBackend, toolIntegrationMode: "mcp",
|
||||
}), /not eligible/);
|
||||
}
|
||||
await assert.rejects(handler({ sender: { id: 7 } }, {
|
||||
requestId: "synthetic", chatSessionId: "plugin-agent:synthetic", sdkBackend: "claude", toolIntegrationMode: "skills",
|
||||
}), /not eligible/);
|
||||
assert.equal(validated, 0);
|
||||
await assert.rejects(handler({ sender: { id: 7 } }, {
|
||||
requestId: "synthetic", chatSessionId: "plugin-agent:synthetic", sdkBackend: "claude", toolIntegrationMode: "mcp",
|
||||
}), /No current delegation/);
|
||||
assert.equal(validated, 1);
|
||||
});
|
||||
|
||||
test("delegated native cancellation is exact-request and cannot mark replacement chat work cancelled", async () => {
|
||||
const broad = [];
|
||||
const { handlers, ctx } = registerWithStubbedCtx({ mcpServerBridge: {
|
||||
isPluginAgentConversation: () => true,
|
||||
assertPluginAgentCaller: () => {},
|
||||
setChatSessionCancelled: () => broad.push('chat'), cancelPtyExecsForSession: () => broad.push('pty'),
|
||||
clearPendingApprovals: () => broad.push('approval'), cancelWorkerBackgroundJobsForSession: () => broad.push('worker'),
|
||||
} });
|
||||
const first = new AbortController(); const second = new AbortController();
|
||||
const chat = 'plugin-agent:synthetic';
|
||||
ctx.sdkActiveStreams.set('native-a', first); ctx.sdkRequestSessions.set('native-a', chat);
|
||||
ctx.sdkRequestRuntimes.set('native-a', { delegationTag: 'tag-a', senderId: 7 });
|
||||
ctx.sdkActiveStreams.set('native-b', second); ctx.sdkRequestSessions.set('native-b', chat);
|
||||
ctx.sdkRequestRuntimes.set('native-b', { delegationTag: 'tag-b', senderId: 7 });
|
||||
const cancel = handlers.get('netcatty:ai:sdk-agent:cancel');
|
||||
assert.equal((await cancel({ sender: { id: 7 } }, { requestId: 'native-a', chatSessionId: chat })).ok, true);
|
||||
assert.equal(first.signal.aborted, true); assert.equal(second.signal.aborted, false);
|
||||
assert.equal((await cancel({ sender: { id: 7 } }, { requestId: '', chatSessionId: chat })).ok, false);
|
||||
assert.equal((await cancel({ sender: { id: 99 } }, { requestId: 'native-b', chatSessionId: chat })).ok, false);
|
||||
assert.equal(second.signal.aborted, false); assert.deepEqual(broad, []);
|
||||
});
|
||||
|
||||
test("legacy chat-wide cleanup cannot abort replacement delegated turn B or remove its metadata", async () => {
|
||||
const effects = [];
|
||||
const { handlers, ctx } = registerWithStubbedCtx({ mcpServerBridge: {
|
||||
isPluginAgentConversation: (id) => id?.startsWith('plugin-agent:'),
|
||||
setChatSessionCancelled: () => effects.push('cancelled'), cancelPtyExecsForSession: () => effects.push('pty'),
|
||||
cancelWorkerBackgroundJobsForSession: () => effects.push('worker'), cleanupScopedMetadata: async () => effects.push('metadata'),
|
||||
} });
|
||||
const chat = 'plugin-agent:11111111-1111-4111-8111-111111111111';
|
||||
const replacement = new AbortController();
|
||||
ctx.sdkActiveStreams.set('native-b', replacement); ctx.sdkRequestSessions.set('native-b', chat);
|
||||
ctx.sdkRequestRuntimes.set('native-b', { backendKey: 'claude', delegationTag: 'turn-b', senderId: 7 });
|
||||
const result = await handlers.get('netcatty:ai:sdk-agent:cleanup')({ sender: { id: 7 } }, { chatSessionId: chat, delegationTag: 'turn-a' });
|
||||
assert.equal(replacement.signal.aborted, false); assert.equal(ctx.sdkActiveStreams.has('native-b'), true);
|
||||
assert.equal(ctx.sdkRequestSessions.get('native-b'), chat); assert.equal(ctx.sdkRequestRuntimes.get('native-b').delegationTag, 'turn-b');
|
||||
assert.deepEqual(effects, []); assert.equal(result.ok, false);
|
||||
});
|
||||
|
||||
test("caller-supplied builtin chat cannot downgrade cancellation of a main-owned delegated request", async () => {
|
||||
const effects = []; const chat = 'plugin-agent:11111111-1111-4111-8111-111111111111';
|
||||
const { handlers, ctx } = registerWithStubbedCtx({ mcpServerBridge: {
|
||||
isPluginAgentConversation: (id) => id?.startsWith('plugin-agent:'),
|
||||
assertPluginAgentCaller: (id, sender, tag) => { if (id !== chat || sender !== 7 || tag !== 'turn-b') throw Error('Unavailable'); },
|
||||
setChatSessionCancelled: () => effects.push('cancelled'), cancelPtyExecsForSession: () => effects.push('pty'),
|
||||
clearPendingApprovals: () => effects.push('approval'), cancelWorkerBackgroundJobsForSession: () => effects.push('worker'),
|
||||
} });
|
||||
const replacement = new AbortController();
|
||||
ctx.sdkActiveStreams.set('native-b', replacement); ctx.sdkRequestSessions.set('native-b', chat);
|
||||
ctx.sdkRequestRuntimes.set('native-b', { backendKey: 'claude', delegationTag: 'turn-b', senderId: 7 });
|
||||
const cancel = handlers.get('netcatty:ai:sdk-agent:cancel');
|
||||
const result = await cancel({ sender: { id: 99 } }, { requestId: 'native-b', chatSessionId: 'builtin-chat' });
|
||||
assert.equal(replacement.signal.aborted, false); assert.equal(result.ok, false); assert.deepEqual(effects, []);
|
||||
assert.equal((await cancel({ sender: { id: 7 } }, { requestId: 'native-b', chatSessionId: chat })).ok, true);
|
||||
assert.equal(replacement.signal.aborted, true);
|
||||
});
|
||||
@@ -10,8 +10,6 @@ const net = require("node:net");
|
||||
const crypto = require("node:crypto");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { PluginAgentMcpDelegations } = require("../plugins/agent/mcpDelegation.cjs");
|
||||
const pluginAgentDelegations = new PluginAgentMcpDelegations();
|
||||
const { existsSync } = require("node:fs");
|
||||
|
||||
const { toUnpackedAsarPath, getFreshIdlePrompt, formatSyntheticEcho } = require("./ai/shellUtils.cjs");
|
||||
@@ -1425,7 +1423,7 @@ function handleConnection(socket) {
|
||||
consumedUntil = newlineIdx + 1;
|
||||
searchFrom = consumedUntil;
|
||||
if (!line.trim()) continue;
|
||||
debugLog("Incoming message", { bytes: Buffer.byteLength(line) });
|
||||
debugLog("Incoming line", line);
|
||||
handleMessage(socket, line);
|
||||
}
|
||||
if (consumedUntil > 0) buffer = buffer.slice(consumedUntil);
|
||||
@@ -1457,8 +1455,7 @@ async function handleMessage(socket, line) {
|
||||
const isExternalToken = Boolean(
|
||||
presentedToken && externalAuthToken && presentedToken === externalAuthToken,
|
||||
);
|
||||
const isDelegatedToken = method === "auth/verify" && pluginAgentDelegations.authenticate(presentedToken, socket);
|
||||
if (method === "auth/verify" && (isCattyToken || isExternalToken || isDelegatedToken)) {
|
||||
if (method === "auth/verify" && (isCattyToken || isExternalToken)) {
|
||||
if (isExternalToken && !externalMcpActivityHook?.isEnabled?.()) {
|
||||
const response = JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
@@ -1499,13 +1496,6 @@ async function handleMessage(socket, line) {
|
||||
|
||||
try {
|
||||
const callParams = { ...(params || {}) };
|
||||
const delegatedChat = pluginAgentDelegations.boundChat(socket);
|
||||
if (delegatedChat) {
|
||||
if (callParams.chatSessionId && callParams.chatSessionId !== delegatedChat) throw Error("Agent connection cannot change its session");
|
||||
callParams.chatSessionId = delegatedChat;
|
||||
} else if (pluginAgentDelegations.isReserved(callParams.chatSessionId)) {
|
||||
throw Error("Delegated Agent credentials required");
|
||||
}
|
||||
// External-token sockets always operate under the reserved app-wide scope so
|
||||
// callers cannot omit chatSessionId and widen access via scopedSessionIds.
|
||||
if (externalMcpSockets.has(socket)) {
|
||||
@@ -1541,7 +1531,7 @@ async function handleMessage(socket, line) {
|
||||
managedPrivacyScopes.set(socket, callParams.chatSessionId);
|
||||
}
|
||||
result = await createManagedPrivacyBoundary(
|
||||
(rpcMethod, rpcParams, context) => dispatch(rpcMethod, rpcParams, { ...context, externalSocket: socket }),
|
||||
(rpcMethod, rpcParams, context) => dispatch(rpcMethod, rpcParams, context),
|
||||
aiPrivacyService,
|
||||
)(method, callParams);
|
||||
}
|
||||
@@ -1663,7 +1653,6 @@ const dispatchCapabilityRpc = createCapabilityRpcDispatcher({
|
||||
return invokeVaultAgentFn(...args);
|
||||
},
|
||||
evaluatePermissionWithGrants,
|
||||
isDelegatedApproval: (context) => pluginAgentDelegations.isApproved(context),
|
||||
get permissionMode() {
|
||||
return permissionMode;
|
||||
},
|
||||
@@ -1978,7 +1967,7 @@ function getWorkerJob(jobId, chatSessionId) {
|
||||
|
||||
const WORKER_JOB_NOT_FOUND_ERROR = "Background job not found";
|
||||
|
||||
async function handleWorkerJobPoll(params = {}, beforeExecute) {
|
||||
async function handleWorkerJobPoll(params = {}) {
|
||||
const { jobId, chatSessionId, scopedSessionIds } = params || {};
|
||||
if (!jobId) throw new Error("jobId is required");
|
||||
const job = getWorkerJob(jobId, chatSessionId || null);
|
||||
@@ -1990,7 +1979,7 @@ async function handleWorkerJobPoll(params = {}, beforeExecute) {
|
||||
const scopeErr = validateSessionScope(job.sessionId, chatSessionId || null, scopedSessionIds);
|
||||
if (scopeErr) return { ok: false, error: scopeErr };
|
||||
}
|
||||
const result = await terminalWorkerManager.request("netcatty:ai:jobPoll", params, typeof beforeExecute === "function" ? { beforeExecute } : {});
|
||||
const result = await terminalWorkerManager.request("netcatty:ai:jobPoll", params, {});
|
||||
if (result?.ok === false && result.error === WORKER_JOB_NOT_FOUND_ERROR) {
|
||||
// The route is still here but the worker no longer knows the job (pruned or restarted).
|
||||
emitJobDiag("job-stop-miss", { jobId, chatSessionId: chatSessionId || null, op: "poll", reason: "worker-job-missing" });
|
||||
@@ -2001,7 +1990,7 @@ async function handleWorkerJobPoll(params = {}, beforeExecute) {
|
||||
return result;
|
||||
}
|
||||
|
||||
async function handleWorkerJobStop(params = {}, beforeExecute) {
|
||||
async function handleWorkerJobStop(params = {}) {
|
||||
const { jobId, chatSessionId, scopedSessionIds } = params || {};
|
||||
if (!jobId) throw new Error("jobId is required");
|
||||
const job = getWorkerJob(jobId, chatSessionId || null);
|
||||
@@ -2012,7 +2001,7 @@ async function handleWorkerJobStop(params = {}, beforeExecute) {
|
||||
if (Array.isArray(scopedSessionIds) && job.sessionId && !scopedSessionIds.includes(job.sessionId)) {
|
||||
return { ok: false, error: `Session "${job.sessionId}" is not in the current scope.` };
|
||||
}
|
||||
const result = await terminalWorkerManager.request("netcatty:ai:jobStop", params, typeof beforeExecute === "function" ? { beforeExecute } : {});
|
||||
const result = await terminalWorkerManager.request("netcatty:ai:jobStop", params, {});
|
||||
if (result?.ok === false && result.error === WORKER_JOB_NOT_FOUND_ERROR) {
|
||||
// The route is still here but the worker no longer knows the job (pruned or restarted).
|
||||
emitJobDiag("job-stop-miss", { jobId, chatSessionId: chatSessionId || null, op: "stop", reason: "worker-job-missing" });
|
||||
@@ -2159,17 +2148,7 @@ function getBuiltinRpcHandlerRegistry() {
|
||||
}
|
||||
|
||||
async function dispatch(method, params, approvalContext = {}) {
|
||||
if (pluginAgentDelegations.isReserved(params?.chatSessionId)) {
|
||||
return pluginAgentDelegations.dispatch(method, params, approvalContext,
|
||||
(approved) => dispatchCore(method, params, approved));
|
||||
}
|
||||
return dispatchCore(method, params, approvalContext);
|
||||
}
|
||||
|
||||
async function dispatchCore(method, params, approvalContext = {}) {
|
||||
const delegated = pluginAgentDelegations.isApproved(approvalContext);
|
||||
if (delegated) debugLog("Delegated dispatch", { method });
|
||||
else debugLog("dispatch", { method, params, permissionMode });
|
||||
debugLog("dispatch", { method, params, permissionMode });
|
||||
|
||||
if (!method.startsWith("netcatty/")) {
|
||||
const capabilityResult = await dispatchCapabilityRpc(method, params || {}, approvalContext);
|
||||
@@ -2185,8 +2164,7 @@ async function dispatchCore(method, params, approvalContext = {}) {
|
||||
pruneCompletedBackgroundJobs();
|
||||
|
||||
const approvalTarget = getApprovalTarget(params);
|
||||
const permission = delegated ? { allowed: !isChatSessionCancelled(params?.chatSessionId), requiresApproval: false }
|
||||
: evaluatePermissionWithGrants({
|
||||
const permission = evaluatePermissionWithGrants({
|
||||
rpcMethod: method,
|
||||
surface: CAPABILITY_SURFACES.BUILTIN,
|
||||
permissionMode,
|
||||
@@ -2288,10 +2266,10 @@ async function dispatchCore(method, params, approvalContext = {}) {
|
||||
return await handleWorkerJobStart(params, approvalContext.beforeExecute);
|
||||
}
|
||||
if (capability?.id === "terminal.poll" && workerBackgroundJobs.has(params?.jobId)) {
|
||||
return await handleWorkerJobPoll(params, approvalContext.beforeExecute);
|
||||
return await handleWorkerJobPoll(params);
|
||||
}
|
||||
if (capability?.id === "terminal.stop" && workerBackgroundJobs.has(params?.jobId)) {
|
||||
return await handleWorkerJobStop(params, approvalContext.beforeExecute);
|
||||
return await handleWorkerJobStop(params);
|
||||
}
|
||||
return await handler(params, approvalContext);
|
||||
} finally {
|
||||
@@ -2306,12 +2284,10 @@ async function dispatchCore(method, params, approvalContext = {}) {
|
||||
|
||||
// ── Handler: getContext ──
|
||||
|
||||
async function handleGetContext(params, approvalContext) {
|
||||
const delegated = pluginAgentDelegations.isApproved(approvalContext);
|
||||
debugLog("handleGetContext:start", delegated ? { delegated: true } : { params, sessionCount: sessions?.size || 0 });
|
||||
const toolHints = delegated ? null : buildMcpToolHints();
|
||||
async function handleGetContext(params) {
|
||||
debugLog("handleGetContext:start", { params, sessionCount: sessions?.size || 0 });
|
||||
const toolHints = buildMcpToolHints();
|
||||
if (!sessions) {
|
||||
if (delegated) return { environment: "netcatty-terminal", description: "No host-selected terminal sessions are available.", hosts: [], hostCount: 0 };
|
||||
return {
|
||||
hosts: [],
|
||||
instructions: "No sessions available.",
|
||||
@@ -2357,7 +2333,7 @@ async function handleGetContext(params, approvalContext) {
|
||||
description: "No hosts are available in the current scope.",
|
||||
hosts: [],
|
||||
hostCount: 0,
|
||||
...(delegated ? {} : { tools: toolHints }),
|
||||
tools: toolHints,
|
||||
};
|
||||
}
|
||||
for (const [sessionId, session] of sessions.entries()) {
|
||||
@@ -2407,12 +2383,6 @@ async function handleGetContext(params, approvalContext) {
|
||||
}
|
||||
}
|
||||
|
||||
if (pluginAgentDelegations.isApproved(approvalContext)) {
|
||||
// Do not query or serialize app-wide tunnel/tool inventory for a delegated
|
||||
// conversation. Its core-owned scope already selected the session metadata.
|
||||
return { environment: "netcatty-terminal", description: "Use only these host-selected session IDs.",
|
||||
hosts, hostCount: hosts.length };
|
||||
}
|
||||
let activePortForwardTunnels = [];
|
||||
try {
|
||||
activePortForwardTunnels = await listActivePortForwards();
|
||||
@@ -2562,35 +2532,12 @@ const configAndCleanupApi = createConfigAndCleanupApi({
|
||||
const { resolveMcpServerRuntimeCommand, buildMcpServerConfig, cleanupScopedMetadata } = configAndCleanupApi;
|
||||
|
||||
function cleanup() {
|
||||
pluginAgentDelegations.shutdown();
|
||||
try { disposeWorkerSessionClosed?.dispose?.(); } catch { /* ignore */ }
|
||||
disposeWorkerSessionClosed = null;
|
||||
shutdownHost();
|
||||
}
|
||||
|
||||
// Keep identifier exports so Node 22's CJS namespace analysis also preserves the
|
||||
// existing named exports consumed by renderer-side harness tests.
|
||||
const registerPluginAgentDelegation = (...args) => pluginAgentDelegations.register(...args);
|
||||
const getPluginAgentMcpConfiguration = (id, tag) => pluginAgentDelegations.configuration(id, tag);
|
||||
const isPluginAgentConversation = (id) => pluginAgentDelegations.isReserved(id);
|
||||
const assertPluginAgentCaller = (id, senderId, tag) => pluginAgentDelegations.assertCaller(id, senderId, tag);
|
||||
const onPluginAgentRelease = (id, tag, cancel) => pluginAgentDelegations.onRelease(id, tag, cancel);
|
||||
|
||||
const beginPluginAgentModelRequest = (id, senderId, tag) => pluginAgentDelegations.beginModelRequest(id, senderId, tag);
|
||||
function getPluginAgentJobTarget(jobId, chatSessionId) {
|
||||
if (!pluginAgentDelegations.isReserved(chatSessionId)) return null;
|
||||
const job = workerBackgroundJobs.get(jobId) ?? backgroundJobs.get(jobId);
|
||||
return job?.chatSessionId === chatSessionId && typeof job.sessionId === "string" ? job.sessionId : null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getPluginAgentJobTarget,
|
||||
beginPluginAgentModelRequest,
|
||||
registerPluginAgentDelegation,
|
||||
getPluginAgentMcpConfiguration,
|
||||
isPluginAgentConversation,
|
||||
assertPluginAgentCaller,
|
||||
onPluginAgentRelease,
|
||||
init,
|
||||
setCommandBlocklist,
|
||||
getCommandBlocklist,
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const net = require("node:net");
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { createNdjsonRpcClient } = require("../capabilities/rpcTransport.cjs");
|
||||
const { DelegatedAgentScopes } = require("../plugins/agent/delegatedScope.cjs");
|
||||
const { buildInjectedMcpServers } = require("./aiBridge/sdk/injectMcp.cjs");
|
||||
const bridge = require("./mcpServerBridge.cjs");
|
||||
const privacy = require("../shared/aiPrivacyService.cjs");
|
||||
|
||||
test("actual main TCP gate binds delegated credentials, scope and policy at worker dispatch without global mode changes", { timeout: 10_000 }, async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-agent-mcp-test-"));
|
||||
const clients = []; const registrations = [];
|
||||
let effects = 0; let inventoryRequests = 0; let decisions = 0; let allowed = true; let targetRevision = "v1";
|
||||
let beforeWorker = () => {}; let authorize = async () => {};
|
||||
t.after(() => {
|
||||
for (const registration of registrations) registration.dispose();
|
||||
for (const client of clients) client.close();
|
||||
bridge.setPermissionMode("confirm"); bridge.cleanup();
|
||||
privacy.configure({ enabled: false });
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
privacy.configure({ enabled: false });
|
||||
bridge.init({ sessions: new Map(), cliDiscoveryFilePath: path.join(directory, "discovery.json"),
|
||||
terminalWorkerManager: { request: async (method, _payload, options) => {
|
||||
if (method !== "netcatty:ai:exec") { inventoryRequests++; return []; }
|
||||
beforeWorker(); options?.beforeExecute?.(); effects++;
|
||||
return { ok: true, stdout: "synthetic output", stderr: "", exitCode: 0 };
|
||||
} } });
|
||||
bridge.setPermissionMode("observer");
|
||||
const port = await bridge.getOrCreateHost();
|
||||
const coreId = `plugin-agent:${randomUUID()}`;
|
||||
const turnTag = randomUUID();
|
||||
const owner = Object.freeze({ runtimeId: "r1", pluginId: "com.example.assistant", privateOwner: "opaque-source-a", sourceKey: "source-a" });
|
||||
const context = {};
|
||||
const scopes = new DelegatedAgentScopes({ resolveOwner: async () => owner, assertHostActive: async () => {},
|
||||
authorizeAction: async () => { decisions++; await authorize(); if (!allowed) throw Error("Denied by source policy"); } });
|
||||
const target = { kind: "terminal", id: "synthetic-a", owner: "window-7", revision: "v1",
|
||||
isCurrent: (snapshot) => snapshot.revision === targetRevision };
|
||||
const scope = await scopes.issue(context, { backend: { key: "configured-claude", revision: "1", isCurrent: () => true },
|
||||
targets: [target], capabilities: ["terminal.execute", "session.environment"] });
|
||||
let ticket = await scopes.begin(scope.handle, context);
|
||||
registrations.push(bridge.registerPluginAgentDelegation(coreId, {
|
||||
senderId: 7, turnTag, tools: ["get_environment", "terminal_execute"],
|
||||
assertCurrent: () => { if (ticket.controller.signal.aborted || targetRevision !== target.revision) throw Error("Stale delegation"); },
|
||||
dispatch: (method, params, execute) => {
|
||||
const capabilityId = method === "netcatty/exec" ? "terminal.execute" : method === "netcatty/getContext" ? "session.environment" : "unsupported";
|
||||
const targets = params.sessionId ? [{ ...target, id: params.sessionId }] : [];
|
||||
return scopes.dispatch(ticket, context, { capabilityId, targets }, execute);
|
||||
},
|
||||
}));
|
||||
bridge.updateSessionMetadata([{ sessionId: target.id, hostname: "fixture.invalid", label: "Synthetic A", protocol: "ssh" }], coreId);
|
||||
const appToken = bridge.buildMcpServerConfig(port, [], coreId).env.find((entry) => entry.name === "NETCATTY_MCP_TOKEN").value;
|
||||
const injected = await buildInjectedMcpServers({ mcpServerBridge: bridge, chatSessionId: coreId, toolIntegrationMode: "mcp", delegationTag: turnTag });
|
||||
const environment = Object.fromEntries(injected[0].env.map((entry) => [entry.name, entry.value]));
|
||||
assert.notEqual(environment.NETCATTY_MCP_TOKEN, appToken);
|
||||
assert.equal(environment.NETCATTY_MCP_PERMISSION_MODE, "confirm");
|
||||
assert.deepEqual(JSON.parse(environment.NETCATTY_MCP_DELEGATED_TOOLS), ["get_environment", "terminal_execute"]);
|
||||
async function connect(token) {
|
||||
const socket = net.createConnection({ host: "127.0.0.1", port });
|
||||
await new Promise((resolve, reject) => { socket.once("connect", resolve); socket.once("error", reject); });
|
||||
const client = createNdjsonRpcClient({ socket }); clients.push(client);
|
||||
await client.call("auth/verify", { token }); return client;
|
||||
}
|
||||
const app = await connect(appToken);
|
||||
await assert.rejects(app.call("netcatty/getContext", { chatSessionId: coreId }), /Delegated Agent credentials/);
|
||||
const client = await connect(environment.NETCATTY_MCP_TOKEN);
|
||||
await assert.rejects(client.call("netcatty/getContext", { chatSessionId: "builtin-chat" }), /cannot change/);
|
||||
const selected = await client.call("netcatty/getContext", {});
|
||||
assert.deepEqual(Object.keys(selected).sort(), ["description", "environment", "hostCount", "hosts"]);
|
||||
assert.deepEqual(selected.hosts.map((item) => item.sessionId), ["synthetic-a"]);
|
||||
assert.equal(inventoryRequests, 0, "delegated context must not query app-wide tunnel inventory");
|
||||
await assert.rejects(client.call("netcatty/getStatus", {}), /outside the Agent delegation/);
|
||||
const run = (sessionId = target.id) => client.call("netcatty/exec", { sessionId, command: "printf synthetic" });
|
||||
const beforeDecision = decisions;
|
||||
assert.equal((await run()).stdout, "synthetic output");
|
||||
assert.equal(effects, 1); assert.equal(decisions, beforeDecision + 1); assert.equal(bridge.getPermissionMode(), "observer");
|
||||
await assert.rejects(run("unselected-session")); assert.equal(effects, 1);
|
||||
allowed = false; await assert.rejects(run(), /Denied by source policy/); assert.equal(effects, 1);
|
||||
allowed = true;
|
||||
const entered = new Promise((resolve) => { authorize = async () => { resolve(); await new Promise((done) => { authorize = done; }); }; });
|
||||
const pending = run(); await entered;
|
||||
scopes.finish(ticket); authorize(); await assert.rejects(pending); assert.equal(effects, 1);
|
||||
ticket = await scopes.begin(scope.handle, context); authorize = async () => {};
|
||||
beforeWorker = () => { targetRevision = "v2"; };
|
||||
await assert.rejects(run()); assert.equal(effects, 1);
|
||||
registrations[0].dispose();
|
||||
await assert.rejects(app.call("netcatty/getContext", { chatSessionId: coreId }));
|
||||
assert.throws(() => bridge.getPluginAgentMcpConfiguration(coreId));
|
||||
});
|
||||
|
||||
for (const sessions of [null, new Map()]) test(`delegated empty environment omits global tool inventory (${sessions === null ? "uninitialized" : "empty scope"})`, async (t) => {
|
||||
bridge.init({ sessions });
|
||||
const id = `plugin-agent:${randomUUID()}`; const tag = randomUUID();
|
||||
const registration = bridge.registerPluginAgentDelegation(id, { senderId: 7, turnTag: tag, tools: ["get_environment"],
|
||||
assertCurrent: () => {}, dispatch: (_method, _params, execute) => execute() });
|
||||
t.after(() => { registration.dispose(); bridge.cleanup(); });
|
||||
const value = await bridge.dispatchBuiltinRpc("netcatty/getContext", { chatSessionId: id }, { trustedAgentSenderId: 7, trustedAgentTurnTag: tag });
|
||||
assert.equal(Object.hasOwn(value, "tools"), false); assert.deepEqual(value.hosts, []);
|
||||
});
|
||||
|
||||
test("MCP bridge retains existing CJS namespace exports for actual Catty harness consumers", async () => {
|
||||
const namespace = await import("./mcpServerBridge.cjs");
|
||||
for (const name of ["init", "cleanup", "dispatchBuiltinRpc", "registerPluginAgentDelegation"]) assert.equal(typeof namespace[name], "function", name);
|
||||
});
|
||||
@@ -157,9 +157,7 @@ function createCapabilityRpcDispatcher(deps) {
|
||||
hostname: host?.hostname || "",
|
||||
};
|
||||
}
|
||||
const permission = deps.isDelegatedApproval?.(approvalContext)
|
||||
? { allowed: !isChatSessionCancelled(params?.chatSessionId), requiresApproval: false }
|
||||
: evaluatePermissionWithGrants({
|
||||
const permission = evaluatePermissionWithGrants({
|
||||
rpcMethod,
|
||||
surface,
|
||||
permissionMode: deps.permissionMode,
|
||||
|
||||
@@ -61,7 +61,7 @@ const HARNESS_CAPABILITIES = [
|
||||
},
|
||||
{
|
||||
id: "harness.terminal.read_context",
|
||||
agentKinds: ["sidebar", "global"],
|
||||
agentKinds: ["sidebar"],
|
||||
domain: "harness",
|
||||
status: CAPABILITY_STATUS.IMPLEMENTED,
|
||||
description: "Read a bounded slice of the current terminal screen or scrollback from the active AI scope.",
|
||||
|
||||
@@ -69,7 +69,6 @@ const CHAT_SESSION_ID = process.env.NETCATTY_MCP_CHAT_SESSION_ID || null;
|
||||
// External MCP clients may keep a long-lived stdio process; re-read discovery so
|
||||
// Settings → AI → Safety changes apply without restarting the client.
|
||||
function readPermissionMode() {
|
||||
if (process.env.NETCATTY_MCP_DELEGATED_TOOLS !== undefined) return "confirm";
|
||||
const discoveryPath = process.env.NETCATTY_EXTERNAL_MCP_DISCOVERY_FILE;
|
||||
if (discoveryPath) {
|
||||
try {
|
||||
@@ -320,20 +319,12 @@ server.resource(
|
||||
);
|
||||
|
||||
// Start with core tools; load specialized catalog groups through load_netcatty_tools.
|
||||
const toolDependencies = {
|
||||
registerProgressiveMcpTools(server, {
|
||||
rpcCall: exposedRpcCall,
|
||||
scopeParams,
|
||||
guardWriteOperation,
|
||||
catalogDescription,
|
||||
};
|
||||
if (process.env.NETCATTY_MCP_DELEGATED_TOOLS !== undefined) {
|
||||
const { listMcpTools } = require("../capabilities/codegen/toolSurfaces.cjs");
|
||||
const { registerMcpTools } = require("../capabilities/codegen/mcpToolRegistry.cjs");
|
||||
const names = JSON.parse(process.env.NETCATTY_MCP_DELEGATED_TOOLS);
|
||||
if (!Array.isArray(names) || names.length > 128 || names.some((name) => typeof name !== "string")) throw Error("Invalid delegated tool profile");
|
||||
const allowed = new Set(names);
|
||||
registerMcpTools(server, toolDependencies, listMcpTools().filter((tool) => allowed.has(tool.mcpTool)));
|
||||
} else registerProgressiveMcpTools(server, toolDependencies);
|
||||
});
|
||||
|
||||
// ── Start ──
|
||||
|
||||
|
||||
@@ -1,374 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { PluginRpcError, RPC_ERRORS } = require("../rpcRouter.cjs");
|
||||
const { createDefinitionValidator } = require("../contractValidator.cjs");
|
||||
const { normalizePermissionDeclarations } = require("../permissionResources.cjs");
|
||||
const { PluginAISourceBinding } = require("../ai/sourceBinding.cjs");
|
||||
const { DelegatedAgentScopes, isRequestCancellation } = require("./delegatedScope.cjs");
|
||||
const { listMcpTools } = require("../../capabilities/codegen/toolSurfaces.cjs");
|
||||
const fail = (code) => new PluginRpcError(RPC_ERRORS[code], "Plugin Agent operation unavailable");
|
||||
const FEATURE = require("../generated/plugin-contract.schema.json").$defs.PluginAgentFeature.const;
|
||||
const CAPABILITIES = Object.freeze(require("../generated/plugin-contract.schema.json").$defs.PluginAgentCapabilities.const);
|
||||
const TOOLS = listMcpTools().filter((tool) => CAPABILITIES.includes(tool.capabilityId));
|
||||
const ROUTES = [
|
||||
["listBackends", "PluginAIEmptyParams", "PluginAgentBackendsResult"],
|
||||
["selectTargets", "PluginAIEmptyParams", "PluginAgentTargetsResult"],
|
||||
["listChats", "PluginAIEmptyParams", "PluginAgentChatsResult"],
|
||||
["openChat", "PluginAgentOpenParams", "PluginAgentChatResult"],
|
||||
["send", "PluginAgentSendParams", "PluginAgentTurnResult"],
|
||||
["read", "PluginAgentTurnRef", "PluginAgentEvent"],
|
||||
["history", "PluginAgentChatRef", "PluginAgentHistoryResult"],
|
||||
["stop", "PluginAgentTurnRef", "PluginAIBooleanResult"],
|
||||
["closeChat", "PluginAgentChatRef", "PluginAIBooleanResult"],
|
||||
];
|
||||
|
||||
class PluginAgentService {
|
||||
constructor(options) {
|
||||
this.source = new PluginAISourceBinding(options);
|
||||
this.database = options.database;
|
||||
this.host = options.hostAdapter;
|
||||
this.permission = options.permissionEngine;
|
||||
this.store = options.conversationStore;
|
||||
this.getSessionBinding = options.getSessionBinding;
|
||||
this.getMcpBridge = options.getMcpBridge;
|
||||
this.getTargetManager = options.getTargetManager ?? (() => null);
|
||||
this.clock = options.clock ?? Date.now;
|
||||
this.backends = new Map(); this.selections = new Map(); this.chats = new Map(); this.turns = new Map();
|
||||
this.budgets = new Map(); this.pendingOpens = new Set(); this.registrations = []; this.closed = false;
|
||||
this.pendingSelections = new Map(); this.targetManager = null; this.targetSubscriptions = [];
|
||||
this.eventValidator = createDefinitionValidator("PluginAgentEvent");
|
||||
this.sessionValidator = createDefinitionValidator("PluginAgentHostSession");
|
||||
this.scopes = new DelegatedAgentScopes({ resolveOwner: (ctx) => this.#guard(ctx),
|
||||
assertHostActive: (ctx) => this.host.assertActive(ctx), clock: this.clock,
|
||||
authorizeAction: async (ctx, owner, action, signal) => {
|
||||
const decisionContext = { ...ctx, signal, permissionOperation: Object.freeze({}), sourceOwner: owner.privateOwner };
|
||||
await this.permission.authorize(decisionContext, {
|
||||
permission: "ai.agent.actions", resources: action.targets.length
|
||||
? action.targets.map((target) => `agent-target:${target.kind}:${target.id}:${target.owner}:${target.revision}`) : ["*"],
|
||||
reason: "Use a delegated Agent tool on selected resources", sessionId: ctx.agentChatId,
|
||||
displayContext: { modelLabel: ctx.agentBackendLabel, selections: action.targets.map((target) => ({
|
||||
title: ctx.agentTargetLabels.get(target.id) ?? target.id, scope: "session", version: target.revision,
|
||||
})), action: { capabilityId: action.capabilityId, text: ctx.agentToolPreview } },
|
||||
});
|
||||
} });
|
||||
this.revocation = this.permission.onDidRevoke((event) => this.releasePlugin(event.pluginId));
|
||||
this.hostInvalidation = this.host.onDidInvalidate(() => this.releaseAll());
|
||||
}
|
||||
|
||||
async #guard(context) {
|
||||
try {
|
||||
if (this.closed) throw fail("unavailable");
|
||||
const owner = await this.source.resolve(context);
|
||||
await this.host.assertActive(context); this.source.assertCurrent(owner);
|
||||
return owner;
|
||||
} catch (error) {
|
||||
const owner = this.source.bindings.get(context.runtimeId);
|
||||
if (!isRequestCancellation(error, context) && owner?.pluginId === context.pluginId
|
||||
&& owner.pluginVersion === context.pluginVersion) this.releaseRuntime(context.runtimeId);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
#assertNow(turn) {
|
||||
if (this.closed || turn.done || this.turns.get(turn.handle) !== turn || turn.chat.activeTurn !== turn
|
||||
|| turn.controller.signal.aborted || turn.chat.expiresAt <= this.clock()
|
||||
|| turn.ticket?.controller.signal.aborted
|
||||
|| this.host.generation !== turn.chat.hostGeneration) throw fail("cancelled");
|
||||
this.source.assertCurrent(turn.owner);
|
||||
if (this.host.getSenderId() !== turn.senderId) throw fail("cancelled");
|
||||
if (this.permission.getPolicyRevision(this.database.getActivePlugin(turn.owner.pluginId)) !== turn.policyRevision) throw fail("cancelled");
|
||||
for (const target of turn.chat.selection.targets) if (!target.isCurrent(target)) throw fail("cancelled");
|
||||
}
|
||||
|
||||
async #chat(params, context) {
|
||||
const owner = await this.#guard(context); const chat = this.chats.get(params.chatHandle);
|
||||
if (!chat || chat.owner !== owner || chat.expiresAt <= this.clock() || chat.hostGeneration !== this.host.generation) throw fail("permissionDenied");
|
||||
return chat;
|
||||
}
|
||||
async #turn(params, context) {
|
||||
const owner = await this.#guard(context); const turn = this.turns.get(params.turnHandle);
|
||||
if (!turn || turn.owner !== owner || turn.expiresAt <= this.clock()) throw fail("permissionDenied");
|
||||
return turn;
|
||||
}
|
||||
async #backendCurrent(backend, context) {
|
||||
if (backend.expiresAt <= this.clock() || backend.hostGeneration !== this.host.generation
|
||||
|| !(await this.host.requestAgent("agent.current", { hostHandle: backend.hostHandle }, context)).current) throw fail("failedPrecondition");
|
||||
}
|
||||
#prune() {
|
||||
for (const map of [this.backends, this.selections]) for (const [key, entry] of map) if (entry.expiresAt <= this.clock()) map.delete(key);
|
||||
for (const [key, turn] of this.turns) if (turn.expiresAt <= this.clock()) { this.#end(turn); this.turns.delete(key); }
|
||||
for (const [key, chat] of this.chats) if (chat.expiresAt <= this.clock()) {
|
||||
this.#forgetChat(chat); this.chats.delete(key);
|
||||
}
|
||||
}
|
||||
#observeTargets() {
|
||||
const manager = this.getTargetManager();
|
||||
if (manager === this.targetManager) return;
|
||||
for (const entry of this.targetSubscriptions) entry.dispose(); this.targetSubscriptions = [];
|
||||
this.targetManager = manager;
|
||||
const invalidate = () => {
|
||||
for (const controller of this.pendingSelections.keys()) controller.abort();
|
||||
for (const [key, chat] of this.chats) if (chat.selection.targets.some((target) => !target.isCurrent(target))) {
|
||||
this.#forgetChat(chat); this.chats.delete(key);
|
||||
}
|
||||
};
|
||||
invalidate();
|
||||
for (const method of ["onSessionOwned", "onSessionClosed", "onWorkerExit"]) {
|
||||
if (typeof manager?.[method] === "function") this.targetSubscriptions.push(manager[method](invalidate));
|
||||
}
|
||||
}
|
||||
#charge(owner) {
|
||||
const key = JSON.stringify([owner.sourceKey, owner.privateOwner]); const now = this.clock();
|
||||
for (const [id, entry] of this.budgets) if (now - entry.start >= 60_000) this.budgets.delete(id);
|
||||
const budget = this.budgets.get(key) ?? { start: now, requests: 0 };
|
||||
if (budget.requests >= 6 || (!this.budgets.has(key) && this.budgets.size >= 256)) throw fail("resourceExhausted");
|
||||
budget.requests++; this.budgets.set(key, budget);
|
||||
}
|
||||
|
||||
registerRpcCapabilities(registry) {
|
||||
for (const [operation, paramsType, resultType] of ROUTES) {
|
||||
const input = createDefinitionValidator(paramsType); const output = createDefinitionValidator(resultType);
|
||||
this.registrations.push(registry.registerRequest(`agent.${operation}`, async (params, context) => {
|
||||
const result = await this[operation](params, context); await this.#guard(context);
|
||||
if (!output(result)) throw fail("internal"); return result;
|
||||
}, { metadata: { capability: "plugin-agent", mutating: !["listBackends", "listChats", "history", "read"].includes(operation), permission: "ai.agent.use" },
|
||||
validateParams: (params) => { if (!input(params)) throw fail("invalidArgument"); return Object.freeze(structuredClone(params)); },
|
||||
authorization: async (params, context) => {
|
||||
await this.#guard(context);
|
||||
const chat = operation === "send" ? await this.#chat(params, context) : null;
|
||||
return { permission: "ai.agent.use", resources: ["*"], reason: "Use this plugin's configured global Agent conversation",
|
||||
...(operation !== "send" ? { deferDecision: true } : {}),
|
||||
...(chat ? { displayContext: { modelLabel: chat.backend.label,
|
||||
selections: chat.selection.items.map((item) => ({ title: item.title, scope: "session", version: "selected" })),
|
||||
action: { capabilityId: "agent.send", text: params.text } } } : {}),
|
||||
};
|
||||
},
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
async listBackends(_params, context) {
|
||||
const owner = await this.#guard(context); this.#prune();
|
||||
const result = await this.host.requestAgent("agent.backends", {}, context); await this.#guard(context);
|
||||
const items = [];
|
||||
for (const entry of result.backends) {
|
||||
let lease = [...this.backends.values()].find((item) => item.owner === owner && item.hostHandle === entry.hostHandle);
|
||||
if (!lease) {
|
||||
if (this.backends.size >= 256) throw fail("resourceExhausted");
|
||||
lease = { ...entry, backendRef: randomUUID(), owner, hostGeneration: this.host.generation, expiresAt: this.clock() + 300_000 };
|
||||
this.backends.set(lease.backendRef, lease);
|
||||
}
|
||||
const eligible = ["catty", "claude"].includes(entry.backend);
|
||||
items.push({ backendRef: lease.backendRef, backend: entry.backend, label: entry.label,
|
||||
status: eligible ? entry.status : entry.status === "unavailable" ? "unavailable" : "unsupported",
|
||||
reason: eligible || entry.status === "unavailable" ? entry.reason : "native-boundary-unverified" });
|
||||
}
|
||||
return { items };
|
||||
}
|
||||
|
||||
async selectTargets(_params, context) {
|
||||
const owner = await this.#guard(context); this.#prune();
|
||||
this.#observeTargets();
|
||||
if (this.selections.size >= 64) throw fail("resourceExhausted");
|
||||
const controller = new AbortController(); this.pendingSelections.set(controller, owner);
|
||||
let result;
|
||||
try {
|
||||
result = await this.host.requestAgent("agent.targets", {}, { ...context,
|
||||
signal: context.signal ? AbortSignal.any([controller.signal, context.signal]) : controller.signal });
|
||||
await this.#guard(context); controller.signal.throwIfAborted();
|
||||
} finally { this.pendingSelections.delete(controller); }
|
||||
const targets = result.targets.map((item) => {
|
||||
const binding = this.getSessionBinding(item.sessionId);
|
||||
if (!binding || !binding.isCurrent(binding)) throw fail("failedPrecondition");
|
||||
return Object.freeze({ ...binding, kind: "terminal", id: item.sessionId });
|
||||
});
|
||||
if (new Set(targets.map((target) => target.id)).size !== targets.length) throw fail("invalidArgument");
|
||||
const selectionHandle = randomUUID(); const expiresAt = this.clock() + 300_000;
|
||||
const items = result.targets.map((item) => ({ kind: "terminal", title: item.label }));
|
||||
this.selections.set(selectionHandle, { owner, targets, terminalSessions: structuredClone(result.targets), items, expiresAt });
|
||||
return { selectionHandle, expiresAt, items };
|
||||
}
|
||||
|
||||
async listChats(_params, context) {
|
||||
const owner = await this.#guard(context);
|
||||
const rows = await this.store.list(owner, () => this.#guard(context));
|
||||
return { items: rows.map((row) => ({ conversationRef: row.conversationRef, title: row.title, backend: row.agentId, updatedAt: row.updatedAt })) };
|
||||
}
|
||||
|
||||
async openChat(params, context) {
|
||||
const owner = await this.#guard(context); this.#prune();
|
||||
const backend = this.backends.get(params.backendRef); const selection = this.selections.get(params.selectionHandle);
|
||||
if (!backend || backend.owner !== owner || !["catty", "claude"].includes(backend.backend) || backend.status !== "supported"
|
||||
|| !selection || selection.owner !== owner || selection.expiresAt <= this.clock()) throw fail("permissionDenied");
|
||||
if (this.chats.size + this.pendingOpens.size >= 64 || [...this.chats.values()].filter((chat) => chat.owner === owner).length >= 8) throw fail("resourceExhausted");
|
||||
if (params.conversationRef && [...this.pendingOpens].some((item) => item.owner === owner && item.conversationRef === params.conversationRef)) throw fail("alreadyExists");
|
||||
const opening = { owner, conversationRef: params.conversationRef, active: true }; this.pendingOpens.add(opening); let scope;
|
||||
try {
|
||||
await this.#backendCurrent(backend, context);
|
||||
let record = params.conversationRef ? await this.store.read(owner, params.conversationRef, () => this.#guard(context)) : null;
|
||||
if (params.conversationRef && !record) throw fail("notFound");
|
||||
if (record && [...this.chats.values()].some((chat) => chat.owner === owner && chat.record.conversationRef === record.conversationRef)) throw fail("alreadyExists");
|
||||
const now = this.clock();
|
||||
record ??= { conversationRef: randomUUID(), id: `plugin-agent:${randomUUID()}`, title: "Global Agent chat", agentId: backend.backend,
|
||||
scope: { type: "global" }, messages: [], createdAt: now, updatedAt: now };
|
||||
// Durable conversation identity is conversationRef. A fresh runtime actor
|
||||
// never reuses revoked privacy/native/tool state when history is reopened.
|
||||
record.id = `plugin-agent:${randomUUID()}`;
|
||||
record.agentId = backend.backend; delete record.externalSessionId;
|
||||
const declared = normalizePermissionDeclarations(context.manifest).has("ai.agent.actions");
|
||||
const capabilities = declared && this.permission.getMode(context, "ai.agent.actions") !== "deny" ? CAPABILITIES : [];
|
||||
scope = await this.scopes.issue(context, { backend: { key: backend.backendRef, revision: backend.hostHandle,
|
||||
isCurrent: () => backend.expiresAt > this.clock() && backend.hostGeneration === this.host.generation }, targets: selection.targets, capabilities });
|
||||
if (!opening.active || await this.#guard(context) !== owner) throw fail("cancelled");
|
||||
await this.store.save(owner, record, async () => { if (!opening.active) throw fail("cancelled"); await this.#guard(context); });
|
||||
if (!opening.active || await this.#guard(context) !== owner) throw fail("cancelled");
|
||||
const chatHandle = randomUUID();
|
||||
this.chats.set(chatHandle, { handle: chatHandle, owner, backend, selection, record, scope, capabilities,
|
||||
expiresAt: Math.min(scope.expiresAt, selection.expiresAt, backend.expiresAt), hostGeneration: this.host.generation, activeTurn: null, generation: 0 });
|
||||
return { chatHandle, conversationRef: record.conversationRef, backendLabel: backend.label,
|
||||
expiresAt: this.chats.get(chatHandle).expiresAt };
|
||||
} catch (error) { if (scope) this.scopes.discard(scope.handle, owner); throw error; }
|
||||
finally { this.pendingOpens.delete(opening); }
|
||||
}
|
||||
|
||||
async #dispatchTool(turn, method, params, execute) {
|
||||
this.#assertNow(turn);
|
||||
if (++turn.toolCalls > 32) { this.#end(turn, "budget-exceeded"); throw fail("resourceExhausted"); }
|
||||
const spec = TOOLS.find((item) => item.rpcMethod === method);
|
||||
if (!spec || !turn.chat.capabilities.includes(spec.capabilityId)) throw fail("permissionDenied");
|
||||
let ids = [];
|
||||
if (spec.capabilityId === "session.environment") ids = turn.chat.selection.targets.map((target) => target.id);
|
||||
else if (["terminal.poll", "terminal.stop"].includes(spec.capabilityId)) {
|
||||
const id = this.getMcpBridge().getPluginAgentJobTarget(params.jobId, turn.chat.record.id);
|
||||
if (!id) throw fail("permissionDenied"); ids = [id];
|
||||
} else { if (typeof params.sessionId !== "string") throw fail("invalidArgument"); ids = [params.sessionId]; }
|
||||
const targets = ids.map((id) => {
|
||||
const target = turn.chat.selection.targets.find((item) => item.id === id);
|
||||
if (!target) throw fail("permissionDenied"); return target;
|
||||
});
|
||||
const preview = JSON.stringify(Object.fromEntries(Object.entries(params).filter(([key]) => !["chatSessionId", "scopedSessionIds"].includes(key))), null, 2);
|
||||
if (Buffer.byteLength(preview) > 16_384) throw fail("resourceExhausted");
|
||||
const ctx = { ...turn.context, agentChatId: turn.chat.record.id, agentBackendLabel: turn.chat.backend.label,
|
||||
agentTargetLabels: new Map(turn.chat.selection.terminalSessions.map((item) => [item.sessionId, item.label])), agentToolPreview: preview };
|
||||
try { await this.#backendCurrent(turn.chat.backend, ctx); }
|
||||
catch (error) { this.#end(turn, "unavailable"); throw error; }
|
||||
return this.scopes.dispatch(turn.ticket, ctx, { capabilityId: spec.capabilityId, targets }, async (execution) => {
|
||||
this.#assertNow(turn); const result = await execute(execution); this.#assertNow(turn); return result;
|
||||
});
|
||||
}
|
||||
|
||||
async send(params, context) {
|
||||
const chat = await this.#chat(params, context); const owner = chat.owner;
|
||||
this.#prune();
|
||||
if (!params.text.trim()) throw fail("invalidArgument");
|
||||
if (this.turns.size >= 256 || chat.activeTurn || Buffer.byteLength(params.text) > 16_384 || chat.record.messages.length > 198) throw fail("resourceExhausted");
|
||||
const controller = new AbortController(); const turn = { handle: randomUUID(), owner, chat, controller, context: { ...context, signal: controller.signal },
|
||||
done: false, reading: false, bytes: 0, toolCalls: 0, generation: ++chat.generation, expiresAt: this.clock() + 300_000, hostHandle: null,
|
||||
policyRevision: this.permission.getPolicyRevision(this.database.getActivePlugin(owner.pluginId)), senderId: this.host.getSenderId() };
|
||||
chat.activeTurn = turn; this.turns.set(turn.handle, turn);
|
||||
try {
|
||||
this.#charge(owner); await this.#backendCurrent(chat.backend, context);
|
||||
turn.ticket = await this.scopes.begin(chat.scope.handle, context);
|
||||
turn.ticket.controller.signal.addEventListener("abort", () => this.#end(turn), { once: true });
|
||||
this.#assertNow(turn);
|
||||
const mcp = this.getMcpBridge();
|
||||
turn.registration = mcp.registerPluginAgentDelegation(chat.record.id, { turnTag: turn.handle, senderId: turn.senderId,
|
||||
tools: TOOLS.filter((tool) => chat.capabilities.includes(tool.capabilityId)).map((tool) => tool.mcpTool),
|
||||
assertCurrent: () => this.#assertNow(turn), dispatch: (method, payload, execute) => this.#dispatchTool(turn, method, payload, execute) });
|
||||
mcp.setChatSessionCancelled(chat.record.id, false);
|
||||
turn.timer = setTimeout(() => this.#end(turn, "budget-exceeded"), Math.max(1, Math.min(120_000, chat.expiresAt - this.clock()))); turn.timer.unref?.();
|
||||
const prior = structuredClone(chat.record);
|
||||
chat.record.messages.push({ id: randomUUID(), role: "user", content: params.text, timestamp: this.clock() });
|
||||
chat.record.updatedAt = this.clock();
|
||||
if (chat.record.title === "Global Agent chat") chat.record.title = params.text.trim().split(/\r?\n/u)[0].slice(0, 80);
|
||||
prior.title = chat.record.title;
|
||||
await this.store.save(owner, chat.record, async () => { await this.#guard(context); this.#assertNow(turn); });
|
||||
const result = await this.host.requestAgent("agent.run", { backendHandle: chat.backend.hostHandle, delegationTag: turn.handle,
|
||||
session: prior, capabilities: chat.capabilities, terminalSessions: chat.selection.terminalSessions, text: params.text, maxIterations: 12 }, turn.context);
|
||||
this.#assertNow(turn); turn.hostHandle = result.hostHandle;
|
||||
return { turnHandle: turn.handle, expiresAt: turn.expiresAt };
|
||||
} catch (error) { this.#end(turn); throw error; }
|
||||
}
|
||||
|
||||
async read(params, context) {
|
||||
const turn = await this.#turn(params, context);
|
||||
if (turn.done) return turn.endEvent;
|
||||
if (turn.reading) throw fail("alreadyExists"); turn.reading = true;
|
||||
try {
|
||||
this.#assertNow(turn);
|
||||
await this.#backendCurrent(turn.chat.backend, context);
|
||||
const result = await this.host.requestAgent("agent.next", { hostHandle: turn.hostHandle },
|
||||
{ ...context, signal: AbortSignal.any([context.signal ?? new AbortController().signal, turn.controller.signal]) });
|
||||
this.#assertNow(turn);
|
||||
if (result.session) {
|
||||
if (!this.sessionValidator(result.session) || result.session.id !== turn.chat.record.id
|
||||
|| result.session.conversationRef !== turn.chat.record.conversationRef || result.session.agentId !== turn.chat.backend.backend) throw fail("internal");
|
||||
turn.chat.record = structuredClone(result.session);
|
||||
await this.store.save(turn.owner, turn.chat.record, async () => { await this.#guard(context); this.#assertNow(turn); });
|
||||
}
|
||||
const event = result.done ? { kind: "end", reason: "completed" } : result.event;
|
||||
if (!this.eventValidator(event)) throw fail("internal");
|
||||
turn.bytes += Buffer.byteLength(JSON.stringify(event));
|
||||
if (turn.bytes > 262_144) throw fail("resourceExhausted");
|
||||
if (event.kind === "end") this.#end(turn, event.reason);
|
||||
return event;
|
||||
} catch (error) { if (turn.done) return turn.endEvent; this.#end(turn, error.code === RPC_ERRORS.resourceExhausted ? "budget-exceeded" : "unavailable"); throw error; }
|
||||
finally { turn.reading = false; }
|
||||
}
|
||||
|
||||
async history(params, context) {
|
||||
const chat = await this.#chat(params, context); const items = []; let bytes = 0;
|
||||
for (const message of [...chat.record.messages].reverse()) {
|
||||
if (!["user", "assistant"].includes(message?.role) || typeof message.content !== "string") continue;
|
||||
const text = message.content.slice(0, 32_768); bytes += Buffer.byteLength(text);
|
||||
if (bytes > 131_072) break; items.unshift({ role: message.role, text });
|
||||
}
|
||||
return { items };
|
||||
}
|
||||
|
||||
#end(turn, reason = "cancelled") {
|
||||
if (turn.done) return;
|
||||
const wasCurrent = turn.chat.activeTurn === turn;
|
||||
turn.done = true; turn.endEvent = { kind: "end", reason }; clearTimeout(turn.timer); turn.controller.abort();
|
||||
if (turn.ticket) this.scopes.finish(turn.ticket);
|
||||
turn.registration?.dispose();
|
||||
if (wasCurrent) {
|
||||
turn.chat.activeTurn = null;
|
||||
try { this.getMcpBridge().applyChatSessionCancelled(turn.chat.record.id, true); } catch {}
|
||||
}
|
||||
if (turn.hostHandle) void this.host.requestAgent("agent.release", { hostHandle: turn.hostHandle },
|
||||
{ ...turn.context, signal: undefined }).catch(() => {});
|
||||
}
|
||||
async stop(params, context) { const turn = await this.#turn(params, context); this.#end(turn); return { ok: true }; }
|
||||
async closeChat(params, context) {
|
||||
const chat = await this.#chat(params, context);
|
||||
this.#forgetChat(chat); this.chats.delete(chat.handle); return { ok: true };
|
||||
}
|
||||
#forgetChat(chat) {
|
||||
if (chat.activeTurn) this.#end(chat.activeTurn);
|
||||
this.scopes.discard(chat.scope.handle, chat.owner);
|
||||
try { this.host.releaseAgentChat?.(chat.record.id, chat.owner.runtimeId); } catch {}
|
||||
try { void this.getMcpBridge().cleanupScopedMetadata?.(chat.record.id)?.catch(() => {}); } catch {}
|
||||
}
|
||||
releaseRuntime(runtimeId) {
|
||||
for (const [controller, owner] of this.pendingSelections) if (owner.runtimeId === runtimeId) controller.abort();
|
||||
for (const turn of this.turns.values()) if (turn.owner.runtimeId === runtimeId) this.#end(turn);
|
||||
for (const chat of this.chats.values()) if (chat.owner.runtimeId === runtimeId) this.#forgetChat(chat);
|
||||
for (const opening of this.pendingOpens) if (opening.owner.runtimeId === runtimeId) opening.active = false;
|
||||
for (const map of [this.backends, this.selections, this.chats, this.turns]) for (const [id, entry] of map) if (entry.owner.runtimeId === runtimeId) map.delete(id);
|
||||
this.scopes.releaseRuntime(runtimeId); this.source.releaseRuntime(runtimeId); this.host.releaseRuntime(runtimeId);
|
||||
}
|
||||
releasePlugin(pluginId) {
|
||||
const ids = new Set([...this.source.bindings.values()].filter((owner) => owner.pluginId === pluginId).map((owner) => owner.runtimeId));
|
||||
for (const id of ids) this.releaseRuntime(id);
|
||||
}
|
||||
releaseAll() { for (const id of [...this.source.bindings.keys()]) this.releaseRuntime(id); }
|
||||
shutdown() {
|
||||
this.releaseAll(); this.closed = true; this.scopes.shutdown(); this.source.shutdown(); this.revocation.dispose(); this.hostInvalidation();
|
||||
for (const item of this.registrations) item.dispose(); this.host.shutdown();
|
||||
for (const item of this.targetSubscriptions) item.dispose(); this.targetSubscriptions = [];
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { PluginAgentService, PLUGIN_AGENT_FEATURE: FEATURE, PLUGIN_AGENT_CAPABILITIES: CAPABILITIES };
|
||||
@@ -1,171 +0,0 @@
|
||||
"use strict";
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { PluginAgentService } = require("./agentService.cjs");
|
||||
const { PluginAgentConversationStore } = require("./conversationStore.cjs");
|
||||
const { PluginAgentMcpDelegations } = require("./mcpDelegation.cjs");
|
||||
const { PluginPermissionEngine } = require("../permissionEngine.cjs");
|
||||
const { PluginHostRpcRegistry } = require("../hostRpcRegistry.cjs");
|
||||
|
||||
function deferred() { let resolve; const promise = new Promise((done) => { resolve = done; }); return { promise, resolve }; }
|
||||
function fixture(t) {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-agent-service-"));
|
||||
const manifest = { id: "com.example.agent", publisher: "example", version: "1.0.0", permissions: { required: ["ai.agent.use", "ai.agent.actions"] } };
|
||||
let identity = { pluginId: manifest.id, pluginVersion: manifest.version, runtimeId: "r1", runtimeKind: "browser", manifest };
|
||||
let sourceId = "source-a"; let time = 1; let locked = false; const modes = new Map(); let focus = "a"; let effects = 0;
|
||||
const audits = []; const decisions = []; const hostRequests = []; const invalidations = new Set();
|
||||
const plugin = () => ({ id: manifest.id, enabled: true, activeVersion: manifest.version, manifest,
|
||||
source: { id: sourceId, kind: "third-party", origin: "https://synthetic.invalid" }, runtime: { status: "running" } });
|
||||
const database = { getActivePlugin: (id) => id === manifest.id ? plugin() : null,
|
||||
getRetainedPluginSource: () => plugin().source, privateOwner: () => `opaque-owner:${sourceId}`,
|
||||
publicPluginId: (owner) => owner === `opaque-owner:${sourceId}` ? manifest.id : null,
|
||||
getPermissionMode: (_id, permission) => modes.get(permission) ?? "allow",
|
||||
listPermissionGrants: () => [], recordSecurityAudit: (_id, event, value) => audits.push({ event, ...value }) };
|
||||
let approve = async (request) => ({ requestId: request.requestId, decision: "allow", scope: "once" });
|
||||
const permission = new PluginPermissionEngine({ database, requestDecision: (request) => { decisions.push(request); return approve(request); } });
|
||||
const targetState = new Map([["a", { owner: "7", revision: "worker-a:1" }], ["b", { owner: "8", revision: "worker-a:2" }]]);
|
||||
const backendHandle = randomUUID(); const externalHandle = randomUUID();
|
||||
const sessions = new Map(); const events = [];
|
||||
let run = async (payload) => { const handle = randomUUID(); sessions.set(handle, structuredClone(payload.session)); return { hostHandle: handle }; };
|
||||
let current = true;
|
||||
let choose = async () => ({ targets: [...targetState.keys()].map((id) => ({ sessionId: id, hostname: `${id}.invalid`, label: `Synthetic ${id}`, connected: true })) });
|
||||
const resourceListeners = new Set();
|
||||
const watch = (callback) => { resourceListeners.add(callback); return { dispose: () => resourceListeners.delete(callback) }; };
|
||||
const targetManager = { onSessionOwned: watch, onSessionClosed: watch, onWorkerExit: watch };
|
||||
const host = { generation: 1, getSenderId: () => 7,
|
||||
assertActive: async (context) => { await context.assertActive(); if (locked) throw Error("Locked"); },
|
||||
onDidInvalidate: (callback) => { invalidations.add(callback); return () => invalidations.delete(callback); },
|
||||
requestAgent: async (kind, payload) => {
|
||||
hostRequests.push({ kind, payload: structuredClone(payload) });
|
||||
if (kind === "agent.backends") return { backends: [
|
||||
{ hostHandle: backendHandle, backend: "catty", label: "Catty fixture", status: "supported", reason: "ready" },
|
||||
{ hostHandle: externalHandle, backend: "claude", label: "Claude fixture", status: "supported", reason: "ready" },
|
||||
{ hostHandle: randomUUID(), backend: "codex", label: "Codex fixture", status: "supported", reason: "ready" },
|
||||
] };
|
||||
if (kind === "agent.current") return { current };
|
||||
if (kind === "agent.targets") return choose();
|
||||
if (kind === "agent.run") return run(payload);
|
||||
if (kind === "agent.next") return { done: false, event: events.shift() ?? { kind: "end", reason: "completed" }, session: sessions.get(payload.hostHandle) };
|
||||
return { ok: true };
|
||||
}, releaseRuntime: () => {}, shutdown: () => {} };
|
||||
const delegation = new PluginAgentMcpDelegations();
|
||||
const mcp = { registerPluginAgentDelegation: (...args) => delegation.register(...args),
|
||||
setChatSessionCancelled: () => {}, applyChatSessionCancelled: () => {}, getPluginAgentJobTarget: () => null };
|
||||
const service = new PluginAgentService({ database, permissionEngine: permission, hostAdapter: host,
|
||||
conversationStore: new PluginAgentConversationStore(directory), getRuntimeIdentity: () => identity, getMcpBridge: () => mcp, clock: () => time,
|
||||
getTargetManager: () => targetManager,
|
||||
getSessionBinding: (id) => { const snapshot = targetState.get(id); return snapshot && { ...snapshot,
|
||||
isCurrent: (target) => targetState.get(id)?.owner === target.owner && targetState.get(id)?.revision === target.revision }; } });
|
||||
const registry = new PluginHostRpcRegistry(); registry.use(permission.createMiddleware()); service.registerRpcCapabilities(registry);
|
||||
const call = (method, params = {}, overrides = {}) => registry.createRoutes(identity).requestHandlers[`agent.${method}`](params, { signal: new AbortController().signal, ...overrides });
|
||||
const open = async (backend = "catty", conversationRef) => {
|
||||
const backends = await call("listBackends"); const selection = await call("selectTargets");
|
||||
return call("openChat", { backendRef: backends.items.find((item) => item.backend === backend).backendRef, selectionHandle: selection.selectionHandle, ...(conversationRef ? { conversationRef } : {}) });
|
||||
};
|
||||
const dispatch = async (turn, id = "a") => {
|
||||
const internal = service.turns.get(turn.turnHandle); if (!internal) throw Error("Turn unavailable");
|
||||
return delegation.dispatch("netcatty/exec", { chatSessionId: internal.chat.record.id, sessionId: id, command: "printf synthetic" },
|
||||
{ trustedAgentSenderId: 7, trustedAgentTurnTag: turn.turnHandle }, (context) => { context.beforeExecute(); effects++; return "synthetic"; });
|
||||
};
|
||||
t.after(() => { service.shutdown(); delegation.shutdown(); permission.shutdown(); fs.rmSync(directory, { recursive: true, force: true }); });
|
||||
return { service, call, open, dispatch, events, sessions, hostRequests, decisions, audits, host, delegation, targetState,
|
||||
effects: () => effects, focusTo: (id) => { focus = id; }, focus: () => focus, modeTo: (value, permission = "ai.agent.actions") => { modes.set(permission, value); },
|
||||
approve: (fn) => { approve = fn; }, run: (fn) => { run = fn; }, tick: (ms) => { time += ms; },
|
||||
choose: (fn) => { choose = fn; }, resourceChanged: () => { for (const callback of resourceListeners) callback(); },
|
||||
replaceSource: () => { sourceId = "source-b"; }, currentTo: (value) => { current = value; },
|
||||
restart: () => { service.releaseRuntime(identity.runtimeId); identity = { ...identity, runtimeId: randomUUID() }; },
|
||||
lock: () => { locked = true; host.generation++; for (const callback of invalidations) callback(); } };
|
||||
}
|
||||
|
||||
test("registered Agent routes validate opaque authority, report unsupported modes and preserve core-only native history", async (t) => {
|
||||
const f = fixture(t); const backends = await f.call("listBackends");
|
||||
assert.equal(backends.items.find((entry) => entry.backend === "codex").status, "unsupported");
|
||||
await assert.rejects(f.call("openChat", { backendRef: randomUUID(), selectionHandle: randomUUID(), permissionMode: "auto" }));
|
||||
const chat = await f.open(); const turn = await f.call("send", { chatHandle: chat.chatHandle, text: "Synthetic conversation" });
|
||||
const [handle, session] = [...f.sessions][0];
|
||||
session.messages = [{ role: "user", content: "Synthetic conversation" }, { role: "assistant", content: "Synthetic answer" }];
|
||||
session.externalSessionId = "NATIVE_PRIVATE_SESSION"; f.events.push({ kind: "text", text: "Synthetic answer" });
|
||||
assert.deepEqual(await f.call("read", { turnHandle: turn.turnHandle }), { kind: "text", text: "Synthetic answer" });
|
||||
await f.call("read", { turnHandle: turn.turnHandle });
|
||||
assert.deepEqual(await f.call("history", { chatHandle: chat.chatHandle }), { items: [
|
||||
{ role: "user", text: "Synthetic conversation" }, { role: "assistant", text: "Synthetic answer" } ] });
|
||||
const summaries = await f.call("listChats"); assert.doesNotMatch(JSON.stringify({ chat, turn, summaries }), /NATIVE_|opaque-owner|source-a|plugin-agent:/);
|
||||
await f.call("closeChat", { chatHandle: chat.chatHandle });
|
||||
const reopened = await f.open("claude", chat.conversationRef);
|
||||
assert.equal(f.service.chats.get(reopened.chatHandle).record.externalSessionId, undefined);
|
||||
assert.equal((await f.call("history", { chatHandle: reopened.chatHandle })).items.length, 2);
|
||||
assert.ok(handle); f.restart(); f.replaceSource();
|
||||
assert.deepEqual(await f.call("listChats"), { items: [] });
|
||||
await assert.rejects(f.open("catty", chat.conversationRef));
|
||||
});
|
||||
|
||||
test("actual source policy decides once per tool and targets never follow focus across workspaces", async (t) => {
|
||||
const f = fixture(t); f.modeTo("ask"); const chat = await f.open();
|
||||
const turn = await f.call("send", { chatHandle: chat.chatHandle, text: "Synthetic action" }); f.focusTo("unselected");
|
||||
assert.equal(await f.dispatch(turn, "b"), "synthetic"); assert.equal(f.effects(), 1); assert.equal(f.decisions.length, 1);
|
||||
assert.equal(f.decisions[0].permission, "ai.agent.actions"); assert.equal(f.decisions[0].displayContext.action.capabilityId, "terminal.execute");
|
||||
await assert.rejects(f.dispatch(turn, f.focus())); assert.equal(f.effects(), 1); assert.equal(f.decisions.length, 1);
|
||||
f.approve(async (request) => ({ requestId: request.requestId, decision: "deny" }));
|
||||
await assert.rejects(f.dispatch(turn)); assert.equal(f.effects(), 1); assert.equal(f.decisions.length, 2);
|
||||
const entered = deferred(); const resume = deferred();
|
||||
f.approve(async (request) => { entered.resolve(); await resume.promise; return { requestId: request.requestId, decision: "allow", scope: "once" }; });
|
||||
const pending = f.dispatch(turn); const rejection = assert.rejects(pending); await entered.promise;
|
||||
f.targetState.set("a", { owner: "new-window", revision: "new-generation" }); resume.resolve(); await rejection;
|
||||
assert.equal(f.effects(), 1);
|
||||
});
|
||||
|
||||
test("Actions Deny keeps model conversation available with no tools; Agent-use Deny prevents host dispatch", async (t) => {
|
||||
const f = fixture(t); f.modeTo("deny"); const chat = await f.open();
|
||||
const turn = await f.call("send", { chatHandle: chat.chatHandle, text: "Synthetic model-only intent" });
|
||||
const internal = f.service.turns.get(turn.turnHandle);
|
||||
assert.deepEqual(f.delegation.configuration(internal.chat.record.id, turn.turnHandle).tools, []);
|
||||
await assert.rejects(f.dispatch(turn)); assert.equal(f.effects(), 0); assert.equal(f.decisions.length, 0);
|
||||
await f.call("stop", { turnHandle: turn.turnHandle });
|
||||
f.modeTo("deny", "ai.agent.use"); const count = f.hostRequests.length;
|
||||
await assert.rejects(f.call("send", { chatHandle: chat.chatHandle, text: "Denied" })); assert.equal(f.hostRequests.length, count);
|
||||
});
|
||||
|
||||
test("source replacement, lock and backend changes revoke native work and reject late events", async (t) => {
|
||||
for (const kind of ["source", "lock", "backend"]) {
|
||||
const f = fixture(t); const chat = await f.open(); const turn = await f.call("send", { chatHandle: chat.chatHandle, text: "Synthetic" });
|
||||
const internal = f.service.turns.get(turn.turnHandle); const native = new AbortController();
|
||||
f.delegation.onRelease(internal.chat.record.id, turn.turnHandle, () => native.abort());
|
||||
if (kind === "source") f.replaceSource(); else if (kind === "lock") f.lock(); else f.currentTo(false);
|
||||
await assert.rejects(f.dispatch(turn)); assert.equal(native.signal.aborted, true); assert.equal(f.effects(), 0);
|
||||
if (kind !== "backend") await assert.rejects(f.call("read", { turnHandle: turn.turnHandle }));
|
||||
}
|
||||
});
|
||||
|
||||
test("per-source turn budget survives runtime restart and is isolated from a different source", async (t) => {
|
||||
const f = fixture(t); let chat = await f.open();
|
||||
for (let i = 0; i < 6; i++) { const turn = await f.call("send", { chatHandle: chat.chatHandle, text: "Synthetic" }); await f.call("stop", { turnHandle: turn.turnHandle }); }
|
||||
f.restart(); chat = await f.open(); await assert.rejects(f.call("send", { chatHandle: chat.chatHandle, text: "Over budget" }));
|
||||
f.restart(); f.replaceSource(); chat = await f.open();
|
||||
assert.ok((await f.call("send", { chatHandle: chat.chatHandle, text: "Isolated source" })).turnHandle);
|
||||
});
|
||||
|
||||
test("late start/open completion after release cannot publish handles or affect a replacement turn", async (t) => {
|
||||
const f = fixture(t); const chat = await f.open(); const entered = deferred(); const resume = deferred();
|
||||
f.run(async () => { entered.resolve(); await resume.promise; return { hostHandle: randomUUID() }; });
|
||||
const starting = f.call("send", { chatHandle: chat.chatHandle, text: "Delayed synthetic start" }); const rejected = assert.rejects(starting);
|
||||
await entered.promise; f.restart(); resume.resolve(); await rejected; assert.equal(f.service.chats.size, 0); assert.equal(f.service.turns.size, 0);
|
||||
const next = await f.open(); f.tick(300_001);
|
||||
await assert.rejects(f.call("send", { chatHandle: next.chatHandle, text: "Expired" }));
|
||||
assert.ok((await f.open()).chatHandle); assert.equal(f.service.chats.size, 1);
|
||||
});
|
||||
|
||||
test("worker lifecycle during target confirmation cannot silently bind a replacement connection or leave native work running", async (t) => {
|
||||
const f = fixture(t); const chat = await f.open(); const turn = await f.call("send", { chatHandle: chat.chatHandle, text: "Synthetic pending work" });
|
||||
const internal = f.service.turns.get(turn.turnHandle); const native = new AbortController();
|
||||
f.delegation.onRelease(internal.chat.record.id, turn.turnHandle, () => native.abort());
|
||||
const entered = deferred(); const resume = deferred();
|
||||
f.choose(async () => { entered.resolve(); await resume.promise; return { targets: [{ sessionId: "a", hostname: "a.invalid", label: "Synthetic a", connected: true }] }; });
|
||||
const pending = f.call("selectTargets"); const rejected = assert.rejects(pending); await entered.promise;
|
||||
f.targetState.set("a", { owner: "replacement-window", revision: "replacement-generation" }); f.resourceChanged();
|
||||
assert.equal(native.signal.aborted, true); assert.equal(f.service.chats.size, 0);
|
||||
const count = f.service.selections.size; resume.resolve(); await rejected; assert.equal(f.service.selections.size, count);
|
||||
});
|
||||
@@ -1,47 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { createDefinitionValidator } = require("../contractValidator.cjs");
|
||||
|
||||
test("Agent wire accepts only opaque host configuration/scope refs, never raw backend authority", () => {
|
||||
const open = createDefinitionValidator("PluginAgentOpenParams");
|
||||
const params = { backendRef: randomUUID(), selectionHandle: randomUUID() };
|
||||
assert.equal(open(params), true);
|
||||
for (const [key, value] of Object.entries({ permissionMode: "auto", owner: "source:forged", privateOwner: "forged",
|
||||
source: "official", model: "chosen", agentId: "claude", apiKey: "synthetic-not-a-key", cli: "node",
|
||||
env: {}, mcpServers: {}, sessionIds: ["focused-session"], externalSessionId: "native-session" })) {
|
||||
assert.equal(open({ ...params, [key]: value }), false, key);
|
||||
}
|
||||
for (const key of ["backendRef", "selectionHandle", "conversationRef"]) {
|
||||
assert.equal(open({ ...params, [key]: "internal-or-path-id" }), false, key);
|
||||
}
|
||||
});
|
||||
|
||||
test("Agent messages and events are bounded and do not serialize raw tools/configuration", () => {
|
||||
const send = createDefinitionValidator("PluginAgentSendParams");
|
||||
const params = { chatHandle: randomUUID(), text: "Synthetic user instruction" };
|
||||
assert.equal(send(params), true);
|
||||
assert.equal(send({ ...params, text: "x".repeat(16_385) }), false);
|
||||
assert.equal(send({ ...params, text: "a\0b" }), false);
|
||||
assert.equal(send({ ...params, turnId: "builtin" }), false);
|
||||
const event = createDefinitionValidator("PluginAgentEvent");
|
||||
assert.equal(event({ kind: "activity", capabilityId: "terminal.execute", state: "started" }), true);
|
||||
assert.equal(event({ kind: "activity", capabilityId: "terminal.execute", state: "started", args: { command: "raw" } }), false);
|
||||
assert.equal(event({ kind: "usage", inputTokens: 2, outputTokens: 4 }), true);
|
||||
assert.equal(event({ kind: "usage", inputTokens: -1, outputTokens: 4 }), false);
|
||||
assert.equal(event({ kind: "text", text: "x".repeat(4097) }), false);
|
||||
assert.equal(event({ kind: "provider-error", message: "private diagnostics" }), false);
|
||||
});
|
||||
|
||||
test("public chat/history summaries do not contain backend/native identifiers, prompts or tool results", () => {
|
||||
const chats = createDefinitionValidator("PluginAgentChatsResult");
|
||||
const chat = { conversationRef: randomUUID(), title: "Synthetic chat", backend: "claude", updatedAt: 1 };
|
||||
assert.equal(chats({ items: [chat] }), true);
|
||||
assert.equal(chats({ items: [{ ...chat, externalSessionId: "native" }] }), false);
|
||||
const history = createDefinitionValidator("PluginAgentHistoryResult");
|
||||
assert.equal(history({ items: [{ role: "assistant", text: "Summary" }] }), true);
|
||||
assert.equal(history({ items: [{ role: "tool", text: "Raw tool result" }] }), false);
|
||||
assert.equal(history({ items: [{ role: "assistant", text: "Summary", apiKey: "synthetic" }] }), false);
|
||||
});
|
||||
@@ -1,122 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { createHash, randomUUID } = require("node:crypto");
|
||||
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
||||
const MAX_BYTES = 1_048_576;
|
||||
const MAX_CONVERSATIONS = 64;
|
||||
|
||||
// Core-owned AISession documents, outside plugin filesystem/storage roots.
|
||||
// The caller must authenticate provenance before supplying the opaque owner.
|
||||
// Native resume identity, compaction and tool history stay in this repository;
|
||||
// only a separate public projection is returned through the plugin API.
|
||||
class PluginAgentConversationStore {
|
||||
constructor(directory) {
|
||||
if (!path.isAbsolute(directory)) throw new TypeError("Absolute host history directory required");
|
||||
this.directory = directory;
|
||||
this.pending = new Map();
|
||||
}
|
||||
|
||||
#ownerDirectory(owner) {
|
||||
if (!owner || typeof owner.privateOwner !== "string" || !owner.privateOwner
|
||||
|| typeof owner.sourceKey !== "string" || !owner.sourceKey) throw new TypeError("Host provenance required");
|
||||
return path.join(this.directory, createHash("sha256").update(JSON.stringify([owner.sourceKey, owner.privateOwner])).digest("hex"));
|
||||
}
|
||||
|
||||
#filename(owner, id) {
|
||||
if (typeof id !== "string" || !UUID.test(id)) throw new TypeError("Invalid owned conversation reference");
|
||||
return path.join(this.#ownerDirectory(owner), `${id}.json`);
|
||||
}
|
||||
|
||||
async #prepare(owner) {
|
||||
await fs.mkdir(this.directory, { recursive: true, mode: 0o700 });
|
||||
if (!(await fs.lstat(this.directory)).isDirectory() || (await fs.lstat(this.directory)).isSymbolicLink()) throw Error("History root unavailable");
|
||||
const directory = this.#ownerDirectory(owner);
|
||||
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
||||
const stat = await fs.lstat(directory);
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error("History owner unavailable");
|
||||
return directory;
|
||||
}
|
||||
|
||||
#validate(record) {
|
||||
if (!record || typeof record !== "object" || !UUID.test(record.conversationRef)
|
||||
|| typeof record.id !== "string" || !record.id.startsWith("plugin-agent:")
|
||||
|| record.scope?.type !== "global" || record.scope.targetId !== undefined
|
||||
|| typeof record.agentId !== "string" || typeof record.title !== "string" || record.title.length > 160
|
||||
|| !Array.isArray(record.messages) || record.messages.length > 200
|
||||
|| !Number.isSafeInteger(record.createdAt) || !Number.isSafeInteger(record.updatedAt)) throw new TypeError("Invalid core Agent history");
|
||||
const text = JSON.stringify(record);
|
||||
if (Buffer.byteLength(text) > MAX_BYTES) throw new RangeError("Agent history budget exceeded");
|
||||
return text;
|
||||
}
|
||||
|
||||
async #serial(owner, operation) {
|
||||
const key = this.#ownerDirectory(owner);
|
||||
const previous = this.pending.get(key) ?? Promise.resolve();
|
||||
const current = previous.catch(() => {}).then(operation);
|
||||
this.pending.set(key, current);
|
||||
try { return await current; }
|
||||
finally { if (this.pending.get(key) === current) this.pending.delete(key); }
|
||||
}
|
||||
|
||||
async list(owner, assertCurrent) {
|
||||
await assertCurrent();
|
||||
const directory = await this.#prepare(owner);
|
||||
const files = await fs.readdir(directory);
|
||||
const records = [];
|
||||
for (const file of files) {
|
||||
const id = file.slice(0, -5);
|
||||
if (!file.endsWith(".json") || !UUID.test(id)) continue;
|
||||
if (records.length >= MAX_CONVERSATIONS) break;
|
||||
const record = await this.read(owner, id, assertCurrent);
|
||||
if (record) records.push(record);
|
||||
}
|
||||
await assertCurrent();
|
||||
return records.sort((a, b) => b.updatedAt - a.updatedAt);
|
||||
}
|
||||
|
||||
async read(owner, id, assertCurrent) {
|
||||
await assertCurrent();
|
||||
const filename = this.#filename(owner, id);
|
||||
await this.#prepare(owner);
|
||||
let file;
|
||||
try {
|
||||
// O_NOFOLLOW avoids following a replaced final path. Core owns ancestors.
|
||||
const { constants } = require("node:fs");
|
||||
file = await fs.open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
||||
const stat = await file.stat();
|
||||
if (!stat.isFile() || stat.size > MAX_BYTES) throw Error("Agent history unavailable");
|
||||
const record = JSON.parse(await file.readFile("utf8"));
|
||||
this.#validate(record);
|
||||
if (record.conversationRef !== id) throw Error("Agent history identity mismatch");
|
||||
await assertCurrent();
|
||||
return record;
|
||||
} catch (error) {
|
||||
if (error.code === "ENOENT") { await assertCurrent(); return null; }
|
||||
throw error;
|
||||
} finally { await file?.close(); }
|
||||
}
|
||||
|
||||
async save(owner, record, assertCurrent) {
|
||||
// Clone/serialize before any await so caller mutation cannot change commit.
|
||||
const text = this.#validate(record);
|
||||
const id = record.conversationRef;
|
||||
return this.#serial(owner, async () => {
|
||||
await assertCurrent();
|
||||
const directory = await this.#prepare(owner);
|
||||
const filename = this.#filename(owner, id);
|
||||
const entries = (await fs.readdir(directory)).filter((name) => name.endsWith(".json"));
|
||||
if (!entries.includes(`${id}.json`) && entries.length >= MAX_CONVERSATIONS) throw new RangeError("Agent conversation budget exceeded");
|
||||
const temporary = path.join(directory, `.${randomUUID()}.tmp`);
|
||||
try {
|
||||
await fs.writeFile(temporary, text, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
||||
await assertCurrent();
|
||||
await fs.rename(temporary, filename);
|
||||
} finally { await fs.rm(temporary, { force: true }); }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { PluginAgentConversationStore };
|
||||
@@ -1,68 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { PluginAgentConversationStore } = require("./conversationStore.cjs");
|
||||
|
||||
const owner = (source) => ({ privateOwner: `opaque:${source}:same-plugin-id`, sourceKey: `source:${source}` });
|
||||
const current = async () => {};
|
||||
function record() {
|
||||
const conversationRef = randomUUID();
|
||||
return { conversationRef, id: `plugin-agent:${randomUUID()}`, title: "Synthetic chat", agentId: "catty",
|
||||
scope: { type: "global" }, messages: [{ id: randomUUID(), role: "user", content: "Synthetic only", timestamp: 1 }], createdAt: 1, updatedAt: 1 };
|
||||
}
|
||||
async function fixture(t) {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "netcatty-agent-history-test-"));
|
||||
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
||||
return { root, store: new PluginAgentConversationStore(path.join(root, "core-history")) };
|
||||
}
|
||||
|
||||
test("core history survives reopening, uses existing AISession shape and isolates the same plugin ID across sources", async (t) => {
|
||||
const { root, store } = await fixture(t); const chat = record();
|
||||
await store.save(owner("a"), chat, current);
|
||||
assert.deepEqual(await store.read(owner("a"), chat.conversationRef, current), chat);
|
||||
const [directory] = await fs.readdir(path.join(root, "core-history"));
|
||||
assert.doesNotMatch(directory, /opaque|same-plugin/);
|
||||
const mode = (await fs.stat(path.join(root, "core-history", directory, `${chat.conversationRef}.json`))).mode;
|
||||
if (process.platform !== "win32") assert.equal(mode & 0o777, 0o600);
|
||||
assert.equal(await store.read(owner("b"), chat.conversationRef, current), null);
|
||||
assert.deepEqual(await store.list(owner("b"), current), []);
|
||||
const reopened = new PluginAgentConversationStore(path.join(root, "core-history"));
|
||||
assert.deepEqual(await reopened.list(owner("a"), current), [chat]);
|
||||
});
|
||||
|
||||
test("source revoked before async rename leaves previous history intact and cleans temporary files", async (t) => {
|
||||
const { store, root } = await fixture(t); const chat = record(); await store.save(owner("a"), chat, current);
|
||||
const next = { ...chat, title: "Must not commit" }; let checks = 0;
|
||||
await assert.rejects(store.save(owner("a"), next, async () => { if (++checks === 2) throw Error("Revoked"); }));
|
||||
assert.equal((await store.read(owner("a"), chat.conversationRef, current)).title, chat.title);
|
||||
const [directory] = await fs.readdir(path.join(root, "core-history"));
|
||||
assert.deepEqual(await fs.readdir(path.join(root, "core-history", directory)), [`${chat.conversationRef}.json`]);
|
||||
});
|
||||
|
||||
test("history snapshots cannot mutate across await, and traversal/builtin IDs/oversized records are rejected", async (t) => {
|
||||
const { store } = await fixture(t); const chat = record(); const savedTitle = chat.title;
|
||||
const saved = store.save(owner("a"), chat, current); chat.title = "Changed after call"; await saved;
|
||||
assert.equal((await store.read(owner("a"), chat.conversationRef, current)).title, savedTitle);
|
||||
for (const id of ["../outside", "builtin-chat", "source:owner", ""]) await assert.rejects(store.read(owner("a"), id, current));
|
||||
await assert.rejects(store.save({ privateOwner: "bare-plugin" }, record(), current));
|
||||
await assert.rejects(store.save(owner("a"), { ...record(), id: "builtin-chat" }, current));
|
||||
await assert.rejects(store.save(owner("a"), { ...record(), scope: { type: "workspace", targetId: "active" } }, current));
|
||||
await assert.rejects(store.save(owner("a"), { ...record(), messages: Array(201).fill({}) }, current));
|
||||
await assert.rejects(store.save(owner("a"), { ...record(), messages: [{ content: "x".repeat(1_048_576) }] }, current));
|
||||
});
|
||||
|
||||
test("symlinked history roots and files do not become history authority", async (t) => {
|
||||
const { root, store } = await fixture(t); const chat = record(); await store.save(owner("a"), chat, current);
|
||||
const history = path.join(root, "core-history"); const [directory] = await fs.readdir(history);
|
||||
const filename = path.join(history, directory, `${chat.conversationRef}.json`);
|
||||
const unrelated = path.join(root, "unrelated.json"); await fs.writeFile(unrelated, JSON.stringify(chat));
|
||||
await fs.rm(filename); await fs.symlink(unrelated, filename);
|
||||
await assert.rejects(store.read(owner("a"), chat.conversationRef, current));
|
||||
const linked = path.join(root, "linked"); await fs.symlink(history, linked, "dir");
|
||||
await assert.rejects(new PluginAgentConversationStore(linked).list(owner("a"), current));
|
||||
});
|
||||
@@ -1,189 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { PluginRpcError, RPC_ERRORS } = require("../rpcRouter.cjs");
|
||||
|
||||
const fail = (code) => new PluginRpcError(RPC_ERRORS[code], "Delegated Agent scope is unavailable");
|
||||
const key = (target) => JSON.stringify([target.kind, target.id]);
|
||||
const isRequestCancellation = (error, context) => context.signal?.aborted === true
|
||||
&& (error === context.signal.reason || error?.name === "AbortError" || error?.name === "TimeoutError"
|
||||
|| error?.code === RPC_ERRORS.cancelled || error?.code === RPC_ERRORS.deadlineExceeded);
|
||||
|
||||
// Host-only authority, not a plugin RPC interface or an Agent engine. The host
|
||||
// supplies snapshots after resolving configured backends and choosing targets.
|
||||
// Plugins never supply owner, revision, capability policy or executable adapters.
|
||||
class DelegatedAgentScopes {
|
||||
constructor({ resolveOwner, assertHostActive, authorizeAction, clock = Date.now }) {
|
||||
for (const fn of [resolveOwner, assertHostActive, authorizeAction, clock]) {
|
||||
if (typeof fn !== "function") throw new TypeError("Host scope adapters are required");
|
||||
}
|
||||
this.resolveOwner = resolveOwner;
|
||||
this.assertHostActive = assertHostActive;
|
||||
this.authorizeAction = authorizeAction;
|
||||
this.clock = clock;
|
||||
this.scopes = new Map();
|
||||
this.closed = false;
|
||||
}
|
||||
|
||||
async #owner(context) {
|
||||
if (this.closed) throw fail("unavailable");
|
||||
const owner = await this.resolveOwner(context);
|
||||
await this.assertHostActive(context);
|
||||
context.signal?.throwIfAborted();
|
||||
if (this.closed || await this.resolveOwner(context) !== owner) throw fail("permissionDenied");
|
||||
return owner;
|
||||
}
|
||||
|
||||
// The snapshot is host-owned. A public schema must only accept returned handles.
|
||||
async issue(context, { backend, targets, capabilities }) {
|
||||
const owner = await this.#owner(context);
|
||||
if (!backend || typeof backend.key !== "string" || typeof backend.revision !== "string"
|
||||
|| typeof backend.isCurrent !== "function" || !Array.isArray(targets) || targets.length > 32
|
||||
|| !Array.isArray(capabilities) || capabilities.length > 128
|
||||
|| capabilities.some((id) => typeof id !== "string" || !id || id.length > 160)) throw fail("invalidArgument");
|
||||
const captured = new Map();
|
||||
for (const target of targets) {
|
||||
if (!target || !["terminal", "host", "note"].includes(target.kind)
|
||||
|| typeof target.id !== "string" || !target.id || target.id.length > 256
|
||||
|| typeof target.revision !== "string" || !target.revision
|
||||
|| typeof target.owner !== "string" || !target.owner
|
||||
|| typeof target.isCurrent !== "function" || captured.has(key(target))) throw fail("invalidArgument");
|
||||
captured.set(key(target), Object.freeze({ ...target }));
|
||||
}
|
||||
const scope = { handle: randomUUID(), owner, backend: Object.freeze({ ...backend }), targets: captured,
|
||||
capabilities: new Set(capabilities), expiresAt: this.clock() + 300_000, activeTurn: null };
|
||||
this.#assertSnapshots(scope);
|
||||
if (await this.#owner(context) !== owner) throw fail("permissionDenied");
|
||||
this.#assertSnapshots(scope);
|
||||
for (const entry of this.scopes.values()) if (entry.expiresAt <= this.clock()) this.#revoke(entry);
|
||||
const existing = [...this.scopes.values()].filter((entry) => entry.owner === owner);
|
||||
if (existing.length >= 8 || this.scopes.size >= 64) throw fail("resourceExhausted");
|
||||
this.scopes.set(scope.handle, scope);
|
||||
return Object.freeze({ handle: scope.handle, expiresAt: scope.expiresAt });
|
||||
}
|
||||
|
||||
#assertSnapshots(scope) {
|
||||
// Current-owner/revision checks are synchronous registry lookups, so the
|
||||
// final dispatch check and native call have no asynchronous focus gap.
|
||||
if (scope.backend.isCurrent(scope.backend) !== true) throw fail("failedPrecondition");
|
||||
for (const target of scope.targets.values()) {
|
||||
if (target.isCurrent(target) !== true) throw fail("failedPrecondition");
|
||||
}
|
||||
}
|
||||
|
||||
async #resolve(handle, context) {
|
||||
const scope = this.scopes.get(handle);
|
||||
let owner;
|
||||
try { owner = await this.#owner(context); }
|
||||
catch (error) {
|
||||
// Context identity comes from the authenticated host transport. Revoke
|
||||
// only its own captured scope, never a victim referenced by another caller.
|
||||
if (!isRequestCancellation(error, context) && scope && scope.owner.runtimeId === context.runtimeId && scope.owner.pluginId === context.pluginId
|
||||
&& scope.owner.pluginVersion === context.pluginVersion) this.#revoke(scope);
|
||||
throw error;
|
||||
}
|
||||
if (!scope || scope.owner !== owner) throw fail("permissionDenied");
|
||||
if (scope.expiresAt <= this.clock()) { this.#revoke(scope); throw fail("permissionDenied"); }
|
||||
try {
|
||||
if (await this.#owner(context) !== owner || this.scopes.get(handle) !== scope
|
||||
|| scope.expiresAt <= this.clock()) throw fail("permissionDenied");
|
||||
this.#assertSnapshots(scope);
|
||||
} catch (error) {
|
||||
// A failed individual RPC has no authority to revoke another turn. Real
|
||||
// owner/target failure still invalidates the scope, even if a request also
|
||||
// happens to be cancelled at that time.
|
||||
if (!isRequestCancellation(error, context)) this.#revoke(scope);
|
||||
throw error;
|
||||
}
|
||||
return scope;
|
||||
}
|
||||
|
||||
async begin(handle, context) {
|
||||
const scope = await this.#resolve(handle, context);
|
||||
if (scope.activeTurn) throw fail("alreadyExists");
|
||||
const ticket = Object.freeze({ scope, controller: new AbortController(), id: randomUUID() });
|
||||
scope.activeTurn = ticket;
|
||||
return ticket;
|
||||
}
|
||||
|
||||
async assertTurn(ticket, context) {
|
||||
if (!ticket?.scope || ticket.controller.signal.aborted) throw fail("cancelled");
|
||||
const scope = await this.#resolve(ticket.scope.handle, context);
|
||||
if (scope.activeTurn !== ticket) throw fail("cancelled");
|
||||
ticket.controller.signal.throwIfAborted();
|
||||
return scope;
|
||||
}
|
||||
|
||||
// Called inside the actual tool dispatcher, after canonical argument/target
|
||||
// resolution. It must not be used merely when displaying the model tool list.
|
||||
async dispatch(ticket, context, action, execute) {
|
||||
const scope = await this.assertTurn(ticket, context);
|
||||
if (!action || !scope.capabilities.has(action.capabilityId) || !Array.isArray(action.targets)
|
||||
|| action.targets.length > 32 || typeof execute !== "function") throw fail("permissionDenied");
|
||||
const targets = action.targets.map((target) => {
|
||||
const captured = target && scope.targets.get(key(target));
|
||||
if (!captured || target.revision !== captured.revision || target.owner !== captured.owner) throw fail("permissionDenied");
|
||||
return captured;
|
||||
});
|
||||
const request = Object.freeze({ capabilityId: action.capabilityId, targets: Object.freeze(targets) });
|
||||
// The adapter combines plugin policy and native Agent restrictions once.
|
||||
// No caller can select a process-global permission mode through this API.
|
||||
await this.authorizeAction(context, scope.owner, request, ticket.controller.signal);
|
||||
await this.assertTurn(ticket, context);
|
||||
this.#assertSnapshots(scope);
|
||||
ticket.controller.signal.throwIfAborted();
|
||||
const result = await execute(Object.freeze({ signal: ticket.controller.signal,
|
||||
assertCurrent: () => this.assertTurn(ticket, context) }));
|
||||
await this.assertTurn(ticket, context);
|
||||
return result;
|
||||
}
|
||||
|
||||
finish(ticket) {
|
||||
if (!ticket || ticket.scope?.activeTurn !== ticket) return false;
|
||||
ticket.scope.activeTurn = null;
|
||||
ticket.controller.abort();
|
||||
return true;
|
||||
}
|
||||
|
||||
async stop(handle, context) {
|
||||
// Capture before the first await. A prior Stop cannot acquire authority over
|
||||
// a turn that replaces the one the caller intended to stop.
|
||||
const candidate = this.scopes.get(handle);
|
||||
const ticket = candidate?.activeTurn;
|
||||
const scope = await this.#resolve(handle, context);
|
||||
return scope === candidate ? this.finish(ticket) : false;
|
||||
}
|
||||
|
||||
#revoke(scope) {
|
||||
this.finish(scope.activeTurn);
|
||||
this.scopes.delete(scope.handle);
|
||||
}
|
||||
|
||||
releaseRuntime(runtimeId) {
|
||||
for (const scope of this.scopes.values()) if (scope.owner.runtimeId === runtimeId) this.#revoke(scope);
|
||||
}
|
||||
|
||||
// Main-owned cleanup after a pending operation loses its lease. Exact owner
|
||||
// object matching prevents old cleanup from deleting a replacement source.
|
||||
discard(handle, owner) {
|
||||
const scope = this.scopes.get(handle);
|
||||
if (!scope || scope.owner !== owner) return false;
|
||||
this.#revoke(scope);
|
||||
return true;
|
||||
}
|
||||
|
||||
releasePlugin(pluginId) {
|
||||
for (const scope of this.scopes.values()) if (scope.owner.pluginId === pluginId) this.#revoke(scope);
|
||||
}
|
||||
|
||||
releaseAll() {
|
||||
for (const scope of this.scopes.values()) this.#revoke(scope);
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
this.closed = true;
|
||||
this.releaseAll();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { DelegatedAgentScopes, isRequestCancellation };
|
||||
@@ -1,229 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
const assert = require("node:assert/strict");
|
||||
const test = require("node:test");
|
||||
const { DelegatedAgentScopes } = require("./delegatedScope.cjs");
|
||||
const { PluginAISourceBinding } = require("../ai/sourceBinding.cjs");
|
||||
|
||||
function deferred() {
|
||||
let resolve;
|
||||
const promise = new Promise((finish) => { resolve = finish; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
let time = 1; let locked = false; let focus = "terminal-a";
|
||||
let source = { id: "source-a", kind: "third-party", origin: "https://example.invalid" };
|
||||
let privateOwner = "source:opaque-owner-a:com.example.assistant";
|
||||
let identity = { pluginId: "com.example.assistant", pluginVersion: "1", runtimeId: "r1", runtimeKind: "browser" };
|
||||
let authorize = async () => {};
|
||||
const context = { ...identity, assertActive: async () => {} };
|
||||
const database = {
|
||||
getActivePlugin: () => ({ source, enabled: true, activeVersion: "1", runtime: { status: "running" } }),
|
||||
getRetainedPluginSource: () => source,
|
||||
privateOwner: () => privateOwner,
|
||||
publicPluginId: (value) => value === privateOwner ? identity.pluginId : null,
|
||||
};
|
||||
const binding = new PluginAISourceBinding({ database, getRuntimeIdentity: () => identity });
|
||||
let backendRevision = "configured-1";
|
||||
const currentTargets = new Map([
|
||||
["terminal-a", { owner: "window-1", revision: "session-a-v1" }],
|
||||
["terminal-b", { owner: "window-2", revision: "session-b-v1" }],
|
||||
]);
|
||||
const backend = { key: "host-configured-claude", revision: backendRevision,
|
||||
isCurrent: (snapshot) => snapshot.revision === backendRevision };
|
||||
const target = (id) => ({ kind: "terminal", id, ...currentTargets.get(id),
|
||||
isCurrent: (snapshot) => { const current = currentTargets.get(snapshot.id);
|
||||
return current?.owner === snapshot.owner && current?.revision === snapshot.revision; } });
|
||||
const scopes = new DelegatedAgentScopes({ resolveOwner: (ctx) => binding.resolve(ctx),
|
||||
assertHostActive: async () => { if (locked) throw Error("Locked"); },
|
||||
authorizeAction: (...args) => authorize(...args), clock: () => time });
|
||||
return { scopes, context, target, targets: currentTargets, database,
|
||||
issue: (targets = [target("terminal-a"), target("terminal-b")]) => scopes.issue(context,
|
||||
{ backend, targets, capabilities: ["terminal.execute", "session.environment"] }),
|
||||
action: (id = "terminal-a") => ({ capabilityId: "terminal.execute", targets: [target(id)] }),
|
||||
tick: (ms) => { time += ms; }, lock: () => { locked = true; scopes.releaseAll(); },
|
||||
focusTo: (id) => { focus = id; }, focus: () => focus,
|
||||
authorize: (fn) => { authorize = fn; }, backendTo: (value) => { backendRevision = value; },
|
||||
replaceSource: () => { source = { ...source, id: "source-b" }; privateOwner = "source:opaque-owner-b:com.example.assistant"; },
|
||||
runtimeTo: (id) => { identity = { ...identity, runtimeId: id }; },
|
||||
};
|
||||
}
|
||||
|
||||
test("host-issued scope exposes only opaque identity and expiry; cross-workspace focus does not change explicit targets", async () => {
|
||||
const f = fixture(); const ref = await f.issue();
|
||||
assert.deepEqual(Object.keys(ref).sort(), ["expiresAt", "handle"]);
|
||||
assert.doesNotMatch(JSON.stringify(ref), /window-|terminal-|source:|configured/);
|
||||
const ticket = await f.scopes.begin(ref.handle, f.context);
|
||||
f.focusTo("unselected-terminal");
|
||||
let calls = 0;
|
||||
assert.equal(await f.scopes.dispatch(ticket, f.context, f.action("terminal-b"), async () => ++calls), 1);
|
||||
assert.equal(f.focus(), "unselected-terminal");
|
||||
await assert.rejects(f.scopes.dispatch(ticket, f.context,
|
||||
{ capabilityId: "terminal.execute", targets: [{ kind: "terminal", id: f.focus(), revision: "1", owner: "window-1" }] }, async () => ++calls));
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test("forged runtime, cross-runtime session and source replacement cannot use a scope", async () => {
|
||||
const f = fixture(); const ref = await f.issue();
|
||||
await assert.rejects(f.scopes.begin(ref.handle, { ...f.context, runtimeId: "forged" }));
|
||||
f.runtimeTo("r2");
|
||||
await assert.rejects(f.scopes.begin(ref.handle, { ...f.context, runtimeId: "r2" }));
|
||||
f.runtimeTo("r1"); f.replaceSource();
|
||||
await assert.rejects(f.scopes.begin(ref.handle, f.context));
|
||||
});
|
||||
|
||||
test("one host policy decision; target owner/revision is revalidated after approval waits", async () => {
|
||||
const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context);
|
||||
const entered = deferred(); const release = deferred(); let decisions = 0; let effects = 0;
|
||||
f.authorize(async (_context, owner, action) => {
|
||||
decisions++; assert.equal(owner.privateOwner, "source:opaque-owner-a:com.example.assistant");
|
||||
assert.equal(action.targets[0].id, "terminal-a"); entered.resolve(); await release.promise;
|
||||
});
|
||||
const result = f.scopes.dispatch(ticket, f.context, f.action(), async () => effects++);
|
||||
await entered.promise;
|
||||
f.targets.set("terminal-a", { owner: "new-window", revision: "session-a-v2" });
|
||||
release.resolve(); await assert.rejects(result);
|
||||
assert.equal(decisions, 1); assert.equal(effects, 0); assert.equal(ticket.controller.signal.aborted, true);
|
||||
});
|
||||
|
||||
test("copied target ID with substituted owner or revision and undelegated capabilities fail before policy/execute", async () => {
|
||||
const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context);
|
||||
let decisions = 0; let effects = 0; f.authorize(async () => { decisions++; });
|
||||
for (const patch of [{ owner: "attacker" }, { revision: "old" }]) {
|
||||
await assert.rejects(f.scopes.dispatch(ticket, f.context,
|
||||
{ capabilityId: "terminal.execute", targets: [{ ...f.target("terminal-a"), ...patch }] }, async () => effects++));
|
||||
}
|
||||
await assert.rejects(f.scopes.dispatch(ticket, f.context,
|
||||
{ capabilityId: "vault.host.delete", targets: [] }, async () => effects++));
|
||||
assert.equal(decisions, 0); assert.equal(effects, 0);
|
||||
});
|
||||
|
||||
test("Deny and revoked source during authorization never dispatch a tool", async () => {
|
||||
const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context);
|
||||
let effects = 0;
|
||||
f.authorize(async () => { throw Error("Denied"); });
|
||||
await assert.rejects(f.scopes.dispatch(ticket, f.context, f.action(), async () => effects++));
|
||||
f.authorize(async () => { f.replaceSource(); });
|
||||
await assert.rejects(f.scopes.dispatch(ticket, f.context, f.action(), async () => effects++));
|
||||
assert.equal(effects, 0);
|
||||
});
|
||||
|
||||
test("Stop while approval waits cancels the exact turn and prevents invocation", async () => {
|
||||
const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context);
|
||||
const entered = deferred(); const release = deferred(); let effects = 0;
|
||||
f.authorize(async (_context, _owner, _action, signal) => {
|
||||
assert.equal(signal, ticket.controller.signal); entered.resolve(); await release.promise;
|
||||
});
|
||||
const result = f.scopes.dispatch(ticket, f.context, f.action(), async () => effects++);
|
||||
await entered.promise; assert.equal(await f.scopes.stop(ref.handle, f.context), true);
|
||||
release.resolve(); await assert.rejects(result); assert.equal(effects, 0);
|
||||
const next = await f.scopes.begin(ref.handle, f.context);
|
||||
assert.equal(f.scopes.finish(ticket), false); assert.equal(next.controller.signal.aborted, false);
|
||||
});
|
||||
|
||||
for (const reason of ["runtime", "plugin", "lock", "stop"]) {
|
||||
test(`${reason} cancellation drops late native results and invalidates the old event ticket`, async () => {
|
||||
const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context);
|
||||
const entered = deferred(); const release = deferred();
|
||||
const result = f.scopes.dispatch(ticket, f.context, f.action(), async ({ signal }) => {
|
||||
assert.equal(signal, ticket.controller.signal); entered.resolve(); await release.promise; return "late";
|
||||
});
|
||||
await entered.promise;
|
||||
if (reason === "runtime") f.scopes.releaseRuntime(f.context.runtimeId);
|
||||
else if (reason === "plugin") f.scopes.releasePlugin(f.context.pluginId);
|
||||
else if (reason === "lock") f.lock();
|
||||
else await f.scopes.stop(ref.handle, f.context);
|
||||
release.resolve(); await assert.rejects(result); await assert.rejects(f.scopes.assertTurn(ticket, f.context));
|
||||
assert.equal(ticket.controller.signal.aborted, true);
|
||||
});
|
||||
}
|
||||
|
||||
test("backend config changes and expiry invalidate scopes; host snapshots cannot silently refresh them", async () => {
|
||||
const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context);
|
||||
f.backendTo("new-config"); await assert.rejects(f.scopes.assertTurn(ticket, f.context));
|
||||
assert.equal(ticket.controller.signal.aborted, true);
|
||||
const g = fixture(); const next = await g.issue(); const active = await g.scopes.begin(next.handle, g.context);
|
||||
g.tick(300_000); await assert.rejects(g.scopes.assertTurn(active, g.context));
|
||||
assert.equal(active.controller.signal.aborted, true); assert.equal(g.scopes.scopes.size, 0);
|
||||
});
|
||||
|
||||
test("source replacement detected during owner authentication aborts already-running native work", async () => {
|
||||
const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context);
|
||||
const entered = deferred(); const release = deferred();
|
||||
const result = f.scopes.dispatch(ticket, f.context, f.action(), async ({ signal }) => {
|
||||
entered.resolve(signal); await release.promise; return "late native result";
|
||||
});
|
||||
const signal = await entered.promise;
|
||||
try {
|
||||
f.replaceSource();
|
||||
await assert.rejects(f.scopes.assertTurn(ticket, f.context));
|
||||
assert.equal(signal.aborted, true, "source detection must abort native work, not only reject its result");
|
||||
assert.equal(f.scopes.scopes.size, 0);
|
||||
} finally { release.resolve(); await assert.rejects(result); }
|
||||
});
|
||||
|
||||
test("Stop captures turn A before owner validation and cannot cancel replacement turn B", async () => {
|
||||
const f = fixture(); const ref = await f.issue(); const first = await f.scopes.begin(ref.handle, f.context);
|
||||
const entered = deferred(); const release = deferred(); let blocked = false;
|
||||
const stopContext = { ...f.context, assertActive: async () => {
|
||||
if (!blocked) { blocked = true; entered.resolve(); await release.promise; }
|
||||
} };
|
||||
const stopping = f.scopes.stop(ref.handle, stopContext);
|
||||
await entered.promise; assert.equal(f.scopes.finish(first), true);
|
||||
const second = await f.scopes.begin(ref.handle, f.context);
|
||||
release.resolve();
|
||||
assert.equal(await stopping, false);
|
||||
assert.equal(second.controller.signal.aborted, false, "an earlier Stop must not cancel a later turn");
|
||||
assert.equal(await f.scopes.assertTurn(second, f.context), second.scope);
|
||||
});
|
||||
|
||||
for (const phase of [1, 5]) {
|
||||
test(`cancelled Stop(A) during owner check ${phase} cannot revoke replacement turn B`, { timeout: 2_000 }, async () => {
|
||||
const f = fixture(); const ref = await f.issue(); const first = await f.scopes.begin(ref.handle, f.context);
|
||||
const entered = deferred(); const release = deferred(); const rpc = new AbortController(); let checks = 0;
|
||||
const stopContext = { ...f.context, signal: rpc.signal, assertActive: async () => {
|
||||
if (++checks === phase) { entered.resolve(); await release.promise; }
|
||||
rpc.signal.throwIfAborted();
|
||||
} };
|
||||
const stopping = f.scopes.stop(ref.handle, stopContext);
|
||||
await entered.promise; f.scopes.finish(first);
|
||||
const second = await f.scopes.begin(ref.handle, f.context);
|
||||
rpc.abort(phase === 1 ? new DOMException("Stop cancelled", "AbortError") : new DOMException("Stop deadline", "TimeoutError"));
|
||||
release.resolve();
|
||||
await assert.rejects(stopping, (error) => error === rpc.signal.reason);
|
||||
assert.equal(second.controller.signal.aborted, false, "a cancelled RPC does not revoke source authority or stop a later turn");
|
||||
assert.equal(f.scopes.scopes.size, 1);
|
||||
assert.equal(await f.scopes.assertTurn(second, f.context), second.scope);
|
||||
});
|
||||
}
|
||||
|
||||
test("verified source failure still aborts native work when the RPC is concurrently cancelled", async () => {
|
||||
const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context);
|
||||
const rpc = new AbortController(); const retained = f.database.getRetainedPluginSource;
|
||||
f.database.getRetainedPluginSource = () => {
|
||||
rpc.abort(new DOMException("Concurrent RPC cancellation", "AbortError"));
|
||||
return { ...retained(), id: "different-retained-source" };
|
||||
};
|
||||
await assert.rejects(f.scopes.assertTurn(ticket, { ...f.context, signal: rpc.signal }),
|
||||
(error) => error !== rpc.signal.reason && error.code === -32007);
|
||||
assert.equal(ticket.controller.signal.aborted, true);
|
||||
assert.equal(f.scopes.scopes.size, 0);
|
||||
});
|
||||
|
||||
test("a foreign runtime cannot revoke a victim scope by failing authentication with its handle", async () => {
|
||||
const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context);
|
||||
await assert.rejects(f.scopes.stop(ref.handle, { ...f.context, runtimeId: "foreign-runtime" }));
|
||||
assert.equal(ticket.controller.signal.aborted, false);
|
||||
assert.equal(f.scopes.scopes.size, 1);
|
||||
assert.equal(await f.scopes.assertTurn(ticket, f.context), ticket.scope);
|
||||
});
|
||||
|
||||
test("bounded host scopes reject malformed snapshots without registering partial targets", async () => {
|
||||
const f = fixture(); await assert.rejects(f.issue([null])); assert.equal(f.scopes.scopes.size, 0);
|
||||
await assert.rejects(f.issue([f.target("terminal-a"), f.target("terminal-a")]));
|
||||
for (let i = 0; i < 8; i++) await f.issue();
|
||||
await assert.rejects(f.issue());
|
||||
f.tick(300_000); await f.issue(); assert.equal(f.scopes.scopes.size, 1);
|
||||
f.scopes.shutdown(); await assert.rejects(f.issue());
|
||||
});
|
||||
@@ -1,113 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
const { randomBytes } = require("node:crypto");
|
||||
const PREFIX = "plugin-agent:";
|
||||
const { listMcpTools } = require("../../capabilities/codegen/toolSurfaces.cjs");
|
||||
const toolsByMethod = new Map(listMcpTools().map((tool) => [tool.rpcMethod, tool.mcpTool]));
|
||||
|
||||
// Main-only per-turn MCP credentials. A managed Agent subprocess receives this
|
||||
// credential instead of the app-wide token; no token crosses the plugin API.
|
||||
class PluginAgentMcpDelegations {
|
||||
constructor() {
|
||||
this.sessions = new Map();
|
||||
this.tokens = new Map();
|
||||
this.sockets = new WeakMap();
|
||||
this.approvedContexts = new WeakSet();
|
||||
}
|
||||
|
||||
register(chatSessionId, { dispatch, assertCurrent, senderId, tools, turnTag }) {
|
||||
if (typeof chatSessionId !== "string" || !chatSessionId.startsWith(PREFIX)
|
||||
|| typeof dispatch !== "function" || typeof assertCurrent !== "function"
|
||||
|| typeof turnTag !== "string" || !/^[0-9a-f-]{36}$/u.test(turnTag)
|
||||
|| !Number.isSafeInteger(senderId) || !Array.isArray(tools) || tools.length > 128
|
||||
|| tools.some((tool) => typeof tool !== "string" || !tool || tool.length > 128)
|
||||
|| this.sessions.has(chatSessionId) || this.sessions.size >= 64) throw Error("Invalid Agent delegation");
|
||||
const token = randomBytes(32).toString("hex");
|
||||
const entry = { chatSessionId, turnTag, token, dispatch, assertCurrent, senderId, modelRequests: 0, tools: Object.freeze([...tools]), sockets: new Set(), cancellations: new Set() };
|
||||
this.sessions.set(chatSessionId, entry); this.tokens.set(token, entry);
|
||||
return Object.freeze({ dispose: () => { if (this.sessions.get(chatSessionId) === entry) this.release(chatSessionId); } });
|
||||
}
|
||||
|
||||
#assert(entry) {
|
||||
if (!entry || this.sessions.get(entry.chatSessionId) !== entry) throw Error("Agent delegation unavailable");
|
||||
try { entry.assertCurrent(); }
|
||||
catch (error) {
|
||||
// This callback is a synchronous main-owned authority check, not an RPC
|
||||
// signal. Discovering revocation must abort already-running native work.
|
||||
if (this.sessions.get(entry.chatSessionId) === entry) this.release(entry.chatSessionId);
|
||||
throw error;
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
authenticate(token, socket) {
|
||||
const entry = this.tokens.get(token);
|
||||
if (!entry) return false;
|
||||
try { this.#assert(entry); } catch { return false; }
|
||||
this.sockets.set(socket, entry); entry.sockets.add(socket);
|
||||
socket.once?.("close", () => entry.sockets.delete(socket));
|
||||
return true;
|
||||
}
|
||||
|
||||
boundChat(socket) {
|
||||
const entry = this.sockets.get(socket);
|
||||
return entry ? this.#assert(entry).chatSessionId : null;
|
||||
}
|
||||
|
||||
configuration(chatSessionId, turnTag) {
|
||||
const entry = this.#assert(this.sessions.get(chatSessionId));
|
||||
if (entry.turnTag !== turnTag) throw Error("Agent turn unavailable");
|
||||
return Object.freeze({ token: entry.token, tools: entry.tools });
|
||||
}
|
||||
|
||||
has(chatSessionId) { return this.sessions.has(chatSessionId); }
|
||||
assertCaller(chatSessionId, senderId, turnTag) {
|
||||
const entry = this.#assert(this.sessions.get(chatSessionId));
|
||||
if (entry.senderId !== senderId || entry.turnTag !== turnTag) throw Error("Agent caller unavailable");
|
||||
}
|
||||
onRelease(chatSessionId, turnTag, cancel) {
|
||||
const entry = this.#assert(this.sessions.get(chatSessionId));
|
||||
if (entry.turnTag !== turnTag) throw Error("Agent turn unavailable");
|
||||
if (typeof cancel !== "function") throw Error("Native cancellation callback required");
|
||||
entry.cancellations.add(cancel);
|
||||
return () => entry.cancellations.delete(cancel);
|
||||
}
|
||||
beginModelRequest(chatSessionId, senderId, turnTag) {
|
||||
this.assertCaller(chatSessionId, senderId, turnTag);
|
||||
const entry = this.sessions.get(chatSessionId);
|
||||
if (++entry.modelRequests > 32) { this.release(chatSessionId); throw Error("Agent model request budget exceeded"); }
|
||||
}
|
||||
isReserved(chatSessionId) { return typeof chatSessionId === "string" && chatSessionId.startsWith(PREFIX); }
|
||||
isApproved(context) { return this.approvedContexts.has(context); }
|
||||
|
||||
async dispatch(method, params, context, execute) {
|
||||
const entry = this.#assert(this.sessions.get(params.chatSessionId));
|
||||
if (!entry.tools.includes(toolsByMethod.get(method))) throw Error("Tool is outside the Agent delegation");
|
||||
const socketEntry = context.externalSocket && this.sockets.get(context.externalSocket);
|
||||
if (socketEntry !== entry && (context.trustedAgentSenderId !== entry.senderId || context.trustedAgentTurnTag !== entry.turnTag)) throw Error("Agent caller unavailable");
|
||||
if (socketEntry && socketEntry !== entry) throw Error("Agent connection cannot change its session");
|
||||
return entry.dispatch(method, params, async () => {
|
||||
this.#assert(entry);
|
||||
const approved = { ...context, beforeExecute: () => {
|
||||
this.#assert(entry); context.beforeExecute?.();
|
||||
} };
|
||||
this.approvedContexts.add(approved);
|
||||
try { return await execute(approved); }
|
||||
finally { this.approvedContexts.delete(approved); }
|
||||
});
|
||||
}
|
||||
|
||||
release(chatSessionId) {
|
||||
const entry = this.sessions.get(chatSessionId);
|
||||
if (!entry) return;
|
||||
this.sessions.delete(chatSessionId); this.tokens.delete(entry.token);
|
||||
for (const cancel of entry.cancellations) { try { cancel(); } catch {} }
|
||||
entry.cancellations.clear();
|
||||
for (const socket of entry.sockets) { try { socket.destroy(); } catch {} }
|
||||
entry.sockets.clear();
|
||||
}
|
||||
|
||||
shutdown() { for (const id of this.sessions.keys()) this.release(id); }
|
||||
}
|
||||
|
||||
module.exports = { PluginAgentMcpDelegations };
|
||||
@@ -1,71 +0,0 @@
|
||||
"use strict";
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { EventEmitter } = require("node:events");
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { PluginAgentMcpDelegations } = require("./mcpDelegation.cjs");
|
||||
|
||||
const options = (turnTag, overrides = {}) => ({ turnTag, senderId: 7, tools: ["get_environment"],
|
||||
assertCurrent: () => {}, dispatch: (_method, _params, execute) => execute(), ...overrides });
|
||||
function socket() {
|
||||
const value = new EventEmitter(); value.destroyed = false;
|
||||
value.destroy = () => { value.destroyed = true; value.emit("close"); }; return value;
|
||||
}
|
||||
|
||||
test("old turn disposer, credentials and late cancellation registration cannot acquire replacement turn B", () => {
|
||||
const registry = new PluginAgentMcpDelegations(); const id = `plugin-agent:${randomUUID()}`;
|
||||
const a = randomUUID(); const b = randomUUID();
|
||||
const first = registry.register(id, options(a));
|
||||
const tokenA = registry.configuration(id, a).token; const connectionA = socket();
|
||||
assert.equal(registry.authenticate(tokenA, connectionA), true);
|
||||
let cancelledA = 0; let cancelledB = 0;
|
||||
registry.onRelease(id, a, () => cancelledA++); first.dispose();
|
||||
const second = registry.register(id, options(b)); registry.onRelease(id, b, () => cancelledB++);
|
||||
first.dispose(); assert.equal(cancelledB, 0); assert.equal(cancelledA, 1);
|
||||
assert.equal(connectionA.destroyed, true);
|
||||
assert.equal(registry.authenticate(tokenA, socket()), false);
|
||||
assert.throws(() => registry.configuration(id, a));
|
||||
assert.throws(() => registry.onRelease(id, a, () => cancelledB++));
|
||||
assert.throws(() => registry.assertCaller(id, 7, a));
|
||||
assert.throws(() => registry.assertCaller(id, 99, b));
|
||||
assert.doesNotThrow(() => registry.assertCaller(id, 7, b));
|
||||
assert.equal(cancelledB, 0); second.dispose(); assert.equal(cancelledB, 1);
|
||||
});
|
||||
|
||||
test("discovered owner revocation aborts native work and one faulty callback cannot interrupt cleanup", () => {
|
||||
const registry = new PluginAgentMcpDelegations(); const id = `plugin-agent:${randomUUID()}`; const tag = randomUUID();
|
||||
let current = true;
|
||||
registry.register(id, options(tag, { assertCurrent: () => { if (!current) throw Error("Source revoked"); } }));
|
||||
const token = registry.configuration(id, tag).token; const connection = socket(); registry.authenticate(token, connection);
|
||||
const native = new AbortController();
|
||||
registry.onRelease(id, tag, () => { throw Error("Faulty cleanup listener"); });
|
||||
registry.onRelease(id, tag, () => native.abort());
|
||||
current = false; assert.throws(() => registry.assertCaller(id, 7, tag), /Source revoked/);
|
||||
assert.equal(native.signal.aborted, true); assert.equal(connection.destroyed, true);
|
||||
assert.equal(registry.has(id), false); assert.equal(registry.authenticate(token, socket()), false);
|
||||
});
|
||||
|
||||
test("tool profile and trusted caller tag are enforced before invoking the host policy callback", async () => {
|
||||
const registry = new PluginAgentMcpDelegations(); const id = `plugin-agent:${randomUUID()}`; const tag = randomUUID();
|
||||
let decisions = 0; let effects = 0;
|
||||
registry.register(id, options(tag, { dispatch: (_method, _params, execute) => { decisions++; return execute(); } }));
|
||||
await assert.rejects(registry.dispatch("netcatty/getContext", { chatSessionId: id }, { trustedAgentSenderId: 7, trustedAgentTurnTag: randomUUID() }, () => effects++));
|
||||
await assert.rejects(registry.dispatch("netcatty/exec", { chatSessionId: id }, { trustedAgentSenderId: 7, trustedAgentTurnTag: tag }, () => effects++));
|
||||
assert.equal(decisions, 0); assert.equal(effects, 0);
|
||||
await registry.dispatch("netcatty/getContext", { chatSessionId: id }, { trustedAgentSenderId: 7, trustedAgentTurnTag: tag }, (context) => {
|
||||
assert.equal(registry.isApproved(context), true); context.beforeExecute(); effects++;
|
||||
});
|
||||
assert.equal(decisions, 1); assert.equal(effects, 1);
|
||||
registry.shutdown();
|
||||
});
|
||||
|
||||
test("model request limits cannot be reset or consumed by a different turn or caller", () => {
|
||||
const registry = new PluginAgentMcpDelegations(); const id = `plugin-agent:${randomUUID()}`; const tag = randomUUID();
|
||||
registry.register(id, options(tag)); let cancelled = 0; registry.onRelease(id, tag, () => cancelled++);
|
||||
for (let i = 0; i < 32; i++) {
|
||||
assert.throws(() => registry.beginModelRequest(id, 8, tag));
|
||||
assert.throws(() => registry.beginModelRequest(id, 7, randomUUID()));
|
||||
registry.beginModelRequest(id, 7, tag);
|
||||
}
|
||||
assert.throws(() => registry.beginModelRequest(id, 7, tag), /budget/); assert.equal(cancelled, 1); assert.equal(registry.has(id), false);
|
||||
});
|
||||
@@ -51,15 +51,6 @@ class PluginAISourceBinding {
|
||||
return binding;
|
||||
}
|
||||
|
||||
// Main-owned final dispatch guard. Only a previously authenticated binding
|
||||
// object can reach this path; it is never reconstructed from plugin fields.
|
||||
assertCurrent(binding) {
|
||||
if (!binding || this.bindings.get(binding.runtimeId) !== binding) throw denied();
|
||||
const current = this.#snapshot(binding);
|
||||
if (current.sourceKey !== binding.sourceKey || current.privateOwner !== binding.privateOwner
|
||||
|| current.pluginId !== binding.pluginId || current.pluginVersion !== binding.pluginVersion) throw denied();
|
||||
}
|
||||
|
||||
releaseRuntime(runtimeId) { this.bindings.delete(runtimeId); }
|
||||
releasePlugin(pluginId) {
|
||||
for (const [runtimeId, binding] of this.bindings) if (binding.pluginId === pluginId) this.bindings.delete(runtimeId);
|
||||
|
||||
@@ -39,12 +39,3 @@ test("source/owner changes during asynchronous authentication cannot commit a bi
|
||||
const context = { ...f.context, assertActive: async () => { if (++checks === 2) f.ownerTo("changed-owner"); } };
|
||||
await assert.rejects(f.binding.resolve(context)); assert.equal(f.binding.bindings.size, 0);
|
||||
});
|
||||
|
||||
test("final dispatch checks require the exact authenticated binding and current host provenance", async () => {
|
||||
const f = fixture(); const binding = await f.binding.resolve(f.context);
|
||||
assert.doesNotThrow(() => f.binding.assertCurrent(binding));
|
||||
assert.throws(() => f.binding.assertCurrent({ ...binding }));
|
||||
f.ownerTo("changed-owner"); assert.throws(() => f.binding.assertCurrent(binding));
|
||||
f.ownerTo("source:opaque-a:com.example.assistant");
|
||||
f.binding.releaseRuntime("r1"); assert.throws(() => f.binding.assertCurrent(binding));
|
||||
});
|
||||
@@ -11,12 +11,6 @@ const CHANNELS = Object.freeze({ request: "netcatty:plugins:ai-host-request", re
|
||||
// supplied by the shared contract task; no provider config or key crosses it.
|
||||
class PluginAITrustedHostAdapter {
|
||||
constructor(options) {
|
||||
// Separate trusted Agent transport instances reuse the same sender/nonce
|
||||
// guards. These construction options never come from a plugin request.
|
||||
this.channels = options.channels ?? CHANNELS;
|
||||
this.requestDefinition = options.requestDefinition ?? "PluginAIHostRequest";
|
||||
this.responseDefinition = options.responseDefinition ?? "PluginAIHostResponse";
|
||||
this.maxEnvelopeBytes = Math.min(options.maxEnvelopeBytes ?? 24_576, 1_048_576);
|
||||
this.getWindow = options.getWindow;
|
||||
this.isLocked = options.isLocked ?? (() => true);
|
||||
this.dialog = options.dialog;
|
||||
@@ -31,11 +25,11 @@ class PluginAITrustedHostAdapter {
|
||||
|
||||
registerIpc(ipcMain) {
|
||||
if (this.ipcRegistration) throw new Error("Trusted AI host IPC is already registered");
|
||||
this.validateRequest ??= createDefinitionValidator(this.requestDefinition);
|
||||
this.validateResponse ??= createDefinitionValidator(this.responseDefinition);
|
||||
ipcMain.handle(this.channels.ready, (event, ready) => this.setReady(event.sender, ready));
|
||||
ipcMain.handle(this.channels.response, (event, response) => this.respond(event.sender, response));
|
||||
this.ipcRegistration = { dispose: () => { ipcMain.removeHandler(this.channels.ready); ipcMain.removeHandler(this.channels.response); } };
|
||||
this.validateRequest ??= createDefinitionValidator("PluginAIHostRequest");
|
||||
this.validateResponse ??= createDefinitionValidator("PluginAIHostResponse");
|
||||
ipcMain.handle(CHANNELS.ready, (event, ready) => this.setReady(event.sender, ready));
|
||||
ipcMain.handle(CHANNELS.response, (event, response) => this.respond(event.sender, response));
|
||||
this.ipcRegistration = { dispose: () => { ipcMain.removeHandler(CHANNELS.ready); ipcMain.removeHandler(CHANNELS.response); } };
|
||||
return this.ipcRegistration;
|
||||
}
|
||||
|
||||
@@ -74,7 +68,7 @@ class PluginAITrustedHostAdapter {
|
||||
|
||||
#envelope(kind, payload, runtimeId) {
|
||||
const request = { requestId: randomUUID(), actionToken: randomBytes(24).toString("base64url"), kind, payload, runtimeId };
|
||||
assertPluginJsonValue(request, { maxBytes: this.maxEnvelopeBytes });
|
||||
assertPluginJsonValue(request, { maxBytes: 24_576 });
|
||||
if (!this.validateRequest?.(request)) throw fail("internal", "Trusted AI host request is invalid");
|
||||
return request;
|
||||
}
|
||||
@@ -86,7 +80,7 @@ class PluginAITrustedHostAdapter {
|
||||
|
||||
#cleanup(kind, payload, runtimeId, sender = this.owner) {
|
||||
if (!sender || sender !== this.getWindow?.()?.webContents || sender.isDestroyed?.()) return;
|
||||
try { sender.send(this.channels.request, this.#envelope(kind, payload, runtimeId)); } catch {}
|
||||
try { sender.send(CHANNELS.request, this.#envelope(kind, payload, runtimeId)); } catch {}
|
||||
}
|
||||
|
||||
async #request(kind, payload, context) {
|
||||
@@ -108,14 +102,14 @@ class PluginAITrustedHostAdapter {
|
||||
this.pending.set(request.requestId, entry);
|
||||
context.signal?.addEventListener("abort", entry.abort, { once: true });
|
||||
if (context.signal?.aborted) { entry.abort(); return; }
|
||||
try { sender.send(this.channels.request, request); }
|
||||
try { sender.send(CHANNELS.request, request); }
|
||||
catch { entry.finish(null, fail("unavailable", "Trusted AI host disconnected")); }
|
||||
});
|
||||
}
|
||||
|
||||
async respond(sender, response) {
|
||||
if (sender !== this.#owner()) throw fail("permissionDenied", "AI host response sender is invalid");
|
||||
assertPluginJsonValue(response, { maxBytes: this.maxEnvelopeBytes });
|
||||
assertPluginJsonValue(response, { maxBytes: 24_576 });
|
||||
if (!this.validateResponse?.(response)) throw fail("invalidArgument", "AI host response is invalid");
|
||||
const entry = this.pending.get(response.requestId);
|
||||
if (!entry || entry.sender !== sender || entry.generation !== this.generation) return false;
|
||||
@@ -132,18 +126,6 @@ class PluginAITrustedHostAdapter {
|
||||
} catch { entry.finish(null, fail("cancelled", "Trusted AI host response became stale")); return false; }
|
||||
}
|
||||
|
||||
// Host-only, canonical typed request path for a separate Agent instance.
|
||||
requestAgent(kind, payload, context) {
|
||||
if (this.requestDefinition !== "PluginAgentHostRequest" || !kind.startsWith("agent.")) throw fail("unsupported", "Agent host route unavailable");
|
||||
return this.#request(kind, payload, context);
|
||||
}
|
||||
|
||||
getSenderId() { return this.#owner().id; }
|
||||
releaseAgentChat(chatSessionId, runtimeId) {
|
||||
if (this.requestDefinition !== "PluginAgentHostRequest" || !/^plugin-agent:[0-9a-f-]{36}$/u.test(chatSessionId)) throw fail("invalidArgument", "Agent conversation unavailable");
|
||||
this.#cleanup("agent.close", { chatSessionId }, runtimeId);
|
||||
}
|
||||
|
||||
async selectModel(context) {
|
||||
const selected = await this.#request("model.select", {}, context);
|
||||
if (typeof selected?.hostHandle !== "string" || typeof selected.label !== "string" || selected.label.length > 160) throw fail("internal", "Selected model is invalid");
|
||||
|
||||
@@ -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/);
|
||||
});
|
||||
@@ -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({
|
||||
|
||||
@@ -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}$"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -188,7 +188,6 @@ class PluginFilesystemBroker {
|
||||
constructor(options = {}) {
|
||||
this.quotaManager = options.quotaManager ?? null;
|
||||
this.protectedDirectories = options.protectedDirectories ?? [];
|
||||
this.protectedReadDirectories = options.protectedReadDirectories ?? [];
|
||||
this.protectedFiles = options.protectedFiles ?? [];
|
||||
this.fileSystem = options.fileSystem ?? fsp;
|
||||
this.openDirectoryHandle = options.openDirectoryHandle ?? null;
|
||||
@@ -236,10 +235,8 @@ class PluginFilesystemBroker {
|
||||
|
||||
async readFile(params, context) {
|
||||
const value = assertReadParams(params);
|
||||
await this.#assertReadable(value.path);
|
||||
assertAuthorizedPath(context, "filesystem.read", value.path);
|
||||
const { canonical, stats } = await resolveExistingPath(value.path, this.fileSystem);
|
||||
await this.#assertReadable(canonical);
|
||||
assertAuthorizedPath(context, "filesystem.read", canonical);
|
||||
if (!stats.isFile()) throw invalidArgument("Plugin filesystem read target is not a file");
|
||||
if (stats.size > value.maxBytes) {
|
||||
@@ -256,9 +253,7 @@ class PluginFilesystemBroker {
|
||||
if (openedStats.size > value.maxBytes) {
|
||||
throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Plugin filesystem file changed or is too large");
|
||||
}
|
||||
const current = await this.fileSystem.realpath(canonical);
|
||||
await this.#assertReadable(current);
|
||||
assertAuthorizedPath(context, "filesystem.read", current);
|
||||
assertAuthorizedPath(context, "filesystem.read", await this.fileSystem.realpath(canonical));
|
||||
const bytes = await readBoundedFileHandle(handle, value.maxBytes);
|
||||
this.quotaManager?.chargeBytes(context.runtimeId, "filesystem", bytes.byteLength);
|
||||
await context.assertActive();
|
||||
@@ -289,20 +284,6 @@ class PluginFilesystemBroker {
|
||||
}
|
||||
}
|
||||
|
||||
async #assertReadable(candidate) {
|
||||
for (const directory of this.protectedReadDirectories) {
|
||||
const variants = [path.resolve(directory)];
|
||||
try { variants.push(await this.fileSystem.realpath(directory)); }
|
||||
catch (error) { if (error?.code !== "ENOENT") throw error; }
|
||||
for (const parent of variants) {
|
||||
const relative = path.relative(parent, candidate);
|
||||
if (relative === "" || (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`))) {
|
||||
throw new PluginRpcError(RPC_ERRORS.permissionDenied, "Private host conversation storage is protected");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async writeFile(params, context) {
|
||||
const value = assertSecureWriteMode(assertWriteParams(params));
|
||||
await this.#assertWritable(path.resolve(value.path));
|
||||
@@ -336,10 +317,8 @@ class PluginFilesystemBroker {
|
||||
|
||||
async stat(params, context) {
|
||||
const value = assertPathParams(params);
|
||||
await this.#assertReadable(value.path);
|
||||
assertAuthorizedPath(context, "filesystem.read", value.path);
|
||||
const { canonical, stats } = await resolveExistingPath(value.path, this.fileSystem);
|
||||
await this.#assertReadable(canonical);
|
||||
assertAuthorizedPath(context, "filesystem.read", canonical);
|
||||
await context.assertActive();
|
||||
return {
|
||||
@@ -351,10 +330,8 @@ class PluginFilesystemBroker {
|
||||
|
||||
async readDirectory(params, context) {
|
||||
const value = assertPathParams(params);
|
||||
await this.#assertReadable(value.path);
|
||||
assertAuthorizedPath(context, "filesystem.read", value.path);
|
||||
const { canonical, stats } = await resolveExistingPath(value.path, this.fileSystem);
|
||||
await this.#assertReadable(canonical);
|
||||
assertAuthorizedPath(context, "filesystem.read", canonical);
|
||||
if (!stats.isDirectory()) throw invalidArgument("Plugin filesystem directory target is not a directory");
|
||||
if (!this.openDirectoryHandle) {
|
||||
|
||||
@@ -93,24 +93,6 @@ test("filesystem broker uses canonical authorization for bounded read, write, st
|
||||
]);
|
||||
});
|
||||
|
||||
test("host conversation roots are unreadable through explicit filesystem grants, including symlink aliases", async (context) => {
|
||||
const root = createRoot(context); const privateRoot = path.join(root, "agent-chats");
|
||||
await fsp.mkdir(privateRoot); const file = path.join(privateRoot, "synthetic.json"); await fsp.writeFile(file, "PRIVATE_OTHER_SOURCE_HISTORY");
|
||||
const broker = new PluginFilesystemBroker({ protectedReadDirectories: [privateRoot], openDirectoryHandle: openTestDirectoryHandle });
|
||||
const authorize = (candidate, kind = "exact") => runtimeContext(broker.describeReadAuthorization({ path: candidate }, kind));
|
||||
await assert.rejects(broker.readFile({ path: file }, authorize(file)), (error) => error.code === RPC_ERRORS.permissionDenied);
|
||||
await assert.rejects(broker.stat({ path: privateRoot }, authorize(privateRoot)), (error) => error.code === RPC_ERRORS.permissionDenied);
|
||||
await assert.rejects(broker.readDirectory({ path: privateRoot }, authorize(privateRoot, "directory")), (error) => error.code === RPC_ERRORS.permissionDenied);
|
||||
if (process.platform !== "win32") {
|
||||
const alias = path.join(root, "alias.json"); await fsp.symlink(file, alias);
|
||||
await assert.rejects(broker.readFile({ path: alias }, authorize(root, "directory")), (error) => error.code === RPC_ERRORS.permissionDenied);
|
||||
const directoryAlias = path.join(root, "directory-alias"); await fsp.symlink(privateRoot, directoryAlias);
|
||||
await assert.rejects(broker.readDirectory({ path: directoryAlias }, authorize(root, "directory")), (error) => error.code === RPC_ERRORS.permissionDenied);
|
||||
}
|
||||
const ordinary = path.join(root, "ordinary.txt"); await fsp.writeFile(ordinary, "Synthetic public file");
|
||||
assert.deepEqual(await broker.readFile({ path: ordinary }, authorize(ordinary)), { data: "Synthetic public file" });
|
||||
});
|
||||
|
||||
test("filesystem authorization removes trailing directory separators before permission", async (context) => {
|
||||
const root = createRoot(context);
|
||||
const requestedPath = `${root}${path.sep}`;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +0,0 @@
|
||||
"use strict";
|
||||
require("./agent/delegatedScope.test.cjs");
|
||||
require("./agent/conversationStore.test.cjs");
|
||||
require("./agent/contract.test.cjs");
|
||||
require("./agent/mcpDelegation.test.cjs");
|
||||
require("./agent/agentService.test.cjs");
|
||||
@@ -32,8 +32,6 @@ const { PluginNetworkBroker } = require("./networkBroker.cjs");
|
||||
const { PluginByteStreamService, FEATURE: BYTE_STREAM_FEATURE } = require("./byteStreamService.cjs");
|
||||
const { PluginAIContextService, PLUGIN_AI_CONTEXT_FEATURES } = require("./ai/aiContextService.cjs");
|
||||
const { PluginAITrustedHostAdapter } = require("./ai/trustedHostAdapter.cjs");
|
||||
const { PluginAgentService, PLUGIN_AGENT_FEATURE } = require("./agent/agentService.cjs");
|
||||
const { PluginAgentConversationStore } = require("./agent/conversationStore.cjs");
|
||||
const { HOST_INTERACTION_FEATURE, PluginHostInteractionService } = require("./hostInteractionService.cjs");
|
||||
const { PluginHostVaultService } = require("./hostVaultService.cjs");
|
||||
const { PluginAISourceBinding } = require("./ai/sourceBinding.cjs");
|
||||
@@ -101,14 +99,12 @@ function createPluginHostService(options) {
|
||||
const paths = createPluginPaths(options.app.getPath("userData"));
|
||||
const appRoot = options.appRoot ?? options.app.getAppPath();
|
||||
const runtimeDirectory = options.runtimeDirectory ?? path.join(__dirname, "runtime");
|
||||
const supportedFeatures = [...new Set(["terminal.input-drafts", "terminal.selection-sharing", "appearance.theme-packs", "metadata.brand-icon", BYTE_STREAM_FEATURE, ...PLUGIN_AI_CONTEXT_FEATURES, PLUGIN_AGENT_FEATURE, NETWORK_CREDENTIAL_LEASE_FEATURE, HOST_INTERACTION_FEATURE, HOST_VAULT_FEATURE, VAULT_PAGES_FEATURE, TERMINAL_SIDEBAR_FEATURE, INTERACTIVE_COMMAND_FEATURE, ...(options.supportedFeatures ?? [])])];
|
||||
const supportedFeatures = [...new Set(["terminal.input-drafts", "terminal.selection-sharing", "appearance.theme-packs", "metadata.brand-icon", BYTE_STREAM_FEATURE, ...PLUGIN_AI_CONTEXT_FEATURES, NETWORK_CREDENTIAL_LEASE_FEATURE, HOST_INTERACTION_FEATURE, HOST_VAULT_FEATURE, VAULT_PAGES_FEATURE, TERMINAL_SIDEBAR_FEATURE, INTERACTIVE_COMMAND_FEATURE, ...(options.supportedFeatures ?? [])])];
|
||||
const database = new PluginDatabase(paths.database);
|
||||
let interactionService;
|
||||
let byteStreamService;
|
||||
let aiContextService;
|
||||
let aiHostAdapter;
|
||||
let agentService;
|
||||
let agentHostAdapter;
|
||||
let permissionDecisionHost;
|
||||
let manager;
|
||||
const logService = new PluginLogService({ paths, electron: options.electron, resolveProvenance: options.resolvePluginProvenance ?? createPluginLogProvenanceResolver(database) });
|
||||
@@ -166,8 +162,7 @@ function createPluginHostService(options) {
|
||||
const filesystemBroker = new PluginFilesystemBroker({
|
||||
quotaManager,
|
||||
openDirectoryHandle: options.openPluginDirectoryHandle,
|
||||
protectedDirectories: [paths.logs, path.join(paths.root, "agent-chats")],
|
||||
protectedReadDirectories: [path.join(paths.root, "agent-chats")],
|
||||
protectedDirectories: [paths.logs],
|
||||
protectedFiles: [logService.preferencesPath, `${logService.preferencesPath}.tmp`],
|
||||
});
|
||||
const networkBroker = new PluginNetworkBroker({
|
||||
@@ -299,7 +294,6 @@ function createPluginHostService(options) {
|
||||
runtimeCleanup: async (identity) => {
|
||||
byteStreamService?.releaseRuntime(identity.runtimeId);
|
||||
aiContextService?.releaseRuntime(identity.runtimeId);
|
||||
agentService?.releaseRuntime(identity.runtimeId);
|
||||
interactionService?.releaseRuntime(identity.runtimeId);
|
||||
leaseStore.revokeRuntime(identity.runtimeId);
|
||||
await companionSupervisor.releaseRuntime(identity.runtimeId);
|
||||
@@ -320,40 +314,9 @@ function createPluginHostService(options) {
|
||||
hostAdapter: aiHostAdapter,
|
||||
});
|
||||
aiContextService.registerRpcCapabilities(rpcRegistry);
|
||||
agentHostAdapter = options.pluginAgentHostAdapter ?? new PluginAITrustedHostAdapter({
|
||||
getWindow: options.getInteractionWindow ?? (() => null),
|
||||
isLocked: options.isAppLocked, subscribeLock: options.subscribeAppLock,
|
||||
channels: { request: "netcatty:plugins:agent-host-request", ready: "netcatty:plugins:agent-host-ready", response: "netcatty:plugins:agent-host-response" },
|
||||
requestDefinition: "PluginAgentHostRequest", responseDefinition: "PluginAgentHostResponse", maxEnvelopeBytes: 1_048_576,
|
||||
// Agent native/model streams have their own exact-turn main lease.
|
||||
cancelProviderStreams: () => {},
|
||||
});
|
||||
if (options.electron.ipcMain) agentHostAdapter.registerIpc?.(options.electron.ipcMain);
|
||||
agentService = new PluginAgentService({ database, permissionEngine,
|
||||
getRuntimeIdentity: (pluginId) => runtimeSupervisor.getRuntimeIdentity(pluginId),
|
||||
hostAdapter: agentHostAdapter,
|
||||
conversationStore: new PluginAgentConversationStore(path.join(paths.root, "agent-chats")),
|
||||
getMcpBridge: () => require("../bridges/mcpServerBridge.cjs"),
|
||||
getTargetManager: options.getTerminalWorkerManager,
|
||||
getSessionBinding: (sessionId) => {
|
||||
const worker = options.getTerminalWorkerManager?.();
|
||||
const ownerId = worker?.getSessionOwnerWebContentsId?.(sessionId);
|
||||
const binding = worker?.getPluginSessionBinding?.(sessionId, ownerId);
|
||||
if (!Number.isSafeInteger(ownerId) || !binding) return null;
|
||||
const revision = JSON.stringify([binding.epoch, binding.generation]);
|
||||
return Object.freeze({ owner: String(ownerId), revision, isCurrent: (snapshot) => {
|
||||
if (options.getTerminalWorkerManager?.() !== worker || worker.getSessionOwnerWebContentsId(sessionId) !== ownerId) return false;
|
||||
const current = worker.getPluginSessionBinding(sessionId, ownerId);
|
||||
return snapshot.owner === String(ownerId) && snapshot.revision === revision && current != null
|
||||
&& JSON.stringify([current.epoch, current.generation]) === revision;
|
||||
} });
|
||||
},
|
||||
});
|
||||
agentService.registerRpcCapabilities(rpcRegistry);
|
||||
const originalOnPluginDisabled = contributionService.onPluginDisabled.bind(contributionService);
|
||||
contributionService.onPluginDisabled = (pluginId) => {
|
||||
aiContextService.releasePlugin(pluginId);
|
||||
agentService.releasePlugin(pluginId);
|
||||
return originalOnPluginDisabled(pluginId);
|
||||
};
|
||||
runtimeSupervisor.onDidChangeRuntime((event) => contributionService.onRuntimeStateChanged(event));
|
||||
@@ -496,7 +459,6 @@ function createPluginHostService(options) {
|
||||
interactionService.shutdown();
|
||||
byteStreamService.shutdown();
|
||||
aiContextService.shutdown();
|
||||
agentService.shutdown();
|
||||
terminalDataPipelineService?.shutdown();
|
||||
extensionProviderService.shutdown();
|
||||
credentialResolver.shutdown?.();
|
||||
@@ -516,7 +478,8 @@ function createPluginHostService(options) {
|
||||
themeService,
|
||||
interactionService,
|
||||
hostVaultService,
|
||||
catalogService: new MarketSourcesService({ database, manager, fetch: options.electron.net?.fetch?.bind(options.electron.net) }),
|
||||
catalogService: new MarketSourcesService({ database, manager, fetch: options.electron.net?.fetch?.bind(options.electron.net),
|
||||
resolveAvatar: (request) => contributionIconService.resolveCatalogAvatar(request) }),
|
||||
companionSupervisor,
|
||||
contributionIconService,
|
||||
contributionService,
|
||||
@@ -535,7 +498,6 @@ function createPluginHostService(options) {
|
||||
networkBroker,
|
||||
byteStreamService,
|
||||
aiContextService,
|
||||
agentService,
|
||||
permissionEngine,
|
||||
permissionDecisionHost,
|
||||
quotaManager,
|
||||
@@ -551,8 +513,6 @@ function createPluginHostService(options) {
|
||||
try { interactionService?.shutdown(); } catch {}
|
||||
try { byteStreamService?.shutdown(); } catch {}
|
||||
try { aiContextService?.shutdown(); } catch {}
|
||||
try { agentService?.shutdown(); } catch {}
|
||||
if (!agentService) { try { agentHostAdapter?.shutdown?.(); } catch {} }
|
||||
if (!aiContextService) { try { aiHostAdapter?.shutdown?.(); } catch {} }
|
||||
void logService.close();
|
||||
database.close();
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
const { PluginSourceRegistry } = require("./sourceRegistry.cjs");
|
||||
const { RegistryCatalogService } = require("./registryCatalogService.cjs");
|
||||
const { createSourceFetch } = require("./sourceFetch.cjs");
|
||||
const { isDeepStrictEqual } = require("node:util");
|
||||
|
||||
const installedIdentity = (plugin) => JSON.stringify([plugin?.id, plugin?.activeVersion, plugin?.archiveSha256, plugin?.source, plugin?.manifest, plugin?.runtime?.quarantinedAt]);
|
||||
|
||||
class MarketSourcesService {
|
||||
constructor(options) {
|
||||
@@ -9,6 +12,15 @@ class MarketSourcesService {
|
||||
this.manager = options.manager;
|
||||
this.registry = new PluginSourceRegistry(options.database);
|
||||
this.catalogs = new Map();
|
||||
this.catalogIdentities = new Map();
|
||||
this.changeListeners = new Set();
|
||||
}
|
||||
onDidChange(listener) {
|
||||
this.changeListeners.add(listener);
|
||||
return { dispose: () => this.changeListeners.delete(listener) };
|
||||
}
|
||||
#changed(sourceId) {
|
||||
for (const listener of this.changeListeners) listener({ sourceId });
|
||||
}
|
||||
#catalog(sourceId = "official") {
|
||||
const source = this.registry.get(sourceId);
|
||||
@@ -22,21 +34,63 @@ class MarketSourcesService {
|
||||
}
|
||||
return catalog;
|
||||
}
|
||||
list(sourceId) { return this.#catalog(sourceId).list(); }
|
||||
async list(sourceId = "official") {
|
||||
const snapshot = await this.#catalog(sourceId).list();
|
||||
// Selection tokens bind the validated entry and its delivery resources.
|
||||
const identity = JSON.stringify(snapshot.entries.map((entry) => [entry.id, entry.selectionToken]));
|
||||
if (this.catalogIdentities.get(sourceId) !== identity) {
|
||||
this.catalogIdentities.set(sourceId, identity);
|
||||
this.#changed(sourceId);
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
readme(id, token, sourceId) { return this.#catalog(sourceId).readme(id, token); }
|
||||
async author(request) {
|
||||
if (!request || typeof request !== "object" || Array.isArray(request)
|
||||
|| typeof request.pluginId !== "string" || !/^[a-z0-9][a-z0-9.-]{1,127}$/u.test(request.pluginId)) throw new TypeError("Invalid plugin author request");
|
||||
if (request.kind === "catalog") {
|
||||
if (Object.keys(request).some((key) => !["kind", "pluginId", "selectionToken", "sourceId"].includes(key))) throw new TypeError("Invalid plugin author request");
|
||||
return this.#catalog(request.sourceId).author(request.pluginId, request.selectionToken);
|
||||
}
|
||||
if (request.kind !== "installed" || Object.keys(request).some((key) => !["kind", "pluginId"].includes(key))) throw new TypeError("Invalid installed author request");
|
||||
const plugin = this.options.database.getActivePlugin(request.pluginId);
|
||||
if (!plugin?.activeVersion) return null;
|
||||
const captured = installedIdentity(plugin);
|
||||
let value = { author: plugin.manifest?.publisher ?? "", avatar: null, officialMaintained: false,
|
||||
sourceId: plugin.source.id, version: plugin.activeVersion, archiveSha256: plugin.archiveSha256 ?? null };
|
||||
if (plugin.runtime?.quarantinedAt == null) {
|
||||
try {
|
||||
// Presentation reuses an already validated catalog. It never refreshes
|
||||
// a source merely because the installed list becomes visible.
|
||||
this.registry.get(plugin.source.id);
|
||||
const catalog = this.catalogs.get(plugin.source.id);
|
||||
const entry = catalog?.publicEntries.find((item) => item.id === plugin.id && item.version === plugin.activeVersion
|
||||
&& item.artifact?.sha256 === plugin.archiveSha256 && isDeepStrictEqual(item.manifest, plugin.manifest));
|
||||
if (entry) value = await catalog.author(entry.id, entry.selectionToken);
|
||||
} catch { /* No exact current source match confers no maintenance badge. */ }
|
||||
}
|
||||
if (captured !== installedIdentity(this.options.database.getActivePlugin(request.pluginId))) throw new Error("Installed plugin changed while loading its author");
|
||||
return value;
|
||||
}
|
||||
install(id, token, sourceId = "official", acceptedSourceId) {
|
||||
if (sourceId !== "official" && acceptedSourceId !== sourceId) throw new Error("Review and confirm this third-party source before installing");
|
||||
return this.#catalog(sourceId).install(id, token);
|
||||
}
|
||||
listSources() { return this.registry.list(); }
|
||||
addSource(payload) { return this.manager.changeMarketSource(() => this.registry.add(payload?.name, payload?.address)); }
|
||||
updateSource(payload) { return this.manager.changeMarketSource(() => this.registry.update(payload?.id, payload?.name, payload?.enabled)); }
|
||||
async updateSource(payload) {
|
||||
const source = await this.manager.changeMarketSource(() => this.registry.update(payload?.id, payload?.name, payload?.enabled));
|
||||
this.#changed(source.id);
|
||||
return source;
|
||||
}
|
||||
async removeSource(payload) {
|
||||
if (typeof payload?.disablePlugins !== "boolean") throw new Error("Choose whether to disable installed plugins");
|
||||
await this.manager.changeMarketSource(() => {
|
||||
this.registry.remove(payload.id);
|
||||
this.catalogs.delete(payload.id);
|
||||
this.catalogIdentities.delete(payload.id);
|
||||
}, payload.disablePlugins ? payload.id : undefined);
|
||||
this.#changed(payload.id);
|
||||
}
|
||||
}
|
||||
module.exports = { MarketSourcesService };
|
||||
@@ -78,10 +78,6 @@ class PluginPermissionDecisionHost {
|
||||
resources: (request.resources ?? []).map((resource) => escapePermissionText(resource)),
|
||||
...(request.displayContext ? { displayContext: {
|
||||
...(request.displayContext.modelLabel ? { modelLabel: escapePermissionText(request.displayContext.modelLabel) } : {}),
|
||||
...(request.displayContext.action ? { action: {
|
||||
capabilityId: escapePermissionText(request.displayContext.action.capabilityId, 160),
|
||||
text: escapePermissionText(request.displayContext.action.text, 16_384),
|
||||
} } : {}),
|
||||
selections: (request.displayContext.selections ?? []).map((item) => ({
|
||||
scope: item.scope, title: escapePermissionText(item.title), version: escapePermissionText(item.version),
|
||||
})),
|
||||
|
||||
@@ -41,7 +41,9 @@ const CHANNELS = Object.freeze({
|
||||
updateSource: "netcatty:plugins:update-source",
|
||||
removeSource: "netcatty:plugins:remove-source",
|
||||
catalog: "netcatty:plugins:catalog",
|
||||
catalogChanged: "netcatty:plugins:catalog-changed",
|
||||
catalogReadme: "netcatty:plugins:catalog-readme",
|
||||
author: "netcatty:plugins:author",
|
||||
catalogInstall: "netcatty:plugins:catalog-install",
|
||||
install: "netcatty:plugins:install",
|
||||
setEnabled: "netcatty:plugins:set-enabled",
|
||||
@@ -679,6 +681,10 @@ function registerPluginBridge(ipcMain, options) {
|
||||
handle(CHANNELS.updateSource, async (_manager, payload) => options.catalogService.updateSource(payload));
|
||||
handle(CHANNELS.removeSource, async (_manager, payload) => options.catalogService.removeSource(payload));
|
||||
handle(CHANNELS.catalog, async (_manager, payload) => options.catalogService?.list(payload?.sourceId) ?? { entries: [], source: "builtin", error: "Plugin catalog unavailable" });
|
||||
handle(CHANNELS.author, async (_manager, payload) => {
|
||||
if (!options.catalogService) throw new Error("Plugin catalog unavailable");
|
||||
return options.catalogService.author(payload);
|
||||
});
|
||||
handle(CHANNELS.catalogReadme, async (_manager, payload) => {
|
||||
if (!options.catalogService) throw new Error("Plugin catalog unavailable");
|
||||
return options.catalogService.readme(payload?.id, payload?.selectionToken, payload?.sourceId);
|
||||
@@ -1703,6 +1709,7 @@ function registerPluginBridge(ipcMain, options) {
|
||||
publishScopeCatalog(event);
|
||||
return null;
|
||||
});
|
||||
options.catalogService?.onDidChange?.((event) => options.broadcast?.(CHANNELS.catalogChanged, event));
|
||||
contributionService?.onDidChange?.((event) => options.broadcast?.(CHANNELS.contributionsChanged, event));
|
||||
contributionService?.onDidPostViewMessage?.((event) => options.broadcast?.(CHANNELS.viewMessagePosted, event));
|
||||
viewHost?.onDidClose?.((event) => options.broadcast?.(CHANNELS.viewClosed, event));
|
||||
|
||||
@@ -101,6 +101,19 @@ test("plugin management bridge checks sender ownership before invoking manager",
|
||||
);
|
||||
});
|
||||
|
||||
test("author presentation is a trusted-app-only route and forwards no invented authority", async () => {
|
||||
const ipcMain = createIpcMain(); const calls = [];
|
||||
registerPluginBridge(ipcMain, { manager: { initialize: async () => {} }, isTrustedSender: createTrustedPluginBridgeSender({ devServerUrl: "http://localhost:5173" }),
|
||||
catalogService: { author: async (request) => { calls.push(request); return { author: "Netcatty", avatar: null, officialMaintained: false }; } } });
|
||||
const payload = { kind: "catalog", pluginId: "com.netcatty.starter", selectionToken: "a".repeat(64), sourceId: "official" };
|
||||
for (const url of ["netcatty-plugin://plugin-runtime/index.html", "https://attacker.invalid/"]) {
|
||||
await assert.rejects(ipcMain.handlers.get(CHANNELS.author)({ senderFrame: { url } }, payload), /Untrusted/);
|
||||
}
|
||||
assert.deepEqual(calls, []);
|
||||
const result = await ipcMain.handlers.get(CHANNELS.author)({ senderFrame: { url: "app://netcatty/index.html" } }, payload);
|
||||
assert.equal(result.officialMaintained, false); assert.deepEqual(calls, [payload]);
|
||||
});
|
||||
|
||||
test("plugin Vault credential catalog updates only through the trusted host bridge", async () => {
|
||||
const ipcMain = createIpcMain();
|
||||
const updates = [];
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
const { createHash } = require("node:crypto");
|
||||
const { PluginCatalogService, validateCatalog, MAX_CATALOG_BYTES } = require("./catalogService.cjs");
|
||||
const { REGISTRY_URL, fetchDistribution, fetchVerified, tuple } = require("./distributionSnapshot.cjs");
|
||||
const { isOfficialMaintained } = require("./sourceIdentity.cjs");
|
||||
const tokenFor = (entry) => createHash("sha256").update(JSON.stringify(entry)).digest("hex");
|
||||
|
||||
function prepareSnapshot(value, resources = new Map(), source) {
|
||||
@@ -19,6 +20,7 @@ class RegistryCatalogService extends PluginCatalogService {
|
||||
this.source = "builtin";
|
||||
this.error = null;
|
||||
this.refreshing = null;
|
||||
this.resolveAvatar = options.resolveAvatar;
|
||||
}
|
||||
async refresh() {
|
||||
if (this.refreshing) return this.refreshing;
|
||||
@@ -58,6 +60,22 @@ class RegistryCatalogService extends PluginCatalogService {
|
||||
return entry;
|
||||
}
|
||||
artifactSize(entry) { return this.resources.get(tuple(entry))?.artifact?.size; }
|
||||
async author(id, token) {
|
||||
this.sourceGuard();
|
||||
const entry = this.selected(id, token);
|
||||
const reference = this.resources.get(tuple(entry))?.avatar;
|
||||
let avatar = null;
|
||||
if (reference && this.resolveAvatar) {
|
||||
try {
|
||||
avatar = await this.resolveAvatar({ sourceId: this.marketSource.id, reference,
|
||||
read: () => fetchVerified(reference, this.fetch, this.origin) });
|
||||
} catch { /* Missing or invalid imagery uses the same author placeholder. */ }
|
||||
}
|
||||
this.sourceGuard();
|
||||
this.selected(id, token);
|
||||
return { author: entry.author, avatar, officialMaintained: isOfficialMaintained(entry, this.marketSource),
|
||||
sourceId: this.marketSource.id, version: entry.version, archiveSha256: entry.artifact?.sha256 ?? null };
|
||||
}
|
||||
async readme(id, token) {
|
||||
const entry = this.selected(id, token);
|
||||
const resource = this.resources.get(tuple(entry))?.readme;
|
||||
|
||||
@@ -401,9 +401,6 @@ function createPluginContext(config, client, runtimeApi) {
|
||||
list: (params) => client.request("context.selected.list", params),
|
||||
read: (params) => client.request("context.selected.read", params),
|
||||
};
|
||||
const agent = Object.fromEntries(["listBackends", "selectTargets", "listChats", "openChat", "send", "read", "history", "stop", "closeChat"].map((operation) => [
|
||||
operation, (params) => client.request(`agent.${operation}`, params, operation === "read" ? { deadlineMs: 65_000 } : {}),
|
||||
]));
|
||||
const filesystem = {
|
||||
readFile: (filePath, options = {}) => client.request("filesystem.readFile", {
|
||||
path: filePath,
|
||||
@@ -586,7 +583,6 @@ function createPluginContext(config, client, runtimeApi) {
|
||||
credentials,
|
||||
network,
|
||||
ai,
|
||||
agent,
|
||||
selectedContext,
|
||||
ui,
|
||||
vault,
|
||||
|
||||
@@ -6,6 +6,11 @@ const { isIP } = require("node:net");
|
||||
const OFFICIAL_ORIGIN = "https://plugins.netcatty.app";
|
||||
const OFFICIAL_SOURCE = Object.freeze({ id: "official", kind: "official", name: "Netcatty marketplace", origin: OFFICIAL_ORIGIN });
|
||||
const LOCAL_SOURCE = Object.freeze({ id: "local", kind: "local", name: "Local import", origin: null });
|
||||
// Curated first-party maintenance authority, independent of manifest publisher text.
|
||||
const FIRST_PARTY_PLUGINS = Object.freeze([
|
||||
Object.freeze({ id: "com.netcatty.starter", repository: "binaricat/Netcatty" }),
|
||||
Object.freeze({ id: "com.netcatty.hello", repository: "binaricat/Netcatty" }),
|
||||
]);
|
||||
const hash = (value) => createHash("sha256").update(value).digest("hex");
|
||||
|
||||
// Source identity is host-owned. Neither a manifest nor a catalog supplies kind/id.
|
||||
@@ -41,4 +46,11 @@ function privateOwner(source, pluginId) {
|
||||
return `source:${hash(assertSource(source).id)}:${pluginId}`;
|
||||
}
|
||||
|
||||
module.exports = { OFFICIAL_SOURCE, LOCAL_SOURCE, canonicalSourceOrigin, thirdPartySource, assertSource, privateOwner };
|
||||
function isOfficialMaintained(entry, source) {
|
||||
const trusted = assertSource(source);
|
||||
return trusted.id === OFFICIAL_SOURCE.id && trusted.kind === OFFICIAL_SOURCE.kind
|
||||
&& trusted.origin === OFFICIAL_SOURCE.origin
|
||||
&& FIRST_PARTY_PLUGINS.some((pair) => pair.id === entry.id && pair.repository === entry.repository);
|
||||
}
|
||||
|
||||
module.exports = { OFFICIAL_SOURCE, LOCAL_SOURCE, canonicalSourceOrigin, thirdPartySource, assertSource, privateOwner, isOfficialMaintained };
|
||||
+18
-19
@@ -106,16 +106,15 @@ function createPreloadApi(ctx) {
|
||||
updatePluginSource: (source) => ipcRenderer.invoke("netcatty:plugins:update-source", source),
|
||||
removePluginSource: (id, disablePlugins) => ipcRenderer.invoke("netcatty:plugins:remove-source", { id, disablePlugins }),
|
||||
listPluginCatalog: (sourceId) => ipcRenderer.invoke("netcatty:plugins:catalog", { sourceId }),
|
||||
getPluginAuthorPresentation: (request) => ipcRenderer.invoke("netcatty:plugins:author", request),
|
||||
onPluginCatalogChanged: (callback) => {
|
||||
const listener = (_event, payload) => callback(payload);
|
||||
ipcRenderer.on("netcatty:plugins:catalog-changed", listener);
|
||||
return () => ipcRenderer.removeListener("netcatty:plugins:catalog-changed", listener);
|
||||
},
|
||||
getPluginCatalogReadme: (id, selectionToken, sourceId) => ipcRenderer.invoke("netcatty:plugins:catalog-readme", { id, selectionToken, sourceId }),
|
||||
installCatalogPlugin: (id, selectionToken, sourceId, acceptedSourceId) => ipcRenderer.invoke("netcatty:plugins:catalog-install", { id, selectionToken, sourceId, acceptedSourceId }),
|
||||
setPluginAIHostReady: (ready) => ipcRenderer.invoke("netcatty:plugins:ai-host-ready", ready),
|
||||
setPluginAgentHostReady: (ready) => ipcRenderer.invoke("netcatty:plugins:agent-host-ready", ready),
|
||||
respondPluginAgentHost: (response) => ipcRenderer.invoke("netcatty:plugins:agent-host-response", response),
|
||||
onPluginAgentHostRequest: (callback) => {
|
||||
const listener = (_event, payload) => callback(payload);
|
||||
ipcRenderer.on("netcatty:plugins:agent-host-request", listener);
|
||||
return () => ipcRenderer.removeListener("netcatty:plugins:agent-host-request", listener);
|
||||
},
|
||||
respondPluginAIHost: (response) => ipcRenderer.invoke("netcatty:plugins:ai-host-response", response),
|
||||
onPluginAIHostRequest: (callback) => {
|
||||
const listener = (_event, payload) => callback(payload);
|
||||
@@ -1994,23 +1993,23 @@ function createPreloadApi(ctx) {
|
||||
aiChatCancel: async (requestId) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:chat:cancel", { requestId });
|
||||
},
|
||||
aiFetch: async (url, method, headers, body, providerId, skipHostCheck, followRedirects, skipTLSVerify, requestId) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:fetch", { url, method, headers, body, providerId, skipHostCheck, followRedirects, skipTLSVerify, ...(requestId ? { requestId } : {}) });
|
||||
aiFetch: async (url, method, headers, body, providerId, skipHostCheck, followRedirects, skipTLSVerify) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:fetch", { url, method, headers, body, providerId, skipHostCheck, followRedirects, skipTLSVerify });
|
||||
},
|
||||
aiAllowlistAddHost: async (baseURL) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:allowlist:add-host", { baseURL });
|
||||
},
|
||||
aiExec: async (sessionId, command, chatSessionId, delegationTag) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:exec", { sessionId, command, chatSessionId, ...(delegationTag ? { delegationTag } : {}) });
|
||||
aiExec: async (sessionId, command, chatSessionId) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:exec", { sessionId, command, chatSessionId });
|
||||
},
|
||||
aiCattyCancelExec: async (chatSessionId, delegationTag) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:catty:cancel", { chatSessionId, ...(delegationTag ? { delegationTag } : {}) });
|
||||
aiCattyCancelExec: async (chatSessionId) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:catty:cancel", { chatSessionId });
|
||||
},
|
||||
aiSetChatSessionCancelled: async (chatSessionId, cancelled = true, delegationTag) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:chat-session:set-cancelled", { chatSessionId, cancelled, ...(delegationTag ? { delegationTag } : {}) });
|
||||
aiSetChatSessionCancelled: async (chatSessionId, cancelled = true) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:chat-session:set-cancelled", { chatSessionId, cancelled });
|
||||
},
|
||||
aiCapability: async (rpcMethod, params, chatSessionId, delegationTag) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:capability", { rpcMethod, params, chatSessionId, ...(delegationTag ? { delegationTag } : {}) });
|
||||
aiCapability: async (rpcMethod, params, chatSessionId) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:capability", { rpcMethod, params, chatSessionId });
|
||||
},
|
||||
aiDiscoverAgents: async (options) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:agents:discover", options);
|
||||
@@ -2071,8 +2070,8 @@ function createPreloadApi(ctx) {
|
||||
aiPrivacyStatus: async () => ipcRenderer.invoke("netcatty:ai:privacy:status"),
|
||||
aiPrivacyTransform: async (request) => ipcRenderer.invoke("netcatty:ai:privacy:transform", request),
|
||||
aiPrivacyClearSession: async (chatSessionId) => ipcRenderer.invoke("netcatty:ai:privacy:clear", chatSessionId),
|
||||
aiMcpUpdateSessions: async (sessions, chatSessionId, delegationTag) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:mcp:update-sessions", { sessions, chatSessionId, ...(delegationTag ? { delegationTag } : {}) });
|
||||
aiMcpUpdateSessions: async (sessions, chatSessionId) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:mcp:update-sessions", { sessions, chatSessionId });
|
||||
},
|
||||
aiMcpUpdateLiveSessions: async (sessions) => {
|
||||
return ipcRenderer.invoke("netcatty:ai:mcp:update-live-sessions", { sessions });
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
.package/
|
||||
dist/
|
||||
*.ncpkg
|
||||
@@ -1,20 +0,0 @@
|
||||
# Global Agent Chat example (work in progress)
|
||||
|
||||
This browser sandbox plugin provides a custom Chat view using the existing
|
||||
host-owned Agent runtime. Choose a configured Catty or Claude Code backend,
|
||||
explicitly choose connected terminal targets, open a new or owned conversation,
|
||||
then Send. Stop cancels the exact turn. Refresh and reselection are explicit;
|
||||
expired authority never silently re-shares targets or retries inference.
|
||||
|
||||
Core stores source-isolated conversation history. The plugin receives text,
|
||||
usage and safe activity summaries, never native session IDs, credentials, raw
|
||||
tool arguments/results or executable/MCP configuration. Tool actions use the
|
||||
plugin's `ai.agent.actions` Allow / Ask / Deny setting. Other backends report
|
||||
unsupported/unavailable until their native tool boundaries are verified.
|
||||
|
||||
Build with `node examples/plugins/global-agent/build.mjs`, then package the
|
||||
`.package` directory using `@netcatty/plugin-cli`. Install the resulting `.ncpkg`
|
||||
through Settings → Plugins. This is a minimal example, not a background service.
|
||||
Real provider/Claude usage requires a user's already configured backend and
|
||||
separate approval for paid acceptance testing. Automated tests use synthetic
|
||||
fixtures and do not establish authenticated Claude service/native acceptance.
|
||||
@@ -1,9 +0,0 @@
|
||||
import { mkdir, copyFile, rm } from 'node:fs/promises';
|
||||
import { URL } from 'node:url';
|
||||
const staging = new URL('./.package/', import.meta.url);
|
||||
await rm(staging, { recursive: true, force: true });
|
||||
await mkdir(new URL('./dist/', staging), { recursive: true });
|
||||
await copyFile(new URL('./src/index.js', import.meta.url), new URL('./dist/index.js', staging));
|
||||
for (const name of ['netcatty.plugin.json', 'panel.html', 'panel.css', 'panel.js', 'README.md']) {
|
||||
await copyFile(new URL(name, import.meta.url), new URL(name, staging));
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"manifestVersion": 1,
|
||||
"id": "com.netcatty.globalagent",
|
||||
"name": "global-agent-example",
|
||||
"displayName": "Global Agent Chat Example",
|
||||
"description": "Custom sandbox Chat UI reusing Netcatty's configured Agent backends and explicitly selected terminal targets.",
|
||||
"version": "0.1.0",
|
||||
"publisher": "netcatty",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"engines": { "netcatty": ">=0.0.0", "api": ">=0.1.0-internal.1 <0.2.0" },
|
||||
"main": { "browser": "dist/index.js" },
|
||||
"activationEvents": ["onView:com.netcatty.globalagent.panel"],
|
||||
"permissions": { "required": ["commands", "views", "ai.agent.use"], "optional": ["ai.agent.actions"] },
|
||||
"features": { "required": ["ai.agent-sessions"] },
|
||||
"contributes": {
|
||||
"commands": [
|
||||
{ "id": "com.netcatty.globalagent.backends", "title": "Global Agent: List Backends" },
|
||||
{ "id": "com.netcatty.globalagent.targets", "title": "Global Agent: Select Targets" },
|
||||
{ "id": "com.netcatty.globalagent.chats", "title": "Global Agent: List Conversations" },
|
||||
{ "id": "com.netcatty.globalagent.open", "title": "Global Agent: Open Conversation" },
|
||||
{ "id": "com.netcatty.globalagent.send", "title": "Global Agent: Send" },
|
||||
{ "id": "com.netcatty.globalagent.read", "title": "Global Agent: Read Events" },
|
||||
{ "id": "com.netcatty.globalagent.history", "title": "Global Agent: Read Conversation" },
|
||||
{ "id": "com.netcatty.globalagent.stop", "title": "Global Agent: Stop" },
|
||||
{ "id": "com.netcatty.globalagent.close", "title": "Global Agent: Close Conversation" }
|
||||
],
|
||||
"views": [{ "id": "com.netcatty.globalagent.panel", "title": "Global Agent Chat", "location": "modal", "entry": "panel.html" }]
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
{"name":"@netcatty/example-global-agent-plugin","version":"0.1.0","private":true,"type":"module","scripts":{"build":"node build.mjs"}}
|
||||
@@ -1,29 +0,0 @@
|
||||
:root { color-scheme: light dark; --background:0 0% 100%; --foreground:222 47% 12%; --muted:210 20% 96%; --muted-foreground:215 20% 35%; --border:215 20% 75%; --primary:221 83% 45%; --primary-foreground:0 0% 100%; font: 15px/1.5 system-ui,sans-serif; color:hsl(var(--foreground)); background:hsl(var(--background)); }
|
||||
:root[data-theme="dark"] { --background:221 39% 11%; --foreground:210 20% 98%; --muted:219 27% 21%; --muted-foreground:220 13% 91%; --border:218 11% 65%; --primary:213 97% 87%; --primary-foreground:221 39% 11%; }
|
||||
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --background:221 39% 11%; --foreground:210 20% 98%; --muted:219 27% 21%; --muted-foreground:220 13% 91%; --border:218 11% 65%; --primary:213 97% 87%; --primary-foreground:221 39% 11%; } }
|
||||
* { box-sizing:border-box; }
|
||||
body { margin:0; }
|
||||
main { max-width:760px; padding:36px; margin:auto; }
|
||||
header { margin-bottom:26px; }
|
||||
.badge { color:hsl(var(--primary)); font-size:11px; font-weight:700; letter-spacing:1.6px; }
|
||||
h1 { font-size:27px; font-weight:650; letter-spacing:-.6px; margin:8px 0; }
|
||||
p { color:hsl(var(--muted-foreground)); margin:4px 0; }
|
||||
.card { border:1px solid hsl(var(--border)); border-radius:10px; padding:16px 18px; margin:14px 0; background:hsl(var(--muted)); }
|
||||
label { display:block; font-size:12px; font-weight:600; color:hsl(var(--muted-foreground)); margin-bottom:8px; }
|
||||
#model { font-weight:600; }
|
||||
select, textarea { width:100%; background:hsl(var(--background)); color:inherit; border:1px solid hsl(var(--border)); padding:10px 12px; border-radius:7px; font:inherit; }
|
||||
select:focus,textarea:focus,button:focus-visible { outline:2px solid hsl(var(--primary)); outline-offset:2px; }
|
||||
textarea { resize:vertical; min-height:84px; }
|
||||
form { margin:22px 0; }
|
||||
.actions { display:flex; flex-wrap:wrap; align-items:center; gap:10px; margin-top:12px; }
|
||||
button { border:1px solid hsl(var(--border)); border-radius:7px; background:transparent; color:inherit; padding:9px 24px; font:inherit; font-weight:600; cursor:pointer; }
|
||||
#send { border-color:transparent; background:hsl(var(--primary)); color:hsl(var(--primary-foreground)); }
|
||||
button:disabled { opacity:.42; cursor:default; }
|
||||
#choose-reference { margin-top:10px; }
|
||||
#status { margin-left:4px; color:hsl(var(--muted-foreground)); font-size:12px; }
|
||||
.response { min-height:160px; }
|
||||
pre { white-space:pre-wrap; overflow-wrap:anywhere; font:16px/1.7 system-ui,sans-serif; margin:0 0 12px; }
|
||||
.hint,footer { font-size:12px; color:hsl(var(--muted-foreground)); margin-top:8px; }
|
||||
footer { padding-top:8px; }
|
||||
@media(max-width:520px) { main { padding:22px; } h1 { font-size:23px; } }
|
||||
@media (forced-colors: active) { button, select, textarea { border:1px solid ButtonText; } }
|
||||
@@ -1,8 +0,0 @@
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Global Agent Chat</title><link rel="stylesheet" href="panel.css"></head>
|
||||
<body><main><header><span class="badge">AGENT PLATFORM EXAMPLE</span><h1>Global Agent Chat</h1><p>A conversation independent of the active terminal or workspace.</p><p id="qa" class="hint"></p></header>
|
||||
<section class="card"><label for="backend">Configured Agent backend</label><select id="backend" disabled></select><button id="refresh" type="button">Refresh backends</button>
|
||||
<label for="conversation">Owned conversation</label><select id="conversation"><option value="">New conversation</option></select>
|
||||
<div class="actions"><button id="targets" type="button">Choose terminals</button><button id="open" type="button" disabled>Open conversation</button></div><p id="selection" class="hint">No targets selected yet.</p></section>
|
||||
<section class="card response"><pre id="transcript" aria-live="polite"></pre><p id="usage" class="hint"></p><p id="activity" class="hint"></p></section>
|
||||
<form id="compose"><label for="prompt">Message</label><textarea id="prompt" maxlength="16384" placeholder="Ask about the selected terminals"></textarea><div class="actions"><button id="send" type="submit" disabled>Send</button><button id="stop" type="button" disabled>Stop</button><span id="status" role="status">Loading configured backends…</span></div></form>
|
||||
<footer>Core owns Agent execution and conversation history. Actions follow this plugin's Allow / Ask / Deny setting. Only Catty and Claude Code MCP mode are eligible in this version; other native modes are unavailable here.</footer></main><script src="panel.js"></script></body></html>
|
||||
@@ -1,93 +0,0 @@
|
||||
/* global window, document */
|
||||
'use strict';
|
||||
const element = (id) => document.getElementById(id);
|
||||
const invoke = (name, params = {}) => window.netcattyView.executeCommand(`com.netcatty.globalagent.${name}`, params);
|
||||
let chat; let selection; let turn; let busy = false; let generation = 0; let closed = false;
|
||||
const option = (value, text) => { const item = document.createElement('option'); item.value = value; item.textContent = text; return item; };
|
||||
const status = (text) => { element('status').textContent = text; };
|
||||
function controls(value) {
|
||||
busy = value;
|
||||
for (const id of ['backend', 'conversation', 'refresh', 'targets', 'prompt']) element(id).disabled = value;
|
||||
element('open').disabled = value || !selection || !element('backend').value;
|
||||
element('send').disabled = value || !chat;
|
||||
element('stop').disabled = !value || !chat;
|
||||
}
|
||||
async function closeChat() { const previous = chat; chat = undefined; if (previous) await invoke('close', { chatHandle: previous.chatHandle }).catch(() => {}); }
|
||||
async function refresh() {
|
||||
if (busy || closed) return; const run = ++generation; controls(true);
|
||||
try {
|
||||
await closeChat();
|
||||
const [backends, chats] = await Promise.all([invoke('backends'), invoke('chats')]);
|
||||
if (closed || run !== generation) return;
|
||||
element('backend').replaceChildren(...backends.items.map((item) => {
|
||||
const entry = option(item.status === 'supported' ? item.backendRef : '', `${item.label}${item.status === 'supported' ? '' : ` (${item.status}: ${item.reason})`}`);
|
||||
entry.disabled = item.status !== 'supported'; return entry;
|
||||
}));
|
||||
const supported = backends.items.find((item) => item.status === 'supported'); element('backend').value = supported?.backendRef ?? '';
|
||||
element('conversation').replaceChildren(option('', 'New conversation'), ...chats.items.map((item) => option(item.conversationRef, `${item.title} · ${item.backend}`)));
|
||||
status('Choose terminals, then open a conversation.');
|
||||
} catch { if (!closed && run === generation) status('Configured Agent unavailable. Check Netcatty settings, then Refresh backends.'); }
|
||||
finally { if (!closed && run === generation) controls(false); }
|
||||
}
|
||||
element('refresh').addEventListener('click', refresh);
|
||||
for (const id of ['backend', 'conversation']) element(id).addEventListener('change', async () => { await closeChat(); controls(false); status('Open the selected conversation before sending.'); });
|
||||
element('targets').addEventListener('click', async () => {
|
||||
if (busy) return; const run = ++generation; controls(true);
|
||||
try {
|
||||
await closeChat(); const result = await invoke('targets');
|
||||
if (closed || run !== generation) return; selection = result;
|
||||
element('selection').textContent = result.items.length ? result.items.map((item) => item.title).join(', ') : 'No terminal targets. Model conversation only.';
|
||||
status('Targets selected. Open a conversation.');
|
||||
} catch { if (!closed && run === generation) status('Target selection ended. Choose terminals again when ready.'); }
|
||||
finally { if (!closed && run === generation) controls(false); }
|
||||
});
|
||||
element('open').addEventListener('click', async () => {
|
||||
if (busy || !selection) return;
|
||||
if (selection.expiresAt <= Date.now()) { status('Target selection expired. Choose terminals again.'); return; }
|
||||
const run = ++generation; controls(true);
|
||||
try {
|
||||
await closeChat(); const reference = element('conversation').value;
|
||||
const result = await invoke('open', { backendRef: element('backend').value, selectionHandle: selection.selectionHandle, ...(reference ? { conversationRef: reference } : {}) });
|
||||
if (closed || run !== generation) { await invoke('close', { chatHandle: result.chatHandle }).catch(() => {}); return; }
|
||||
chat = result; const history = await invoke('history', { chatHandle: chat.chatHandle });
|
||||
if (closed || run !== generation) return;
|
||||
element('transcript').textContent = history.items.map((item) => `${item.role}: ${item.text}`).join('\n\n');
|
||||
status(`Ready · ${result.backendLabel}`);
|
||||
} catch { await closeChat(); if (!closed && run === generation) status('Conversation unavailable. Refresh backends or choose terminals again; your draft is kept.'); }
|
||||
finally { if (!closed && run === generation) controls(false); }
|
||||
});
|
||||
element('compose').addEventListener('submit', async (event) => {
|
||||
event.preventDefault(); if (busy || !chat || !element('prompt').value.trim()) return;
|
||||
if (chat.expiresAt <= Date.now()) { status('Conversation targets expired. Choose terminals and reopen; your draft is kept.'); return; }
|
||||
const run = ++generation; controls(true); status('Running…'); element('usage').textContent = ''; element('activity').textContent = '';
|
||||
const text = element('prompt').value; element('transcript').textContent += `\n\nuser: ${text}\n\nassistant: `;
|
||||
try {
|
||||
const result = await invoke('send', { chatHandle: chat.chatHandle, text });
|
||||
if (closed || run !== generation) { await invoke('stop', { turnHandle: result.turnHandle }).catch(() => {}); return; }
|
||||
turn = result.turnHandle;
|
||||
for (;;) {
|
||||
const item = await invoke('read', { turnHandle: turn }); if (closed || run !== generation) return;
|
||||
if (item.kind === 'end') { status(item.reason === 'completed' ? 'Complete' : `Ended: ${item.reason}`); break; }
|
||||
if (item.kind === 'text') element('transcript').textContent += item.text;
|
||||
if (item.kind === 'activity') element('activity').textContent = `${item.capabilityId}: ${item.state}`;
|
||||
if (item.kind === 'usage') element('usage').textContent = `${item.inputTokens} input tokens · ${item.outputTokens} output tokens`;
|
||||
}
|
||||
} catch { if (!closed && run === generation) status('Request ended. Check access or refresh/reselect before another explicit Send; your draft is kept.'); }
|
||||
finally { if (!closed && run === generation) { turn = undefined; controls(false); } }
|
||||
});
|
||||
element('stop').addEventListener('click', async () => {
|
||||
if (!busy) return; const run = ++generation; const previous = turn; turn = undefined; status('Stopping…');
|
||||
try { if (previous) await invoke('stop', { turnHandle: previous }); else await closeChat(); }
|
||||
catch { /* Revocation may already have stopped this exact turn. */ }
|
||||
finally { if (!closed && run === generation) { controls(false); status('Stopped'); } }
|
||||
});
|
||||
const theme = window.netcattyView.onDidChangeEnvironment?.((environment) => {
|
||||
const root = document.documentElement; root.dataset.theme = ['light', 'dark'].includes(environment.theme) ? environment.theme : 'system';
|
||||
root.style.colorScheme = root.dataset.theme === 'system' ? 'light dark' : root.dataset.theme;
|
||||
for (const name of ['--background', '--foreground', '--muted', '--muted-foreground', '--border', '--primary', '--primary-foreground']) {
|
||||
const value = environment.themeTokens?.[name]; if (typeof value === 'string' && value.length <= 96) root.style.setProperty(name, value); else root.style.removeProperty(name);
|
||||
}
|
||||
});
|
||||
window.netcattyView.onDidReceiveMessage?.((message) => { if (message?.qaFixture === true) element('qa').textContent = 'Isolated deterministic fixture · no real model inference or paid API'; });
|
||||
window.addEventListener('pagehide', () => { closed = true; ++generation; theme?.dispose(); if (turn) void invoke('stop', { turnHandle: turn }).catch(() => {}); void closeChat(); });
|
||||
void refresh();
|
||||
@@ -1,41 +0,0 @@
|
||||
"use strict";
|
||||
/* global __dirname, setImmediate */
|
||||
const test = require("node:test"); const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs"); const path = require("node:path"); const { JSDOM } = require("jsdom");
|
||||
|
||||
test("global Chat sample follows host theme and preserves drafts on explicit target expiry without re-sharing or retrying", async (t) => {
|
||||
const dom = new JSDOM(fs.readFileSync(path.join(__dirname, "panel.html"), "utf8"), { runScripts: "outside-only" });
|
||||
let now = 1; let environment; let selections = 0; let sends = 0; let disposed = 0;
|
||||
const calls = [];
|
||||
dom.window.Date.now = () => now;
|
||||
Object.defineProperty(dom.window, "netcattyView", { value: {
|
||||
onDidChangeEnvironment: (callback) => { environment = callback; return { dispose: () => disposed++ }; }, onDidReceiveMessage: () => ({ dispose() {} }),
|
||||
executeCommand: async (name) => {
|
||||
const op = name.split(".").at(-1); calls.push(op);
|
||||
if (op === "backends") return { items: [{ backendRef: "host-ref", label: "Synthetic configured Catty", status: "supported", reason: "ready" }] };
|
||||
if (op === "chats" || op === "history") return { items: [] };
|
||||
if (op === "targets") { selections++; return { selectionHandle: "selection", expiresAt: now + 300_000, items: [{ title: "Synthetic terminal" }] }; }
|
||||
if (op === "open") return { chatHandle: "chat", backendLabel: "Synthetic Catty", expiresAt: now + 300_000 };
|
||||
if (op === "send") { sends++; throw Error("Synthetic denied send"); }
|
||||
return { ok: true };
|
||||
},
|
||||
} });
|
||||
t.after(() => { dom.window.dispatchEvent(new dom.window.Event("pagehide")); dom.window.close(); });
|
||||
const element = (id) => dom.window.document.getElementById(id);
|
||||
const settle = async () => { for (let i = 0; i < 8; i++) await new Promise(setImmediate); };
|
||||
dom.window.eval(fs.readFileSync(path.join(__dirname, "panel.js"), "utf8")); await settle();
|
||||
environment({ theme: "light", themeTokens: { "--primary": "120 70% 40%" } });
|
||||
assert.equal(dom.window.document.documentElement.dataset.theme, "light"); assert.equal(dom.window.document.documentElement.style.getPropertyValue("--primary"), "120 70% 40%");
|
||||
environment({ theme: "dark", themeTokens: {} }); assert.equal(dom.window.document.documentElement.dataset.theme, "dark");
|
||||
assert.equal(dom.window.document.documentElement.style.getPropertyValue("--primary"), "");
|
||||
element("targets").click(); await settle(); element("open").click(); await settle();
|
||||
element("prompt").value = "Keep this synthetic draft"; now += 300_001;
|
||||
const send = () => element("compose").dispatchEvent(new dom.window.Event("submit", { cancelable: true }));
|
||||
send(); await settle(); assert.match(element("status").textContent, /expired/); assert.equal(sends, 0); assert.equal(selections, 1);
|
||||
element("refresh").click(); await settle(); element("open").click(); await settle();
|
||||
assert.match(element("status").textContent, /expired/); assert.equal(selections, 1); assert.equal(element("prompt").value, "Keep this synthetic draft");
|
||||
element("targets").click(); await settle(); element("open").click(); await settle();
|
||||
send(); await settle(); assert.equal(sends, 1); assert.equal(selections, 2); assert.match(element("status").textContent, /Request ended/);
|
||||
await settle(); assert.equal(sends, 1, "a failed inference is never automatically retried");
|
||||
assert.equal(element("prompt").value, "Keep this synthetic draft"); assert.ok(calls.includes("history")); assert.equal(disposed, 0);
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
export default {
|
||||
activate(context) {
|
||||
const operations = { backends: 'listBackends', targets: 'selectTargets', chats: 'listChats', open: 'openChat',
|
||||
send: 'send', read: 'read', history: 'history', stop: 'stop', close: 'closeChat' };
|
||||
for (const [name, operation] of Object.entries(operations)) context.subscriptions.add(context.commands.registerCommand(
|
||||
`com.netcatty.globalagent.${name}`, (params = {}) => context.agent[operation](params),
|
||||
));
|
||||
},
|
||||
};
|
||||
@@ -11,9 +11,11 @@ Group results contain the chosen current members and never include future member
|
||||
label change for the first chosen host. Netcatty displays editable fields and the
|
||||
normalized field diff before either action saves.
|
||||
|
||||
`connect` asks Netcatty to confirm a saved-host connection. The confirmation shows
|
||||
whether saved scripts can run. The acknowledgement contains no session identifier
|
||||
or terminal data. Selecting metadata never authorizes a connection by itself.
|
||||
`connect` requests a saved-host connection under the plugin's permission settings.
|
||||
Ask displays the target and whether saved scripts can run; Allow can dispatch
|
||||
without that permission-only dialog, and Deny blocks the request. Normal SSH
|
||||
authentication still applies. The acknowledgement contains no session identifier
|
||||
or terminal data. Selecting metadata does not change those permission settings.
|
||||
|
||||
All sample test resources use synthetic hostnames. Native acceptance must use
|
||||
synthetic hosts and must not establish a real host connection.
|
||||
Vendored
+14
-3
@@ -355,6 +355,18 @@ declare global {
|
||||
artifact?: { url: string; sha256: string };
|
||||
}
|
||||
|
||||
type NetcattyPluginAuthorRequest =
|
||||
| { kind: 'catalog'; pluginId: string; selectionToken: string; sourceId: string }
|
||||
| { kind: 'installed'; pluginId: string };
|
||||
interface NetcattyPluginAuthorPresentation {
|
||||
author: string;
|
||||
avatar: string | null;
|
||||
officialMaintained: boolean;
|
||||
sourceId: string;
|
||||
version: string;
|
||||
archiveSha256: string | null;
|
||||
}
|
||||
|
||||
type PluginPermissionMode = 'allow' | 'ask' | 'deny';
|
||||
type NetcattyPluginPermissionPrompt = import('@netcatty/plugin-contract').PermissionRequest & {
|
||||
actionToken: string; resources: string[];
|
||||
@@ -477,12 +489,11 @@ declare global {
|
||||
updatePluginSource?(source: { id: string; name: string; enabled: boolean }): Promise<NetcattyPluginSource>;
|
||||
removePluginSource?(id: string, disablePlugins: boolean): Promise<void>;
|
||||
listPluginCatalog?(sourceId?: string): Promise<NetcattyPluginCatalogSnapshot>;
|
||||
getPluginAuthorPresentation?(request: NetcattyPluginAuthorRequest): Promise<NetcattyPluginAuthorPresentation | null>;
|
||||
onPluginCatalogChanged?(callback: (event: { sourceId: string }) => void): () => void;
|
||||
getPluginCatalogReadme?(id: string, selectionToken?: string, sourceId?: string): Promise<string>;
|
||||
installCatalogPlugin?(id: string, selectionToken?: string, sourceId?: string, acceptedSourceId?: string): Promise<NetcattyInstalledPlugin>;
|
||||
setPluginAIHostReady?(ready: boolean): Promise<boolean>;
|
||||
setPluginAgentHostReady?(ready: boolean): Promise<boolean>;
|
||||
respondPluginAgentHost?(response: import("@netcatty/plugin-contract").PluginAgentHostResponse): Promise<boolean>;
|
||||
onPluginAgentHostRequest?(callback: (request: import("@netcatty/plugin-contract").PluginAgentHostRequest) => void): () => void;
|
||||
respondPluginAIHost?(response: import("@netcatty/plugin-contract").PluginAIHostResponse): Promise<boolean>;
|
||||
onPluginAIHostRequest?(callback: (request: import("@netcatty/plugin-contract").PluginAIHostRequest) => void): () => void;
|
||||
setPluginInteractionReady?(ready: boolean): Promise<boolean>;
|
||||
|
||||
@@ -148,7 +148,7 @@ export interface PanelBridge extends NetcattyBridge {
|
||||
credentialsDecrypt?: (value: string) => Promise<string>;
|
||||
aiSyncProviders?: (providers: Array<{ id: string; providerId: string; apiKey?: string; baseURL?: string; enabled: boolean }>) => Promise<{ ok: boolean }>;
|
||||
aiSyncWebSearch?: (apiHost: string | null, apiKey: string | null) => Promise<{ ok: boolean }>;
|
||||
aiMcpUpdateSessions?: (sessions: TerminalSessionInfo[], chatSessionId?: string, delegationTag?: string) => Promise<unknown>;
|
||||
aiMcpUpdateSessions?: (sessions: TerminalSessionInfo[], chatSessionId?: string) => Promise<unknown>;
|
||||
aiMcpUpdateAttachments?: (
|
||||
attachments: Array<{ base64Data?: string; mediaType?: string; filename?: string; filePath?: string }>,
|
||||
chatSessionId?: string,
|
||||
@@ -163,8 +163,8 @@ export interface PanelBridge extends NetcattyBridge {
|
||||
codexRuntime?: 'sdk' | 'app-server',
|
||||
force?: boolean,
|
||||
) => Promise<{ ok: boolean; models?: Array<{ id: string; name: string; description?: string; thinkingLevels?: string[]; defaultThinkingLevel?: string }>; currentModelId?: string | null; warning?: string; source?: 'live' | 'last-known-good'; fetchedAt?: string; error?: string }>;
|
||||
aiCattyCancelExec?(chatSessionId: string, delegationTag?: string): Promise<unknown>;
|
||||
aiSetChatSessionCancelled?(chatSessionId: string, cancelled?: boolean, delegationTag?: string): Promise<{ ok: boolean; error?: string }>;
|
||||
aiCattyCancelExec?(chatSessionId: string): Promise<unknown>;
|
||||
aiSetChatSessionCancelled?(chatSessionId: string, cancelled?: boolean): Promise<{ ok: boolean; error?: string }>;
|
||||
aiMcpSyncPermissionGrants?(grants: Array<Record<string, unknown>>): Promise<{ ok: boolean; count?: number; error?: string }>;
|
||||
aiSdkAgentCancel?: (requestId: string, chatSessionId?: string) => Promise<{ ok: boolean; error?: string }>;
|
||||
aiSdkAgentSteer?: (
|
||||
|
||||
@@ -22,7 +22,6 @@ export interface NetcattyBridge {
|
||||
sessionId: string,
|
||||
command: string,
|
||||
chatSessionId?: string,
|
||||
delegationTag?: string,
|
||||
): Promise<{
|
||||
ok: boolean;
|
||||
stdout?: string;
|
||||
@@ -37,13 +36,12 @@ export interface NetcattyBridge {
|
||||
* window if the user clicks Stop after we've already dispatched
|
||||
* `aiExec` but before the main process has registered it.
|
||||
*/
|
||||
aiCattyCancelExec?(chatSessionId: string, delegationTag?: string): Promise<unknown>;
|
||||
aiSetChatSessionCancelled?(chatSessionId: string, cancelled?: boolean, delegationTag?: string): Promise<{ ok: boolean; error?: string }>;
|
||||
aiCattyCancelExec?(chatSessionId: string): Promise<unknown>;
|
||||
aiSetChatSessionCancelled?(chatSessionId: string, cancelled?: boolean): Promise<{ ok: boolean; error?: string }>;
|
||||
aiCapability?(
|
||||
rpcMethod: string,
|
||||
params: Record<string, unknown>,
|
||||
chatSessionId?: string,
|
||||
delegationTag?: string,
|
||||
): Promise<unknown>;
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user