Compare commits

...
Author SHA1 Message Date
陈大猫 36fbc8b85b fix(plugins): cancel stuck SSH exec dials before the plugin RPC deadline
Plugin vault.execHostCommand could hit "Plugin request deadline exceeded"
when a pooled SSH reconnect used the interactive 20s/120s handshake
timeouts, and retries hitchhiked on the leftover pendingDial.

- Stop and drop a pending plugin dial when its last waiter cancels
- Pass tighter startPortForward connect/auth budgets (8s/8s) under an
  18s prepare+dial envelope, and map failures to "SSH connection timed out"
- Evict half-open or channel-open/RPC-deadline-failed pooled connections
2026-12-02 01:49:26 +08:00
陈大猫 960cc05219 fix(ai): move chat manager multi-select into overflow menu and confirm bulk delete (#4618) 2026-12-02 00:56:52 +08:00
陈大猫 7ad4a7daf5 fix(plugins): raise host-ui view message budget, deduplicate SDK CSS, and log runtime/view failures (#4616) 2026-12-02 00:21:31 +08:00
28 changed files with 1999 additions and 254 deletions

No files matched your search

+2
View File
@@ -640,6 +640,8 @@ export const enAiMessages: Messages = {
'ai.chat.managerMessagesCount': '{n} messages',
'ai.chat.managerDeleteTitle': 'Delete this chat?',
'ai.chat.managerDeleteMessage': '"{title}" and its messages will be removed from every panel. This cannot be undone.',
'ai.chat.managerBulkDeleteTitle': 'Delete {n} chats?',
'ai.chat.managerBulkDeleteMessage': '{n} selected chats and their messages will be removed from every panel. This cannot be undone.',
'ai.chat.justNow': 'Just now',
'ai.chat.minutesAgo': '{n}m ago',
'ai.chat.hoursAgo': '{n}h ago',
+2
View File
@@ -640,6 +640,8 @@ export const esAiMessages: Messages = {
'ai.chat.managerMessagesCount': '{n} mensajes',
'ai.chat.managerDeleteTitle': '¿Eliminar este chat?',
'ai.chat.managerDeleteMessage': '«{title}» y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
'ai.chat.managerBulkDeleteTitle': '¿Eliminar {n} chats?',
'ai.chat.managerBulkDeleteMessage': 'Los {n} chats seleccionados y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
'ai.chat.justNow': 'Ahora mismo',
'ai.chat.minutesAgo': 'hace {n} min',
'ai.chat.hoursAgo': 'hace {n} h',
+2
View File
@@ -639,6 +639,8 @@ export const ruAiMessages: Messages = {
'ai.chat.managerMessagesCount': '{n} сообщений',
'ai.chat.managerDeleteTitle': 'Удалить этот чат?',
'ai.chat.managerDeleteMessage': '«{title}» и его сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
'ai.chat.managerBulkDeleteTitle': 'Удалить выбранные чаты ({n})?',
'ai.chat.managerBulkDeleteMessage': 'Выбранные чаты ({n}) и их сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
'ai.chat.justNow': 'Только что',
'ai.chat.minutesAgo': '{n}м назад',
'ai.chat.hoursAgo': '{n}ч назад',
+2
View File
@@ -640,6 +640,8 @@ export const zhCNAiMessages: Messages = {
'ai.chat.managerMessagesCount': '{n} 条消息',
'ai.chat.managerDeleteTitle': '删除此会话?',
'ai.chat.managerDeleteMessage': '“{title}”及其消息将从所有面板中移除,且无法撤销。',
'ai.chat.managerBulkDeleteTitle': '删除选中的 {n} 个会话?',
'ai.chat.managerBulkDeleteMessage': '选中的 {n} 个会话及其消息将从所有面板中移除,且无法撤销。',
'ai.chat.justNow': '刚刚',
'ai.chat.minutesAgo': '{n}分钟前',
'ai.chat.hoursAgo': '{n}小时前',
+2
View File
@@ -639,6 +639,8 @@ export const zhTWAiMessages: Messages = {
'ai.chat.managerMessagesCount': '{n} 則訊息',
'ai.chat.managerDeleteTitle': '刪除此會話?',
'ai.chat.managerDeleteMessage': '「{title}」及其訊息將從所有面板中移除,且無法復原。',
'ai.chat.managerBulkDeleteTitle': '刪除選取的 {n} 個工作階段?',
'ai.chat.managerBulkDeleteMessage': '選取的 {n} 個工作階段及其訊息將從所有面板中移除,且無法復原。',
'ai.chat.justNow': '剛剛',
'ai.chat.minutesAgo': '{n}分鐘前',
'ai.chat.hoursAgo': '{n}小時前',
@@ -337,3 +337,43 @@ test('explicit CSS matching the last committed value supersedes pending CSS', ()
console.warn = originalWarn;
}
});
test('omitted css preserves previous stylesheet and apply failures emit diagnostics', () => {
const originalWarn = console.warn;
console.warn = () => {};
try {
const f = fixture();
const diagnostics: Array<{ source?: string; message: string; extra?: Record<string, unknown> }> = [];
const bridgeWithDiag = {
...f.bridge,
logDiagnostic: async (payload: { source?: string; message: string; extra?: Record<string, unknown> }) => {
diagnostics.push(payload);
return { success: true };
},
};
const store = new PluginViewSessions();
const view = store.acquire('diag-test', bridgeWithDiag, request);
const id = f.opened[0].instanceId;
const node = { id: 'n1', type: 1 as const, element: 'div', attributes: {}, children: [] };
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.n{display:flex}', mutations: [[0, '~', node, 0]] });
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 2, mutations: [[3, 'n1', 'class', 'n']] });
assert.equal(view.getSnapshot().css.includes('display:flex'), true);
assert.equal(view.getSnapshot().error, false);
// Duplicate-node recoverable errors should emit at most one diagnostic per session.
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 3, mutations: [[0, 'n1', { id: 'n1', type: 1, element: 'span', attributes: {}, children: [] }, 0]] } as Update);
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 4, mutations: [[0, 'n1', { id: 'n1', type: 1, element: 'span', attributes: {}, children: [] }, 0]] } as Update);
assert.equal(diagnostics.length, 1);
assert.equal(diagnostics[0].extra?.kind, 'duplicate-node-update');
// Trigger an out-of-order sequence failure and verify diagnostic is logged.
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 99, mutations: [] });
assert.equal(view.getSnapshot().error, true);
assert.equal(diagnostics.length, 2);
assert.equal(diagnostics[1].source, 'plugin-view');
assert.match(diagnostics[1].message, /Invalid plugin update order/);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
+27 -3
View File
@@ -3,7 +3,9 @@ import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry';
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
type Bridge = Pick<NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>;
type NetcattyBridgeApi = NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>;
type Bridge = Pick<NetcattyBridgeApi, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>
& Partial<Pick<NetcattyBridgeApi, 'logDiagnostic'>>;
export type PluginViewSnapshot = { tree: ReturnType<ReturnType<typeof createPluginRemoteTree>['snapshot']>; css: string; loading: boolean; error: boolean; settled: boolean };
const empty = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
const EMPTY_FIRST_FRAME_GRACE_MS = 60;
@@ -26,6 +28,7 @@ export class PluginViewSessions {
const id = crypto.randomUUID();
const tree = createPluginRemoteTree();
let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0;
let loggedDuplicateNode = false;
let lastRawCss: string | null = null;
let pendingCss: string | null = null;
let pendingRawCss: string | null = null;
@@ -48,7 +51,7 @@ export class PluginViewSessions {
let stagedRawCss: string | null = null;
try {
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
if (update.cssUnchanged) {
if (update.cssUnchanged || update.css === undefined) {
// keep pending CSS, if any, for the nextCss fallback below
} else if (lastRawCss !== null && update.css === lastRawCss) {
// Explicit CSS equal to the last committed raw CSS supersedes any pending stylesheet.
@@ -85,9 +88,23 @@ export class PluginViewSessions {
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.warn(`[PluginViewSession] Failed to apply update for ${request.viewId}: ${message}`, error);
const duplicateNode = isDuplicatePluginViewNodeError(error);
if (!duplicateNode || !loggedDuplicateNode) {
if (duplicateNode) loggedDuplicateNode = true;
void bridge.logDiagnostic?.({
source: 'plugin-view',
message: `Failed to apply update for ${request.viewId}: ${message}`,
extra: {
kind: duplicateNode ? 'duplicate-node-update' : 'apply-update-failed',
viewId: request.viewId,
sequence: update.sequence,
mutationCount: Array.isArray(update.mutations) ? update.mutations.length : null,
},
}).catch(() => {});
}
// Recoverable duplicate-only batches are normalized as moves in
// createPluginRemoteTree(); only unrecoverable duplicates reach here.
if (isDuplicatePluginViewNodeError(error)) {
if (duplicateNode) {
if (stagedCss !== null && stagedRawCss !== null) {
pendingCss = stagedCss;
pendingRawCss = stagedRawCss;
@@ -130,6 +147,13 @@ export class PluginViewSessions {
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch((error) => {
const message = error instanceof Error ? error.message : String(error);
console.warn(`[PluginViewSession] Failed to send event for ${request.viewId}: ${message}`);
if (!disposed) {
void bridge.logDiagnostic?.({
source: 'plugin-view',
message: `Failed to send event for ${request.viewId}: ${message}`,
extra: { kind: 'send-event-failed', viewId: request.viewId, eventType: event.type },
}).catch(() => {});
}
dispose(true);
});
},
+49 -4
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useRef, useState } from 'react';
import { Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { CheckSquare, Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
import type { AISession } from '../infrastructure/ai/types';
import { useI18n } from '../application/i18n/I18nProvider';
import { cn } from '../lib/utils';
@@ -9,6 +9,7 @@ import { Input } from './ui/input';
import { ScrollArea } from './ui/scroll-area';
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
import { SESSION_HISTORY_ROW_CLASSNAMES } from './ai/sessionHistoryLayout';
import { GlobalSessionSelectionContext } from './ai/sessionHistorySelectionContext';
import { useSessionHistorySearch } from '../application/state/useSessionHistorySearch';
// -------------------------------------------------------------------
@@ -52,6 +53,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
const { t } = useI18n();
const [view, setView] = useState<'scoped' | 'global'>('scoped');
const [headerMenuOpen, setHeaderMenuOpen] = useState(false);
const [globalSelectionMode, setGlobalSelectionMode] = useState(false);
const [renderCount, setRenderCount] = useState(SESSION_RENDER_BATCH);
const [searchQuery, setSearchQuery] = useState('');
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
@@ -70,6 +72,22 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
setRenderCount(SESSION_RENDER_BATCH);
}, [sessions, searchQuery]);
useEffect(() => {
if (view !== 'global' || !globalManager) {
setGlobalSelectionMode(false);
}
}, [view, globalManager]);
const selectionContextValue = useMemo(
() => ({
selectionMode: globalSelectionMode,
setSelectionMode: setGlobalSelectionMode,
}),
[globalSelectionMode],
);
const canSelectGlobalChats = view === 'global' && Boolean(globalManager);
const hasHeaderMenu = Boolean(canSelectGlobalChats || onImportSessions || onExportSessions);
const displayedSessions = filteredSessions.slice(0, renderCount);
const hiddenSessionCount = Math.max(0, filteredSessions.length - renderCount);
@@ -132,7 +150,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
)}
</div>
<div className="flex items-center gap-2">
{(onImportSessions || onExportSessions) && (
{hasHeaderMenu && (
<Dropdown open={headerMenuOpen} onOpenChange={setHeaderMenuOpen}>
<DropdownTrigger asChild>
<button
@@ -144,6 +162,31 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
</button>
</DropdownTrigger>
<DropdownContent align="end" className="min-w-[152px] p-1" keyboardNavigation>
{canSelectGlobalChats && (
<>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setHeaderMenuOpen(false);
setGlobalSelectionMode((prev) => !prev);
}}
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted cursor-pointer"
>
<CheckSquare
size={12}
className={cn(
'shrink-0',
globalSelectionMode ? 'text-primary' : 'text-muted-foreground',
)}
/>
<span>{t('ai.chat.managerToggleSelection')}</span>
</button>
{(onImportSessions || onExportSessions) && (
<div className="my-1 h-px bg-border/50" />
)}
</>
)}
{onImportSessions && (
<button
type="button"
@@ -184,7 +227,9 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
</div>
</div>
{view === 'global' && globalManager ? (
globalManager
<GlobalSessionSelectionContext.Provider value={selectionContextValue}>
{globalManager}
</GlobalSessionSelectionContext.Provider>
) : (
<>
<div className="px-3 py-2 shrink-0 border-b border-border/30">
+130 -12
View File
@@ -566,9 +566,16 @@ test("subtitle styling keeps agent label emphasized and message count normal whe
}
});
test("selection mode batches delete and title regeneration without activating rows", async () => {
test("selection mode is triggered from the drawer overflow menu, confirms bulk delete, and supports Cancel/Escape/tab exit", async () => {
const dom = installDomEnvironment();
const restoreGlobals = installRadixGlobals(dom);
try {
const { SessionHistoryDrawer } = await import("../AIChatSessionHistoryDrawer.tsx");
const { GlobalAIChatSessionManager } = await import("./GlobalAIChatSessionManager.tsx");
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
const { TooltipProvider } = await import("../ui/tooltip.tsx");
const renderer = await createDomRenderer(dom.document);
const props = baseProps();
props.sessions = [
makeSession({ id: "s-a", title: "A" }),
@@ -581,30 +588,141 @@ test("selection mode batches delete and title regeneration without activating ro
props.onRegenerateTitle = (id) => regenerated.push(id);
props.onSelect = (id) => activated.push(id);
const renderer = await renderManager(dom, props);
const toggle = renderer.container.querySelector<HTMLElement>(
`button[aria-label="${t("ai.chat.managerToggleSelection")}"]`,
await renderer.render(
<I18nProvider locale="en">
<TooltipProvider>
<SessionHistoryDrawer
sessions={props.sessions}
activeSessionId="s-a"
onSelect={() => {}}
onDelete={() => {}}
onExportSessions={() => {}}
onClose={() => {}}
globalManager={<GlobalAIChatSessionManager {...props} />}
/>
</TooltipProvider>
</I18nProvider>,
);
assert.ok(toggle, "selection toggle present");
await dispatchDomEvent(toggle, new dom.window.MouseEvent("click", { bubbles: true }));
// Clicking rows toggles selection instead of opening the chat.
const openHeaderMenu = async () => {
const trigger = renderer.container.querySelector<HTMLButtonElement>(
`button[aria-label="${t("ai.chat.managerMoreActions")}"]`,
);
assert.ok(trigger, "drawer overflow trigger present");
await dispatchDomEvent(trigger, new dom.window.MouseEvent("click", { bubbles: true }));
await new Promise((resolve) => setTimeout(resolve, 10));
};
// On the default "Current chats" tab, "Select chats" is not shown in the overflow menu.
await openHeaderMenu();
const scopedSelectItem = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"));
assert.equal(scopedSelectItem, undefined, "Select chats is hidden on current tab");
// Close header menu before switching tabs.
await openHeaderMenu();
// Switch to the "All chats" tab.
const tabs = renderer.container.querySelectorAll<HTMLButtonElement>('[role="tab"]');
await dispatchDomEvent(tabs[1], new dom.window.MouseEvent("click", { bubbles: true }));
// Search/filter bar must not contain an inline selection toggle button.
const manager = renderer.container.querySelector('[data-section="ai-global-session-manager"]')!;
assert.equal(
manager.querySelector(`button[aria-label="${t("ai.chat.managerToggleSelection")}"]`),
null,
"no standalone selection button in filter bar",
);
// Trigger selection mode from the drawer's top-right overflow menu.
await openHeaderMenu();
const selectItem = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"));
assert.ok(selectItem, "Select chats menu item present on All chats tab");
await dispatchDomEvent(selectItem, new dom.window.MouseEvent("click", { bubbles: true }));
assert.ok(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
"selection action bar opens",
);
// Clicking Cancel exits selection mode cleanly.
const cancelBtn = Array.from(
manager.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
).find((b) => b.textContent?.trim() === t("common.cancel"));
assert.ok(cancelBtn, "Cancel button present in selection bar");
await dispatchDomEvent(cancelBtn, new dom.window.MouseEvent("click", { bubbles: true }));
assert.equal(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"Cancel exits selection mode",
);
// Re-enter selection mode, verify Escape exits, then re-enter for bulk actions.
await openHeaderMenu();
const selectItem2 = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
await dispatchDomEvent(selectItem2, new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(dom.window, new dom.window.KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
assert.equal(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"Escape exits selection mode",
);
// Switching back to "Current chats" and returning to "All chats" clears selection mode.
await openHeaderMenu();
const selectItemTab = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
await dispatchDomEvent(selectItemTab, new dom.window.MouseEvent("click", { bubbles: true }));
assert.ok(
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
"selection bar open before tab switch",
);
await dispatchDomEvent(tabs[0], new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(tabs[1], new dom.window.MouseEvent("click", { bubbles: true }));
const managerAfterTabSwitch = renderer.container.querySelector('[data-section="ai-global-session-manager"]')!;
assert.equal(
managerAfterTabSwitch.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"switching away from All chats resets selection mode",
);
await openHeaderMenu();
const selectItem3 = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
await dispatchDomEvent(selectItem3, new dom.window.MouseEvent("click", { bubbles: true }));
// Clicking and keyboard-activating rows toggles selection instead of opening the chat.
await dispatchDomEvent(rows(renderer)[0], new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(rows(renderer)[1], new dom.window.MouseEvent("click", { bubbles: true }));
await dispatchDomEvent(rows(renderer)[1], new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
assert.deepEqual(activated, []);
const bulkRegen = Array.from(renderer.container.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.includes(t("ai.chat.managerRegenerateTitle")));
const bulkRegen = Array.from(
managerAfterTabSwitch.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
).find((b) => b.textContent?.includes(t("ai.chat.managerRegenerateTitle")));
assert.ok(bulkRegen, "bulk regenerate button present");
await dispatchDomEvent(bulkRegen, new dom.window.MouseEvent("click", { bubbles: true }));
assert.deepEqual(regenerated.sort(), ["s-a", "s-b"]);
const bulkDelete = Array.from(renderer.container.querySelectorAll<HTMLButtonElement>("button"))
.find((b) => b.textContent?.includes(t("common.delete")));
// Bulk delete is confirm-gated.
const bulkDelete = Array.from(
managerAfterTabSwitch.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
).find((b) => b.textContent?.includes(t("common.delete")));
assert.ok(bulkDelete, "bulk delete button present");
await dispatchDomEvent(bulkDelete, new dom.window.MouseEvent("click", { bubbles: true }));
assert.deepEqual(deletedMany, [], "no bulk deletion before confirmation");
const confirmButton = dom.document.body.querySelector<HTMLButtonElement>("button.bg-destructive");
assert.ok(confirmButton, "destructive confirm button rendered for bulk delete");
await dispatchDomEvent(confirmButton, new dom.window.MouseEvent("click", { bubbles: true }));
await new Promise((resolve) => setTimeout(resolve, 10));
assert.deepEqual(deletedMany, [["s-a", "s-b"]]);
assert.equal(
managerAfterTabSwitch.querySelector('[data-section="ai-global-session-selection-bar"]'),
null,
"selection mode exits after confirmed bulk delete",
);
} finally {
restoreGlobals();
dom.cleanup();
}
});
+161 -86
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { CheckSquare, Download, FolderInput, MoreHorizontal, Pencil, RefreshCw, Search, Square, Trash2, X } from 'lucide-react';
import type { AISession, ExternalAgentConfig } from '../../infrastructure/ai/types';
import { useI18n } from '../../application/i18n/I18nProvider';
@@ -15,6 +15,7 @@ import {
} from '../ui/select';
import { ConfirmDialog } from '../ui/confirm-dialog';
import { SESSION_HISTORY_ROW_CLASSNAMES } from './sessionHistoryLayout';
import { GlobalSessionSelectionContext } from './sessionHistorySelectionContext';
import { formatRelativeTime } from '../AIChatSessionHistoryDrawer';
import {
buildGlobalManagerRows,
@@ -60,6 +61,9 @@ interface GlobalAIChatSessionManagerProps {
/** Re-run LLM title generation for an existing chat (no placeholder gate). */
onRegenerateTitle?: (sessionId: string) => void;
onExport: (sessionId: string) => void;
/** Optional controlled selection mode; falls back to SessionHistoryDrawer context. */
selectionMode?: boolean;
onSelectionModeChange?: (active: boolean) => void;
}
const MANAGER_RENDER_BATCH = 80;
@@ -84,20 +88,41 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
onDeleteMany,
onRegenerateTitle,
onExport,
selectionMode: controlledSelectionMode,
onSelectionModeChange,
}) => {
const { t } = useI18n();
const selectionContext = useContext(GlobalSessionSelectionContext);
const [searchQuery, setSearchQuery] = useState('');
const [agentFilter, setAgentFilter] = useState<string>('all');
const [renderCount, setRenderCount] = useState(MANAGER_RENDER_BATCH);
const [deleteTarget, setDeleteTarget] = useState<AISession | null>(null);
const [bulkDeleteConfirmOpen, setBulkDeleteConfirmOpen] = useState(false);
const [moveSession, setMoveSession] = useState<AISession | null>(null);
const [openMenuSessionId, setOpenMenuSessionId] = useState<string | null>(null);
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
const [selectionMode, setSelectionMode] = useState(false);
const [uncontrolledSelectionMode, setUncontrolledSelectionMode] = useState(false);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [renameDraft, setRenameDraft] = useState('');
const renameInputRef = useRef<HTMLInputElement>(null);
const selectionMode =
controlledSelectionMode ?? selectionContext?.selectionMode ?? uncontrolledSelectionMode;
const setSelectionMode = useCallback(
(active: boolean) => {
if (controlledSelectionMode !== undefined) {
onSelectionModeChange?.(active);
} else if (selectionContext) {
selectionContext.setSelectionMode(active);
onSelectionModeChange?.(active);
} else {
setUncontrolledSelectionMode(active);
onSelectionModeChange?.(active);
}
},
[controlledSelectionMode, onSelectionModeChange, selectionContext],
);
const rows = useMemo(
() => buildGlobalManagerRows({
sessions,
@@ -136,6 +161,26 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
if (renamingSessionId) renameInputRef.current?.focus();
}, [renamingSessionId]);
useEffect(() => {
if (!selectionMode) {
setSelectedIds(new Set());
setBulkDeleteConfirmOpen(false);
}
}, [selectionMode]);
const rowSessionIds = useMemo(
() => new Set(rows.map((row) => row.session.id)),
[rows],
);
const activeSelectedIds = useMemo(() => {
if (selectedIds.size === 0) return selectedIds;
const next = new Set<string>();
selectedIds.forEach((id) => {
if (rowSessionIds.has(id)) next.add(id);
});
return next;
}, [selectedIds, rowSessionIds]);
const displayedRows = filteredRows.slice(0, renderCount);
const hiddenRowCount = Math.max(0, filteredRows.length - renderCount);
@@ -166,10 +211,24 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
return next;
});
};
const exitSelectionMode = () => {
const exitSelectionMode = useCallback(() => {
setSelectionMode(false);
setSelectedIds(new Set());
};
setBulkDeleteConfirmOpen(false);
}, [setSelectionMode]);
useEffect(() => {
if (!selectionMode || bulkDeleteConfirmOpen || renamingSessionId) return;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
event.preventDefault();
exitSelectionMode();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [selectionMode, bulkDeleteConfirmOpen, renamingSessionId, exitSelectionMode]);
const toggleSelectAll = () => {
const visibleIds = displayedRows.map((row) => row.session.id);
setSelectedIds((prev) => {
@@ -178,15 +237,15 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
});
};
const commitBulkDelete = () => {
if (selectedIds.size === 0) return;
const ids = [...selectedIds];
if (activeSelectedIds.size === 0) return;
const ids = [...activeSelectedIds];
if (onDeleteMany) onDeleteMany(ids);
else ids.forEach((id) => onDelete(id));
exitSelectionMode();
};
const commitBulkRegenerate = () => {
if (!onRegenerateTitle || selectedIds.size === 0) return;
selectedIds.forEach((id) => onRegenerateTitle(id));
if (!onRegenerateTitle || activeSelectedIds.size === 0) return;
activeSelectedIds.forEach((id) => onRegenerateTitle(id));
};
const getOtherMoveTargets = (session: AISession) =>
@@ -252,18 +311,6 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
</button>
)}
</div>
<button
type="button"
aria-label={t('ai.chat.managerToggleSelection')}
title={t('ai.chat.managerToggleSelection')}
onClick={() => (selectionMode ? exitSelectionMode() : setSelectionMode(true))}
className={cn(
'h-8 w-8 shrink-0 grid place-items-center rounded-md transition-colors cursor-pointer',
selectionMode ? 'bg-primary/15 text-primary' : 'text-muted-foreground/60 hover:text-foreground hover:bg-muted',
)}
>
<CheckSquare size={14} />
</button>
{showAgentMeta && (
<Select value={effectiveAgentFilter} onValueChange={setAgentFilter}>
<SelectTrigger
@@ -286,24 +333,29 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
)}
</div>
{selectionMode && (
<div className="px-3 py-1.5 shrink-0 border-b border-border/30 flex items-center gap-2 text-[12px]">
<div
className="px-3 py-1.5 shrink-0 border-b border-border/30 bg-muted/30 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px]"
data-section="ai-global-session-selection-bar"
>
<button
type="button"
onClick={toggleSelectAll}
className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer"
className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground whitespace-nowrap cursor-pointer"
>
{displayedRows.length > 0 && displayedRows.every((row) => selectedIds.has(row.session.id))
? <CheckSquare size={13} /> : <Square size={13} />}
{displayedRows.length > 0 && displayedRows.every((row) => activeSelectedIds.has(row.session.id))
? <CheckSquare size={13} className="text-primary" /> : <Square size={13} />}
{t('ai.chat.managerSelectAll')}
</button>
<span className="text-muted-foreground/60">{t('ai.chat.managerSelectedCount', { n: String(selectedIds.size) })}</span>
<div className="ml-auto flex items-center gap-2">
<span className="text-muted-foreground/60 whitespace-nowrap">
{t('ai.chat.managerSelectedCount', { n: String(activeSelectedIds.size) })}
</span>
<div className="ml-auto flex items-center gap-1">
{onRegenerateTitle && (
<button
type="button"
disabled={selectedIds.size === 0}
disabled={activeSelectedIds.size === 0}
onClick={commitBulkRegenerate}
className="flex items-center gap-1 rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 cursor-pointer"
className="flex items-center gap-1 rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 whitespace-nowrap cursor-pointer"
>
<RefreshCw size={12} />
{t('ai.chat.managerRegenerateTitle')}
@@ -311,13 +363,20 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
)}
<button
type="button"
disabled={selectedIds.size === 0}
onClick={commitBulkDelete}
className="flex items-center gap-1 rounded px-2 py-1 text-destructive hover:bg-destructive/10 disabled:opacity-40 cursor-pointer"
disabled={activeSelectedIds.size === 0}
onClick={() => setBulkDeleteConfirmOpen(true)}
className="flex items-center gap-1 rounded px-2 py-1 text-destructive hover:bg-destructive/10 disabled:opacity-40 whitespace-nowrap cursor-pointer"
>
<Trash2 size={12} />
{t('common.delete')}
</button>
<button
type="button"
onClick={exitSelectionMode}
className="rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted whitespace-nowrap cursor-pointer"
>
{t('common.cancel')}
</button>
</div>
</div>
)}
@@ -362,7 +421,7 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
<React.Fragment key={row.session.id}>
<div
role="button"
tabIndex={row.canActivate ? 0 : -1}
tabIndex={selectionMode || row.canActivate ? 0 : -1}
onClick={() => {
if (selectionMode) {
toggleSelected(row.session.id);
@@ -389,87 +448,91 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
row.isCurrentActive
? 'text-foreground'
: 'text-foreground/75 hover:text-foreground',
!row.canActivate && 'cursor-default',
!selectionMode && !row.canActivate && 'cursor-default',
)}
data-session-id={row.session.id}
data-scope-state={row.scopeState}
>
<div className="min-w-0">
<div className={cn('min-w-0', selectionMode && 'flex items-center gap-2.5')}>
{selectionMode && (
<button
type="button"
aria-label={t('ai.chat.managerSelectRow')}
aria-pressed={activeSelectedIds.has(row.session.id)}
onClick={(e) => {
e.stopPropagation();
toggleSelected(row.session.id);
}}
className="float-left mr-2 mt-0.5 text-muted-foreground/60 hover:text-primary cursor-pointer"
className="shrink-0 text-muted-foreground/60 hover:text-primary cursor-pointer"
>
{selectedIds.has(row.session.id)
{activeSelectedIds.has(row.session.id)
? <CheckSquare size={14} className="text-primary" />
: <Square size={14} />}
</button>
)}
<div className="flex items-center gap-1.5 min-w-0">
{row.isCurrentActive && (
<span
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
aria-hidden
/>
)}
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
{isRenaming ? (
<Input
ref={renameInputRef}
type="text"
value={renameDraft}
aria-label={t('ai.chat.renameChat')}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === 'Enter') {
e.preventDefault();
commitRename();
} else if (e.key === 'Escape') {
e.preventDefault();
setRenamingSessionId(null);
setRenameDraft('');
}
}}
onChange={(e) => setRenameDraft(e.target.value)}
onBlur={commitRename}
className="h-6 text-[12px]"
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5 min-w-0">
{row.isCurrentActive && (
<span
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
aria-hidden
/>
) : (
row.title
)}
</span>
{row.isActiveElsewhere && (
<span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground/75">
{t('ai.chat.managerBadgeActive')}
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
{isRenaming ? (
<Input
ref={renameInputRef}
type="text"
value={renameDraft}
aria-label={t('ai.chat.renameChat')}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === 'Enter') {
e.preventDefault();
commitRename();
} else if (e.key === 'Escape') {
e.preventDefault();
setRenamingSessionId(null);
setRenameDraft('');
}
}}
onChange={(e) => setRenameDraft(e.target.value)}
onBlur={commitRename}
className="h-6 text-[12px]"
/>
) : (
row.title
)}
</span>
{row.isActiveElsewhere && (
<span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground/75">
{t('ai.chat.managerBadgeActive')}
</span>
)}
</div>
{subtitleParts.length > 0 && (
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/70 min-w-0">
{subtitleParts.map((part, index) => (
<React.Fragment key={`${row.session.id}-meta-${index}`}>
{index > 0 && <span aria-hidden>·</span>}
<span className={cn(
part.truncate ? 'truncate' : 'shrink-0',
part.bold && 'font-medium',
)}>
{part.text}
</span>
</React.Fragment>
))}
</div>
)}
</div>
{subtitleParts.length > 0 && (
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/70 min-w-0">
{subtitleParts.map((part, index) => (
<React.Fragment key={`${row.session.id}-meta-${index}`}>
{index > 0 && <span aria-hidden>·</span>}
<span className={cn(
part.truncate ? 'truncate' : 'shrink-0',
part.bold && 'font-medium',
)}>
{part.text}
</span>
</React.Fragment>
))}
</div>
)}
</div>
<div className={SESSION_HISTORY_ROW_CLASSNAMES.meta}>
<span className={SESSION_HISTORY_ROW_CLASSNAMES.time}>
{formatRelativeTime(new Date(row.session.updatedAt), t)}
</span>
{!selectionMode && (
<Dropdown
open={isMenuOpen}
onOpenChange={(open) => setOpenMenuSessionId(open ? row.session.id : null)}
@@ -562,6 +625,7 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
</button>
</DropdownContent>
</Dropdown>
)}
</div>
</div>
{moveSession?.id === row.session.id && (
@@ -622,6 +686,17 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
}}
onConfirm={commitDelete}
/>
<ConfirmDialog
open={bulkDeleteConfirmOpen && activeSelectedIds.size > 0}
title={t('ai.chat.managerBulkDeleteTitle', { n: String(activeSelectedIds.size) })}
message={t('ai.chat.managerBulkDeleteMessage', { n: String(activeSelectedIds.size) })}
confirmLabel={t('common.delete')}
destructive
onOpenChange={(open) => {
if (!open) setBulkDeleteConfirmOpen(false);
}}
onConfirm={commitBulkDelete}
/>
</div>
);
};
@@ -0,0 +1,9 @@
import { createContext } from 'react';
export interface GlobalSessionSelectionContextValue {
selectionMode: boolean;
setSelectionMode: (active: boolean) => void;
}
export const GlobalSessionSelectionContext =
createContext<GlobalSessionSelectionContextValue | null>(null);
+17
View File
@@ -343,6 +343,23 @@ function createBridgeRegistrar(context) {
isAppLocked: () => getAppLockController?.()?.getRuntimeState?.()?.locked !== false,
subscribeAppLock: (listener) => getAppLockController?.()?.subscribe?.(listener),
getLocale: () => getWindowManager().getCurrentLanguage?.() ?? "en",
onRuntimeFailure: ({ kind, pluginId, pluginVersion, runtimeId, runtimeKind, crashCount, quarantined, error }) => {
crashLogBridge.captureError("plugin-runtime", error ?? new Error(`Plugin runtime failure (${kind})`), {
kind,
pluginId,
pluginVersion,
runtimeId,
runtimeKind,
crashCount,
quarantined,
});
},
onViewDiagnostic: (kind, message, extra) => {
crashLogBridge.captureDiagnostic("plugin-view", message, {
kind,
...(extra && typeof extra === "object" ? extra : {}),
});
},
requestTerminalInterceptorSelection: async ({ direction, providers }) => {
const messages = terminalInterceptorMessages(getWindowManager().getCurrentLanguage?.() ?? "en");
const buttons = [
+17 -3
View File
@@ -10,6 +10,11 @@ const { invalidArgument, freezeJson } = require("./validationUtils.cjs");
const { InteractiveCommandFeature, InteractiveCommandLimits } = require("./generated/plugin-contract.schema.json").$defs;
const MAX_SETTING_BYTES = 128 * 1024;
// Host-drawn view updates may carry up to MAX_BATCH_BYTES (1 MiB) of remote DOM
// mutations plus MAX_CSS_LENGTH (128 KiB) of stylesheet text and JSON escaping
// overhead; keep a dedicated view-message cap aligned with those downstream
// policies instead of reusing the 128 KiB setting cap.
const MAX_VIEW_MESSAGE_BYTES = 2 * 1024 * 1024;
const MAX_PATTERN_LENGTH = 512;
const MAX_PATTERN_VALUE_LENGTH = 4_096;
const MAX_SCOPE_ID_LENGTH = 256;
@@ -19,8 +24,8 @@ function notFound(message) {
return new PluginRpcError(RPC_ERRORS.notFound, message);
}
function assertJsonValue(value, label = "value") {
try { assertPluginJsonValue(value, { maxBytes: MAX_SETTING_BYTES }); }
function assertJsonValue(value, label = "value", maxBytes = MAX_SETTING_BYTES) {
try { assertPluginJsonValue(value, { maxBytes }); }
catch (error) {
throw invalidArgument(`Plugin ${label} must be a bounded JSON value: ${error?.message ?? error}`);
}
@@ -201,7 +206,15 @@ class PluginContributionService {
});
registry.registerNotification("views.postMessage", (params, context) => {
const view = this.#assertOwnedContribution(context.manifest, "views", params?.viewId, context.pluginId);
assertJsonValue(params?.message, "view message");
const isHostUiUpdate = params?.message
&& typeof params.message === "object"
&& !Array.isArray(params.message)
&& params.message.kind === "host-ui.update";
assertJsonValue(
params?.message,
"view message",
isHostUiUpdate ? MAX_VIEW_MESSAGE_BYTES : MAX_SETTING_BYTES,
);
const event = freezeJson({ pluginId: context.pluginId, viewId: view.id, message: params.message });
for (const listener of [...this.viewMessageListeners]) {
try { listener(event); } catch {}
@@ -611,6 +624,7 @@ class PluginContributionService {
module.exports = {
MAX_SETTING_BYTES,
MAX_VIEW_MESSAGE_BYTES,
MAX_PATTERN_VALUE_LENGTH,
PluginContributionService,
assertJsonValue,
+58 -1
View File
@@ -6,7 +6,7 @@ const os = require("node:os");
const path = require("node:path");
const test = require("node:test");
const { assertJsonValue, MAX_SETTING_BYTES, PluginContributionService } = require("./contributionService.cjs");
const { assertJsonValue, MAX_SETTING_BYTES, MAX_VIEW_MESSAGE_BYTES, PluginContributionService } = require("./contributionService.cjs");
const { PluginDatabase } = require("./database.cjs");
const { PluginHostRpcRegistry } = require("./hostRpcRegistry.cjs");
const { PluginPermissionEngine } = require("./permissionEngine.cjs");
@@ -740,3 +740,60 @@ test("host settings groups are localized and preferences persist without activat
await service.resetSetting(pluginManifest.id, settingId);
assert.equal(snapshot().value, "hello");
});
test("views.postMessage allows view payloads above MAX_SETTING_BYTES up to MAX_VIEW_MESSAGE_BYTES", async (t) => {
const pluginManifest = manifest();
pluginManifest.permissions = { required: ["views"] };
const { service, database } = setup(t, pluginManifest);
const registry = new PluginHostRpcRegistry();
const permissionEngine = new PluginPermissionEngine({ database });
permissionEngine.setMode(database.getActivePlugin(pluginManifest.id), "views", "allow");
registry.use(permissionEngine.createMiddleware());
service.registerRpcCapabilities(registry);
const delivered = [];
service.onDidPostViewMessage((event) => delivered.push(event));
const routes = registry.createRoutes({
pluginId: pluginManifest.id,
pluginVersion: pluginManifest.version,
runtimeId: "runtime-views-budget",
runtimeKind: "browser",
manifest: pluginManifest,
assertCurrent() {},
});
const transport = { signal: new AbortController().signal };
// A 256 KiB host-ui.update payload exceeds MAX_SETTING_BYTES (128 KiB) but
// must succeed within MAX_VIEW_MESSAGE_BYTES (2 MiB).
const largeMessage = {
kind: "host-ui.update",
instanceId: "inst-large",
sequence: 1,
css: ".x{display:grid}",
mutations: [[0, "~", { id: "1", type: 3, data: "a".repeat(MAX_SETTING_BYTES + 64 * 1024) }, 0]],
};
await routes.notificationHandlers["views.postMessage"](
{ viewId: `${pluginManifest.id}.view`, message: largeMessage },
transport,
);
assert.equal(delivered.length, 1);
assert.equal(delivered[0].message.instanceId, "inst-large");
// Non-host-ui.update view messages keep the tighter MAX_SETTING_BYTES cap.
await assert.rejects(
() => Promise.resolve(routes.notificationHandlers["views.postMessage"](
{ viewId: `${pluginManifest.id}.view`, message: { kind: "custom.event", payload: "x".repeat(MAX_SETTING_BYTES) } },
transport,
)),
/Plugin view message must be a bounded JSON value/,
);
// host-ui.update payloads exceeding MAX_VIEW_MESSAGE_BYTES must still be rejected.
await assert.rejects(
() => Promise.resolve(routes.notificationHandlers["views.postMessage"](
{ viewId: `${pluginManifest.id}.view`, message: { kind: "host-ui.update", payload: "x".repeat(MAX_VIEW_MESSAGE_BYTES) } },
transport,
)),
/Plugin view message must be a bounded JSON value/,
);
});
@@ -4215,6 +4215,9 @@
"stateScope": {
"type": "string",
"maxLength": 128
},
"supportsOptionalCss": {
"type": "boolean"
}
},
"additionalProperties": false
@@ -4243,8 +4246,7 @@
"kind",
"instanceId",
"sequence",
"mutations",
"css"
"mutations"
],
"properties": {
"kind": {
+86 -12
View File
@@ -2,21 +2,36 @@
const { createHash } = require("node:crypto");
const { createDefinitionValidator } = require("./contractValidator.cjs");
const { redactLogValue } = require("./pluginLogger.cjs");
const { describePluginRuntime } = require("../../domain/pluginRuntimePolicy.cjs");
const { validatePluginMutationBatch } = require("../../domain/pluginRemoteTreePolicy.cjs");
const { validatePluginStylesheet } = require("../../domain/pluginViewStylePolicy.cjs");
const validateMessage = createDefinitionValidator("HostDrawnViewMessage");
const validateOpen = createDefinitionValidator("HostDrawnViewOpenRequest");
const validateEvent = createDefinitionValidator("HostDrawnViewEvent");
const DIAGNOSTIC_WINDOW_MS = 60_000;
const DIAGNOSTIC_MAX_PER_WINDOW = 5;
const DIAGNOSTIC_MAX_KEYS = 256;
function sanitizeViewErrorReason(error) {
if (error?.remote === true) {
const code = Number.isInteger(error.code) ? error.code : "unknown";
return `Remote plugin RPC error (code ${code})`;
}
const raw = error instanceof Error ? error.message : String(error ?? "unknown");
return String(redactLogValue(raw)).slice(0, 512);
}
/** Owns logical views only: never creates a native view or exposes plugin code to the host. */
class HostDrawnViewHost {
constructor({ electron, contributionService, resources, packageStore, permissionEngine, runtimePool, isLocked = () => false, subscribeLock, logger = console }) {
constructor({ electron, contributionService, resources, packageStore, permissionEngine, runtimePool, isLocked = () => false, subscribeLock, logger = console, onDiagnostic = null }) {
this.resources = resources;
this.packageStore = packageStore ?? null;
this.permissionEngine = permissionEngine ?? null;
this.runtimePool = runtimePool ?? null;
this.logger = logger ?? null;
this.onDiagnostic = typeof onDiagnostic === "function" ? onDiagnostic : null;
this.diagnosticWindows = new Map();
this.electron = electron; this.contributions = contributionService; this.isLocked = isLocked;
this.instances = new Map(); this.opening = new Map(); this.activationWaiters = new Set(); this.closed = false;
this.messageSubscription = contributionService.onDidPostViewMessage((event) => this.receive(event));
@@ -37,6 +52,32 @@ class HostDrawnViewHost {
for (const id of [...this.instances.keys()]) void this.close(id, undefined, "app-locked");
});
}
#emitDiagnostic(kind, pluginId, summary, extra = {}) {
if (!this.onDiagnostic || this.isLocked()) return;
const key = `${pluginId ?? "unknown"}:${kind}`;
const now = Date.now();
let entry = this.diagnosticWindows.get(key);
if (!entry || now - entry.start >= DIAGNOSTIC_WINDOW_MS) {
if (!entry && this.diagnosticWindows.size >= DIAGNOSTIC_MAX_KEYS) {
const oldestKey = this.diagnosticWindows.keys().next().value;
if (oldestKey !== undefined) this.diagnosticWindows.delete(oldestKey);
}
entry = { start: now, count: 0 };
this.diagnosticWindows.set(key, entry);
}
if (entry.count >= DIAGNOSTIC_MAX_PER_WINDOW) return;
entry.count += 1;
const safeSummary = String(redactLogValue(summary)).slice(0, 512);
const safeExtra = {};
for (const [field, value] of Object.entries(extra)) {
safeExtra[field] = typeof value === "string"
? String(redactLogValue(value)).slice(0, 512)
: value;
}
try {
this.onDiagnostic(kind, safeSummary, safeExtra);
} catch {}
}
owned(id, sender) {
const instance = this.instances.get(id);
if (!instance) throw new Error("Plugin view was not found");
@@ -77,7 +118,7 @@ class HostDrawnViewHost {
};
this.instances.set(id, instance);
owner.once("closed", instance.ownerClosed); sender.on("render-process-gone", instance.rendererGone); sender.on("did-start-navigation", instance.navigating);
instance.startPromise = this.contributions.runtimeSupervisor.notify(plugin.id, "plugin.view.message", { viewId: view.id, message: { kind: "host-ui.open", instanceId: id, stateScope: createHash("sha256").update(payload.scopeId).digest("hex") } }, { expectedIdentity: identity });
instance.startPromise = this.contributions.runtimeSupervisor.notify(plugin.id, "plugin.view.message", { viewId: view.id, message: { kind: "host-ui.open", instanceId: id, stateScope: createHash("sha256").update(payload.scopeId).digest("hex"), supportsOptionalCss: true } }, { expectedIdentity: identity });
await instance.startPromise;
ensure();
this.contributions.assertViewActivationCurrent(activation, { context: payload.context });
@@ -86,6 +127,19 @@ class HostDrawnViewHost {
this.#notifyInstanceReady(instance);
return { instanceId: id };
} catch (error) {
if (!opening.cancelled && !this.closed && !this.isLocked()) {
const reason = sanitizeViewErrorReason(error);
this.#emitDiagnostic(
"open-failed",
null,
`Failed to open plugin view ${payload.viewId}: ${reason}`,
{
viewId: payload.viewId,
instanceId: id,
reason,
},
);
}
await this.close(id, undefined, "open-failed");
throw error;
} finally {
@@ -97,9 +151,19 @@ class HostDrawnViewHost {
const message = event.message;
if (!validateMessage(message) || message.kind !== "host-ui.update") {
if (message && typeof message === "object" && message.kind === "host-ui.update") {
this.logger?.warn?.(
`[HostDrawnViewHost] Dropped schema-invalid update for ${event.viewId ?? "unknown"} (${event.pluginId ?? "unknown"})`,
);
const summary = `Dropped schema-invalid update for ${event.viewId ?? "unknown"} (${event.pluginId ?? "unknown"})`;
this.logger?.warn?.(`[HostDrawnViewHost] ${summary}`);
const knownInstanceId = typeof message.instanceId === "string"
&& message.instanceId.length <= 128
&& this.instances.has(message.instanceId)
? message.instanceId
: null;
this.#emitDiagnostic("schema-invalid-update", event.pluginId ?? null, summary, {
pluginId: event.pluginId ?? null,
viewId: event.viewId ?? null,
instanceId: knownInstanceId,
sequence: typeof message.sequence === "number" && Number.isSafeInteger(message.sequence) ? message.sequence : null,
});
}
return;
}
@@ -112,11 +176,13 @@ class HostDrawnViewHost {
if (now - instance.rateStart >= 1000) { instance.rateStart = now; instance.rateCount = 0; }
if (++instance.rateCount > 120) throw new Error("Plugin view update rate exceeded");
validatePluginMutationBatch(message.mutations);
const cssUnchanged = instance.lastRawCss !== null && message.css === instance.lastRawCss;
const cssOmitted = message.css === undefined;
const cssUnchanged = instance.lastRawCss !== null && (cssOmitted || message.css === instance.lastRawCss);
let canonicalCss = instance.lastCanonicalCss;
if (!cssUnchanged) {
canonicalCss = validatePluginStylesheet(message.css);
instance.lastRawCss = message.css;
const rawCss = cssOmitted ? "" : message.css;
canonicalCss = validatePluginStylesheet(rawCss);
instance.lastRawCss = rawCss;
instance.lastCanonicalCss = canonicalCss;
}
instance.sequence = message.sequence;
@@ -127,10 +193,18 @@ class HostDrawnViewHost {
instance.sender.send("netcatty:plugins:host-ui-update", outgoing);
}
} catch (error) {
const reason = error instanceof Error ? error.message : String(error);
this.logger?.warn?.(
`[HostDrawnViewHost] Closing view ${instance.viewId} (${instance.pluginId}) after invalid update #${message.sequence}: ${reason}`,
);
const reason = sanitizeViewErrorReason(error);
const summary = `Closing view ${instance.viewId} (${instance.pluginId}) after invalid update #${message.sequence}: ${reason}`;
this.logger?.warn?.(`[HostDrawnViewHost] ${summary}`);
this.#emitDiagnostic("invalid-update", instance.pluginId, summary, {
pluginId: instance.pluginId,
viewId: instance.viewId,
instanceId: instance.id,
sequence: message.sequence,
mutationCount: Array.isArray(message.mutations) ? message.mutations.length : null,
cssLength: typeof message.css === "string" ? message.css.length : null,
reason,
});
void this.close(instance.id, undefined, "invalid-update");
}
}
+46 -4
View File
@@ -15,8 +15,16 @@ function fixture(resources) {
runtimeSupervisor: { async notify(...args) { notifications.push(args); } },
};
const warnings = [];
const host = new HostDrawnViewHost({ electron: { BrowserWindow: { fromWebContents: (s) => s === sender ? owner : null } }, contributionService: contributions, resources, isLocked: () => locked, logger: { warn: (msg) => warnings.push(msg) } });
return { host, sender, other, owner, notifications, warnings, message: (message, overrides = {}) => onMessage({ pluginId: identity.pluginId, viewId: "com.test.plugin.view", message, ...overrides }), change: (event) => onChange(event), lock() { locked = true; }, stale() { valid = false; } };
const diagnostics = [];
const host = new HostDrawnViewHost({
electron: { BrowserWindow: { fromWebContents: (s) => s === sender ? owner : null } },
contributionService: contributions,
resources,
isLocked: () => locked,
logger: { warn: (msg) => warnings.push(msg) },
onDiagnostic: (kind, message, extra) => diagnostics.push({ kind, message, extra }),
});
return { host, sender, other, owner, notifications, warnings, diagnostics, message: (message, overrides = {}) => onMessage({ pluginId: identity.pluginId, viewId: "com.test.plugin.view", message, ...overrides }), change: (event) => onChange(event), lock() { locked = true; }, stale() { valid = false; } };
}
const open = (f) => f.host.open({ viewId: "com.test.plugin.view", instanceId: "instance-1", scopeId: "scope", context: {} }, f.sender);
const update = (sequence = 1) => ({ kind: "host-ui.update", instanceId: "instance-1", sequence, css: '.x{display:grid}', mutations: [[0, "~", { id: "1", type: 1, element: "div", attributes: {}, children: [] }, 0]] });
@@ -87,15 +95,49 @@ test("updates are rate limited and resource caches are bounded", async () => {
assert.equal(f.host.instances.size, 0); await f.host.shutdown();
});
test("unchanged CSS is deduplicated over internal host-to-renderer IPC", async () => {
test("unchanged CSS is deduplicated over internal host-to-renderer IPC and omitted CSS is accepted", async () => {
const f = fixture(); await open(f);
assert.equal(f.notifications[0][2].message.supportsOptionalCss, true);
f.message(update(1));
f.message(update(2));
assert.equal(f.sender.sent.length, 2);
const omittedCssUpdate = { kind: "host-ui.update", instanceId: "instance-1", sequence: 3, mutations: [] };
f.message(omittedCssUpdate);
assert.equal(f.sender.sent.length, 3);
assert.equal(f.sender.sent[0][1].css, ".x{display:grid}");
assert.equal(f.sender.sent[0][1].cssUnchanged, undefined);
assert.equal(f.sender.sent[1][1].css, "");
assert.equal(f.sender.sent[1][1].cssUnchanged, true);
assert.equal(f.sender.sent[2][1].css, "");
assert.equal(f.sender.sent[2][1].cssUnchanged, true);
await f.host.shutdown();
});
test("diagnostics hook receives schema-invalid and invalid-update events with rate limiting and safe fields", async () => {
const f = fixture(); await open(f);
// Untrusted oversized instanceId must never be logged verbatim, and spam is rate-limited.
for (let i = 0; i < 10; i++) {
f.message({ kind: "host-ui.update", instanceId: "secret-".repeat(100), sequence: 0, mutations: [] });
}
assert.equal(f.diagnostics.length, 5);
assert.equal(f.diagnostics[0].kind, "schema-invalid-update");
assert.equal(f.diagnostics[0].extra.instanceId, null);
f.message(update(2));
assert.equal(f.diagnostics.length, 6);
assert.equal(f.diagnostics[5].kind, "invalid-update");
assert.equal(f.diagnostics[5].extra.pluginId, "com.test.plugin");
assert.match(f.diagnostics[5].extra.reason, /Invalid view update sequence/);
await f.host.shutdown();
});
test("sequence 1 with omitted css defaults cleanly to empty stylesheet", async () => {
const f = fixture(); await open(f);
f.message({ kind: "host-ui.update", instanceId: "instance-1", sequence: 1, mutations: [] });
assert.equal(f.sender.sent.length, 1);
assert.equal(f.sender.sent[0][1].css, "");
assert.equal(f.sender.sent[0][1].cssUnchanged, undefined);
f.message({ kind: "host-ui.update", instanceId: "instance-1", sequence: 2, mutations: [] });
assert.equal(f.sender.sent[1][1].cssUnchanged, true);
await f.host.shutdown();
});
+2
View File
@@ -388,6 +388,7 @@ function createPluginHostService(options) {
resolveRuntimeKind,
resolveSecurityPrincipal: options.resolveSecurityPrincipal,
runtimeMessageGuard,
onRuntimeFailure: options.onRuntimeFailure,
getInitialEnvironment: () => contributionService.getEnvironment(),
runtimeResourceMonitor: quotaManager,
runtimeCleanup: async (identity) => {
@@ -604,6 +605,7 @@ function createPluginHostService(options) {
}),
isLocked: options.isAppLocked,
subscribeLock: options.subscribeAppLock,
onDiagnostic: options.onViewDiagnostic,
})
: null;
viewOpenService = new PluginViewOpenService({
+470 -118
View File
@@ -12,6 +12,18 @@ const fail = (code, message) => new PluginRpcError(RPC_ERRORS[code], message);
const DEFAULT_IDLE_TTL_MS = 120_000;
const DEFAULT_MAX_CONCURRENT_PER_RUNTIME = 16;
const DEFAULT_MAX_CONCURRENT_TOTAL = 64;
// Tighter than interactive SSH defaults (20s TCP / 120s auth) so background
// plugin dials fail with a clear timeout before the ~30s plugin RPC deadline
// (interactive prompts such as host-key/passphrase/2FA still share that RPC budget).
const DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS = 8_000;
const DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS = 8_000;
const DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS = 18_000;
// resolveSshConnectionTimeouts() ignores values below 1000ms and falls back to 20s/120s.
const MIN_SSH_CONNECT_STAGE_TIMEOUT_MS = 1_000;
function positiveMs(value, fallback) {
return Number.isFinite(value) && value > 0 ? Math.round(value) : fallback;
}
let vendorDetectorPromise = null;
function loadVendorDetector() {
@@ -41,13 +53,25 @@ class PluginHostSshExecTransport {
this.idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
this.maxConcurrentPerRuntime = options.maxConcurrentPerRuntime ?? DEFAULT_MAX_CONCURRENT_PER_RUNTIME;
this.maxConcurrentTotal = options.maxConcurrentTotal ?? DEFAULT_MAX_CONCURRENT_TOTAL;
this.sshTcpConnectTimeoutMs = positiveMs(
options.sshTcpConnectTimeoutMs,
DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS,
);
this.sshAuthReadyTimeoutMs = positiveMs(
options.sshAuthReadyTimeoutMs,
DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS,
);
this.sshDialEnvelopeMs = positiveMs(
options.sshDialEnvelopeMs,
DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS,
);
this.clock = options.clock ?? Date.now;
this.isLocked = options.isLocked ?? (() => false);
this.getSender = options.getSender ?? (() => null);
/** @type {Map<string, object>} `${runtimeId}\0${hostId}` -> pooled entry */
this.connections = new Map();
/** @type {Map<string, Promise<object>>} `${runtimeId}\0${hostId}` -> in-flight dial */
/** @type {Map<string, object>} `${runtimeId}\0${hostId}` -> in-flight dial record */
this.pendingDials = new Map();
/** @type {Set<{ controller: AbortController, runtimeId: string, pluginId: string, hostId: string }>} */
this.activeExecs = new Set();
@@ -69,10 +93,165 @@ class PluginHostSshExecTransport {
#isEntryHealthy(entry) {
if (!entry || entry.closed || !entry.conn) return false;
const sock = entry.conn._sock;
if (sock && (sock.destroyed || sock.writableEnded)) return false;
if (sock && (
sock.destroyed
|| sock.writableEnded
|| sock.readableEnded
|| sock.writableFinished
|| sock.writable === false
|| sock.readyState === "closed"
|| sock.readyState === "readOnly"
)) {
return false;
}
return true;
}
#isDeadlineAbort(signal) {
if (!signal?.aborted) return false;
const reason = signal.reason;
if (!reason) return false;
if (reason.code === RPC_ERRORS.deadlineExceeded) return true;
const message = typeof reason === "string" ? reason : String(reason?.message ?? "");
return /plugin (?:request|notification) deadline exceeded/i.test(message);
}
#isConnectTimeoutError(err) {
if (!err) return false;
if (err?.code === "ETIMEDOUT" || err?.code === RPC_ERRORS.deadlineExceeded) return true;
const message = typeof err === "string" ? err : String(err?.message ?? "");
return /\btimed?\s*out\b|\btimeout\b/i.test(message);
}
#callerAbortError(signal, fallbackMessage = "SSH connection was cancelled") {
if (signal?.reason instanceof PluginRpcError) return signal.reason;
if (this.#isDeadlineAbort(signal)) {
return fail("deadlineExceeded", "Plugin request deadline exceeded");
}
return fail("cancelled", fallbackMessage);
}
#dialAbortError(dialRecord) {
if (dialRecord.timedOut) {
return fail("deadlineExceeded", "SSH connection timed out");
}
const reason = dialRecord.controller.signal.reason;
if (reason instanceof PluginRpcError) return reason;
if (dialRecord.cancelledByWaiters) {
return fail("cancelled", "SSH connection was cancelled");
}
return fail("unavailable", "Host SSH execution is unavailable");
}
#isStopConfirmed(result) {
return result?.success === true;
}
#clearStopRetryTimer(dialRecord) {
if (dialRecord?.stopRetryTimer) {
clearTimeout(dialRecord.stopRetryTimer);
dialRecord.stopRetryTimer = null;
}
}
#scheduleStopRetry(dialRecord) {
if (
!dialRecord
|| !dialRecord.tunnelId
|| !dialRecord.stopRequested
|| dialRecord.stopConfirmed
|| dialRecord.dialDone
|| dialRecord.settled
|| dialRecord.stopRetryTimer
) {
return;
}
const maxAttempts = Math.min(200, Math.max(25, Math.ceil(this.sshDialEnvelopeMs / 100)));
const attempt = dialRecord.stopRetryAttempts ?? 0;
if (attempt >= maxAttempts) {
return;
}
const delayMs = Math.min(100, 10 * (2 ** Math.min(attempt, 4)));
dialRecord.stopRetryAttempts = attempt + 1;
dialRecord.stopRetryTimer = setTimeout(() => {
dialRecord.stopRetryTimer = null;
if (
!dialRecord.stopRequested
|| dialRecord.stopConfirmed
|| dialRecord.dialDone
|| dialRecord.settled
) {
return;
}
void this.#stopDialTunnel(dialRecord);
}, delayMs);
dialRecord.stopRetryTimer.unref?.();
}
async #stopDialTunnel(dialRecord, { afterDialReturn = false } = {}) {
if (!dialRecord?.tunnelId) return false;
dialRecord.stopRequested = true;
this.#clearStopRetryTimer(dialRecord);
if (dialRecord.stopConfirmed) return true;
if (dialRecord.stopInFlight) {
if (!afterDialReturn) {
return dialRecord.stopInFlight;
}
while (dialRecord.stopInFlight) {
await dialRecord.stopInFlight;
}
if (dialRecord.stopConfirmed) return true;
}
const { tunnelId, sender } = dialRecord;
const stopPromise = (async () => {
try {
hostKeyVerifier.cancelRequestsForSession(tunnelId);
} catch { /* ignore */ }
let result = null;
try {
result = await this.#bridge().stopPortForward({ sender }, { tunnelId });
} catch {
result = null;
}
if (this.#isStopConfirmed(result)) {
dialRecord.stopConfirmed = true;
this.#clearStopRetryTimer(dialRecord);
return true;
}
if (!dialRecord.dialDone && !dialRecord.settled && dialRecord.stopRequested) {
this.#scheduleStopRetry(dialRecord);
}
return false;
})();
const tracked = stopPromise.finally(() => {
if (dialRecord.stopInFlight === tracked) {
dialRecord.stopInFlight = null;
}
});
dialRecord.stopInFlight = tracked;
return tracked;
}
#cancelPendingDial(dialRecord, reason) {
if (!dialRecord) return;
dialRecord.stopRequested = true;
if (dialRecord.envelopeTimer) {
clearTimeout(dialRecord.envelopeTimer);
dialRecord.envelopeTimer = null;
}
if (this.pendingDials.get(dialRecord.key) === dialRecord) {
this.pendingDials.delete(dialRecord.key);
}
if (!dialRecord.settled && dialRecord.tunnelId) {
void this.#stopDialTunnel(dialRecord);
}
if (!dialRecord.controller.signal.aborted) {
dialRecord.controller.abort(reason);
}
}
#touchIdleTimer(entry) {
if (entry.idleTimer) clearTimeout(entry.idleTimer);
if (entry.closed || this.idleTtlMs <= 0) return;
@@ -102,6 +281,9 @@ class PluginHostSshExecTransport {
}
async #dialEntry({ runtimeId, pluginId, hostId, prepareConnection, signal }) {
if (signal?.aborted) {
throw this.#callerAbortError(signal);
}
const key = this.#key(runtimeId, hostId);
const existing = this.connections.get(key);
if (this.#isEntryHealthy(existing)) {
@@ -111,126 +293,280 @@ class PluginHostSshExecTransport {
void this.#closeEntry(existing);
}
const raceCallerSignal = (promise) => {
if (!signal) return promise;
if (signal.aborted) return Promise.reject(fail("cancelled", "SSH connection was cancelled"));
const attachWaiter = (dialRecord) => {
if (signal?.aborted) {
return Promise.reject(this.#callerAbortError(signal));
}
if (dialRecord.controller.signal.aborted && !dialRecord.settled) {
return Promise.reject(this.#dialAbortError(dialRecord));
}
dialRecord.waiterCount += 1;
let released = false;
const releaseWaiter = (abortedByCaller) => {
if (released) return;
released = true;
dialRecord.waiterCount = Math.max(0, dialRecord.waiterCount - 1);
// Tear down the shared dial only when the last waiter leaves while
// still in flight so retries do not hitchhike on a wedged handshake.
// Keep dialing when another waiter remains, and never stop a settled entry.
if (abortedByCaller && dialRecord.waiterCount === 0 && !dialRecord.settled) {
dialRecord.cancelledByWaiters = true;
this.#cancelPendingDial(dialRecord, fail("cancelled", "SSH connection was cancelled"));
}
};
return new Promise((resolve, reject) => {
const onAbort = () => reject(fail("cancelled", "SSH connection was cancelled"));
signal.addEventListener("abort", onAbort, { once: true });
promise.then(
(val) => { signal.removeEventListener("abort", onAbort); resolve(val); },
(err) => { signal.removeEventListener("abort", onAbort); reject(err); },
const dialSignal = dialRecord.controller.signal;
const cleanup = () => {
signal?.removeEventListener("abort", onCallerAbort);
dialSignal.removeEventListener("abort", onDialAbort);
};
const onCallerAbort = () => {
cleanup();
releaseWaiter(true);
reject(this.#callerAbortError(signal));
};
const onDialAbort = () => {
cleanup();
releaseWaiter(false);
reject(this.#dialAbortError(dialRecord));
};
signal?.addEventListener("abort", onCallerAbort, { once: true });
dialSignal.addEventListener("abort", onDialAbort, { once: true });
dialRecord.promise.then(
(val) => {
cleanup();
releaseWaiter(false);
resolve(val);
},
(err) => {
cleanup();
releaseWaiter(false);
reject(err);
},
);
});
};
const inflight = this.pendingDials.get(key);
if (inflight) {
return raceCallerSignal(inflight.promise);
return attachWaiter(inflight);
}
const dialStartedAt = this.clock();
const envelopeMs = this.sshDialEnvelopeMs;
const dialController = new AbortController();
const dialRecord = {
key,
controller: dialController,
promise: null,
runtimeId,
pluginId,
hostId,
waiterCount: 0,
settled: false,
cancelledByWaiters: false,
timedOut: false,
tunnelId: null,
sender: null,
stopRequested: false,
stopConfirmed: false,
stopInFlight: null,
stopRetryTimer: null,
stopRetryAttempts: 0,
dialDone: false,
envelopeTimer: null,
};
this.pendingDials.set(key, dialRecord);
dialRecord.envelopeTimer = setTimeout(() => {
dialRecord.envelopeTimer = null;
if (dialRecord.settled) return;
dialRecord.timedOut = true;
this.#cancelPendingDial(dialRecord, fail("deadlineExceeded", "SSH connection timed out"));
}, envelopeMs);
dialRecord.envelopeTimer.unref?.();
const dialPromise = (async () => {
if (this.closed || this.isLocked() || dialController.signal.aborted) {
throw fail("unavailable", "Host SSH execution is unavailable");
}
const connectionOptions = await prepareConnection(hostId, dialController.signal);
if (!connectionOptions || typeof connectionOptions !== "object") {
throw fail("unavailable", "Could not prepare SSH connection for host");
}
if (connectionOptions.singleChannelSsh) {
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
}
if (this.closed || this.isLocked() || dialController.signal.aborted) {
throw fail("unavailable", "Host SSH execution is unavailable");
}
try {
if (this.closed || this.isLocked() || dialController.signal.aborted) {
throw this.#dialAbortError(dialRecord);
}
let connectionOptions;
try {
connectionOptions = await prepareConnection(hostId, dialController.signal);
} catch (err) {
if (dialRecord.timedOut || dialController.signal.aborted) {
throw this.#dialAbortError(dialRecord);
}
throw err;
}
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted) {
throw this.#dialAbortError(dialRecord);
}
if (!connectionOptions || typeof connectionOptions !== "object") {
throw fail("unavailable", "Could not prepare SSH connection for host");
}
if (connectionOptions.singleChannelSsh) {
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
}
const sender = this.getSender();
const tunnelId = `plugin-exec-${randomUUID()}`;
const event = { sender };
let liveConn = null;
let rejectedUnsupported = false;
const detectVendor = await loadVendorDetector();
const detectVendor = await loadVendorDetector();
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted) {
throw this.#dialAbortError(dialRecord);
}
const result = await this.#bridge().startPortForward(
event,
{
...connectionOptions,
const elapsedMs = Math.max(0, this.clock() - dialStartedAt);
const remainingMs = envelopeMs - elapsedMs;
if (remainingMs <= 0) {
dialRecord.timedOut = true;
throw fail("deadlineExceeded", "SSH connection timed out");
}
const minStageMs = Math.min(
MIN_SSH_CONNECT_STAGE_TIMEOUT_MS,
this.sshTcpConnectTimeoutMs,
this.sshAuthReadyTimeoutMs,
);
const stageBudgetMs = Math.max(minStageMs, Math.round(remainingMs));
const sshTcpConnectTimeoutMs = Math.min(this.sshTcpConnectTimeoutMs, stageBudgetMs);
const sshAuthReadyTimeoutMs = Math.min(this.sshAuthReadyTimeoutMs, stageBudgetMs);
const sender = this.getSender();
const bridge = this.#bridge();
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted || dialRecord.stopRequested) {
throw this.#dialAbortError(dialRecord);
}
const tunnelId = `plugin-exec-${randomUUID()}`;
const event = { sender };
dialRecord.tunnelId = tunnelId;
dialRecord.sender = sender;
let liveConn = null;
let rejectedUnsupported = false;
let result;
try {
result = await bridge.startPortForward(
event,
{
...connectionOptions,
tunnelId,
ruleId: undefined,
type: "local",
localPort: 0,
bindAddress: "127.0.0.1",
remoteHost: "127.0.0.1",
remotePort: 1,
reuseTransport: true,
sshTcpConnectTimeoutMs,
sshAuthReadyTimeoutMs,
},
{
bindChannels: async ({ conn, tunnelState, chainConnections }) => {
tunnelState.conn = conn;
tunnelState.pendingConn = null;
tunnelState.chainConnections = chainConnections;
const remoteVer = typeof conn?._remoteVer === "string" ? conn._remoteVer : "";
if (detectVendor(remoteVer) || remoteSoftwareRequiresSingleChannel(remoteVer)) {
rejectedUnsupported = true;
throw new Error("SINGLE_CHANNEL_UNSUPPORTED");
}
liveConn = conn;
tunnelState.status = "active";
return { success: true };
},
},
);
} catch (err) {
dialRecord.dialDone = true;
this.#clearStopRetryTimer(dialRecord);
await this.#stopDialTunnel(dialRecord, { afterDialReturn: true });
if (rejectedUnsupported) {
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
}
if (dialRecord.timedOut || dialController.signal.aborted) {
throw this.#dialAbortError(dialRecord);
}
if (this.#isConnectTimeoutError(err)) {
throw fail("deadlineExceeded", "SSH connection timed out");
}
if (err instanceof PluginRpcError) throw err;
throw fail("unavailable", "Could not connect to the selected SSH server");
}
dialRecord.dialDone = true;
this.#clearStopRetryTimer(dialRecord);
if (rejectedUnsupported) {
await this.#stopDialTunnel(dialRecord, { afterDialReturn: true });
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
}
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted || dialRecord.stopRequested) {
await this.#stopDialTunnel(dialRecord, { afterDialReturn: true });
throw this.#dialAbortError(dialRecord);
}
if (!result?.success || !liveConn) {
await this.#stopDialTunnel(dialRecord, { afterDialReturn: true });
if (result?.cancelled) {
throw fail("cancelled", "SSH connection was cancelled");
}
if (this.#isConnectTimeoutError(result?.error)) {
throw fail("deadlineExceeded", "SSH connection timed out");
}
throw fail("unavailable", "Could not connect to the selected SSH server");
}
const entry = {
key,
runtimeId,
pluginId,
hostId,
tunnelId,
ruleId: undefined,
type: "local",
localPort: 0,
bindAddress: "127.0.0.1",
remoteHost: "127.0.0.1",
remotePort: 1,
reuseTransport: true,
},
{
bindChannels: async ({ conn, tunnelState, chainConnections }) => {
tunnelState.conn = conn;
tunnelState.pendingConn = null;
tunnelState.chainConnections = chainConnections;
const remoteVer = typeof conn?._remoteVer === "string" ? conn._remoteVer : "";
if (detectVendor(remoteVer) || remoteSoftwareRequiresSingleChannel(remoteVer)) {
rejectedUnsupported = true;
throw new Error("SINGLE_CHANNEL_UNSUPPORTED");
}
liveConn = conn;
tunnelState.status = "active";
return { success: true };
},
},
);
sender,
conn: liveConn,
closed: false,
activeCount: 0,
idleTimer: null,
};
const onConnDead = () => {
void this.#closeEntry(entry);
};
liveConn.once?.("close", onConnDead);
liveConn.once?.("end", onConnDead);
liveConn.once?.("error", onConnDead);
if (rejectedUnsupported) {
hostKeyVerifier.cancelRequestsForSession(tunnelId);
await this.#bridge().stopPortForward(event, { tunnelId }).catch(() => {});
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted || dialRecord.stopRequested) {
await this.#closeEntry(entry);
throw this.#dialAbortError(dialRecord);
}
// Publish and mark settled synchronously before resolving so a waiter
// abort in the settlement microtask cannot tear down the pooled entry.
dialRecord.settled = true;
if (dialRecord.envelopeTimer) {
clearTimeout(dialRecord.envelopeTimer);
dialRecord.envelopeTimer = null;
}
if (this.pendingDials.get(key) === dialRecord) {
this.pendingDials.delete(key);
}
this.connections.set(key, entry);
this.#touchIdleTimer(entry);
return entry;
} finally {
dialRecord.settled = true;
dialRecord.dialDone = true;
this.#clearStopRetryTimer(dialRecord);
if (dialRecord.envelopeTimer) {
clearTimeout(dialRecord.envelopeTimer);
dialRecord.envelopeTimer = null;
}
if (this.pendingDials.get(key) === dialRecord) {
this.pendingDials.delete(key);
}
}
if (!result?.success || !liveConn) {
hostKeyVerifier.cancelRequestsForSession(tunnelId);
await this.#bridge().stopPortForward(event, { tunnelId }).catch(() => {});
throw fail("unavailable", "Could not connect to the selected SSH server");
}
const entry = {
key,
runtimeId,
pluginId,
hostId,
tunnelId,
sender,
conn: liveConn,
closed: false,
activeCount: 0,
idleTimer: null,
};
const onConnDead = () => {
void this.#closeEntry(entry);
};
liveConn.once?.("close", onConnDead);
liveConn.once?.("end", onConnDead);
liveConn.once?.("error", onConnDead);
if (this.closed || this.isLocked() || dialController.signal.aborted) {
await this.#closeEntry(entry);
throw fail("unavailable", "Host SSH execution is unavailable");
}
this.connections.set(key, entry);
this.#touchIdleTimer(entry);
return entry;
})();
const dialRecord = { controller: dialController, promise: dialPromise, runtimeId, pluginId, hostId };
this.pendingDials.set(key, dialRecord);
const cleanupPending = () => {
if (this.pendingDials.get(key) === dialRecord) {
this.pendingDials.delete(key);
}
};
dialPromise.then(cleanupPending, cleanupPending);
return raceCallerSignal(dialPromise);
dialRecord.promise = dialPromise;
dialPromise.catch(() => {});
return attachWaiter(dialRecord);
}
/**
@@ -249,15 +585,19 @@ class PluginHostSshExecTransport {
const controller = new AbortController();
const lease = { controller, runtimeId, pluginId, hostId };
this.activeExecs.add(lease);
const onCallerAbort = () => controller.abort(signal?.reason ?? fail("cancelled", "SSH operation was cancelled"));
if (signal?.aborted) {
this.activeExecs.delete(lease);
throw fail("cancelled", "SSH operation was cancelled");
}
signal?.addEventListener("abort", onCallerAbort, { once: true });
let entry = null;
let acquired = false;
const onCallerAbort = () => {
controller.abort(signal?.reason ?? fail("cancelled", "SSH operation was cancelled"));
if (entry && acquired && this.#isDeadlineAbort(controller.signal)) {
void this.#closeEntry(entry);
}
};
if (signal?.aborted) {
this.activeExecs.delete(lease);
throw this.#callerAbortError(signal, "SSH operation was cancelled");
}
signal?.addEventListener("abort", onCallerAbort, { once: true });
try {
await assertActive?.();
controller.signal.throwIfAborted();
@@ -330,7 +670,7 @@ class PluginHostSshExecTransport {
const onCallerAbort = () => controller.abort(signal?.reason ?? fail("cancelled", "SSH command was cancelled"));
if (signal?.aborted) {
this.activeExecs.delete(lease);
throw fail("cancelled", "SSH command was cancelled");
throw this.#callerAbortError(signal, "SSH command was cancelled");
}
signal?.addEventListener("abort", onCallerAbort, { once: true });
@@ -371,10 +711,19 @@ class PluginHostSshExecTransport {
runTimeoutMs: timeoutMs,
maxOutputBytes,
signal: controller.signal,
// Leave transport teardown to this plugin transport so a healthy
// user cancel preserves the pool while open-timeout/deadline evicts.
invalidateTransportOnAbort: false,
});
} catch (err) {
if (!this.#isEntryHealthy(entry) || err?.code === "ECONNRESET" || err?.code === "EPIPE") {
const isDeadlineAbort = this.#isDeadlineAbort(controller.signal);
if (
!this.#isEntryHealthy(entry)
|| err?.code === "ECONNRESET"
|| err?.code === "EPIPE"
|| err?.code === "SSH_EXEC_OPEN_TIMEOUT"
|| isDeadlineAbort
) {
void this.#closeEntry(entry);
}
if (err instanceof PluginRpcError) throw err;
@@ -382,7 +731,7 @@ class PluginHostSshExecTransport {
throw fail("resourceExhausted", "SSH command output exceeded the configured byte limit");
}
if (controller.signal.aborted) {
throw fail("cancelled", "SSH command was cancelled");
throw this.#callerAbortError(controller.signal, "SSH command was cancelled");
}
if (/timed out/i.test(String(err?.message ?? ""))) {
throw fail("deadlineExceeded", "SSH command timed out");
@@ -422,7 +771,7 @@ class PluginHostSshExecTransport {
releaseHost(pluginId, hostId) {
for (const dial of [...this.pendingDials.values()]) {
if (dial.pluginId === pluginId && dial.hostId === hostId) {
dial.controller.abort(fail("permissionDenied", "Host binding was revoked"));
this.#cancelPendingDial(dial, fail("permissionDenied", "Host binding was revoked"));
}
}
for (const lease of [...this.activeExecs]) {
@@ -440,7 +789,7 @@ class PluginHostSshExecTransport {
releaseRuntime(runtimeId) {
for (const dial of [...this.pendingDials.values()]) {
if (dial.runtimeId === runtimeId) {
dial.controller.abort(fail("cancelled", "Plugin runtime stopped"));
this.#cancelPendingDial(dial, fail("cancelled", "Plugin runtime stopped"));
}
}
for (const lease of [...this.activeExecs]) {
@@ -458,7 +807,7 @@ class PluginHostSshExecTransport {
releasePlugin(pluginId) {
for (const dial of [...this.pendingDials.values()]) {
if (dial.pluginId === pluginId) {
dial.controller.abort(fail("permissionDenied", "Plugin SSH execution permission revoked or disabled"));
this.#cancelPendingDial(dial, fail("permissionDenied", "Plugin SSH execution permission revoked or disabled"));
}
}
for (const lease of [...this.activeExecs]) {
@@ -475,7 +824,7 @@ class PluginHostSshExecTransport {
closeAll(reason = "Host SSH execution unavailable") {
for (const dial of [...this.pendingDials.values()]) {
dial.controller.abort(fail("unavailable", reason));
this.#cancelPendingDial(dial, fail("unavailable", reason));
}
for (const lease of [...this.activeExecs]) {
lease.controller.abort(fail("unavailable", reason));
@@ -498,4 +847,7 @@ module.exports = {
DEFAULT_IDLE_TTL_MS,
DEFAULT_MAX_CONCURRENT_PER_RUNTIME,
DEFAULT_MAX_CONCURRENT_TOTAL,
DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS,
DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS,
DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS,
};
@@ -0,0 +1,710 @@
"use strict";
const assert = require("node:assert/strict");
const EventEmitter = require("node:events");
const test = require("node:test");
const {
PluginHostSshExecTransport,
DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS,
DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS,
DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS,
} = require("./hostSshExecTransport.cjs");
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
function createFakeConn(sockOverrides = {}) {
const conn = new EventEmitter();
conn._remoteVer = "SSH-2.0-OpenSSH_9.6";
if (sockOverrides !== null) {
conn._sock = {
destroyed: false,
writableEnded: false,
readableEnded: false,
writableFinished: false,
writable: true,
readyState: "open",
...sockOverrides,
};
}
return conn;
}
function defaultPrepareConnection(hostId) {
return Promise.resolve({
hostId,
hostname: "10.0.0.10",
port: 22,
username: "ubuntu",
});
}
function createBaseExecArgs(overrides = {}) {
return {
runtimeId: "rt-1",
pluginId: "com.example.monitor",
hostId: "host-1",
command: "uptime",
timeoutMs: 10_000,
maxOutputBytes: 64 * 1024,
prepareConnection: defaultPrepareConnection,
...overrides,
};
}
test("last-waiter abort during in-flight dial stops tunnel, clears pendingDials, and allows fresh retry", async () => {
const sender = { id: 1 };
let dialCount = 0;
const stoppedTunnels = [];
const inflightStops = new Map();
const portForwardingBridge = {
startPortForward(_event, opts, hooks) {
dialCount += 1;
const attempt = dialCount;
if (attempt === 1) {
// First dial hangs until stopPortForward tears it down.
return new Promise((resolve) => {
inflightStops.set(opts.tunnelId, () => {
resolve({ tunnelId: opts.tunnelId, success: false, cancelled: true });
});
});
}
const conn = createFakeConn();
return hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
}).then(() => ({ success: true }));
},
async stopPortForward(event, { tunnelId }) {
stoppedTunnels.push({ sender: event?.sender, tunnelId });
const cancel = inflightStops.get(tunnelId);
if (cancel) {
inflightStops.delete(tunnelId);
cancel();
}
return { success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
measurePing: async () => 5,
getSender: () => sender,
});
const abort1 = new AbortController();
const p1 = transport.exec(createBaseExecArgs({ command: "first", signal: abort1.signal }));
// Wait until startPortForward has been entered for attempt 1.
while (dialCount < 1) await new Promise((r) => setTimeout(r, 5));
assert.equal(transport.pendingDials.size, 1);
abort1.abort(new PluginRpcError(RPC_ERRORS.deadlineExceeded, "Plugin request deadline exceeded"));
await assert.rejects(p1, (err) => err.code === RPC_ERRORS.deadlineExceeded);
assert.equal(stoppedTunnels.length, 1, "last waiter abort must call stopPortForward");
assert.equal(stoppedTunnels[0].sender, sender);
assert.equal(transport.pendingDials.size, 0, "pendingDials must be cleared immediately");
assert.equal(inflightStops.size, 0, "hung startPortForward must be torn down");
// A subsequent retry must dial fresh and succeed instead of hitchhiking.
const res2 = await transport.exec(createBaseExecArgs({ command: "retry" }));
assert.equal(res2.stdout, "ok:retry");
assert.equal(dialCount, 2, "retry must start a new startPortForward dial");
// Completing normally must NOT stop the live pooled tunnel.
assert.equal(stoppedTunnels.length, 1);
assert.equal(transport.connections.size, 1);
transport.shutdown();
});
test("non-last waiter cancel keeps shared dial alive for remaining waiter, while cancelling all stops tunnel", async () => {
let dialCount = 0;
let stopCount = 0;
let finishDial = null;
let dialEntered = false;
const portForwardingBridge = {
startPortForward(_event, opts, hooks) {
dialCount += 1;
dialEntered = true;
return new Promise((resolve) => {
finishDial = async (cancelled = false) => {
if (cancelled) {
resolve({ tunnelId: opts.tunnelId, success: false, cancelled: true });
return;
}
const conn = createFakeConn();
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
resolve({ success: true });
};
});
},
async stopPortForward() {
stopCount += 1;
finishDial?.(true);
return { success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
measurePing: async () => 7,
getSender: () => ({ id: 1 }),
});
const abortA = new AbortController();
const pA = transport.exec(createBaseExecArgs({ command: "a", signal: abortA.signal }));
const pB = transport.exec(createBaseExecArgs({ command: "b" }));
while (!dialEntered) await new Promise((r) => setTimeout(r, 5));
assert.equal(dialCount, 1);
abortA.abort();
await assert.rejects(pA, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopCount, 0, "aborting one of two waiters must not stop shared tunnel");
assert.equal(transport.pendingDials.size, 1);
await finishDial(false);
const resB = await pB;
assert.equal(resB.stdout, "ok:b");
assert.equal(dialCount, 1);
assert.equal(stopCount, 0);
// Now verify that cancelling ALL waiters (A then B) on a fresh host tears down the dial.
dialEntered = false;
const abortC = new AbortController();
const abortD = new AbortController();
const pC = transport.exec(createBaseExecArgs({ hostId: "host-2", command: "c", signal: abortC.signal }));
const pD = transport.exec(createBaseExecArgs({ hostId: "host-2", command: "d", signal: abortD.signal }));
while (!dialEntered) await new Promise((r) => setTimeout(r, 5));
assert.equal(dialCount, 2);
abortC.abort();
await assert.rejects(pC, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopCount, 0);
abortD.abort();
await assert.rejects(pD, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopCount, 1, "cancelling the final remaining waiter must stop the tunnel");
assert.equal(transport.pendingDials.size, 0);
transport.shutdown();
});
test("releaseRuntime and releasePlugin stop in-flight dial tunnels", async () => {
const stopped = [];
let entered = 0;
const portForwardingBridge = {
startPortForward(_event, opts) {
entered += 1;
return new Promise(() => {
// intentionally never resolves on its own
void opts;
});
},
async stopPortForward(_event, { tunnelId }) {
stopped.push(tunnelId);
return { success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async () => ({ stdout: "", stderr: "", code: 0 }),
measurePing: async () => 5,
getSender: () => ({ id: 1 }),
});
const p1 = transport.exec(createBaseExecArgs({ runtimeId: "rt-1", hostId: "host-1" }));
while (entered < 1) await new Promise((r) => setTimeout(r, 5));
transport.releaseRuntime("rt-1");
await assert.rejects(p1, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopped.length, 1);
assert.equal(transport.pendingDials.size, 0);
const p2 = transport.exec(createBaseExecArgs({ runtimeId: "rt-2", pluginId: "p-2", hostId: "host-2" }));
while (entered < 2) await new Promise((r) => setTimeout(r, 5));
transport.releasePlugin("p-2");
await assert.rejects(p2, (err) => err.code === RPC_ERRORS.permissionDenied);
assert.equal(stopped.length, 2);
assert.equal(transport.pendingDials.size, 0);
transport.shutdown();
});
test("passes tightened SSH dial timeouts and maps connect timeout / envelope expiry to deadlineExceeded", async () => {
assert.equal(DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS, 8_000);
assert.equal(DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS, 8_000);
assert.ok(DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS >= 15_000 && DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS <= 20_000);
const seenOpts = [];
let now = 1_000;
let bridgeBehavior = "timeout-error";
let stopCount = 0;
const hungStops = new Map();
const portForwardingBridge = {
async startPortForward(_event, opts) {
seenOpts.push(opts);
if (bridgeBehavior === "timeout-error") {
throw new Error("Connection timeout to 10.0.0.10");
}
// Simulate an open hung socket handle that is torn down by stopPortForward.
return new Promise((resolve) => {
const socketHandle = setTimeout(() => {}, 10_000);
hungStops.set(opts.tunnelId, () => {
clearTimeout(socketHandle);
resolve({ tunnelId: opts.tunnelId, success: false, cancelled: true });
});
});
},
async stopPortForward(_event, { tunnelId }) {
stopCount += 1;
const cancel = hungStops.get(tunnelId);
if (cancel) {
hungStops.delete(tunnelId);
cancel();
}
return { success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async () => ({ stdout: "ok", stderr: "", code: 0 }),
measurePing: async () => 5,
clock: () => now,
getSender: () => ({ id: 1 }),
});
// 1) Default connect budgets passed to startPortForward + timeout error mapping.
await assert.rejects(
transport.exec(createBaseExecArgs()),
(err) => err instanceof PluginRpcError
&& err.code === RPC_ERRORS.deadlineExceeded
&& err.message === "SSH connection timed out",
);
assert.equal(seenOpts.length, 1);
assert.equal(seenOpts[0].sshTcpConnectTimeoutMs, DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS);
assert.equal(seenOpts[0].sshAuthReadyTimeoutMs, DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS);
assert.ok(seenOpts[0].sshTcpConnectTimeoutMs < 30_000);
assert.ok(seenOpts[0].sshAuthReadyTimeoutMs < 30_000);
// 2) Slow prepareConnection shrinks remaining stage budgets (clamped >= 1000ms).
await assert.rejects(
transport.exec(createBaseExecArgs({
prepareConnection: async (hostId) => {
now += DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS - 3_500;
return defaultPrepareConnection(hostId);
},
})),
(err) => err.code === RPC_ERRORS.deadlineExceeded && err.message === "SSH connection timed out",
);
assert.equal(seenOpts.length, 2);
assert.equal(seenOpts[1].sshTcpConnectTimeoutMs, 3_500);
assert.equal(seenOpts[1].sshAuthReadyTimeoutMs, 3_500);
transport.shutdown();
// 3) Connect envelope actively aborts a hung dial before 30s and tears down the tunnel.
bridgeBehavior = "hang";
stopCount = 0;
const envelopeTransport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async () => ({ stdout: "ok", stderr: "", code: 0 }),
measurePing: async () => 5,
sshDialEnvelopeMs: 40,
getSender: () => ({ id: 1 }),
});
const startedAt = Date.now();
await assert.rejects(
envelopeTransport.exec(createBaseExecArgs()),
(err) => err instanceof PluginRpcError
&& err.code === RPC_ERRORS.deadlineExceeded
&& err.message === "SSH connection timed out",
);
const elapsed = Date.now() - startedAt;
assert.ok(elapsed < 2_000, `envelope abort should be fast, took ${elapsed}ms`);
assert.equal(stopCount, 1, "envelope abort must stop the in-flight tunnel");
assert.equal(envelopeTransport.pendingDials.size, 0);
envelopeTransport.shutdown();
});
test("health check reuses healthy sockets and re-dials half-open or closed sockets", async () => {
let dialCount = 0;
let stopCount = 0;
let currentConn = null;
const portForwardingBridge = {
async startPortForward(_event, opts, hooks) {
dialCount += 1;
currentConn = createFakeConn();
await hooks.bindChannels({
conn: currentConn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
},
async stopPortForward() {
stopCount += 1;
return { success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async () => ({ stdout: "ok", stderr: "", code: 0 }),
measurePing: async () => 3,
getSender: () => ({ id: 1 }),
});
// Healthy socket is reused across consecutive execs.
await transport.exec(createBaseExecArgs());
await transport.exec(createBaseExecArgs());
assert.equal(dialCount, 1);
assert.equal(stopCount, 0);
const unhealthyMutations = [
["writableEnded", (sock) => { sock.writableEnded = true; }],
["readableEnded", (sock) => { sock.readableEnded = true; }],
["destroyed", (sock) => { sock.destroyed = true; }],
["writableFinished", (sock) => { sock.writableFinished = true; }],
["writable=false", (sock) => { sock.writable = false; }],
["readyState=closed", (sock) => { sock.readyState = "closed"; }],
["readyState=readOnly", (sock) => { sock.readyState = "readOnly"; }],
];
let expectedDials = 1;
let expectedStops = 0;
for (const [label, mutate] of unhealthyMutations) {
mutate(currentConn._sock);
await transport.exec(createBaseExecArgs());
expectedDials += 1;
expectedStops += 1;
assert.equal(dialCount, expectedDials, `expected redial when socket has ${label}`);
assert.equal(stopCount, expectedStops, `expected eviction when socket has ${label}`);
}
// Omitting _sock completely remains healthy (backward-compatible with minimal fakes).
delete currentConn._sock;
await transport.exec(createBaseExecArgs());
assert.equal(dialCount, expectedDials, "missing _sock must still reuse pooled entry");
transport.shutdown();
});
test("evicts pooled entry on SSH_EXEC_OPEN_TIMEOUT and RPC deadline abort, but keeps it on user cancel", async () => {
let dialCount = 0;
let stopCount = 0;
let execHandler = async () => ({ stdout: "ok", stderr: "", code: 0 });
const portForwardingBridge = {
async startPortForward(_event, opts, hooks) {
dialCount += 1;
const conn = createFakeConn();
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
},
async stopPortForward() {
stopCount += 1;
return { success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: (conn, cmd, opts) => execHandler(conn, cmd, opts),
measurePing: async () => 4,
getSender: () => ({ id: 1 }),
});
// Prime the pool.
await transport.exec(createBaseExecArgs());
assert.equal(dialCount, 1);
assert.equal(stopCount, 0);
// 1) User cancel (RPC_ERRORS.cancelled) of a healthy running exec must NOT evict.
execHandler = (_conn, _cmd, opts) => new Promise((_resolve, reject) => {
opts.signal.addEventListener("abort", () => reject(opts.signal.reason || new Error("aborted")), { once: true });
});
const userAbort = new AbortController();
const userCancelPromise = transport.exec(createBaseExecArgs({ signal: userAbort.signal }));
setTimeout(() => userAbort.abort(new PluginRpcError(RPC_ERRORS.cancelled, "User cancelled")), 10);
await assert.rejects(userCancelPromise, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopCount, 0, "user cancel of healthy exec must not evict pooled entry");
execHandler = async () => ({ stdout: "reused", stderr: "", code: 0 });
const reused = await transport.exec(createBaseExecArgs());
assert.equal(reused.stdout, "reused");
assert.equal(dialCount, 1, "pooled connection must be reused after healthy user cancel");
// 2) SSH_EXEC_OPEN_TIMEOUT must evict so next exec dials fresh.
execHandler = async () => {
const err = new Error("SSH exec channel open timed out after 10000 ms");
err.code = "SSH_EXEC_OPEN_TIMEOUT";
throw err;
};
await assert.rejects(
transport.exec(createBaseExecArgs()),
(err) => err.code === RPC_ERRORS.deadlineExceeded,
);
assert.equal(stopCount, 1, "SSH_EXEC_OPEN_TIMEOUT must evict pooled entry");
execHandler = async () => ({ stdout: "fresh-after-open-timeout", stderr: "", code: 0 });
const afterOpenTimeout = await transport.exec(createBaseExecArgs());
assert.equal(afterOpenTimeout.stdout, "fresh-after-open-timeout");
assert.equal(dialCount, 2, "next exec after SSH_EXEC_OPEN_TIMEOUT must re-dial");
// 3) RPC deadline abort after connection acquisition must evict so next exec dials fresh.
execHandler = (_conn, _cmd, opts) => new Promise((_resolve, reject) => {
opts.signal.addEventListener("abort", () => reject(opts.signal.reason || new Error("aborted")), { once: true });
});
const deadlineAbort = new AbortController();
const deadlinePromise = transport.exec(createBaseExecArgs({ signal: deadlineAbort.signal }));
setTimeout(() => {
deadlineAbort.abort(new PluginRpcError(RPC_ERRORS.deadlineExceeded, "Plugin request deadline exceeded"));
}, 10);
await assert.rejects(deadlinePromise, (err) => err.code === RPC_ERRORS.deadlineExceeded);
assert.equal(stopCount, 2, "RPC deadline abort must evict pooled entry");
execHandler = async () => ({ stdout: "fresh-after-deadline", stderr: "", code: 0 });
const afterDeadline = await transport.exec(createBaseExecArgs());
assert.equal(afterDeadline.stdout, "fresh-after-deadline");
assert.equal(dialCount, 3, "next exec after RPC deadline abort must re-dial");
transport.shutdown();
});
test("premature stop before startPortForward registers retries after registration, cancels hung dial, and allows fresh retry", async () => {
const sender = { id: 7 };
let dialCount = 0;
let firstTunnelId = null;
const stopCalls = [];
const registeredTunnels = new Map();
let resolveDialAtGate;
const dialAtGate = new Promise((resolve) => { resolveDialAtGate = resolve; });
let releaseRegistrationGate;
const registrationGate = new Promise((resolve) => { releaseRegistrationGate = resolve; });
let resolveFirstDialCancelled;
const firstDialCancelled = new Promise((resolve) => { resolveFirstDialCancelled = resolve; });
const portForwardingBridge = {
async startPortForward(_event, opts, hooks) {
dialCount += 1;
if (dialCount === 1) {
firstTunnelId = opts.tunnelId;
resolveDialAtGate();
// Simulate preemption/delay before portForwardingTunnels.set(tunnelId, ...).
await registrationGate;
// Now register the tunnel and hang until stopPortForward cancels it.
return new Promise((resolve) => {
registeredTunnels.set(opts.tunnelId, () => {
resolveFirstDialCancelled();
resolve({ tunnelId: opts.tunnelId, success: false, cancelled: true });
});
});
}
const conn = createFakeConn();
registeredTunnels.set(opts.tunnelId, () => {});
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
},
async stopPortForward(event, { tunnelId }) {
const cancel = registeredTunnels.get(tunnelId);
stopCalls.push({ sender: event?.sender, tunnelId, found: Boolean(cancel) });
if (!cancel) {
return { tunnelId, success: false, error: "Tunnel not found" };
}
registeredTunnels.delete(tunnelId);
cancel();
return { tunnelId, success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
measurePing: async () => 5,
getSender: () => sender,
});
const abort1 = new AbortController();
const p1 = transport.exec(createBaseExecArgs({ command: "first", signal: abort1.signal }));
await dialAtGate;
assert.ok(firstTunnelId, "tunnelId must be assigned before gate");
assert.equal(registeredTunnels.size, 0, "tunnel must not be registered yet");
assert.equal(transport.pendingDials.size, 1);
// Last waiter aborts BEFORE startPortForward registers the tunnel.
abort1.abort(new PluginRpcError(RPC_ERRORS.deadlineExceeded, "Plugin request deadline exceeded"));
await assert.rejects(p1, (err) => err.code === RPC_ERRORS.deadlineExceeded);
assert.equal(transport.pendingDials.size, 0, "pendingDials must be cleared immediately");
assert.ok(stopCalls.length >= 1, "initial stop attempt must have fired");
assert.equal(stopCalls[0].tunnelId, firstTunnelId);
assert.equal(stopCalls[0].sender, sender);
assert.equal(stopCalls[0].found, false, "initial stop before registration must report Tunnel not found");
// Allow startPortForward to register and begin the hung handshake.
releaseRegistrationGate();
// Wait for the retry stop to cancel the newly registered hung dial.
await Promise.race([
firstDialCancelled,
new Promise((_, reject) => setTimeout(() => reject(new Error("Hung dial was not cancelled after registration")), 2_000)),
]);
// Give settlement microtasks / any stale timer a moment to confirm no double-close.
await new Promise((r) => setTimeout(r, 40));
const confirmedStopsForFirst = stopCalls.filter((c) => c.tunnelId === firstTunnelId && c.found);
assert.equal(confirmedStopsForFirst.length, 1, "stopPortForward must succeed once after registration without double-closing");
assert.equal(registeredTunnels.size, 0, "no zombie tunnel may remain registered");
assert.equal(transport.pendingDials.size, 0);
// A later retry must start a fresh dial and succeed without being stopped.
const res2 = await transport.exec(createBaseExecArgs({ command: "retry" }));
assert.equal(res2.stdout, "ok:retry");
assert.equal(dialCount, 2, "retry must start a fresh dial");
assert.equal(transport.connections.size, 1);
assert.equal(registeredTunnels.size, 1, "live retry tunnel must remain active");
transport.shutdown();
});
test("post-return abort stops tunnel after early Tunnel not found on both success and throw", async () => {
const stopCalls = [];
const registeredTunnels = new Map();
let dialCount = 0;
let resolveGateReached;
let gateReached;
let releaseGate;
let gate;
let resolveRegistered;
let registered;
let mode = "succeed";
const resetGate = () => {
gateReached = new Promise((resolve) => { resolveGateReached = resolve; });
gate = new Promise((resolve) => { releaseGate = resolve; });
registered = new Promise((resolve) => { resolveRegistered = resolve; });
};
const portForwardingBridge = {
async startPortForward(_event, opts, hooks) {
dialCount += 1;
if (mode === "succeed" || mode === "throw") {
resolveGateReached(opts.tunnelId);
await gate;
registeredTunnels.set(opts.tunnelId, () => {});
resolveRegistered();
if (mode === "throw") {
throw new Error("late dial failure");
}
const conn = createFakeConn();
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
}
const conn = createFakeConn();
registeredTunnels.set(opts.tunnelId, () => {});
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
},
async stopPortForward(_event, { tunnelId }) {
const found = registeredTunnels.has(tunnelId);
stopCalls.push({ tunnelId, found });
if (!found) {
return { tunnelId, success: false, error: "Tunnel not found" };
}
registeredTunnels.delete(tunnelId);
return { tunnelId, success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
measurePing: async () => 3,
getSender: () => ({ id: 2 }),
});
// 1) startPortForward resolves { success: true } immediately after an early Tunnel not found.
resetGate();
mode = "succeed";
const abort1 = new AbortController();
const p1 = transport.exec(createBaseExecArgs({ hostId: "host-a", signal: abort1.signal }));
const tunnelId1 = await gateReached;
abort1.abort(new PluginRpcError(RPC_ERRORS.cancelled, "cancelled"));
await assert.rejects(p1, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopCalls.filter((c) => c.tunnelId === tunnelId1 && !c.found).length, 1);
releaseGate();
await registered;
for (let i = 0; i < 50 && registeredTunnels.has(tunnelId1); i += 1) {
await new Promise((r) => setTimeout(r, 5));
}
assert.equal(registeredTunnels.has(tunnelId1), false, "post-return abort must stop tunnel that succeeded after early not-found");
assert.equal(stopCalls.filter((c) => c.tunnelId === tunnelId1 && c.found).length, 1);
assert.equal(transport.connections.size, 0);
assert.equal(transport.pendingDials.size, 0);
// 2) startPortForward throws after an early Tunnel not found.
resetGate();
mode = "throw";
const abort2 = new AbortController();
const p2 = transport.exec(createBaseExecArgs({ hostId: "host-b", signal: abort2.signal }));
const tunnelId2 = await gateReached;
abort2.abort(new PluginRpcError(RPC_ERRORS.cancelled, "cancelled"));
await assert.rejects(p2, (err) => err.code === RPC_ERRORS.cancelled);
assert.equal(stopCalls.filter((c) => c.tunnelId === tunnelId2 && !c.found).length, 1);
releaseGate();
await registered;
for (let i = 0; i < 50 && registeredTunnels.has(tunnelId2); i += 1) {
await new Promise((r) => setTimeout(r, 5));
}
assert.equal(registeredTunnels.has(tunnelId2), false, "post-throw abort must stop tunnel after early not-found");
assert.equal(stopCalls.filter((c) => c.tunnelId === tunnelId2 && c.found).length, 1);
assert.equal(transport.pendingDials.size, 0);
// 3) Later retry succeeds fresh.
mode = "normal";
const res = await transport.exec(createBaseExecArgs({ hostId: "host-a", command: "after-cleanup" }));
assert.equal(res.stdout, "ok:after-cleanup");
assert.equal(dialCount, 3);
assert.equal(transport.connections.size, 1);
transport.shutdown();
});
+3 -1
View File
@@ -220,7 +220,9 @@ class PluginRpcRouter {
}
this.#forgetPending(message.id, pending);
if (Object.hasOwn(message, "error")) {
pending.reject(new PluginRpcError(message.error.code, message.error.message, message.error.data));
const remoteError = new PluginRpcError(message.error.code, message.error.message, message.error.data);
remoteError.remote = true;
pending.reject(remoteError);
return;
}
try {
+37 -1
View File
@@ -12,7 +12,7 @@ const {
PLUGIN_CRASH_QUARANTINE_THRESHOLD,
PLUGIN_CRASH_WINDOW_MS,
} = require("./constants.cjs");
const { PluginLogger } = require("./pluginLogger.cjs");
const { PluginLogger, redactLogValue } = require("./pluginLogger.cjs");
const { PluginRpcError, RPC_ERRORS, raceWithAbort } = require("./rpcRouter.cjs");
const {
assertHostMethod,
@@ -48,6 +48,15 @@ function resolveDefaultRuntimeKind({ plugin }) {
return describePluginRuntime(plugin.manifest).defaultRuntimeKind;
}
function sanitizeHostErrorMessage(error) {
if (error?.remote === true) {
const code = Number.isInteger(error.code) ? error.code : "unknown";
return `Remote plugin RPC error (code ${code})`;
}
const raw = error instanceof Error ? error.message : String(error ?? "unknown");
return String(redactLogValue(raw)).slice(0, 512);
}
class RuntimeSupervisor {
constructor(options) {
this.electron = options.electron;
@@ -69,6 +78,7 @@ class RuntimeSupervisor {
if (this.runtimeMessageGuard != null && typeof this.runtimeMessageGuard !== "function") {
throw new TypeError("Plugin runtime message guard must be a function");
}
this.onRuntimeFailure = typeof options.onRuntimeFailure === "function" ? options.onRuntimeFailure : null;
this.getInitialEnvironment = options.getInitialEnvironment ?? (() => null);
if (typeof this.getInitialEnvironment !== "function") {
throw new TypeError("Plugin initial-environment provider must be a function");
@@ -429,6 +439,25 @@ class RuntimeSupervisor {
return error;
}
#reportRuntimeFailure(kind, identity, error, extra = {}) {
if (!this.onRuntimeFailure) return;
const safeError = new Error(sanitizeHostErrorMessage(error));
if (error instanceof Error && error.remote !== true && typeof error.code !== "undefined") {
safeError.code = error.code;
}
try {
this.onRuntimeFailure({
kind,
pluginId: identity.pluginId,
pluginVersion: identity.pluginVersion,
runtimeId: identity.runtimeId,
runtimeKind: identity.runtimeKind,
...extra,
error: safeError,
});
} catch {}
}
#recordContainmentFailure(identity, error) {
this.uncontainedPlugins.add(identity.pluginId);
const active = this.database.getActivePlugin(identity.pluginId);
@@ -439,6 +468,7 @@ class RuntimeSupervisor {
error: error?.message ?? String(error),
quarantinedAt: Date.now(),
});
this.#reportRuntimeFailure("containment-failure", identity, error, { quarantined: true });
}
async #handleExit(pluginId, runtime, identity, details) {
@@ -469,6 +499,7 @@ class RuntimeSupervisor {
this.#emitRuntimeState(identity, "error", {
error: error?.message ?? String(error),
});
this.#reportRuntimeFailure("runtime-error", identity, error, { quarantined: false });
return;
}
const crash = this.database.recordCrash(
@@ -481,6 +512,10 @@ class RuntimeSupervisor {
error: error?.message ?? String(error),
quarantinedAt: crash.quarantinedAt,
});
this.#reportRuntimeFailure("runtime-crash", identity, error, {
crashCount: crash.count,
quarantined: crash.quarantined,
});
}
stop(pluginId) {
@@ -581,6 +616,7 @@ class RuntimeSupervisor {
if (plugin?.enabled) this.database.setEnabled(identity.pluginId, false);
await this.stop(identity.pluginId);
this.#setRuntimeState(identity, "error", { error: error?.message ?? String(error) });
this.#reportRuntimeFailure("policy-violation", identity, error, { quarantined: false });
}
getRuntimeIdentity(pluginId) {
@@ -215,6 +215,7 @@ test("repeated activation failures quarantine after the third crash window event
test("unexpected process exit is contained and recorded without touching other runtimes", async (context) => {
let exit;
const failures = [];
const fixture = createFixture(context, (options) => {
exit = options.onExit;
return {
@@ -228,6 +229,8 @@ test("unexpected process exit is contained and recorded without touching other r
},
async stop() {},
};
}, {
onRuntimeFailure: (event) => failures.push(event),
});
await fixture.supervisor.start(fixture.manifest.id);
exit({ expected: false, error: new Error("process crashed") });
@@ -235,6 +238,29 @@ test("unexpected process exit is contained and recorded without touching other r
const plugin = fixture.database.getActivePlugin(fixture.manifest.id);
assert.equal(plugin.runtime.status, "error");
assert.match(plugin.runtime.lastError, /process crashed/);
assert.equal(failures.length, 1);
assert.equal(failures[0].kind, "runtime-crash");
assert.equal(failures[0].pluginId, fixture.manifest.id);
assert.equal(failures[0].crashCount, 1);
assert.match(failures[0].error.message, /process crashed/);
// Remote plugin-authored RPC errors must be redacted before reaching onRuntimeFailure.
const remoteErr = new Error("SELECT * FROM users WHERE password='super-secret-value'");
remoteErr.code = -32603;
remoteErr.remote = true;
await fixture.supervisor.start(fixture.manifest.id);
exit({ expected: false, error: remoteErr });
await new Promise((resolve) => setImmediate(resolve));
assert.equal(failures.length, 2);
assert.equal(failures[1].error.message, "Remote plugin RPC error (code -32603)");
assert.doesNotMatch(failures[1].error.message, /super-secret-value/);
// Policy violation stops the runtime and reports policy-violation failure.
const identity = await fixture.supervisor.start(fixture.manifest.id);
await fixture.supervisor.enforcePolicyViolation(identity, new Error("Plugin memory limit exceeded"));
assert.equal(failures.length, 3);
assert.equal(failures[2].kind, "policy-violation");
assert.match(failures[2].error.message, /Plugin memory limit exceeded/);
});
test("a startup exit and its rejected start count as one crash", async (context) => {
@@ -3612,6 +3612,9 @@
"stateScope": {
"type": "string",
"maxLength": 128
},
"supportsOptionalCss": {
"type": "boolean"
}
},
"additionalProperties": false
@@ -3640,8 +3643,7 @@
"kind",
"instanceId",
"sequence",
"mutations",
"css"
"mutations"
],
"properties": {
"kind": {
@@ -1564,6 +1564,9 @@ test("ViewOpenParams, ViewOpenResult, and HostDrawnViewMessage host-ui.activate
for (const valid of [
{ kind: "host-ui.open", instanceId: "inst-1" },
{ kind: "host-ui.open", instanceId: "inst-1", stateScope: "scope-hash" },
{ kind: "host-ui.open", instanceId: "inst-1", stateScope: "scope-hash", supportsOptionalCss: true },
{ kind: "host-ui.update", instanceId: "inst-1", sequence: 1, css: ".a{color:red}", mutations: [] },
{ kind: "host-ui.update", instanceId: "inst-1", sequence: 2, mutations: [] },
{ kind: "host-ui.activate", instanceId: "inst-1" },
{ kind: "host-ui.activate", instanceId: "inst-1", params: { connectionId: "conn-1" } },
{ kind: "host-ui.activate", instanceId: "inst-1", params: null },
@@ -306,6 +306,7 @@ export type HostDrawnViewMessage = ({
kind: "host-ui.open";
instanceId: string;
stateScope?: string;
supportsOptionalCss?: boolean;
}) | ({
kind: "host-ui.close";
instanceId: string;
@@ -315,7 +316,7 @@ export type HostDrawnViewMessage = ({
sequence: number;
acknowledgedEvent?: number;
mutations: Array<JsonValue>;
css: string;
css?: string;
}) | ({
kind: "host-ui.event";
instanceId: string;
+11 -4
View File
@@ -286,6 +286,7 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
syncElementIndex: () => void;
scheduleFlush: () => void;
flushScheduled: boolean;
supportsOptionalCss: boolean;
sequence: number;
acknowledgedEvent: number;
sentAck: number;
@@ -651,16 +652,19 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
}
for (const nodeId of view.controls.keys()) if (!live.has(nodeId)) view.controls.delete(nodeId);
if (!mutations.length && view.sentAck === view.acknowledgedEvent) return;
view.sentAck = view.acknowledgedEvent;
const safeMutations = JSON.parse(JSON.stringify(mutations)) as JsonValue;
const nextSequence = view.sequence + 1;
const includeCss = !view.supportsOptionalCss || view.sequence === 0;
views.postMessage(viewId, {
kind: 'host-ui.update',
instanceId: id,
sequence: ++view.sequence,
sequence: nextSequence,
acknowledgedEvent: view.acknowledgedEvent,
css,
...(includeCss ? { css } : {}),
mutations: safeMutations,
} as JsonValue);
view.sequence = nextSequence;
view.sentAck = view.acknowledgedEvent;
};
const domObserver = new MutationObserver((records) => {
send(records);
@@ -710,6 +714,7 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
syncElementIndex,
scheduleFlush,
flushScheduled: false,
supportsOptionalCss: message.supportsOptionalCss === true,
sequence: 0,
acknowledgedEvent: 0,
sentAck: 0,
@@ -736,7 +741,9 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
// next microtask if mount produced no DOM mutations.
void Promise.resolve().then(() => {
if (instances.get(id) === view && view.sequence === 0) {
views.postMessage(viewId, { kind: 'host-ui.update', instanceId: id, sequence: ++view.sequence, css, mutations: [] });
const nextSequence = view.sequence + 1;
views.postMessage(viewId, { kind: 'host-ui.update', instanceId: id, sequence: nextSequence, css, mutations: [] });
view.sequence = nextSequence;
}
});
} else if (message.kind === 'host-ui.close') close(id);
@@ -1267,3 +1267,80 @@ test('hostDom preserves leading header and nav siblings across React Suspense la
dom.window.close();
}
});
test('hostDom omits unchanged css after sequence 1 when host advertises supportsOptionalCss', async () => {
const dom = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'MouseEvent']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
const { act, useState } = await import('react');
const { registerHostReactView } = await import('./hostReact.js');
let receive: (value: JsonValue) => void = () => {};
const messages: Array<Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>> = [];
const views = {
onDidReceiveMessage(_id: string, listener: (value: JsonValue) => void) { receive = listener; return { dispose() {} }; },
postMessage(_id: string, value: JsonValue) { messages.push(value as unknown as Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>); },
getState: async () => undefined,
setState: async () => {},
};
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount((v) => v + 1)}>Count {count}</button>;
}
const stylesheet = '.btn{display:flex}';
const registration = registerHostReactView(views, 'com.example.optional-css', () => <Counter />, stylesheet);
try {
// 1. Host advertises supportsOptionalCss: css sent once on sequence 1, omitted afterwards.
await act(async () => { receive({ kind: 'host-ui.open', instanceId: 'opt-1', supportsOptionalCss: true }); await new Promise((r) => setTimeout(r, 20)); });
assert.equal(messages.length, 1);
assert.equal(messages[0].css, stylesheet);
const mountRoot = (messages[0].mutations[0] as unknown[])[2] as { children: Array<{ id: string }> };
const buttonId = mountRoot.children[0].id;
await act(async () => { receive({ kind: 'host-ui.event', instanceId: 'opt-1', event: { eventId: 1, type: 'click', nodeId: buttonId } }); await new Promise((r) => setTimeout(r, 20)); });
assert.ok(messages.length >= 2);
for (const subsequent of messages.slice(1)) {
assert.equal(Object.hasOwn(subsequent, 'css'), false, 'subsequent updates must omit unchanged css when supportsOptionalCss is true');
}
await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'opt-1' }); });
// 2. Legacy host without supportsOptionalCss (or supportsOptionalCss: false): css continues to be included on every update.
messages.length = 0;
await act(async () => { receive({ kind: 'host-ui.open', instanceId: 'legacy-1', supportsOptionalCss: false }); await new Promise((r) => setTimeout(r, 20)); });
assert.equal(messages[0].css, stylesheet);
const legacyRoot = (messages[0].mutations[0] as unknown[])[2] as { children: Array<{ id: string }> };
await act(async () => { receive({ kind: 'host-ui.event', instanceId: 'legacy-1', event: { eventId: 1, type: 'click', nodeId: legacyRoot.children[0].id } }); await new Promise((r) => setTimeout(r, 20)); });
assert.ok(messages.length >= 2);
assert.equal(messages.at(-1)!.css, stylesheet, 'legacy hosts without supportsOptionalCss must still receive css');
await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'legacy-1' }); });
// 3. Empty initial render (null component) sends css on sequence 1 and omits it on subsequent render.
messages.length = 0;
let triggerShow: (() => void) | null = null;
function Delayed() {
const [shown, setShown] = useState(false);
triggerShow = () => setShown(true);
return shown ? <div>ready</div> : null;
}
const delayedReg = registerHostReactView(views, 'com.example.optional-css-empty', () => <Delayed />, stylesheet);
try {
await act(async () => { receive({ kind: 'host-ui.open', instanceId: 'empty-1', supportsOptionalCss: true }); await new Promise((r) => setTimeout(r, 20)); });
assert.ok(messages.length >= 1);
assert.equal(messages[0].css, stylesheet);
const countBefore = messages.length;
await act(async () => { triggerShow?.(); await new Promise((r) => setTimeout(r, 20)); });
assert.ok(messages.length > countBefore);
assert.equal(Object.hasOwn(messages.at(-1)!, 'css'), false);
await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'empty-1' }); });
} finally {
delayedReg.dispose();
}
} finally {
registration.dispose();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
dom.window.close();
}
});