diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index 1783c95aa..6c74959fa 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -1246,6 +1246,9 @@ Highlight the focused split pane: "settings.plugins.manager.remove": "Uninstall", "settings.plugins.manager.removeNote": "Uninstall removes package code and local KV data. User-owned settings, secrets and sync sidecars are retained.", "settings.plugins.permissions.statusUnknown": "Status unknown", + "plugins.sidebar.extensions": "Extension pages", + "plugins.sidebar.selectTerminal": "Select an open terminal first.", + "plugins.sidebar.loading": "Loading extension page…", "plugins.vault.loading": "Loading plugin page…", "plugins.vault.extensions": "Extensions", "plugins.vault.back": "Back to hosts", diff --git a/application/i18n/locales/es/core.ts b/application/i18n/locales/es/core.ts index 128a57db1..b754a9b71 100644 --- a/application/i18n/locales/es/core.ts +++ b/application/i18n/locales/es/core.ts @@ -1246,6 +1246,9 @@ Resalta el panel dividido enfocado: "settings.plugins.manager.remove": "Desinstalar", "settings.plugins.manager.removeNote": "La desinstalación elimina el código y los datos KV locales. Se conservan los ajustes del usuario, los secretos y los datos auxiliares de sincronización.", "settings.plugins.permissions.statusUnknown": "Estado desconocido", + "plugins.sidebar.extensions": "Páginas de extensiones", + "plugins.sidebar.selectTerminal": "Selecciona primero un terminal abierto.", + "plugins.sidebar.loading": "Cargando página de extensión…", "plugins.vault.loading": "Cargando página del plugin…", "plugins.vault.extensions": "Extensiones", "plugins.vault.back": "Volver a hosts", diff --git a/application/i18n/locales/ru/core.ts b/application/i18n/locales/ru/core.ts index 63c0e0808..45ea9edaf 100644 --- a/application/i18n/locales/ru/core.ts +++ b/application/i18n/locales/ru/core.ts @@ -1141,6 +1141,9 @@ export const ruCoreMessages: Messages = { "settings.plugins.manager.remove": "Удалить", "settings.plugins.manager.removeNote": "Удаление очищает код пакета и локальные данные KV. Настройки пользователя, секреты и данные синхронизации сохраняются.", "settings.plugins.permissions.statusUnknown": "Состояние неизвестно", + "plugins.sidebar.extensions": "Страницы расширений", + "plugins.sidebar.selectTerminal": "Сначала выберите открытый терминал.", + "plugins.sidebar.loading": "Загрузка страницы расширения…", "plugins.vault.loading": "Загрузка страницы плагина…", "plugins.vault.extensions": "Расширения", "plugins.vault.back": "К хостам", diff --git a/application/i18n/locales/zh-CN/core.ts b/application/i18n/locales/zh-CN/core.ts index 8b02f115b..cab3a63e7 100644 --- a/application/i18n/locales/zh-CN/core.ts +++ b/application/i18n/locales/zh-CN/core.ts @@ -1161,6 +1161,9 @@ Vaults 标签保持扁平,不使用这块背景。 "settings.plugins.manager.remove": "卸载", "settings.plugins.manager.removeNote": "卸载会移除插件代码和本地 KV 数据,保留用户设置、秘密存储和同步 sidecar。", "settings.plugins.permissions.statusUnknown": "状态未知", + "plugins.sidebar.extensions": "扩展页面", + "plugins.sidebar.selectTerminal": "请先选择已打开的终端。", + "plugins.sidebar.loading": "正在加载扩展页面…", "plugins.vault.loading": "正在加载插件页面…", "plugins.vault.extensions": "扩展", "plugins.vault.back": "返回主机", diff --git a/application/i18n/locales/zh-TW/core.ts b/application/i18n/locales/zh-TW/core.ts index cb6eacf76..c98eba239 100644 --- a/application/i18n/locales/zh-TW/core.ts +++ b/application/i18n/locales/zh-TW/core.ts @@ -1164,6 +1164,9 @@ Vaults 分頁維持扁平,不使用這塊背景。 "settings.plugins.manager.remove": "卸載", "settings.plugins.manager.removeNote": "卸載會移除插件代碼和本地 KV 數據,保留用戶設置、秘密存儲和同步 sidecar。", "settings.plugins.permissions.statusUnknown": "狀態不明", + "plugins.sidebar.extensions": "擴充功能頁面", + "plugins.sidebar.selectTerminal": "請先選擇已開啟的終端。", + "plugins.sidebar.loading": "正在載入擴充功能頁面…", "plugins.vault.loading": "正在載入擴充功能頁面…", "plugins.vault.extensions": "擴充功能", "plugins.vault.back": "返回主機", diff --git a/application/state/pluginViewOcclusion.ts b/application/state/pluginViewOcclusion.ts index a43a0c56e..cb26013df 100644 --- a/application/state/pluginViewOcclusion.ts +++ b/application/state/pluginViewOcclusion.ts @@ -1,7 +1,7 @@ /** Native child views must yield to host dialogs and overlapping portals. */ export function isPluginViewOccluded(mount: HTMLElement): boolean { const rect = mount.getBoundingClientRect(); - if (!mount.isConnected || mount.closest('[hidden], [inert]')) return true; + if (!mount.isConnected || mount.closest('[hidden], [inert], [aria-hidden="true"]')) return true; const overlays = mount.ownerDocument.querySelectorAll( '[data-app-lock-overlay], [role="dialog"], [role="alertdialog"], ' + '[role="menu"][data-state="open"], [data-radix-popper-content-wrapper] > *, [data-native-view-occluder]', diff --git a/application/state/terminalSidePanelTabs.ts b/application/state/terminalSidePanelTabs.ts index 849ba72fb..dcfed3362 100644 --- a/application/state/terminalSidePanelTabs.ts +++ b/application/state/terminalSidePanelTabs.ts @@ -13,11 +13,11 @@ import { } from '../../infrastructure/config/storageKeys'; import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter'; import { useToolbarItemLayout } from './useToolbarItemLayout'; -import type { SidePanelTool } from '../../domain/sidePanelLayout'; +import type { BuiltinSidePanelTool, SidePanelTool } from '../../domain/sidePanelLayout'; export type TerminalSidePanelTabId = SidePanelTool; -export const TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER: TerminalSidePanelTabId[] = [ +export const TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER: BuiltinSidePanelTool[] = [ 'sftp', 'browser', 'scripts', diff --git a/application/state/useEmbeddedPluginView.ts b/application/state/useEmbeddedPluginView.ts index 8cb032a16..a2727ece7 100644 --- a/application/state/useEmbeddedPluginView.ts +++ b/application/state/useEmbeddedPluginView.ts @@ -4,10 +4,10 @@ import { resolvePluginViewWindowScope } from './pluginViewScopes'; import { isPluginViewOccluded } from './pluginViewOcclusion'; import type { UsePluginContributionsResult } from './usePluginContributions'; -type ViewAdapter = Pick; +type ViewAdapter = Pick; /** Host-owned mounting only. No plugin router, DOM, session or vault data API. */ -export function useEmbeddedPluginView({ viewId, version, slot, active, context, adapter, subscribeHidden, unavailable }: { +export function useEmbeddedPluginView({ viewId, version, slot, active, context, adapter, subscribeHidden, unavailable, focused, focusOnReveal = false }: { viewId: string; version: string; slot: string; @@ -16,11 +16,18 @@ export function useEmbeddedPluginView({ viewId, version, slot, active, context, adapter: ViewAdapter; subscribeHidden(listener: () => void): () => void; unavailable(): void; + focused?(): void; + focusOnReveal?: boolean; }) { const mountRef = useRef(null); const [loading, setLoading] = useState(true); const adapterRef = useRef(adapter); const unavailableRef = useRef(unavailable); + const focusedRef = useRef(focused); + const revealFocusRef = useRef(focusOnReveal); + const requestFocusRef = useRef<() => void>(() => {}); + revealFocusRef.current = focusOnReveal; + focusedRef.current = focused; adapterRef.current = adapter; unavailableRef.current = unavailable; useEffect(() => { @@ -31,7 +38,7 @@ export function useEmbeddedPluginView({ viewId, version, slot, active, context, const instanceId = crypto.randomUUID(); const scopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` }); - const { openView, closeView, setViewBounds, setViewVisibility, onViewClosed } = adapterRef.current; + const { openView, closeView, focusView, setViewBounds, setViewVisibility, onViewClosed, onViewFocused } = adapterRef.current; const close = () => { if (cancelled) return; cancelled = true; @@ -51,29 +58,41 @@ export function useEmbeddedPluginView({ viewId, version, slot, active, context, } }); const stopOnHide = subscribeHidden(close); + const stopOnFocus = onViewFocused((event) => { + if (!cancelled && event.instanceId === instanceId) focusedRef.current?.(); + }); const bounds = () => { const rect = mount.getBoundingClientRect(); return { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.max(1, Math.round(rect.width)), height: Math.max(1, Math.round(rect.height)) }; }; let opened = false; + let lastBounds = ''; let visible = false; + const focus = () => { + if (!cancelled && opened && visible && revealFocusRef.current && !isPluginViewOccluded(mount)) void focusView(instanceId).catch(() => {}); + }; + requestFocusRef.current = focus; const updateVisibility = () => { if (!opened || cancelled) return; const rect = mount.getBoundingClientRect(); const next = rect.width > 0 && rect.height > 0 && !isPluginViewOccluded(mount); if (visible === next) return; visible = next; - void setViewVisibility(instanceId, next).catch(failCurrent); + void setViewVisibility(instanceId, next).then(() => { if (next) focus(); }).catch(failCurrent); }; const resize = () => { - if (opened && !cancelled) void setViewBounds(instanceId, bounds()).catch(failCurrent); + if (opened && !cancelled) { + const next = bounds(); + const key = JSON.stringify(next); + if (key !== lastBounds) { lastBounds = key; void setViewBounds(instanceId, next).catch(failCurrent); } + } updateVisibility(); }; const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(resize); observer?.observe(mount); - const mutations = new MutationObserver(updateVisibility); + const mutations = new MutationObserver(resize); mutations.observe(document.body, { childList: true, subtree: true, attributes: true, - attributeFilter: ['class', 'style', 'hidden', 'inert', 'role', 'aria-modal', 'data-state', 'data-app-lock-overlay', 'data-native-view-occluder'] }); + attributeFilter: ['class', 'style', 'hidden', 'inert', 'role', 'aria-modal', 'aria-hidden', 'data-state', 'data-app-lock-overlay', 'data-radix-popper-content-wrapper', 'data-native-view-occluder'] }); window.addEventListener('resize', resize); document.addEventListener('scroll', resize, true); setLoading(true); @@ -91,9 +110,10 @@ export function useEmbeddedPluginView({ viewId, version, slot, active, context, if (!cancelled) { close(); unavailableRef.current(); } }).finally(() => lifecycle.finishOpen({ token: opening, viewKey: viewId })); return () => { - close(); unsubscribe(); stopOnHide(); observer?.disconnect(); mutations.disconnect(); + close(); unsubscribe(); stopOnHide(); stopOnFocus(); observer?.disconnect(); mutations.disconnect(); window.removeEventListener('resize', resize); document.removeEventListener('scroll', resize, true); }; }, [active, context, slot, subscribeHidden, version, viewId]); + useEffect(() => { if (focusOnReveal) requestFocusRef.current(); }, [focusOnReveal]); return { mountRef, loading }; } diff --git a/application/state/usePluginContributions.ts b/application/state/usePluginContributions.ts index 24220d485..2d2230747 100644 --- a/application/state/usePluginContributions.ts +++ b/application/state/usePluginContributions.ts @@ -88,10 +88,12 @@ export interface UsePluginContributionsResult { selectSettingPath(kind: 'file' | 'directory', title: string, defaultPath?: string): Promise; openView(payload: NetcattyPluginViewOpenRequest): Promise<{ instanceId: string }>; closeView(instanceId: string): Promise; + focusView(instanceId: string): Promise; setViewBounds(instanceId: string, bounds: { x: number; y: number; width: number; height: number }): Promise; setViewVisibility(instanceId: string, visible: boolean): Promise; setEnvironment(environment: NetcattyPluginEnvironment): Promise; onViewClosed(callback: (event: NetcattyPluginViewClosedEvent) => void): () => void; + onViewFocused(callback: (event: import('@netcatty/plugin-contract').PluginViewFocusEvent) => void): () => void; } export function usePluginContributions( @@ -196,6 +198,9 @@ export function usePluginContributions( if (!bridge?.closePluginView) return; await bridge.closePluginView(instanceId); }, [bridge]); + const focusView = useCallback(async (instanceId: string) => { + await bridge?.focusPluginView?.({ instanceId }); + }, [bridge]); const setViewBounds = useCallback(async ( instanceId: string, @@ -218,6 +223,9 @@ export function usePluginContributions( const onViewClosed = useCallback((callback: (event: NetcattyPluginViewClosedEvent) => void) => ( bridge?.onPluginViewClosed?.(callback) ?? (() => {}) ), [bridge]); + const onViewFocused = useCallback((callback: (event: import('@netcatty/plugin-contract').PluginViewFocusEvent) => void) => ( + bridge?.onPluginViewFocused?.(callback) ?? (() => {}) + ), [bridge]); const currentLoadState = resolvePluginContributionLoadState({ currentQueryKey: queryKey, @@ -239,9 +247,11 @@ export function usePluginContributions( selectSettingPath, openView, closeView, + focusView, setViewBounds, setViewVisibility, setEnvironment, onViewClosed, + onViewFocused, }; } diff --git a/application/state/usePluginTerminalSidebar.ts b/application/state/usePluginTerminalSidebar.ts new file mode 100644 index 000000000..4d58d3c2a --- /dev/null +++ b/application/state/usePluginTerminalSidebar.ts @@ -0,0 +1,73 @@ +import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react'; +import { useI18n } from '../i18n/I18nProvider'; +import { toast } from '../../components/ui/toast'; +import { collectSidePanelPanes, isPluginSidePanelTool, type SidePanelLayout } from '../../domain/sidePanelLayout'; +import { activeTabStore, useActiveTabId } from './activeTabStore'; +import { getSidePanelLiveSnapshot, subscribeSidePanelLiveSnapshot } from './sidePanelLiveStore'; +import { usePluginContributions } from './usePluginContributions'; +import { OPEN_PLUGIN_VIEW_EVENT, type OpenPluginViewDetail } from './usePluginViewLifecycle'; + +export const OPEN_PLUGIN_TERMINAL_SIDEBAR_EVENT = 'netcatty:open-plugin-terminal-sidebar'; +export const PLUGIN_TERMINAL_SIDEBAR_CONTEXT = Object.freeze({ 'netcatty.surface': 'terminal-sidebar' }); +export interface PluginTerminalSidebarPage { + tool: `plugin-view:${string}`; + viewId: string; + pluginId: string; + pluginName: string; + version: string; + title: string; + icon?: NetcattyPluginIconReference; + order: number; +} +export function collectPluginTerminalSidebarPages(plugins: NetcattyPluginContributionSnapshot['plugins']): PluginTerminalSidebarPage[] { + return plugins.flatMap((plugin) => plugin.views.filter((view) => view.location === 'terminal-sidebar' && view.visible) + .map((view): PluginTerminalSidebarPage => ({ tool: `plugin-view:${view.id}`, viewId: view.id, pluginId: plugin.id, + pluginName: plugin.displayName, version: plugin.version, title: view.title, icon: view.icon, order: view.order ?? 0 }))) + .sort((a, b) => a.order - b.order || a.viewId.localeCompare(b.viewId)); +} +export function requestOpenPluginTerminalSidebar(viewId: string, sessionId: string) { + window.dispatchEvent(new CustomEvent(OPEN_PLUGIN_TERMINAL_SIDEBAR_EVENT, { detail: { viewId, sessionId } })); +} +export function usePluginTerminalSidebar(host: { + layouts: ReadonlyMap; + getSession(): string | null; + isTerminalTab(tabId: string): boolean; + select(tool: `plugin-view:${string}`): void; + withdraw(tabId: string, paneId: string, tool: `plugin-view:${string}`): void; +}) { + const { locale, t } = useI18n(); + const activeTabId = useActiveTabId(); + // Follow workspace focus without subscribing the whole sidebar to cwd/title + // or forwarding the host's live session DTO to a plugin. + useSyncExternalStore((listener) => subscribeSidePanelLiveSnapshot(true, listener), + () => getSidePanelLiveSnapshot(true).focusedSessionId, () => null); + const hostRef = useRef(host); hostRef.current = host; + const contributions = usePluginContributions({ locale, context: PLUGIN_TERMINAL_SIDEBAR_CONTEXT }); + const pages = useMemo(() => collectPluginTerminalSidebarPages(contributions.snapshot.plugins), [contributions.snapshot.plugins]); + const sessionId = activeTabId && host.isTerminalTab(activeTabId) ? host.getSession() : null; + useEffect(() => { + const open = (event: Event) => { + const detail = (event as CustomEvent).detail; + const page = pages.find((item) => item.viewId === detail?.viewId); + if (!page) return; + const tabId = activeTabStore.getActiveTabId(); + const current = hostRef.current.getSession(); + if (!hostRef.current.isTerminalTab(tabId) || !current || (detail.sessionId && detail.sessionId !== current)) { + toast.info(t('plugins.sidebar.selectTerminal')); + return; + } + hostRef.current.select(page.tool); + }; + window.addEventListener(OPEN_PLUGIN_TERMINAL_SIDEBAR_EVENT, open); + window.addEventListener(OPEN_PLUGIN_VIEW_EVENT, open); + return () => { window.removeEventListener(OPEN_PLUGIN_TERMINAL_SIDEBAR_EVENT, open); window.removeEventListener(OPEN_PLUGIN_VIEW_EVENT, open); }; + }, [pages, t]); + useEffect(() => { + if (contributions.loading) return; + const allowed = new Set(pages.map((page) => page.tool)); + for (const [tabId, layout] of host.layouts) for (const pane of collectSidePanelPanes(layout.root)) { + if (isPluginSidePanelTool(pane.tool) && !allowed.has(pane.tool)) host.withdraw(tabId, pane.id, pane.tool); + } + }, [contributions.loading, host, pages]); + return { pages, contributions, tabId: activeTabId, sessionId }; +} diff --git a/application/state/usePluginViewLifecycle.ts b/application/state/usePluginViewLifecycle.ts index dded6b565..66f96c072 100644 --- a/application/state/usePluginViewLifecycle.ts +++ b/application/state/usePluginViewLifecycle.ts @@ -82,7 +82,7 @@ export function usePluginViewLifecycle({ const mountRef = useRef(null); const resolvedActiveView = useMemo(() => viewContributions.snapshot.plugins .flatMap((plugin) => plugin.views.map((view) => ({ plugin, view }))) - .find(({ view }) => view.id === effectiveRequested?.viewId && view.visible && view.location !== 'vault-page') ?? null, + .find(({ view }) => view.id === effectiveRequested?.viewId && view.visible && !['vault-page', 'terminal-sidebar'].includes(view.location)) ?? null, [effectiveRequested?.viewId, viewContributions.snapshot.plugins]); const stableActiveViewRef = useRef | null>(null); const activeView = resolvePluginViewSnapshotSelection({ diff --git a/components/PluginTerminalSidebar.test.tsx b/components/PluginTerminalSidebar.test.tsx new file mode 100644 index 000000000..361da711e --- /dev/null +++ b/components/PluginTerminalSidebar.test.tsx @@ -0,0 +1,122 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { JSDOM } from 'jsdom'; + +test('terminal extension pages use actual split panes, focus and session ownership without sharing session data', 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', 'Element', 'SVGElement', 'Node', 'NodeFilter', 'MutationObserver', 'CustomEvent', 'Event', 'KeyboardEvent', 'MouseEvent']) { + install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]); + } + install('PointerEvent', dom.window.MouseEvent); + install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window)); + install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window)); install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window)); install('IS_REACT_ACT_ENVIRONMENT', true); + let rectX = 200; + dom.window.HTMLElement.prototype.getBoundingClientRect = () => new dom.window.DOMRect(rectX, 100, 400, 300); + const { default: React, act, useCallback, useRef, useState } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { I18nProvider } = await import('../application/i18n/I18nProvider'); + const { activeTabStore } = await import('../application/state/activeTabStore'); + const { sidePanelLiveStore, SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT } = await import('../application/state/sidePanelLiveStore'); + const { useTerminalSidePanelLayoutState } = await import('../application/state/useTerminalSidePanelLayoutState'); + const { usePluginTerminalSidebar } = await import('../application/state/usePluginTerminalSidebar'); + const { PluginTerminalSidebarLauncher, PluginTerminalSidebarPageHost } = await import('./plugins/PluginTerminalSidebar'); + const { SidePanelLayoutTree } = await import('./terminalLayer/TerminalLayerSidePanelSection'); + const { PersistentSidePanelPortal } = await import('./terminalLayer/terminalLayerSidePanelSlots'); + const { collectSidePanelPanes } = await import('../domain/sidePanelLayout'); + type Tool = import('../domain/sidePanelLayout').SidePanelTool; + let selectedSession = 'synthetic-session-a'; + const getSession = () => selectedSession; + const a = { id: 'com.example.sidebar.first', title: 'First page', location: 'terminal-sidebar', entry: 'page.html', visible: true }; + const b = { ...a, id: 'com.example.sidebar.second', title: 'Second page' }; + let snapshot = { locale: 'en', plugins: [{ id: 'com.example.sidebar', displayName: 'Synthetic plugin', version: '1.0.0', commands: [], keybindings: [], menus: [], settings: [], views: [a, b] }] }; + const changed = new Set<() => void>(), focusListeners = new Set<(event: { instanceId: string }) => void>(); + const opens: NetcattyPluginViewOpenRequest[] = [], closes: string[] = [], focus: string[] = [], bounds: Array<{ instanceId: string; x: number }> = []; + const visible = new Map(); + Object.assign(dom.window, { netcatty: { + async getPluginRuntimeStatus() { return { available: true }; }, async getPluginContributions() { return snapshot; }, + onPluginContributionsChanged(fn: () => void) { changed.add(fn); return () => { changed.delete(fn); }; }, + onPluginViewClosed() { return () => {}; }, + onPluginViewFocused(fn: (event: { instanceId: string }) => void) { focusListeners.add(fn); return () => { focusListeners.delete(fn); }; }, + async openPluginView(payload: NetcattyPluginViewOpenRequest) { opens.push(payload); return { instanceId: payload.instanceId! }; }, + async closePluginView(id: string) { closes.push(id); }, + async setPluginViewBounds(id: string, rect: { x: number }) { bounds.push({ instanceId: id, x: rect.x }); }, + async setPluginViewVisibility(id: string, value: boolean) { visible.set(id, value); }, + async focusPluginView(event: { instanceId: string }) { focus.push(event.instanceId); for (const fn of focusListeners) fn(event); }, + } }); + let split!: () => void; + function Fixture() { + const state = useTerminalSidePanelLayoutState(); const latest = useRef(state); latest.current = state; + const model = usePluginTerminalSidebar({ layouts: state.sidePanelLayouts, getSession, isTerminalTab: (id) => id === 'workspace-synthetic', + select: (tool) => state.selectSidePanelToolForTab('workspace-synthetic', tool), + withdraw: (tabId, paneId, tool) => { + const layout = state.sidePanelLayoutsRef.current.get(tabId); + if (layout && collectSidePanelPanes(layout.root).some((pane) => pane.id === paneId && pane.tool === tool)) state.closePane(tabId, paneId); + } }); + const [hosts, setHosts] = useState(new Map()); const parking = useRef(null); + const register = useCallback((tool: Tool, host: HTMLElement | null) => setHosts((prior) => { + if ((prior.get(tool) ?? null) === host) return prior; + const next = new Map(prior); if (host) next.set(tool, host); else next.delete(tool); return next; + }), []); + const focusPane = useCallback((id: string) => latest.current.focusPane('workspace-synthetic', id), []); + const closePane = useCallback((id: string) => { latest.current.closePane('workspace-synthetic', id); }, []); + const resize = useCallback(() => {}, []); + const layout = model.tabId ? state.sidePanelLayouts.get(model.tabId) : null; + const panes = layout ? collectSidePanelPanes(layout.root) : []; + split = () => state.splitPane('workspace-synthetic', `plugin-view:${b.id}`, 'vertical', { paneId: 'second-pane', splitId: 'plugin-split' }, 600); + return <> + {layout && [page.tool, page.title]))} + onClose={closePane} onFocus={focusPane} onHostChange={register} onResize={resize} separator="#777" accent="#4488cc" closePaneLabel="Close pane" resizeLabel="Resize" />} + diff --git a/components/terminalLayer/terminalLayerSidePanelSlots.tsx b/components/terminalLayer/terminalLayerSidePanelSlots.tsx index ed4590669..255e07819 100644 --- a/components/terminalLayer/terminalLayerSidePanelSlots.tsx +++ b/components/terminalLayer/terminalLayerSidePanelSlots.tsx @@ -693,7 +693,7 @@ export function movePersistentPortalNode( } } -function PersistentSidePanelPortal({ +export function PersistentSidePanelPortal({ portalKey, target, children, diff --git a/components/terminalLayer/terminalLayerViewMemo.ts b/components/terminalLayer/terminalLayerViewMemo.ts index 3b31d0d69..1cdcb6b10 100644 --- a/components/terminalLayer/terminalLayerViewMemo.ts +++ b/components/terminalLayer/terminalLayerViewMemo.ts @@ -316,6 +316,9 @@ const SIDE_PANEL_STABLE_CTX_KEYS = [ 'handleOpenTheme', 'handleOpenAI', 'handleOpenNotes', + 'getActiveTerminalSessionId', + 'handleSwitchSidePanelTab', + 'handleWithdrawPluginSidebarPane', 'handleOpenBrowser', 'handleBackFromNotes', 'handleOpenHostFromNotes', diff --git a/docs/plugin-platform/capability-coverage.md b/docs/plugin-platform/capability-coverage.md index abb57a510..e25d88a16 100644 --- a/docs/plugin-platform/capability-coverage.md +++ b/docs/plugin-platform/capability-coverage.md @@ -32,7 +32,7 @@ mean complete. Existing APIs remain available. | AI, MCP, automation | Host agent catalog and harness exist separately | No generic plugin AI or tool forwarding | Selection-to-proposal workflow through the same controlled primitives | Content disclosure, account authority and model cost | Explicit content sharing plus service origin/budget | No inherited history, tools, account, or hidden cron | Controlled workflow planned. Generic host AI and visible schedules deferred to distinct product decision | | Known hosts, app lock and global security | Host security management UI | No plugin management API | Future allowlisted security-page navigation | Host-key trust, unlock, keys and security policy affect all sessions | Host navigation action only | No mutation or sensitive DTO | Security policy mutation, private-key reads, auto-trust and unlocking deferred indefinitely | | Plugin blob/cache | Local KV exists | No exclusive blob cache | Evaluate bounded plugin-owned cache when a real workflow needs it | Disk growth and lifecycle ambiguity | Plugin namespace, no arbitrary path | Size quota, eviction and uninstall policy required | Deferred until a concrete larger-than-KV workflow establishes value and retention policy | -| Vault and terminal navigation | `tab` mounts a sandbox page through TopTabs/QuickSwitcher; aside/panel are overlays | No Vault subpage registry or terminal side-panel plugin tool. `settings` is a detail entry, not a new settings category | Accepted independent slice: host-owned namespaced Vault pages in an Extensions group, mounted in the Vault content area through existing ViewHost; then terminal pane/split pages for the selected session | Navigation cannot disclose session contents or replace built-in/security navigation | Declared page contribution plus host selection. Content reads have independent permissions | Host order/when/focus, cancellation of late open, view cleanup on hide/update/disable/uninstall, safe invalid-link fallback | [Vault page slice](./vault-pages.md) implemented and synthetic-tested: actual Vault content slot, private Scratchpad, catalog withdrawal, host occlusion, reserved-open cancellation, owner/crash/lock cleanup. Exact CI/independent/native acceptance pending. Terminal pane/split pages remain the next separate stage. No arbitrary router/DOM API | +| Vault and terminal navigation | `tab` mounts a sandbox page through TopTabs/QuickSwitcher; aside/panel are overlays | No Vault subpage registry or terminal side-panel plugin tool. `settings` is a detail entry, not a new settings category | Accepted independent slice: host-owned namespaced Vault pages in an Extensions group, mounted in the Vault content area through existing ViewHost; then terminal pane/split pages for the selected session | Navigation cannot disclose session contents or replace built-in/security navigation | Declared page contribution plus host selection. Content reads have independent permissions | Host order/when/focus, cancellation of late open, view cleanup on hide/update/disable/uninstall, safe invalid-link fallback | [Vault page slice](./vault-pages.md) implemented and synthetic-tested: actual Vault content slot, private Scratchpad, catalog withdrawal, host occlusion, reserved-open cancellation, owner/crash/lock cleanup. Exact CI/independent/native acceptance pending. [Terminal sidebar slice](./terminal-sidebar.md) also implemented with actual pane/split mounting, owner focus and session-change cleanup; no automatic session data. Exact CI/independent/native acceptance pending for the new stack. No arbitrary router/DOM API | | Distribution and runtimes | Browser-only public catalog, immutable packages, advanced developer gate | Signing/trust and release remain separate phase | Retain existing boundary | Package execution and publisher trust | Pinned catalog selection, hash, engine/features | Existing install transaction, quarantine and cleanup | No merge/release. Do not extend to arbitrary Node, IPC, shell, or global capabilities | ## Delivery order and stopping rule @@ -98,3 +98,16 @@ components/hooks, and localized strings. PluginMarketplace/PluginPackageManager layouts are not rewritten. Native acceptance belongs to the parent with a new fixture-specific own-views approval. Sidebar, ThemePack, selected context and SFTP remain unfinished; this checkpoint is not overall completion. + +## Terminal sidebar checkpoint + +`views.terminal-sidebar` exposes one more existing sandbox view placement, +using only the existing own-views permission. The host owns navigation, +selection, split/close and focus. Its context is a surface string only; no +terminal DTO or resource authority is implied. The Session Scratchpad fixture +uses explicitly typed synthetic text and its own view state. + +This stage builds on ordinary merges containing #3960 8e4dd0c and the #3971 +stale-layout callback fix. Prior QA heads and PR bases are not rewritten. The +ThemePack implementation, selected-context/drafts and file handles remain +unfinished; parent review/native gates still apply to each delivered head. diff --git a/docs/plugin-platform/terminal-sidebar.md b/docs/plugin-platform/terminal-sidebar.md new file mode 100644 index 000000000..8abe7560b --- /dev/null +++ b/docs/plugin-platform/terminal-sidebar.md @@ -0,0 +1,74 @@ +# Terminal sidebar pages + +The `terminal-sidebar` view location requires `views.terminal-sidebar` and the +existing `views` permission. This adds navigation and plugin-owned content to +the existing terminal pane/split system. It is not a session-data capability, +Provider subscription, terminal history reader or command execution API. + +## Host-owned navigation + +An Extension pages menu in the normal terminal toolbar lists visible pages +with their plugin source. Selecting one switches the existing focused pane; +selecting an already-open tool focuses that pane. Existing split menus include +the same contributions and enforce unique tools and the eight-pane limit. +Host-generated `plugin-view:` keys cannot replace built-in +tools. Declared order and ID determine listing order; existing host docking, +split resizing, magnification and close controls remain authoritative. + +The manager's internal Open event can select a page only when an open terminal +is already selected. Otherwise the host asks the user to select a terminal; it +does not connect or open a saved host. Launcher events target the session from +the actual host terminal toolbar and are rechecked against current selection. +These are internal host UI events, not public SDK router methods or trusted +plugin `userGesture` flags. + +## Session ownership without data sharing + +The renderer binds each page to the actual terminal tab/workspace and current +focused child session. It passes only `netcatty.surface: terminal-sidebar` as +the view context. Internal ownership IDs are used for host state scoping, not +returned to the page or treated as resource grants. A future selected-session +data API must establish its own live endpoint authority and permissions. + +Changing terminal tabs or workspace focus closes the old native view before +the new one can receive focus. Session removal, pane close, withdrawal of a +visible contribution, disable/update/uninstall and runtime loss remove the +affected page. Unknown saved routes are pruned without opening them; restoring +a layout never grants the page or any session-data permission. State buckets +are for the plugin's own UI data, not an isolation boundary against that same +plugin's already-authorized own-state API. Ordinary KV does not become synced. + +PersistentSidePanelPortal moves a stable mount between the actual pane, +magnification host and hidden parking host. There is no fallback native view +over the entire terminal layer. Native geometry follows host DOM relocation, +resize and scrolling; duplicate geometry updates are suppressed. Hidden/inert +or parked mounts cannot reveal a native view. + +## Focus and security surfaces + +The existing sandbox ViewHost, immutable package/protocol checks, own-command +and view-state boundaries are reused. Embedded pages start hidden. Host +dialogs and overlapping portals hide them, and main-process App Lock closes +them. Escape is host-owned and closes the plugin pane. + +Native WebContents focus is reported only to its actual owner's trusted +renderer using a canonical instance-ID event. It updates the selected pane; +it does not expose an Electron object to the plugin. Revealing multiple panes +does not focus all of them: only the host-selected pane can request focus. +The main process verifies actual owner, visibility, foreground and unlocked +state before honoring that request. A plugin has no SDK method to invoke the +host focus bridge. No session or page text is added to focus/audit logs. + +## Example and evidence + +`com.netcatty.session-scratchpad` 0.1.0 asks only for its own `views`. It saves, +reopens and clears explicitly typed synthetic text. Package instructions and +minimal native actions are in its README. Repository tests use real split +tree, layout state, persistent portal, launcher and embedded-view components; +host tests cover owner-bound focus, hidden/locked refusal and withdrawal. +Feature and permission admission, limits, old APIs and previous Vault/command +fixes are checked on the same stack. Independent review, exact-SHA CI and +parent native QA remain separate acceptance gates recorded on the Draft PR. + +ThemePack, selected context/terminal drafts and SFTP handles remain subsequent +bounded stages. Adding a sidebar page does not count as implementing them. diff --git a/domain/sidePanelLayout.ts b/domain/sidePanelLayout.ts index 456fa991d..7715e4ae3 100644 --- a/domain/sidePanelLayout.ts +++ b/domain/sidePanelLayout.ts @@ -1,4 +1,4 @@ -export type SidePanelTool = +export type BuiltinSidePanelTool = | 'sftp' | 'browser' | 'scripts' @@ -8,6 +8,12 @@ export type SidePanelTool = | 'system' | 'notes'; +export type SidePanelTool = BuiltinSidePanelTool | `plugin-view:${string}`; + +export function isPluginSidePanelTool(value: unknown): value is `plugin-view:${string}` { + return typeof value === 'string' && value.length <= 256 && /^plugin-view:[A-Za-z0-9_.-]+$/.test(value); +} + export type SidePanelSplitDirection = 'horizontal' | 'vertical'; export type SidePanelPaneNode = { diff --git a/domain/workspaceLayoutPreset.test.ts b/domain/workspaceLayoutPreset.test.ts index 9fb1b7768..a9f90fd7b 100644 --- a/domain/workspaceLayoutPreset.test.ts +++ b/domain/workspaceLayoutPreset.test.ts @@ -90,6 +90,21 @@ test('sanitize accepts a valid saved preset and rejects malformed data', () => { ); }); +test('plugin panes keep split uniqueness and limits; saved routes grant no availability and can be pruned', () => { + const tool = 'plugin-view:com.example.plugin.page' as const; + let layout = createSidePanelLayout('notes', 'notes'); + layout = splitSidePanelPane(layout, 'notes', tool, 'vertical', { paneId: 'plugin', splitId: 'root' }, 600); + const unique = splitSidePanelPane(layout, 'notes', tool, 'vertical', { paneId: 'duplicate', splitId: 'unused' }, 600); + assert.equal(collectSidePanelPanes(unique.root).length, 2); + assert.equal(getFocusedSidePanelPane(unique).tool, tool); + assert.ok(createWorkspaceLayoutPreset(layout)); + assert.equal(withoutUnavailableSidePanelTools(layout, (item) => item === 'notes')?.root.type, 'pane'); + for (let i = 0; i < 10; i++) layout = splitSidePanelPane(layout, getFocusedSidePanelPane(layout).id, + `plugin-view:com.example.plugin.page${i}`, 'horizontal', { paneId: `p${i}`, splitId: `s${i}` }, 600); + assert.equal(collectSidePanelPanes(layout.root).length, 8); + assert.equal(sanitizeWorkspaceLayoutPreset({ version: 1, layout: { root: { id: 'invalid', type: 'pane', tool: 'plugin-view:../outside' }, focusedPaneId: 'invalid' } }), null); +}); + test('sanitize rejects duplicate node ids', () => { assert.equal( sanitizeWorkspaceLayoutPreset({ diff --git a/domain/workspaceLayoutPreset.ts b/domain/workspaceLayoutPreset.ts index ff2621802..4b2a08db4 100644 --- a/domain/workspaceLayoutPreset.ts +++ b/domain/workspaceLayoutPreset.ts @@ -3,6 +3,7 @@ import { closeSidePanelPane, collectSidePanelPanes, getFocusedSidePanelPane, + isPluginSidePanelTool, type SidePanelLayout, type SidePanelLayoutNode, type SidePanelTool, @@ -32,7 +33,7 @@ const SIDE_PANEL_TOOLS: ReadonlySet = new Set([ ]); function isSidePanelTool(value: unknown): value is SidePanelTool { - return typeof value === 'string' && SIDE_PANEL_TOOLS.has(value as SidePanelTool); + return typeof value === 'string' && (SIDE_PANEL_TOOLS.has(value as SidePanelTool) || isPluginSidePanelTool(value)); } function sanitizeSidePanelLayoutNode( diff --git a/electron/plugins/generated/plugin-contract.schema.json b/electron/plugins/generated/plugin-contract.schema.json index 0523bc9c3..ea2d9b289 100644 --- a/electron/plugins/generated/plugin-contract.schema.json +++ b/electron/plugins/generated/plugin-contract.schema.json @@ -1294,12 +1294,33 @@ "tab", "modal", "settings", - "vault-page" + "vault-page", + "terminal-sidebar" ] }, "VaultPagesFeature": { "const": "views.vault-pages" }, + "TerminalSidebarFeature": { + "const": "views.terminal-sidebar" + }, + "PluginViewFocusEvent": { + "type": "object", + "required": [ + "instanceId" + ], + "properties": { + "instanceId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + "additionalProperties": false + }, + "PluginViewFocusRequest": { + "$ref": "#/$defs/PluginViewFocusEvent" + }, "ViewContribution": { "type": "object", "required": [ diff --git a/electron/plugins/hostService.cjs b/electron/plugins/hostService.cjs index 2f8b3fbe2..c2b49d3c3 100644 --- a/electron/plugins/hostService.cjs +++ b/electron/plugins/hostService.cjs @@ -3,6 +3,7 @@ const path = require("node:path"); const NETWORK_CREDENTIAL_LEASE_FEATURE = require("./generated/plugin-contract.schema.json").$defs.NetworkCredentialLeaseFeature.const; const VAULT_PAGES_FEATURE = require("./generated/plugin-contract.schema.json").$defs.VaultPagesFeature.const; +const TERMINAL_SIDEBAR_FEATURE = require("./generated/plugin-contract.schema.json").$defs.TerminalSidebarFeature.const; const INTERACTIVE_COMMAND_FEATURE = require("./generated/plugin-contract.schema.json").$defs.InteractiveCommandFeature.const; const { assertBrowserOnlyPlugin } = require("../../domain/pluginRuntimePolicy.cjs"); @@ -97,7 +98,7 @@ function createPluginHostService(options) { database, netcattyVersion: options.app.getVersion(), apiVersion: PLUGIN_API_VERSION, - supportedFeatures: [...new Set(["metadata.brand-icon", NETWORK_CREDENTIAL_LEASE_FEATURE, HOST_INTERACTION_FEATURE, VAULT_PAGES_FEATURE, INTERACTIVE_COMMAND_FEATURE, ...(options.supportedFeatures ?? [])])], + supportedFeatures: [...new Set(["metadata.brand-icon", NETWORK_CREDENTIAL_LEASE_FEATURE, HOST_INTERACTION_FEATURE, VAULT_PAGES_FEATURE, TERMINAL_SIDEBAR_FEATURE, INTERACTIVE_COMMAND_FEATURE, ...(options.supportedFeatures ?? [])])], }); const contributionIconService = new PluginContributionIconService({ database, @@ -237,7 +238,7 @@ function createPluginHostService(options) { paths, netcattyVersion: options.app.getVersion(), apiVersion: PLUGIN_API_VERSION, - supportedFeatures: [...new Set(["metadata.brand-icon", NETWORK_CREDENTIAL_LEASE_FEATURE, HOST_INTERACTION_FEATURE, VAULT_PAGES_FEATURE, INTERACTIVE_COMMAND_FEATURE, ...(options.supportedFeatures ?? [])])], + supportedFeatures: [...new Set(["metadata.brand-icon", NETWORK_CREDENTIAL_LEASE_FEATURE, HOST_INTERACTION_FEATURE, VAULT_PAGES_FEATURE, TERMINAL_SIDEBAR_FEATURE, INTERACTIVE_COMMAND_FEATURE, ...(options.supportedFeatures ?? [])])], runtimeDirectory, appRoot, rpcRegistry, diff --git a/electron/plugins/pluginBridge.cjs b/electron/plugins/pluginBridge.cjs index 21602e719..af194e1cf 100644 --- a/electron/plugins/pluginBridge.cjs +++ b/electron/plugins/pluginBridge.cjs @@ -5,6 +5,7 @@ const { randomUUID } = require("node:crypto"); const { createDefinitionValidator } = require("./contractValidator.cjs"); const validateManagedPluginId = createDefinitionValidator("PluginId"); +const validateViewFocus = createDefinitionValidator("PluginViewFocusRequest"); const { raceWithAbort } = require("./rpcRouter.cjs"); const { @@ -75,6 +76,7 @@ const CHANNELS = Object.freeze({ importerProgress: "netcatty:plugins:importer-progress", openView: "netcatty:plugins:open-view", closeView: "netcatty:plugins:close-view", + focusView: "netcatty:plugins:focus-view", setViewBounds: "netcatty:plugins:set-view-bounds", setViewVisibility: "netcatty:plugins:set-view-visibility", viewMessage: "netcatty:plugins:view-message", @@ -1605,6 +1607,12 @@ function registerPluginBridge(ipcMain, options) { await viewHost.close(payload?.instanceId, event.sender); return null; }); + handle(CHANNELS.focusView, async (_activeManager, payload, event) => { + if (!viewHost) throw new Error("Plugin views are unavailable"); + if (!validateViewFocus(payload)) throw new TypeError("Plugin view focus request is invalid"); + viewHost.focus(payload.instanceId, event.sender); + return null; + }); handle(CHANNELS.setViewBounds, async (_activeManager, payload, event) => { if (!viewHost) throw new Error("Plugin views are unavailable"); viewHost.setBounds(payload?.instanceId, payload?.bounds, event.sender); diff --git a/electron/plugins/pluginViewHost.cjs b/electron/plugins/pluginViewHost.cjs index 8b97baa84..00cbd235c 100644 --- a/electron/plugins/pluginViewHost.cjs +++ b/electron/plugins/pluginViewHost.cjs @@ -62,7 +62,7 @@ class PluginViewHost { if (["plugin-disabled", "runtime-stopped", "runtime-error", "runtime-quarantined"].includes(event.reason) && instance.pluginId === event.pluginId) { void this.close(instance.instanceId, undefined, event.reason); - } else if (instance.location === "vault-page") { + } else if (["vault-page", "terminal-sidebar"].includes(instance.location)) { try { this.contributionService.assertViewActivationCurrent(instance.activation, { context: instance.context }); } catch { void this.close(instance.instanceId, undefined, "contribution-unavailable"); } } @@ -233,7 +233,7 @@ class PluginViewHost { }); contents.on("will-attach-webview", (event) => event.preventDefault()); contents.once("render-process-gone", () => { void this.close(instanceId, undefined, "view-renderer-gone"); }); - if (view.location === "vault-page") contents.on("before-input-event", (event, input) => { + if (["vault-page", "terminal-sidebar"].includes(view.location)) contents.on("before-input-event", (event, input) => { if (input.type === "keyDown" && input.key === "Escape" && !input.control && !input.meta && !input.alt && !input.shift) { event.preventDefault(); void this.close(instanceId, undefined, "host-escape"); @@ -256,9 +256,13 @@ class PluginViewHost { sessionRegistration, state: "opening", attached: false, - visible: view.location !== "vault-page", + visible: !["vault-page", "terminal-sidebar"].includes(view.location), }; this.instances.set(instanceId, instance); + contents.on("focus", () => { + if (this.instances.get(instanceId) !== instance || instance.state !== "open") return; + try { owner.webContents?.send("netcatty:plugins:view-focused", { instanceId }); } catch {} + }); this.byWebContentsId.set(contents.id, instance); owner.once?.("closed", ownerClosed); contents.once("destroyed", () => { void this.close(instanceId, undefined, "contents-destroyed"); }); @@ -271,7 +275,7 @@ class PluginViewHost { this.#assertOpening(opening); // Embedded pages start hidden until the trusted renderer checks host // dialogs/lock/popovers. A late open must never cover a security surface. - if (view.location === "vault-page") contentsView.setVisible(false); + if (["vault-page", "terminal-sidebar"].includes(view.location)) contentsView.setVisible(false); owner.contentView.addChildView(contentsView); instance.attached = true; contentsView.setBounds(normalizeBounds(payload.bounds)); @@ -303,6 +307,12 @@ class PluginViewHost { if (rising && instance.location === "vault-page" && instance.owner.isFocused?.()) instance.contents.focus?.(); } + focus(instanceId, sender) { + const instance = this.#ownedInstance(instanceId, sender); + if (!instance.visible || this.isLocked() || instance.owner.isFocused?.() !== true) return; + instance.contents.focus?.(); + } + async postMessage(instanceId, message, sender) { const instance = this.#ownedInstance(instanceId, sender); assertJsonValue(message, "view message"); diff --git a/electron/plugins/pluginViewHost.test.cjs b/electron/plugins/pluginViewHost.test.cjs index 666cd5908..4ecad1763 100644 --- a/electron/plugins/pluginViewHost.test.cjs +++ b/electron/plugins/pluginViewHost.test.cjs @@ -25,6 +25,7 @@ function fixture(options = {}) { if (options.loadURL) await options.loadURL(this); } send(channel, payload) { this.sent.push([channel, payload]); } + focus() { this.emit("focus"); } isDestroyed() { return this.destroyed; } close() { this.destroyed = true; this.emit("destroyed"); } } @@ -455,3 +456,21 @@ test("host reload, host/view renderer exit, and host Escape close embedded pages await value.host.shutdown(); } }); + +test("sidebar native focus is explicit, owner-bound and cannot raise a hidden or locked page", async () => { + let locked = false; + const value = fixture({ location: "terminal-sidebar", isLocked: () => locked }); + const { owner, sender } = value.createOwner(); const other = value.createOwner(); + const events = []; + sender.send = (channel, event) => events.push({ channel, event }); owner.webContents = sender; owner.isFocused = () => true; + const { instanceId } = await value.host.open({ viewId: "com.example.view.panel", scopeId: "window-1:terminal-sidebar" }, sender); + assert.equal(value.views[0].visible, false); + value.host.focus(instanceId, sender); assert.deepEqual(events, []); + value.host.setVisible(instanceId, true, sender); assert.deepEqual(events, [], "revealing multiple panes does not focus each one"); + assert.throws(() => value.host.focus(instanceId, other.sender), /another window/i); + value.host.focus(instanceId, sender); + assert.deepEqual(events, [{ channel: "netcatty:plugins:view-focused", event: { instanceId } }]); + locked = true; value.host.focus(instanceId, sender); assert.equal(events.length, 1); + locked = false; value.setActivationCurrent(false); value.changeListener()({ reason: "context-key-changed" }); + assert.equal(owner.children.length, 0); await value.host.shutdown(); +}); diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index 211968dfe..1337432f0 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -270,6 +270,7 @@ function createPreloadApi(ctx) { }, openPluginView: (payload) => ipcRenderer.invoke("netcatty:plugins:open-view", payload), closePluginView: (instanceId) => ipcRenderer.invoke("netcatty:plugins:close-view", { instanceId }), + focusPluginView: (payload) => ipcRenderer.invoke("netcatty:plugins:focus-view", payload), setPluginViewBounds: (instanceId, bounds) => ipcRenderer.invoke("netcatty:plugins:set-view-bounds", { instanceId, bounds }), setPluginViewVisibility: (instanceId, visible) => ipcRenderer.invoke("netcatty:plugins:set-view-visibility", { instanceId, @@ -290,6 +291,11 @@ function createPreloadApi(ctx) { ipcRenderer.on("netcatty:plugins:view-closed", listener); return () => ipcRenderer.removeListener("netcatty:plugins:view-closed", listener); }, + onPluginViewFocused: (callback) => { + const listener = (_event, payload) => callback(payload); + ipcRenderer.on("netcatty:plugins:view-focused", listener); + return () => ipcRenderer.removeListener("netcatty:plugins:view-focused", listener); + }, getPluginScopeCatalog: () => ipcRenderer.invoke("netcatty:plugins:get-scope-catalog"), setPluginScopeCatalog: (catalog) => ipcRenderer.invoke("netcatty:plugins:set-scope-catalog", catalog), onPluginScopeCatalogChanged: (callback) => { diff --git a/examples/plugins/session-scratchpad/README.md b/examples/plugins/session-scratchpad/README.md new file mode 100644 index 000000000..7d5537e47 --- /dev/null +++ b/examples/plugins/session-scratchpad/README.md @@ -0,0 +1,30 @@ +# Session Scratchpad + +Fixture ID: `com.netcatty.session-scratchpad`, version `0.1.0`. +Required permission: **views**, for this plugin's own pages only. Required +feature: `views.terminal-sidebar`. No terminal/session read, clipboard, network, +Vault, filesystem, credential or shell permission is requested. + +```sh +node packages/plugin-cli/dist/cli.js pack examples/plugins/session-scratchpad --out /tmp/session-scratchpad.ncpkg +``` + +Import disabled through normal Settings, inspect and enable. Parent native QA +must obtain a fixture-specific own-views approval; no previous plugin's grant +applies. Use only an explicitly approved synthetic terminal target, without +entering commands or connecting to real hosts for this page check. + +In an open terminal, choose **Extension pages** in its toolbar, then **Session +scratchpad**. This is a real existing side-panel pane. Save synthetic text, +split beside a built-in tool, resize/move/magnify, return and reopen. The host +keeps this page's state in a placement/session bucket; the page never receives +the session ID, endpoint, cwd, title, history, selection or terminal output. +This is plugin-owned text, not a Vault Note, and is not automatically synced. + +For a separately approved second synthetic terminal/workspace focus target, +verify that navigation closes the old native view and uses a separate draft +bucket. Switch back to verify the saved first draft. Clear it to verify +deletion. Close the pane, press Escape, disable/revoke, and verify cleanup. +Settings/permission dialogs and overlapping menus must stay above native +content. No new native target or persistent grant should be inferred from this +README; parent coordinates the exact test and records source SHA/package hash. diff --git a/examples/plugins/session-scratchpad/browser.js b/examples/plugins/session-scratchpad/browser.js new file mode 100644 index 000000000..7bf25c994 --- /dev/null +++ b/examples/plugins/session-scratchpad/browser.js @@ -0,0 +1 @@ +export default { activate() {} }; diff --git a/examples/plugins/session-scratchpad/netcatty.plugin.json b/examples/plugins/session-scratchpad/netcatty.plugin.json new file mode 100644 index 000000000..24a830d8c --- /dev/null +++ b/examples/plugins/session-scratchpad/netcatty.plugin.json @@ -0,0 +1,46 @@ +{ + "manifestVersion": 1, + "id": "com.netcatty.session-scratchpad", + "name": "session-scratchpad", + "displayName": { + "en": "Session Scratchpad", + "zh-CN": "会话草稿板" + }, + "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" + }, + "features": { + "required": [ + "views.terminal-sidebar" + ] + }, + "main": { + "browser": "browser.js" + }, + "activationEvents": [ + "onView:com.netcatty.session-scratchpad.page" + ], + "permissions": { + "required": [ + "views" + ] + }, + "contributes": { + "views": [ + { + "id": "com.netcatty.session-scratchpad.page", + "title": { + "en": "Session scratchpad", + "zh-CN": "会话草稿板" + }, + "location": "terminal-sidebar", + "entry": "page.html", + "order": 10 + } + ] + } +} diff --git a/examples/plugins/session-scratchpad/page.css b/examples/plugins/session-scratchpad/page.css new file mode 100644 index 000000000..89803bc2a --- /dev/null +++ b/examples/plugins/session-scratchpad/page.css @@ -0,0 +1,5 @@ +:root { color-scheme: light dark; font-family: system-ui, sans-serif; } +body { margin: 0; padding: 24px; } main { max-width: 720px; margin: auto; } +textarea { display: block; box-sizing: border-box; width: 100%; margin: 12px 0; padding: 10px; font: inherit; } +button { padding: 8px 12px; margin: 0 8px 0 0; font: inherit; } +#status { min-height: 1.5em; } diff --git a/examples/plugins/session-scratchpad/page.html b/examples/plugins/session-scratchpad/page.html new file mode 100644 index 000000000..174719823 --- /dev/null +++ b/examples/plugins/session-scratchpad/page.html @@ -0,0 +1,7 @@ + + +Session Scratchpad +

Session scratchpad

This page stores only text you type here, in this plugin's own view state. It cannot read Vault hosts, notes, credentials, sessions or the clipboard.

+ + +

Loading your plugin draft…

diff --git a/examples/plugins/session-scratchpad/page.js b/examples/plugins/session-scratchpad/page.js new file mode 100644 index 000000000..ebf3590eb --- /dev/null +++ b/examples/plugins/session-scratchpad/page.js @@ -0,0 +1,25 @@ +"use strict"; +/* global document, window */ +const draft = document.getElementById("draft"); +const status = document.getElementById("status"); +let busy = false; +async function save(clear) { + if (busy) return; + busy = true; + try { + const text = clear ? "" : draft.value; + await window.netcattyView.setState({ version: 1, text }); + if (clear) draft.value = ""; + status.textContent = clear ? "Draft cleared." : "Draft saved in this plugin only."; + } catch { status.textContent = "Could not save this draft."; } + finally { busy = false; } +} +document.getElementById("save").addEventListener("click", () => { void save(false); }); +document.getElementById("clear").addEventListener("click", () => { void save(true); }); +window.netcattyView.getState().then((state) => { + if (state?.version === 1 && typeof state.text === "string" && state.text.length <= 4096) draft.value = state.text; + status.textContent = "Ready. Use synthetic text for this example."; + draft.disabled = false; + document.getElementById("save").disabled = false; + document.getElementById("clear").disabled = false; +}).catch(() => { status.textContent = "Could not load this plugin draft."; }); diff --git a/global.d.ts b/global.d.ts index b93c8bf00..48bbb7082 100644 --- a/global.d.ts +++ b/global.d.ts @@ -581,10 +581,12 @@ declare global { closePluginView?(instanceId: string): Promise; setPluginViewBounds?(instanceId: string, bounds: { x: number; y: number; width: number; height: number }): Promise; setPluginViewVisibility?(instanceId: string, visible: boolean): Promise; + focusPluginView?(payload: import('@netcatty/plugin-contract').PluginViewFocusRequest): Promise; postPluginViewMessage?(instanceId: string, message: unknown): Promise; onPluginContributionsChanged?(callback: (event: { reason: string; pluginId: string | null; revision: number }) => void): () => void; onPluginViewMessage?(callback: (event: { pluginId: string; viewId: string; message: unknown }) => void): () => void; onPluginViewClosed?(callback: (event: NetcattyPluginViewClosedEvent) => void): () => void; + onPluginViewFocused?(callback: (event: import('@netcatty/plugin-contract').PluginViewFocusEvent) => void): () => void; getPluginScopeCatalog?(): Promise; setPluginScopeCatalog?(catalog: NetcattyPluginScopeCatalog): Promise; onPluginScopeCatalogChanged?(callback: (catalog: NetcattyPluginScopeCatalog) => void): () => void; diff --git a/packages/plugin-cli/src/manifest.ts b/packages/plugin-cli/src/manifest.ts index af043ceab..77b798fd8 100644 --- a/packages/plugin-cli/src/manifest.ts +++ b/packages/plugin-cli/src/manifest.ts @@ -367,6 +367,8 @@ function validateSemantics(manifest: PluginManifest): string[] { } const requiredFeatures = new Set(manifest.features?.required ?? []); + if (manifest.contributes?.views?.some((view) => view.location === 'terminal-sidebar') + && !requiredFeatures.has('views.terminal-sidebar')) errors.push('Terminal sidebar pages require views.terminal-sidebar'); if (manifest.contributes?.views?.some((view) => view.location === 'vault-page') && !requiredFeatures.has('views.vault-pages')) { errors.push('Vault pages require views.vault-pages'); diff --git a/packages/plugin-cli/src/terminalSidebar.test.ts b/packages/plugin-cli/src/terminalSidebar.test.ts new file mode 100644 index 000000000..9e655d91c --- /dev/null +++ b/packages/plugin-cli/src/terminalSidebar.test.ts @@ -0,0 +1,14 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { readFile } from 'node:fs/promises'; +import { validateManifestValue } from './manifest.js'; +import { checkPluginCompatibility } from './compatibility.js'; +const manifest = JSON.parse(await readFile(new URL('../../../examples/plugins/session-scratchpad/netcatty.plugin.json', import.meta.url), 'utf8')); +test('terminal sidebar pages require views and their exact feature without session data permissions', () => { + assert.equal(validateManifestValue(manifest).valid, true); + assert.equal(validateManifestValue({ ...manifest, features: {} }).valid, false); + assert.equal(validateManifestValue({ ...manifest, permissions: {} }).valid, false); + assert.equal(checkPluginCompatibility(manifest, { netcattyVersion: '1.0.0', features: ['views.vault-pages'] }).compatible, false); + assert.equal(checkPluginCompatibility(manifest, { netcattyVersion: '1.0.0', features: ['views.terminal-sidebar'] }).compatible, true); + assert.deepEqual(manifest.permissions.required, ['views']); +}); diff --git a/packages/plugin-contract/schema/plugin-contract.schema.json b/packages/plugin-contract/schema/plugin-contract.schema.json index 1935dc655..46b8cd042 100644 --- a/packages/plugin-contract/schema/plugin-contract.schema.json +++ b/packages/plugin-contract/schema/plugin-contract.schema.json @@ -1005,11 +1005,21 @@ }, "ViewLocation": { "type": "string", - "enum": ["aside", "panel", "tab", "modal", "settings", "vault-page"] + "enum": ["aside", "panel", "tab", "modal", "settings", "vault-page", "terminal-sidebar"] }, "VaultPagesFeature": { "const": "views.vault-pages" }, + "TerminalSidebarFeature": { + "const": "views.terminal-sidebar" + }, + "PluginViewFocusEvent": { + "type": "object", + "required": ["instanceId"], + "properties": { "instanceId": { "type": "string", "minLength": 1, "maxLength": 128 } }, + "additionalProperties": false + }, + "PluginViewFocusRequest": { "$ref": "#/$defs/PluginViewFocusEvent" }, "ViewContribution": { "type": "object", "required": ["id", "title", "location", "entry"], diff --git a/packages/plugin-contract/src/generated/plugin-contract.ts b/packages/plugin-contract/src/generated/plugin-contract.ts index 9f0c23a9e..d6a374e1f 100644 --- a/packages/plugin-contract/src/generated/plugin-contract.ts +++ b/packages/plugin-contract/src/generated/plugin-contract.ts @@ -587,6 +587,12 @@ export type PluginNetworkResponse = { export type PluginPermission = "storage" | "runtime.advanced" | "settings.read" | "settings.write" | "commands" | "menus" | "views" | "ui.interact" | "clipboard.read" | "clipboard.write" | "terminal.metadata" | "terminal.output" | "terminal.input" | "terminal.decorate" | "terminal.complete" | "terminal.intercept.input" | "terminal.intercept.output" | "vault.metadata" | "vault.write" | "vault.credentials" | "sftp.read" | "sftp.write" | "network" | "filesystem.read" | "filesystem.write" | "secrets" | "companion.execute" | "provider.terminal" | "provider.connection" | "provider.authentication" | "provider.sync" | "provider.importer"; +export type PluginViewFocusEvent = { + instanceId: string; +}; + +export type PluginViewFocusRequest = PluginViewFocusEvent; + export type PluginWireErrorCode = -32001 | -32002 | -32003 | -32004 | -32005 | -32006 | -32007 | -32008 | -32009 | -32010 | -32011 | -32012 | -32013 | -32014 | -32015 | -32016; export type ProgressBegin = { @@ -1035,6 +1041,8 @@ export type TerminalSessionSnapshot = { alternateScreen?: boolean; }; +export type TerminalSidebarFeature = "views.terminal-sidebar"; + export type ThemeIcon = { kind: "theme"; name: string; @@ -1053,6 +1061,6 @@ export type ViewContribution = { retainContextWhenHidden?: boolean; }; -export type ViewLocation = "aside" | "panel" | "tab" | "modal" | "settings" | "vault-page"; +export type ViewLocation = "aside" | "panel" | "tab" | "modal" | "settings" | "vault-page" | "terminal-sidebar"; export type WireIntegerLimits = {"maxSafeInteger":9007199254740991}; diff --git a/packages/plugin-contract/src/index.ts b/packages/plugin-contract/src/index.ts index a0c6f013e..1a95a10b4 100644 --- a/packages/plugin-contract/src/index.ts +++ b/packages/plugin-contract/src/index.ts @@ -56,4 +56,5 @@ export const PLUGIN_NETWORK_CREDENTIAL_LEASE_FEATURE = "network.credential-lease export const PLUGIN_HOST_INTERACTION_FEATURE = "host.interactions" as const satisfies import("./generated/plugin-contract.js").HostInteractionFeature; export const PLUGIN_VAULT_PAGES_FEATURE = "views.vault-pages" as const satisfies import("./generated/plugin-contract.js").VaultPagesFeature; +export const PLUGIN_TERMINAL_SIDEBAR_FEATURE = "views.terminal-sidebar" as const satisfies import("./generated/plugin-contract.js").TerminalSidebarFeature; export const PLUGIN_INTERACTIVE_COMMAND_FEATURE = "commands.interactive" as const satisfies import("./generated/plugin-contract.js").InteractiveCommandFeature; diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts index 9704da80a..d199cf92c 100644 --- a/packages/plugin-sdk/src/index.ts +++ b/packages/plugin-sdk/src/index.ts @@ -931,4 +931,5 @@ export { PLUGIN_NETWORK_CREDENTIAL_LEASE_FEATURE } from "@netcatty/plugin-contra export { PLUGIN_HOST_INTERACTION_FEATURE } from "@netcatty/plugin-contract"; export { PLUGIN_VAULT_PAGES_FEATURE } from "@netcatty/plugin-contract"; +export { PLUGIN_TERMINAL_SIDEBAR_FEATURE } from "@netcatty/plugin-contract"; export { PLUGIN_INTERACTIVE_COMMAND_FEATURE } from "@netcatty/plugin-contract";