diff --git a/application/i18n/locales/es/core.ts b/application/i18n/locales/es/core.ts index 7e4d7fd25..f24b414d3 100644 --- a/application/i18n/locales/es/core.ts +++ b/application/i18n/locales/es/core.ts @@ -1298,7 +1298,11 @@ Resalta el panel dividido enfocado: "plugins.interaction.closeDraft": "Close draft", "settings.plugins.permissions.current": "Coincide con la ejecución actual", "settings.plugins.permissions.inactive": "No activa para la ejecución actual", - "settings.plugins.permissions.title": "Autorizaciones guardadas", + "settings.plugins.permissions.note": "Las capacidades declaradas se permiten de forma predeterminada. Preguntar solicita una decisión con un alcance concreto; Denegar bloquea el acceso de inmediato. La selección de destinos y la edición de borradores siguen usando la interfaz de la aplicación.", + "settings.plugins.permissions.allow": "Permitir", + "settings.plugins.permissions.ask": "Preguntar", + "settings.plugins.permissions.deny": "Denegar", + "settings.plugins.permissions.title": "Permisos", "settings.plugins.permissions.refresh": "Actualizar", "settings.plugins.permissions.loading": "Cargando autorizaciones...", "settings.plugins.permissions.empty": "No hay autorizaciones guardadas. Las decisiones de un solo uso no se conservan.", @@ -1310,7 +1314,7 @@ Resalta el panel dividido enfocado: "settings.plugins.permissions.revokeNote": "Desactiva el complemento, cancela su trabajo y elimina las autorizaciones guardadas. Actívelo para solicitar acceso de nuevo.", "settings.plugins.permissions.unavailable": "La gestión de permisos no está disponible", "settings.plugins.manager.permissions": "Permisos declarados", - "settings.plugins.manager.permissionNote": "Del manifiesto, no es una autorización. Activado permite la activación diferida; los permisos obligatorios se solicitan antes del primer uso y los opcionales cuando se necesitan. Las operaciones sensibles siguen verificándose.", + "settings.plugins.manager.permissionNote": "Las capacidades declaradas y compatibles se permiten de forma predeterminada. Puede cambiar cada capacidad a Preguntar o Denegar en los controles de permisos. Siempre se verifican los destinos y el alcance de los recursos.", "settings.plugins.manager.noPermissions": "No se han declarado permisos privilegiados.", "settings.plugins.manager.required": "Obligatorio", "settings.plugins.manager.optional": "Opcional", diff --git a/components/PluginAIContextHost.test.tsx b/components/PluginAIContextHost.test.tsx index 6ce37c3c8..fddb7943c 100644 --- a/components/PluginAIContextHost.test.tsx +++ b/components/PluginAIContextHost.test.tsx @@ -47,7 +47,7 @@ test('default host adapter, real preload, mounted host chooser and installed ass let service: ReturnType | undefined; let panel: JSDOM | undefined; const root = createRoot(document.getElementById('root')!); - let locked = false; let contentAllowed = false; let reviewAllowed = false; + let locked = false; let contentAllowed = false; const lockListeners = new Set<(state: { locked: boolean }) => void>(); const reviews: Array> = []; const trustedPayloads: unknown[] = []; @@ -88,8 +88,8 @@ test('default host adapter, real preload, mounted host chooser and installed ass getInteractionWindow: () => mainWindow, isAppLocked: () => locked, subscribeAppLock: (listener: (state: { locked: boolean }) => void) => { lockListeners.add(listener); return () => lockListeners.delete(listener); }, electron: { ipcMain: { handle: (name: string, handler: (...args: unknown[]) => unknown) => ipcHandlers.set(name, handler), removeHandler: (name: string) => ipcHandlers.delete(name) }, - dialog: { showMessageBox: async (_window: unknown, options: Record) => { reviews.push(options); return { response: reviewAllowed ? 0 : 1 }; } } }, - requestPermissionDecision: async (request: { requestId: string; permission: string }) => request.permission === 'context.selected.read' && !contentAllowed + dialog: { showMessageBox: async (_window: unknown, options: Record) => { reviews.push(options); return { response: 1 }; } } }, + requestPermissionDecision: async (request: { requestId: string; permission: string; relatedPermissions?: Array<{ permission: string }> }) => (request.permission === 'context.selected.read' || request.relatedPermissions?.some((item) => item.permission === 'context.selected.read')) && !contentAllowed ? { requestId: request.requestId, decision: 'deny' } : { requestId: request.requestId, decision: 'allow', scope: request.permission === 'context.selected.read' ? 'once' : 'application' }, }); @@ -101,6 +101,7 @@ test('default host adapter, real preload, mounted host chooser and installed ass fs.copyFileSync(path.join(sample, 'src/index.js'), path.join(staging, 'dist/index.js')); const { buildPluginPackage } = await import('@netcatty/plugin-cli'); const archive = path.join(fixtureRoot, 'assistant.ncpkg'); await buildPluginPackage(staging, archive); + service.database.setPermissionMode('com.netcatty.assistant', 'context.selected.read', 'ask'); await service.manager.install(archive, { enable: true }); await act(async () => root.render()); const waitFor = async (condition: () => boolean) => { @@ -131,11 +132,8 @@ test('default host adapter, real preload, mounted host chooser and installed ass send(); await waitFor(() => element('status').textContent!.startsWith('Request ended')); assert.equal(counts.requests, 0); assert.equal(reviews.length, 0); contentAllowed = true; - send(); await waitFor(() => element('status').textContent!.startsWith('Request ended')); - assert.equal(counts.requests, 0); assert.equal(reviews.length, 1); - assert.equal(reviews[0].defaultId, reviews[0].cancelId); assert.match(String(reviews[0].detail), /Synthetic retry plan: add a retry button/); - reviewAllowed = true; send(); await waitFor(() => element('status').textContent === 'Complete'); + assert.equal(reviews.length, 0, 'content policy must not open a second native sharing review'); assert.equal(counts.completed, 1); assert.match(element('response').textContent!, /Synthetic plan/); assert.match(element('usage').textContent!, /12 input tokens/); send(); await waitFor(() => element('response').textContent!.startsWith('Synthetic plan: ')); element('stop').dispatchEvent(new panel.window.Event('click')); diff --git a/components/PluginPermissionHost.test.tsx b/components/PluginPermissionHost.test.tsx index 2c9e4dc58..0ed2a14ce 100644 --- a/components/PluginPermissionHost.test.tsx +++ b/components/PluginPermissionHost.test.tsx @@ -73,6 +73,18 @@ test('registered Ask uses one in-app dialog; policy controls apply Allow and Den await assert.rejects(route({}, {}), /disabled/); assert.equal(effects, 2); assert.equal(document.querySelector('[role="dialog"]'), null); await choose('Allow'); assert.equal(mode, 'allow'); await route({}, {}); assert.equal(effects, 3); assert.equal(document.querySelector('[role="dialog"]'), null); + let displayed!: Promise; + const opaque = 'selected:0cfc16d6-3448-4333-82ef-dd4ffbddfdab:v1'; + await act(async () => { + displayed = host.request({ requestId: 'host-display-fixture', pluginId: plugin.id, permission: 'ai.invoke', resources: ['*'], reason: 'Host model invocation', + relatedPermissions: [{ permission: 'context.selected.read', resources: [opaque] }], + displayContext: { modelLabel: 'QA fixture · deterministic-fixture', selections: [{ title: 'Synthetic retry plan', scope: 'note', version: 'bf304994-039a-4884-a707-3a1a40a5d3a9' }] }, + }); await settle(); + }); + const text = document.querySelector('[role="dialog"]')!.textContent!; + assert.match(text, /QA fixture · deterministic-fixture/); assert.match(text, /Synthetic retry plan/); + assert.doesNotMatch(text, /selected:|0cfc16d6|bf304994/); + await act(async () => { button('Deny').click(); await displayed; await settle(); }); } finally { await act(async () => root.unmount()); host.shutdown(); engine.shutdown(); dom.window.close(); for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); } diff --git a/components/PluginSelectedContextPermission.entrypoint.test.tsx b/components/PluginSelectedContextPermission.entrypoint.test.tsx new file mode 100644 index 000000000..b06abb550 --- /dev/null +++ b/components/PluginSelectedContextPermission.entrypoint.test.tsx @@ -0,0 +1,115 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { EventEmitter } from 'node:events'; +import { createRequire } from 'node:module'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { JSDOM } from 'jsdom'; +const require = createRequire(import.meta.url); + +test('registered selected-summary Ask is one host chooser; Allow still selects and Deny releases nothing', { timeout: 45_000 }, async () => { + const dom = new JSDOM('
', { pretendToBeVisual: true, url: 'http://localhost' }); + const previous = new Map(); + const install = (key: string, value: unknown) => { + previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); + }; + for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'HTMLSelectElement', 'Element', 'Node', 'NodeFilter', 'MutationObserver', 'CustomEvent', 'Event', 'KeyboardEvent', 'MouseEvent']) install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]); + install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window)); + install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window)); + install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window)); + install('IS_REACT_ACT_ENVIRONMENT', true); + const { default: React, act } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { I18nProvider } = await import('../application/i18n/I18nProvider'); + const { PluginAIContextHost } = await import('./plugins/PluginAIContextHost'); + const { PluginPermissionHost } = await import('./plugins/PluginPermissionHost'); + const { publishNotesSnapshot, getNotesSnapshot } = await import('../application/state/notesStore'); + const { registerAppAppLockRuntime, getAppAppLockRuntime } = await import('../application/state/appRuntimeBridge'); + const { createPluginHostService } = require('../electron/plugins/hostService.cjs'); + const { inProcessBrowserRuntime } = require('../electron/plugins/fixtures/inProcessBrowserRuntime.cjs'); + const { registerPluginBridge } = require('../electron/plugins/pluginBridge.cjs'); + const { createPreloadApi } = require('../electron/preload/api.cjs'); + const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'netcatty-selected-policy-')); + const oldNotes = getNotesSnapshot(); const oldLock = getAppAppLockRuntime(); + const handlers = new Map unknown>(); + const ipcMain = Object.assign(new EventEmitter(), { handle: (channel: string, handler: (...args: unknown[]) => unknown) => handlers.set(channel, handler), removeHandler: (channel: string) => handlers.delete(channel) }); + const ipcRenderer = Object.assign(new EventEmitter(), { invoke: async (channel: string, payload: unknown) => { + const handler = handlers.get(channel); assert.ok(handler, channel); return handler({ sender }, structuredClone(payload)); + } }); + const prompts: Array<{ channel: string; kind?: string; closed?: boolean }> = []; + const sender = Object.assign(new EventEmitter(), { id: 42, isDestroyed: () => false, send: (channel: string, payload: { kind?: string; closed?: boolean }) => { + prompts.push({ channel, kind: payload.kind, closed: payload.closed }); ipcRenderer.emit(channel, {}, structuredClone(payload)); + } }); + const owner = Object.assign(new EventEmitter(), { webContents: sender, isFocused: () => true, isVisible: () => true, isDestroyed: () => false }); + const service = createPluginHostService({ app: { getAppPath: () => process.cwd(), getPath: () => fixtureRoot, getVersion: () => '0.0.0' }, + electron: { ipcMain }, env: {}, getInteractionWindow: () => owner, isAppLocked: () => false }); + service.runtimeSupervisor.runtimeFactories.browser = inProcessBrowserRuntime; + registerPluginBridge(ipcMain, { ...service, isTrustedSender: (event: { sender: unknown }) => event.sender === sender }); + Object.assign(dom.window, { netcatty: createPreloadApi({ ipcRenderer, webUtils: {} }) }); + const note = { id: 'synthetic-selected-note', title: 'Synthetic selection', content: 'BODY MUST NOT BE SHARED', createdAt: 1, updatedAt: 1 }; + publishNotesSnapshot({ notes: [note], noteGroups: [] }); registerAppAppLockRuntime({ locked: false } as never); + const root = createRoot(document.getElementById('root')!); + const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); + const waitForDialog = async () => { + const deadline = Date.now() + 5_000; + while (!document.querySelector('[role="dialog"]')) { + assert.ok(Date.now() < deadline, 'registered route did not present a host interaction'); + await act(async () => { await settle(); }); + } + }; + const button = (label: string) => Array.from(document.querySelectorAll('button')).find((element) => element.textContent === label)!; + const begin = () => { + const result = service.contributionService.executeCommand('com.netcatty.assistant.contexts') as Promise>; + void result.catch(() => {}); + return result; + }; + try { + await service.manager.initialize(); + const stage = path.join(fixtureRoot, 'package'); fs.mkdirSync(path.join(stage, 'dist'), { recursive: true }); + const sample = path.resolve('examples/plugins/assistant'); + for (const file of ['netcatty.plugin.json', 'panel.html', 'panel.css', 'panel.js', 'README.md']) fs.copyFileSync(path.join(sample, file), path.join(stage, file)); + fs.copyFileSync(path.join(sample, 'src/index.js'), path.join(stage, 'dist/index.js')); + const { buildPluginPackage } = await import('@netcatty/plugin-cli'); + const archive = path.join(fixtureRoot, 'assistant.ncpkg'); await buildPluginPackage(stage, archive); await service.manager.install(archive, { enable: true }); + await act(async () => root.render()); + const plugin = service.database.getActivePlugin('com.netcatty.assistant'); + for (const mode of ['ask', 'allow']) { + service.permissionEngine.setMode(plugin, 'context.selected.list', mode); + let result!: ReturnType; + await act(async () => { result = begin(); await settle(); }); + await waitForDialog(); + assert.ok(document.getElementById('plugin-ai-note'), 'the first interaction must be the real host chooser'); + assert.equal(document.querySelectorAll('[role="dialog"]').length, 1); + assert.equal(prompts.filter((prompt) => prompt.channel === 'netcatty:plugins:permission-prompt' && !prompt.closed).length, 0, 'no capability dialog before the chooser'); + await act(async () => { + const select = document.getElementById('plugin-ai-note') as HTMLSelectElement; select.value = note.id; select.dispatchEvent(new dom.window.Event('change', { bubbles: true })); await settle(); + }); + await act(async () => { button('Share selected summaries').click(); await settle(); }); + const summaries = await result; + assert.ok(summaries.some((item) => item.title === note.title)); + assert.doesNotMatch(JSON.stringify(summaries), /BODY MUST NOT BE SHARED/); + assert.equal(document.querySelector('[role="dialog"]'), null); + } + service.permissionEngine.setMode(plugin, 'context.selected.list', 'deny'); + const count = prompts.filter((prompt) => prompt.kind === 'context.select').length; + await assert.rejects(service.contributionService.executeCommand('com.netcatty.assistant.contexts'), /disabled/); + assert.equal(prompts.filter((prompt) => prompt.kind === 'context.select').length, count); assert.equal(document.querySelector('[role="dialog"]'), null); + service.permissionEngine.setMode(plugin, 'context.selected.list', 'ask'); + let cancelled!: ReturnType; + await act(async () => { cancelled = begin(); await settle(); }); + await waitForDialog(); + await act(async () => { button('Cancel').click(); await settle(); }); + await assert.rejects(cancelled); assert.equal(service.aiContextService.selected.handles.size, 0); + let revoked!: ReturnType; + await act(async () => { revoked = begin(); await settle(); }); + await waitForDialog(); + await act(async () => { service.permissionEngine.setMode(plugin, 'context.selected.list', 'deny'); await settle(); }); + await assert.rejects(revoked); assert.equal(document.querySelector('[role="dialog"]'), null); assert.equal(service.aiContextService.selected.handles.size, 0); + } finally { + await act(async () => root.unmount()); await service.manager.shutdown(); + publishNotesSnapshot(oldNotes); registerAppAppLockRuntime(oldLock); dom.window.close(); fs.rmSync(fixtureRoot, { recursive: true, force: true }); + for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); } + } +}); diff --git a/components/plugins/PluginAIContextHost.tsx b/components/plugins/PluginAIContextHost.tsx index 8fe5d30ac..701bd1ae3 100644 --- a/components/plugins/PluginAIContextHost.tsx +++ b/components/plugins/PluginAIContextHost.tsx @@ -9,7 +9,7 @@ export function PluginAIContextHost({ sessions, workspaces }: { sessions: Termin return { if (!open) choice?.cancel(); }}> Choose a reference for the plugin - Share a Note summary and the current selected workspace, tab, session, and host summaries. Reading content requires a separate permission and text review. + Share a Note summary and the current selected workspace, tab, session, and host summaries. Content access follows this plugin's Allow / Ask / Deny settings; this chooser shares summaries only.