Compare commits

...
Author SHA1 Message Date
陈大猫 cb7e49c409 fix(terminal): prevent autocomplete crash from double-sending keys (#4539) (#4632) 2026-12-02 14:49:08 +08:00
Netcatty-Bot 02be8a2e0a Update Nix release metadata for v1.2.0 (#4631) 2026-12-02 13:38:39 +08:00
陈大猫 ca2cdcbd12 fix(terminal): show sudo password hint for bare Password: prompts (#4628) (#4629) 2026-12-02 12:20:18 +08:00
陈大猫 f7fed5fd6f fix(plugins): systematic reliability hardening across transports, streams, RPC lifecycle, and UI (#4630) 2026-12-02 12:17:21 +08:00
陈大猫 25aa27bbf8 fix(plugins): settle pending SSH dial coordination and isolate plugin exec transport (#4627) 2026-12-02 11:34:05 +08:00
Netcatty-Botandgithub-actions[bot] 7e44b774f8 Update Nix release metadata for v1.1.99 (#4623)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-12-02 09:36:35 +08:00
陈大猫 c5c7cfdae3 fix(ai): loop-strip stacked decorative prompt prefixes (#4620)
* fix(ai): loop-strip stacked decorative prompt prefixes

Related #4354

After a non-zero exit, p10k (and similar) may prefix a status glyph
such as ✘ before the existing theme decoration (⚡). Recognition only
stripped one 1-4 char decorative token, so the leftover ⚡ still missed
the idle-prompt matchers and MCP terminal_execute never sent the command.

* fix(ai): match decorative prefix candidates after each strip

Related #4354

isDefaultPosixPromptLine must try the original line and each
intermediate strip so a status glyph in front of an Oh My Zsh
➜ prompt does not drop the ➜ before matching.
2026-12-02 08:35:18 +08:00
陈大猫 62085cb3c2 fix(plugins): cancel stuck SSH exec dials before the plugin RPC deadline (#4622)
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 08:15:51 +08:00
40 changed files with 2365 additions and 321 deletions

No files matched your search

+24 -12
View File
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { useAppLockChrome } from './appRuntimeBridge';
import { resolvePluginViewWindowScope } from './pluginViewScopes';
import { pluginViewSessions, type PluginViewSnapshot } from './pluginViewSession';
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
@@ -7,15 +8,17 @@ import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
const initial = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
export function useHostDrawnPluginView({ viewId, version, slot, active, context, subscribeHidden, unavailable }: {
viewId: string; version: string; slot: string; active: boolean; context: Record<string, unknown>;
subscribeHidden(listener: () => void): () => void; unavailable(): void;
subscribeHidden(listener: (hidden?: boolean) => void): () => void; unavailable(): void;
}) {
const { locked } = useAppLockChrome();
const effectiveActive = active && !locked;
const contextKey = JSON.stringify(context);
const key = JSON.stringify([viewId, version, slot, contextKey]);
const scopeId = typeof window !== 'undefined'
? resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` })
: '';
const sessionKey = scopeId ? JSON.stringify([scopeId, key]) : '';
const cachedSession = active && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
const cachedSession = effectiveActive && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
const [state, setState] = useState<{
key: string;
snapshot: PluginViewSnapshot;
@@ -29,7 +32,7 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable;
const sessionRef = useRef<{ key: string; image(path: string): Promise<string>; send(event: HostDrawnViewEvent): void } | null>(null);
useEffect(() => {
if (!active) {
if (!effectiveActive) {
setHidden(false);
return;
}
@@ -38,22 +41,31 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
const resolvedScopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
try {
const session = pluginViewSessions.acquire(JSON.stringify([resolvedScopeId, key]), bridge, { viewId, scopeId: resolvedScopeId, context: JSON.parse(contextKey) });
sessionRef.current = { key, send: session.send, image: session.image };
const activeHandle = { key, send: session.send, image: session.image };
sessionRef.current = activeHandle;
const update = () => {
const snapshot = session.getSnapshot();
if (snapshot.error) sessionRef.current = null;
setState({ key, snapshot, image: session.image });
};
const stop = session.subscribe(update); update(); setHidden(false);
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
const stopHidden = subscribeHidden((nextHidden = true) => {
if (nextHidden) {
sessionRef.current = null;
setHidden(true);
} else {
if (!session.getSnapshot().error) sessionRef.current = activeHandle;
setHidden(false);
}
});
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
} catch { unavailableRef.current(); }
}, [active, contextKey, key, slot, subscribeHidden, viewId]);
}, [effectiveActive, contextKey, key, slot, subscribeHidden, viewId]);
const fallbackLoadImage = useCallback((path: string) => {
const session = sessionRef.current;
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
}, [active, key]);
const hasCurrentState = active
return effectiveActive && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
}, [effectiveActive, key]);
const hasCurrentState = effectiveActive
&& state.key === key
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
const resolvedSnapshot = hasCurrentState
@@ -65,9 +77,9 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
? state.image
: (cachedSession?.image ?? fallbackLoadImage);
const sendEvent = useCallback((event: HostDrawnViewEvent) => {
const session = sessionRef.current; if (active && session?.key === key) session.send(event);
}, [active, key]);
const session = sessionRef.current; if (effectiveActive && session?.key === key) session.send(event);
}, [effectiveActive, key]);
// A newly selected plugin must never receive values from the previous tree,
// even during the render before effect cleanup and the next activation.
return { ...resolvedSnapshot, visible: active && !hidden, loadImage, sendEvent };
return { ...resolvedSnapshot, visible: effectiveActive && !hidden, loadImage, sendEvent };
}
+40 -10
View File
@@ -73,15 +73,31 @@ export function usePluginHostActions() {
if (entry.prompt.request.kind === 'vault.requestHostDraft' && vault.managedSources !== entry.managedSources) throw new Error('Managed sources changed during draft review');
}, [getVault]);
const clearReview = useCallback((entry: Review) => {
if (current.current !== entry) return;
current.current = null;
responding.current = false;
setReview(null);
setRemember(false);
setBusy(false);
setError(false);
}, []);
const fail = useCallback(async (entry: Review) => {
if (current.current !== entry) return;
setError(true);
try {
await netcattyBridge.get()?.respondPluginInteraction?.({
const accepted = await netcattyBridge.get()?.respondPluginInteraction?.({
requestId: entry.prompt.requestId, actionToken: entry.completionToken ?? entry.prompt.actionToken, action: 'fail',
});
} catch { /* A stopped runtime or closed window already invalidates it. */ }
}, []);
if (accepted === false) {
clearReview(entry);
}
} catch {
// A stopped runtime, closed window, or already-settled prompt will never send { closed: true }.
clearReview(entry);
}
}, [clearReview]);
const execute = useCallback(async (entry: Review) => {
const bridge = netcattyBridge.get();
@@ -140,7 +156,8 @@ export function usePluginHostActions() {
entry.claimed = true;
assertCurrent(entry);
await openHostSession(entry.host);
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
const completed = await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
if (completed === false) clearReview(entry);
return;
}
let action: PluginHostAction;
@@ -161,9 +178,16 @@ export function usePluginHostActions() {
},
connect: openHostSession,
});
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
const completed = await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
if (completed === false) clearReview(entry);
} catch { await fail(entry); }
}, [assertCurrent, fail, getVault]);
finally {
if (current.current === entry) {
responding.current = false;
setBusy(false);
}
}
}, [assertCurrent, clearReview, fail, getVault]);
useEffect(() => {
const bridge = netcattyBridge.get();
@@ -282,7 +306,7 @@ export function usePluginHostActions() {
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
responding.current = true; setBusy(true); setError(false);
try {
assertCurrent(entry);
if (action !== 'cancel') assertCurrent(entry);
const request = entry.prompt.request;
const selected = request.kind === 'vault.selectHosts' && action === 'submit' ? selectedIds.map((id) => {
const revision = entry.candidateRevisions.get(id);
@@ -296,18 +320,24 @@ export function usePluginHostActions() {
|| request.kind === 'network.stream.tlsConfirm'
);
const effectiveRemember = rememberOverride ?? remember;
await netcattyBridge.require().respondPluginInteraction?.({
const accepted = await netcattyBridge.require().respondPluginInteraction?.({
requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action,
...(selected === undefined ? {} : { resources: selected }),
...(draft === undefined ? {} : { draft }),
...(request.kind === 'vault.requestConnect' && action === 'submit' ? { scriptsRun: entry.scriptsRun } : {}),
...(includeRemember && effectiveRemember ? { remember: true } : {}),
});
} catch { await fail(entry); }
if (accepted === false) {
clearReview(entry);
}
} catch {
if (action === 'cancel') clearReview(entry);
else await fail(entry);
}
finally {
if (current.current === entry && entry.prompt.phase === 'request') { responding.current = false; setBusy(false); }
}
}, [assertCurrent, fail, remember, selectedIds]);
}, [assertCurrent, clearReview, fail, remember, selectedIds]);
return { review, selectedIds, setSelectedIds, remember, setRemember, busy, error, respond };
}
@@ -19,7 +19,7 @@ export function usePluginHostInteractions() {
if (current.current?.requestId !== event.requestId) return;
current.current = null; setPrompt(null);
} else {
if (event.request.kind.startsWith('vault.') || event.request.kind === 'network.stream.connectViaHost') return;
if (event.request.kind.startsWith('vault.') || event.request.kind.startsWith('network.stream.')) return;
current.current = event as UiPrompt;
if (event.request.kind === 'terminal.selection.read' && event.phase === 'request') {
setPrompt(null);
+7 -2
View File
@@ -149,7 +149,12 @@ export function usePluginViewLifecycle({
}, [contributions.loading, contributions.snapshot.plugins]);
useEffect(() => {
if (!requested || activeView?.view.location !== 'tab') return;
if (!requested || viewContributions.loading) return;
if (!resolvedActiveView) {
setRequested(null);
return;
}
if (activeView?.view.location !== 'tab') return;
pluginViewTabStore.open({
pluginId: activeView.plugin.id,
pluginName: activeView.plugin.displayName,
@@ -159,7 +164,7 @@ export function usePluginViewLifecycle({
context: requested.context,
});
setRequested(null);
}, [activeView, requested]);
}, [activeView, requested, resolvedActiveView, viewContributions.loading]);
useEffect(() => {
const stop = pluginViewTabStore.onDidClose(({ tab }) => closePluginViewSessionIfLoaded(tab.viewId));
+6 -3
View File
@@ -58,9 +58,12 @@ export function PluginTerminalSidebarPageHost({ page, tabId, sessionId, getSessi
showHeader?: boolean;
}) {
const { t } = useI18n();
const subscribeHidden = useMemo(() => (hide: () => void) => {
const stopTab = activeTabStore.subscribeSync((id) => { if (id !== tabId) hide(); });
const stopSession = subscribeSidePanelLiveSnapshot(true, () => { if (getSession() !== sessionId) hide(); });
const subscribeHidden = useMemo(() => (onVisibilityChange: (hidden?: boolean) => void) => {
const sync = (tab = activeTabStore.getActiveTabId()) => {
onVisibilityChange(tab !== tabId || getSession() !== sessionId);
};
const stopTab = activeTabStore.subscribeSync((id) => sync(id));
const stopSession = subscribeSidePanelLiveSnapshot(true, () => sync());
return () => { stopTab(); stopSession(); };
}, [getSession, sessionId, tabId]);
return <section className="flex h-full min-h-0 flex-col overflow-hidden" aria-label={`${page.title} — ${page.pluginName}`} data-plugin-terminal-sidebar>
+2 -1
View File
@@ -15,7 +15,8 @@ import { LazyPluginHostDrawnPage, prewarmPluginView } from './LazyPluginHostDraw
import { PluginVaultAISidebar } from './PluginVaultAISidebar';
type VaultPages = ReturnType<typeof usePluginVaultPages>;
const subscribeHidden = (hide: () => void) => activeTabStore.subscribeSync((id) => { if (id !== 'vault') hide(); });
const subscribeHidden = (onVisibilityChange: (hidden?: boolean) => void) =>
activeTabStore.subscribeSync((id) => { onVisibilityChange(id !== 'vault'); });
let nextPluginPromptId = 1;
export function PluginVaultNavigation({ model, collapsed }: { model: VaultPages; collapsed: boolean }) {
@@ -0,0 +1,115 @@
import test from "node:test";
import assert from "node:assert/strict";
import { JSDOM } from "jsdom";
import type { Terminal as XTerm } from "@xterm/xterm";
import { GhostTextAddon } from "./GhostTextAddon.ts";
import { getXTermCellDimensions, invalidateCellDimensionCache } from "./xtermUtils.ts";
import {
keepImeCommittedTextThroughModifierKeyDowns,
keepLateImeTextInsert,
} from "../runtime/imeModifierKeyDownSeenGuard.ts";
test("autocomplete on a disposed renderer does not double-send a key (#4539)", async () => {
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
url: "http://localhost/",
pretendToBeVisual: true,
});
const win = dom.window;
win.matchMedia = () => ({
matches: false, media: "", onchange: null,
addEventListener() {}, removeEventListener() {},
addListener() {}, removeListener() {}, dispatchEvent: () => false,
});
win.HTMLCanvasElement.prototype.getContext = () => ({
font: "10px monospace", measureText: () => ({ width: 8 }),
}) as unknown as CanvasRenderingContext2D;
const globals = {
window: win, document: win.document, HTMLElement: win.HTMLElement,
HTMLTextAreaElement: win.HTMLTextAreaElement, Node: win.Node,
Element: win.Element, getComputedStyle: win.getComputedStyle.bind(win),
};
const previousGlobals = Object.fromEntries(
Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
);
Object.assign(globalThis, globals);
const errors: unknown[] = [];
win.addEventListener("error", (event) => {
errors.push(event.error);
event.preventDefault();
});
let oldTerm: XTerm | undefined;
let liveTerm: XTerm | undefined;
const ghost = new GhostTextAddon();
try {
const imported = await import("@xterm/xterm");
const Terminal = (imported as { default?: { Terminal: typeof imported.Terminal } }).default?.Terminal
?? imported.Terminal;
const openTerminal = () => {
const parent = win.document.createElement("div");
win.document.body.appendChild(parent);
const term = new Terminal({ cols: 80, rows: 24, cursorBlink: false });
keepImeCommittedTextThroughModifierKeyDowns(term);
keepLateImeTextInsert(term);
term.open(parent);
return term;
};
oldTerm = openTerminal();
ghost.activate(oldTerm);
// Runtime replacement leaves the separately activated autocomplete addon
// holding the old terminal, whose RenderService still exists after dispose.
oldTerm.dispose();
liveTerm = openTerminal();
const sent: string[] = [];
liveTerm.onData((data) => {
// Match createXTermRuntime: write first, then notify autocomplete.
sent.push(data);
ghost.applyKeystroke(data);
});
const textarea = liveTerm.textarea!;
const cancelled: boolean[] = [];
const typeKey = (key: string) => {
const keyCode = key.toUpperCase().charCodeAt(0);
const keydown = new win.KeyboardEvent("keydown", {
key, code: `Key${key.toUpperCase()}`, keyCode,
bubbles: true, cancelable: true,
});
textarea.dispatchEvent(keydown);
cancelled.push(keydown.defaultPrevented);
// JSDOM does not perform native keyboard default actions. Deliver the
// browser's keypress/input sequence only when keydown was not cancelled.
if (!keydown.defaultPrevented) {
textarea.dispatchEvent(new win.KeyboardEvent("keypress", {
key, charCode: key.charCodeAt(0), keyCode: key.charCodeAt(0),
bubbles: true, cancelable: true,
}));
for (const type of ["beforeinput", "input"]) {
textarea.dispatchEvent(new win.InputEvent(type, {
data: key, inputType: "insertText", composed: true, bubbles: true,
}));
}
}
textarea.dispatchEvent(new win.KeyboardEvent("keyup", { key, keyCode, bubbles: true }));
};
typeKey("a");
// The first suggestion arrives asynchronously, as in the reporter's trace.
await Promise.resolve().then(() => ghost.show("apt update -y", "a")).catch((error) => errors.push(error));
typeKey("p");
typeKey("t");
assert.equal(sent.join(""), "apt", "one PTY write per physical key");
assert.deepEqual(cancelled, [true, true, true]);
assert.deepEqual(errors, []);
// With no cached size, the absent renderer also reaches the DOM fallback.
invalidateCellDimensionCache();
assert.deepEqual(getXTermCellDimensions(oldTerm), { width: 8, height: 16 });
} finally {
ghost.dispose();
liveTerm?.dispose();
oldTerm?.dispose();
dom.window.close();
invalidateCellDimensionCache();
for (const [key, descriptor] of Object.entries(previousGlobals)) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
+10 -2
View File
@@ -33,9 +33,17 @@ function getTermId(term: XTerm): number {
export function getXTermCellDimensions(term: XTerm): CellDimensions {
// Try xterm core renderer API (fast path)
const coreAccess = term as XTerm & {
_core?: { _renderService?: { dimensions?: { css?: { cell?: CellDimensions } } } };
_core?: { _renderService?: {
hasRenderer?: () => boolean;
dimensions?: { css?: { cell?: CellDimensions } };
} };
};
const coreDims = coreAccess._core?._renderService?.dimensions?.css?.cell;
const renderService = coreAccess._core?._renderService;
// The dimensions getter dereferences its renderer even after disposal.
// Avoid throwing through onData before xterm can prevent the key's default.
const coreDims = renderService?.hasRenderer?.() === false
? undefined
: renderService?.dimensions?.css?.cell;
if (coreDims && coreDims.width > 0 && coreDims.height > 0) {
// Update cache while we have a good value
const id = getTermId(term);
@@ -257,19 +257,79 @@ test("does not arm when the hint cannot be shown (overlay unavailable)", () => {
assert.deepEqual(writes, []);
});
test("a bare Password prompt does not hint until a su command is submitted", () => {
test("a bare Password prompt does not hint until a su or sudo command is submitted", () => {
const { autofill, hints } = make();
autofill.handleOutput("Password: ");
assert.deepEqual(hints, []);
// sudo-armed bare Password: is too generic (mysql/ssh); su-armed is expected
// macOS / Synology sudo uses the same bare prompt as su (#4628).
autofill.armForCommand("sudo whoami");
autofill.handleOutput("Password: ");
assert.deepEqual(hints, []);
assert.deepEqual(hints, [true]);
autofill.armForCommand("su -");
autofill.handleOutput("Password: ");
assert.deepEqual(hints, [true]);
assert.deepEqual(hints, [true, false, true]);
});
for (const command of ["sudo ping 192.168.30.4", "sudo su"]) {
for (const prompt of ["Password:", "密码:"]) {
test(`${command} shows only the host-password hint for ${prompt} (#4628)`, () => {
const hints: boolean[] = [];
const writes: string[] = [];
const autofill = createSudoPasswordAutofill({
mode: "picker",
password: "host-secret",
candidates: [{ id: "other", label: "Other", password: "other-secret" }],
write: (data) => writes.push(data),
onHint: (active) => {
hints.push(active);
return true;
},
onPicker: () => assert.fail("sudo must not open the full keychain picker"),
});
autofill.armForCommand(command);
autofill.handleOutput(prompt);
assert.deepEqual(hints, [true]);
assert.deepEqual(writes, []);
assert.equal(autofill.isPromptPending(), true);
assert.equal(autofill.isPickerPending(), false);
autofill.confirmFill();
assert.deepEqual(writes, ["host-secret\n"]);
});
}
}
test("sudo arms still reject child and remote password prompts (#4628)", () => {
for (const prompt of ["Enter password:", "Password for user postgres:", "user@host's password:"]) {
const { autofill, hints, writes } = make();
autofill.armForCommand("sudo su");
autofill.handleOutput(prompt);
assert.deepEqual(hints, [], prompt);
assert.equal(autofill.isPromptPending(), false, prompt);
autofill.confirmFill();
assert.deepEqual(writes, [], prompt);
}
});
for (const { output, retry } of [
{ output: "\r\nPassword:", retry: false },
{ output: "\r\nSorry, try again.\r\nPassword:", retry: true },
{ output: "\r\n[sudo] password for alice:", retry: true },
]) {
test(`sudo bare prompt after confirmFill requires auth retry evidence: ${JSON.stringify(output)} (#4628)`, () => {
const { autofill, hints, writes } = make();
autofill.armForCommand("sudo su");
autofill.handleOutput("Password:");
assert.equal(autofill.isPromptPending(), true);
autofill.confirmFill();
assert.deepEqual(writes, ["secret\n"]);
autofill.handleOutput(output);
assert.equal(autofill.isPromptPending(), retry);
assert.deepEqual(hints, retry ? [true, false, true] : [true, false]);
autofill.confirmFill();
assert.deepEqual(writes, retry ? ["secret\n", "secret\n"] : ["secret\n"]);
});
}
test("an explicit [sudo] prompt hints without a recorded sudo command", () => {
// The [sudo] tag is sudo-specific, so we hint even when arming didn't fire —
// manual typing's recordedCommand is flaky (#1281/#1284), and the hint only
@@ -350,9 +350,10 @@ export const createSudoPasswordAutofill = (_options: {
if (!armActive) return false;
// su always prompts with a bare Password: line (not Enter password / DB).
if (armedKind === "su") return isSuBarePasswordPrompt(line);
// sudo: only sudo-scoped prompts, never generic "Enter password:" from
// child programs when sudo credentials are already cached.
if (armedKind === "sudo") return isSudoScopedBarePasswordPrompt(line);
// macOS / Synology / BSD sudo uses the same short bare Password: as su (#4628).
if (armedKind === "sudo") {
return isSudoScopedBarePasswordPrompt(line) || isSuBarePasswordPrompt(line);
}
return false;
};
@@ -442,8 +443,8 @@ export const createSudoPasswordAutofill = (_options: {
dismissedWhileArmed = false;
armedKind = null;
}
// Explicit "[sudo] …" always; su arm accepts bare Password:; sudo arm only
// accepts sudo-scoped bare prompts (not generic Enter password from mysql).
// Explicit "[sudo] …" always; su/sudo arms accept short bare Password:;
// sudo also accepts scoped prompts (not generic Enter password from mysql).
const isPrompt = isArmedPromptLine(lastLine, armActive);
if (pending) {
// The prompt moved on: a new line arrived and the latest line is no
+11 -6
View File
@@ -174,7 +174,7 @@ function isDefaultCmdPromptLine(line) {
}
function stripLeadingDecorativeToken(line) {
// Optional short decorative token, stripped only for recognition (#4354).
// Optional short decorative tokens, stripped only for recognition (#4354).
return line.replace(/^\s*[^\s\w\p{L}\p{N}@:#$\\\/>\[\]().]{1,4}\s+/u, "");
}
@@ -183,9 +183,11 @@ function isDefaultPosixPromptLine(line) {
// Optional virtualenv / conda / BT-panel style env name prefix: "(name) "
// before the shell prompt. Recognition only; callers still return the full
// prompt line so suffix matching sees the visible prefix (#3947).
const withoutEnvPrefix = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
return [withoutEnvPrefix, stripLeadingDecorativeToken(withoutEnvPrefix)].some(
(prompt) => (
let prompt = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
// Check each candidate before stripping again: a glyph such as the
// robbyrussell arrow may be part of the prompt itself (#4354).
while (true) {
if (
POSIX_PROMPT_PATTERN.test(prompt) ||
BRACKET_TIME_POSIX_PROMPT_PATTERN.test(prompt) ||
BRACKET_PATH_POSIX_PROMPT_PATTERN.test(prompt) ||
@@ -196,8 +198,11 @@ function isDefaultPosixPromptLine(line) {
POWERLEVEL10K_PROMPT_PATTERN.test(prompt) ||
POWERLINE_PROMPT_PATTERN.test(prompt) ||
OH_MY_ZSH_ROBBYRUSSELL_PROMPT_PATTERN.test(prompt)
),
);
) return true;
const stripped = stripLeadingDecorativeToken(prompt);
if (stripped === prompt) return false;
prompt = stripped;
}
}
function extractTrailingIdlePrompt(output) {
+31
View File
@@ -518,10 +518,41 @@ test("isDefaultPosixPromptLine matches short decorative prefixes and keeps the f
}
});
test("stacked decorative prefixes preserve the full extracted and tracked prompt", () => {
for (const prompt of [
...["\u2718", "\u2714", "\u2717", "\u2713"].flatMap(status => [
`${status} \u26A1 root@testhost:~# `,
`${status} \u26A1 root@testhost:~#`,
`${status} \u26A1 root@testhost \uE0B0 ~ \uE0B0 `,
`(venv) ${status} \u26A1 user@host:~# `,
`${status} \u279C netcatty`,
`${status} \u279C netcatty `,
`${status} \u279C ~ git:(main) \u2717`,
`(venv) ${status} \u279C netcatty git:(main) \u2713 `,
]),
"\u2718 \u2714 \u26A1 root@testhost:~# ",
"\u2718 \u2714 \u279C netcatty ",
]) {
assert.equal(isDefaultPosixPromptLine(prompt), true, prompt);
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt);
const session = {};
trackSessionIdlePrompt(session, `welcome\r\n${prompt}`);
assert.equal(session.lastIdlePrompt, prompt, prompt);
assert.equal(getFreshIdlePrompt(session), prompt, prompt);
}
});
test("decorative prefix recognition rejects pending input and non-decorative prefixes", () => {
for (const line of [
"\u26A1 root@testhost:~# echo hi",
" \u26A1 root@testhost \uE0B0 ~ \uE0B0 ls",
"\u2718 \u26A1 root@testhost:~# echo hi",
"\u2718 \u26A1 root@testhost \uE0B0 ~ \uE0B0 ls",
...["\u2718", "\u2714", "\u2717", "\u2713"].flatMap(status => [
`${status} \u279C netcatty ls`,
`(venv) ${status} \u279C netcatty git:(main) \u2713 ls`,
]),
"\u2718 \u2714 \u279C netcatty ls",
"OK root@testhost:~# ",
"yes root@testhost:~# ",
"git:(main) root@testhost:~# ",
@@ -685,3 +685,121 @@ test("stop by rule id reports cleanup failures and keeps the tunnel retryable",
cancelled: true,
});
});
test("startPortForward settles pendingDialCoordination when custom bindChannels succeeds without publishing a transport", async (t) => {
resetSshTransportRegistryForTests({ defaultIdleTtlMs: 0 });
t.after(() => resetSshTransportRegistryForTests({ defaultIdleTtlMs: 0 }));
const ssh2 = require("ssh2");
const originalConnect = ssh2.Client.prototype.connect;
const originalEnd = ssh2.Client.prototype.end;
let connectCount = 0;
ssh2.Client.prototype.connect = function fakeConnect() {
connectCount += 1;
this._remoteVer = "SSH-2.0-OpenSSH_9.6";
this._sock = { destroyed: false, writableEnded: false, setTimeout() {} };
setImmediate(() => this.emit("ready"));
return this;
};
ssh2.Client.prototype.end = function fakeEnd() {
setImmediate(() => this.emit("close"));
return this;
};
t.after(() => {
ssh2.Client.prototype.connect = originalConnect;
ssh2.Client.prototype.end = originalEnd;
});
const event = { sender: createSender() };
const basePayload = {
type: "local",
localPort: 0,
bindAddress: "127.0.0.1",
remoteHost: "127.0.0.1",
remotePort: 1,
hostname: "custom-bind.example",
hostId: "host-custom-bind",
port: 22,
username: "root",
password: "secret",
verifyHostKeys: false,
useSshAgent: false,
reuseTransport: true,
};
const customHooks = {
bindChannels: async ({ conn, tunnelState, chainConnections }) => {
tunnelState.conn = conn;
tunnelState.pendingConn = null;
tunnelState.chainConnections = chainConnections;
tunnelState.status = "active";
return { success: true };
},
};
const first = await startPortForward(event, { ...basePayload, tunnelId: "pf-custom-bind-1" }, customHooks);
assert.equal(first.success, true);
assert.equal(connectCount, 1);
assert.equal(
getTransportStats().pendingDials,
0,
"custom bindChannels must not leave an unsettled pendingDialCoordination in sshConnectionPool",
);
await stopPortForward(event, { tunnelId: "pf-custom-bind-1" });
// Before the fix, the second dial joined the leaked leader coordination and hung forever.
const second = await startPortForward(event, { ...basePayload, tunnelId: "pf-custom-bind-2" }, customHooks);
assert.equal(second.success, true);
assert.equal(connectCount, 2, "second dial must establish a fresh SSH connection instead of deadlocking");
assert.equal(getTransportStats().pendingDials, 0);
await stopPortForward(event, { tunnelId: "pf-custom-bind-2" });
});
test("startPortForward settles pendingDialCoordination for single-channel SSH peers", async (t) => {
resetSshTransportRegistryForTests({ defaultIdleTtlMs: 0 });
t.after(() => resetSshTransportRegistryForTests({ defaultIdleTtlMs: 0 }));
const ssh2 = require("ssh2");
const originalConnect = ssh2.Client.prototype.connect;
const originalEnd = ssh2.Client.prototype.end;
ssh2.Client.prototype.connect = function fakeSingleChannelConnect() {
this._remoteVer = "SSH-2.0-BHostSSH_7.0";
this._sock = { destroyed: false, writableEnded: false, setTimeout() {} };
setImmediate(() => this.emit("ready"));
return this;
};
ssh2.Client.prototype.end = function fakeEnd() {
setImmediate(() => this.emit("close"));
return this;
};
t.after(() => {
ssh2.Client.prototype.connect = originalConnect;
ssh2.Client.prototype.end = originalEnd;
});
const event = { sender: createSender() };
const result = await startPortForward(event, {
tunnelId: "pf-single-channel-1",
type: "local",
localPort: 0,
bindAddress: "127.0.0.1",
remoteHost: "127.0.0.1",
remotePort: 80,
hostname: "single-channel.example",
hostId: "host-single-channel",
port: 22,
username: "root",
password: "secret",
verifyHostKeys: false,
useSshAgent: false,
reuseTransport: true,
});
assert.equal(result.success, true);
assert.equal(
getTransportStats().pendingDials,
0,
"single-channel peer skipping transport registration must still clear pendingDialCoordination",
);
await stopPortForward(event, { tunnelId: "pf-single-channel-1" });
});
+28 -9
View File
@@ -1322,10 +1322,6 @@ async function startPortForward(event, payload, { bindChannels = bindPortForward
sendStatus('error', error?.message || String(error));
throw error;
}
if (isTunnelCancelled(tunnelState)) {
portForwardingTunnels.delete(tunnelId);
return { tunnelId, success: false, cancelled: true };
}
const abandonPendingDial = (reason) => {
if (!pendingDialCoordination) return;
failTransportDial(
@@ -1333,6 +1329,11 @@ async function startPortForward(event, payload, { bindChannels = bindPortForward
reason instanceof Error ? reason : new Error(String(reason || "Port forward connection cancelled")),
);
};
if (isTunnelCancelled(tunnelState)) {
portForwardingTunnels.delete(tunnelId);
abandonPendingDial("Port forward connection cancelled");
return { tunnelId, success: false, cancelled: true };
}
// Prefer an already-authenticated transport (live terminal or idle park).
if (existingTransport?.conn) {
@@ -1744,7 +1745,7 @@ async function startPortForward(event, payload, { bindChannels = bindPortForward
console.log(`[PortForward] SSH connection ready for tunnel ${tunnelId}`);
const peerSingleChannelSsh = remoteSoftwareRequiresSingleChannel(conn._remoteVer);
bindChannels({
Promise.resolve().then(() => bindChannels({
type,
conn,
tunnelId,
@@ -1762,9 +1763,17 @@ async function startPortForward(event, payload, { bindChannels = bindPortForward
: reuseEndpoint,
registerTransport: allowTransportReuse && !peerSingleChannelSsh,
dialCoordination: pendingDialCoordination,
}).then((result) => {
if (!result?.success && pendingDialCoordination) {
failTransportDial(pendingDialCoordination, new Error("Port forward cancelled before activation"));
})).then((result) => {
if (pendingDialCoordination) {
// No-op when bindChannels already settled the leader via completeTransportDial().
// Guarantees custom bindChannels hooks or single-channel peers never leave an
// unsettled leader record in sshConnectionPool for later dials to hang on.
const reason = !result?.success
? new Error("Port forward cancelled before activation")
: peerSingleChannelSsh
? new Error("SSH server does not support shared transport reuse")
: new Error("Port forward did not publish a reusable SSH transport");
failTransportDial(pendingDialCoordination, reason);
}
settled = true;
resolve(result);
@@ -1842,7 +1851,17 @@ async function startPortForward(event, payload, { bindChannels = bindPortForward
conn.end();
});
conn.connect(connectOpts);
try {
conn.connect(connectOpts);
} catch (connectErr) {
clearAuthReadyTimer();
if (pendingDialCoordination) failTransportDial(pendingDialCoordination, connectErr);
sendStatus('error', connectErr?.message || String(connectErr));
cleanupChainConnections(chainConnections);
portForwardingTunnels.delete(tunnelId);
settled = true;
reject(connectErr);
}
});
}
+68 -30
View File
@@ -215,9 +215,20 @@ class BrowserPluginRuntime {
port1.on("close", () => this.#handleExit(new Error("Plugin message port closed")));
port1.start();
let resolvePreloadReady;
const preloadReady = new Promise((resolve) => { resolvePreloadReady = resolve; });
let rejectPreloadReady;
const preloadReady = new Promise((resolve, reject) => {
resolvePreloadReady = resolve;
rejectPreloadReady = reject;
});
preloadReady.catch(() => {});
let resolveRuntimeConnected;
const runtimeConnected = new Promise((resolve) => { resolveRuntimeConnected = resolve; });
let rejectRuntimeConnected;
const runtimeConnected = new Promise((resolve, reject) => {
resolveRuntimeConnected = resolve;
rejectRuntimeConnected = reject;
});
runtimeConnected.catch(() => {});
this.startupRejecters = [rejectPreloadReady, rejectRuntimeConnected];
const onPreloadMessage = (_event, channel) => {
if (channel === "netcatty-plugin:preload-ready") {
void this.logger.write("debug", "Plugin browser preload ready");
@@ -229,6 +240,7 @@ class BrowserPluginRuntime {
}
};
contents.on("ipc-message", onPreloadMessage);
let port2Transferred = false;
const loading = contents.loadURL(this.registration.url);
let preloadTimer;
const preloadDeadline = new Promise((_, reject) => {
@@ -238,32 +250,41 @@ class BrowserPluginRuntime {
);
});
try {
await Promise.race([
preloadReady,
preloadDeadline,
loading.then(() => preloadReady),
]);
try {
await Promise.race([
preloadReady,
preloadDeadline,
loading.then(() => preloadReady),
]);
} finally {
clearTimeout(preloadTimer);
}
this.#assertStarting(signal);
port2Transferred = true;
contents.postMessage("netcatty-plugin:connect", null, [port2]);
let connectionTimer;
const connectionDeadline = new Promise((_, reject) => {
connectionTimer = setTimeout(
() => reject(new Error("Plugin browser runtime did not accept its message port")),
PLUGIN_ACTIVATION_TIMEOUT_MS,
);
});
try {
await Promise.all([
loading,
Promise.race([runtimeConnected, connectionDeadline]),
]);
} finally {
clearTimeout(connectionTimer);
}
} finally {
clearTimeout(preloadTimer);
}
this.#assertStarting(signal);
contents.postMessage("netcatty-plugin:connect", null, [port2]);
let connectionTimer;
const connectionDeadline = new Promise((_, reject) => {
connectionTimer = setTimeout(
() => reject(new Error("Plugin browser runtime did not accept its message port")),
PLUGIN_ACTIVATION_TIMEOUT_MS,
);
});
try {
await Promise.all([
loading,
Promise.race([runtimeConnected, connectionDeadline]),
]);
} finally {
clearTimeout(connectionTimer);
this.startupRejecters = null;
contents.removeListener("ipc-message", onPreloadMessage);
if (!port2Transferred) {
try { port2.close(); } catch {}
}
}
this.connected = true;
this.#assertStarting(signal);
const initialized = await this.router.request("plugin.initialize", {
netcattyVersion: config.netcattyVersion,
@@ -281,16 +302,28 @@ class BrowserPluginRuntime {
return initialized;
}
async stop() {
if (this.stopping) return;
stop() {
this.stopPromise ??= this.#stop();
return this.stopPromise;
}
async #stop() {
this.stopping = true;
if (this.startupRejecters) {
const stopErr = new Error("Plugin browser runtime stopped");
for (const reject of this.startupRejecters) reject(stopErr);
this.startupRejecters = null;
}
try {
await this.router?.request("plugin.deactivate", {}, {
timeoutMs: PLUGIN_DEACTIVATION_TIMEOUT_MS,
});
if (this.connected) {
await this.router?.request("plugin.deactivate", {}, {
timeoutMs: PLUGIN_DEACTIVATION_TIMEOUT_MS,
});
}
} finally {
const router = this.router;
this.router = null;
this.connected = false;
router?.close();
this.port?.close();
this.registration?.dispose();
@@ -320,9 +353,14 @@ class BrowserPluginRuntime {
}
#handleExit(error) {
if (this.startupRejecters) {
for (const reject of this.startupRejecters) reject(error);
this.startupRejecters = null;
}
if (!this.router) return;
const router = this.router;
this.router = null;
this.connected = false;
router.close(error);
this.port?.close();
this.registration?.dispose();
+4 -2
View File
@@ -156,7 +156,7 @@ class PluginByteStreamBroker {
reason: String(socket.authorizationError || "UNTRUSTED_CERT").slice(0, 256),
});
const decision = await raceWithAbort(
Promise.resolve(this.confirmTlsCert(certInfo, state, context)),
Promise.resolve(this.confirmTlsCert(certInfo, state, { ...context, signal: state.controller.signal })),
state.controller.signal,
);
await this.active(state, context);
@@ -216,6 +216,7 @@ class PluginByteStreamBroker {
await this.active(state, context);
state.connectTimer = setTimeout(() => this.finish(state,
failure("deadlineExceeded", "Byte stream connect timeout")), state.limits.connectMs);
state.connectTimer.unref?.();
let socket;
const effectiveServername = servername ?? (net.isIP(target.host) ? undefined : target.host);
if (hostTransport) {
@@ -270,6 +271,8 @@ class PluginByteStreamBroker {
if (!hostTransport) await raceWithAbort(new Promise((resolve) => socket.once(
target.transport === "tls" ? "secureConnect" : "connect", resolve,
)), state.controller.signal);
clearTimeout(state.connectTimer);
state.connectTimer = null;
await this.active(state, context);
if (target.transport === "tls" && !socket.authorized) {
if (!allowSelfSigned) {
@@ -277,7 +280,6 @@ class PluginByteStreamBroker {
}
await this.#verifyUntrustedTlsSocket(socket, state, context, effectiveServername);
}
clearTimeout(state.connectTimer);
state.lifetimeTimer = setTimeout(() => this.finish(state,
failure("deadlineExceeded", "Byte stream lifetime exceeded")), state.limits.lifetimeMs);
state.lifetimeTimer.unref?.();
+18 -1
View File
@@ -323,11 +323,27 @@ class PluginByteStreamService {
registry.registerRequest("network.stream.upgradeTls", async ({ handleId, servername, allowSelfSigned, caPem }, caller) => {
const context = await this.authenticate(caller);
const record = this.get(handleId, context);
const signals = [context.signal, record.context.signal].filter(Boolean);
const combinedSignal = signals.length > 1
? AbortSignal.any(signals)
: signals[0];
const upgradeContext = {
...record.context,
signal: combinedSignal,
assertActive: async () => {
await context.assertActive();
await record.context.assertActive();
},
assertCommit: () => {
context.assertCommit?.();
record.context.assertCommit?.();
},
};
return this.broker.upgradeTls(handleId, {
...(servername === undefined ? {} : { servername }),
allowSelfSigned: allowSelfSigned === true,
...(caPem === undefined ? {} : { caPem }),
}, record.context);
}, upgradeContext);
}, { validateParams: validator("ByteStreamUpgradeTlsRequest"), metadata: { capability: "network.stream", mutating: true, public: true } });
registry.registerRequest("network.stream.attach", async ({ handleId }, caller) => {
@@ -362,6 +378,7 @@ class PluginByteStreamService {
const record = [...this.records.values()].find((item) => item.inputStreamId === stream.streamId);
if (!record) return false;
const context = await this.authenticate(caller);
if (record.closing || this.records.get(record.handleId) !== record) return false;
this.get(record.handleId, context);
if (record.input || stream.windowBytes !== LIMITS.bufferBytes) throw denied();
record.input = stream;
+31 -3
View File
@@ -53,6 +53,12 @@ function probeTcpReachability({ host, port, timeoutMs, signal }) {
socket.once("timeout", () => {
finish({ reachable: true, protocol: "ssh", port, rttMs, bannerVerified: false });
});
socket.once("end", () => {
finish({ reachable: true, protocol: "ssh", port, rttMs, bannerVerified: false });
});
socket.once("close", () => {
finish({ reachable: true, protocol: "ssh", port, rttMs, bannerVerified: false });
});
});
socket.once("timeout", onConnectTimeout);
socket.once("error", (err) => finish({ reachable: false, protocol: "ssh", port, rttMs: null, bannerVerified: false, error: String(err?.message || "Connection failed").slice(0, 256) }));
@@ -272,7 +278,12 @@ class PluginHostCapabilitiesService {
for (const op of ["start", "stop", "delete"]) {
registry.registerRequest(`portForward.${op}`, async (params, context) => {
await context.assertActive();
return this.vaultDataBridge.request(`portForward.${op}`, { ruleId: params.ruleId }, context.signal);
return this.vaultDataBridge.request(
`portForward.${op}`,
{ ruleId: params.ruleId },
context.signal,
op === "start" ? { timeoutMs: 30_000 } : undefined,
);
}, {
metadata: { capability: "portForward", mutating: true },
validateParams: (params) => this.#validate("PortForwardRuleIdParams", params),
@@ -481,11 +492,19 @@ class PluginHostCapabilitiesService {
port: configuredPort,
securityMode: target.rdpSecurityMode || "auto",
mode: "heartbeat",
tcpTimeoutMs: timeoutMs,
connectTimeoutMs: timeoutMs,
handshakeTimeoutMs: Math.min(timeoutMs, 3_000),
},
{ signal: controller.signal },
);
if (this.closed || this.isLocked()) {
throw fail("unavailable", "Host probe is unavailable");
}
if (controller.signal.aborted) {
throw controller.signal.reason instanceof PluginRpcError
? controller.signal.reason
: fail("cancelled", "Host probe cancelled");
}
return {
reachable: Boolean(res?.ok || res?.reachable),
protocol,
@@ -498,7 +517,16 @@ class PluginHostCapabilitiesService {
};
}
return await this.probeTcp({ host: target.hostname, port: configuredPort, timeoutMs, signal: controller.signal });
const tcpRes = await this.probeTcp({ host: target.hostname, port: configuredPort, timeoutMs, signal: controller.signal });
if (this.closed || this.isLocked()) {
throw fail("unavailable", "Host probe is unavailable");
}
if (controller.signal.aborted) {
throw controller.signal.reason instanceof PluginRpcError
? controller.signal.reason
: fail("cancelled", "Host probe cancelled");
}
return tcpRes;
} finally {
context.signal?.removeEventListener("abort", onAbort);
this.activeProbes.delete(lease);
+20 -5
View File
@@ -630,6 +630,10 @@ class PluginHostInteractionService {
await fs.unlink(stagingPath).catch(() => {});
throw error;
}
if (this.fileHandles.get(handle.id) !== handle) {
await fs.unlink(stagingPath).catch(() => {});
throw fail("unavailable", "File handle was closed during write");
}
handle.stagingPath = stagingPath;
handle.stagingBytes = buf.byteLength;
} else {
@@ -649,11 +653,11 @@ class PluginHostInteractionService {
}
const totalSize = handle.stagingBytes;
if (commit) {
await context.assertActive();
const temp = handle.stagingPath;
handle.stagingPath = null;
handle.stagingBytes = 0;
try {
await context.assertActive();
await fs.rename(temp, handle.filePath);
} catch (error) {
await fs.unlink(temp).catch(() => {});
@@ -687,7 +691,7 @@ class PluginHostInteractionService {
setReady(sender, ready) {
const window = this.getWindow();
if (!sender || window?.webContents !== sender || sender.isDestroyed?.()) {
if (!sender || !window || window.isDestroyed?.() || window.webContents !== sender || sender.isDestroyed?.()) {
throw fail("permissionDenied", "Host interaction window is not the owner");
}
if (typeof ready !== "boolean") throw fail("invalidArgument", "Host interaction readiness is invalid");
@@ -726,7 +730,7 @@ class PluginHostInteractionService {
#assertWindow(sender = this.owner) {
const window = this.getWindow();
if (this.closed || this.isLocked() || !sender || sender !== this.owner
|| window?.webContents !== sender || window.isDestroyed?.()
|| !window || window.isDestroyed?.() || window.webContents !== sender
|| sender.isDestroyed?.() || window.isVisible?.() === false || window.isFocused?.() !== true) {
throw fail("unavailable", "Host interactions require the focused unlocked main window");
}
@@ -820,8 +824,8 @@ class PluginHostInteractionService {
throw fail("cancelled", "Host interaction admission was revoked");
}
const window = this.getWindow();
if (this.closed || this.isLocked() || window?.webContents !== admission.sender
|| window.isDestroyed?.() || admission.sender.isDestroyed?.() || window.isVisible?.() === false) {
if (this.closed || this.isLocked() || !window || window.isDestroyed?.() || window.webContents !== admission.sender
|| admission.sender.isDestroyed?.() || window.isVisible?.() === false) {
throw fail("unavailable", "Host interaction owner is unavailable");
}
if (window.isFocused?.() === true) break;
@@ -935,6 +939,14 @@ class PluginHostInteractionService {
});
}
if (this.vaultService?.isRequest(entry.params)) {
const hostStreamConnectMs = schema.$defs.HostByteStreamLimits?.const?.connectMs ?? 120_000;
if (entry.params.kind === "network.stream.connectViaHost" && response.action === "commit") {
const extendedMs = Math.max(this.timeoutMs, hostStreamConnectMs);
if (entry.timer) clearTimeout(entry.timer);
entry.expiresAt = this.clock() + extendedMs;
entry.timer = setTimeout(() => this.#finish(entry, null, fail("deadlineExceeded", "Host interaction expired")), extendedMs);
entry.timer.unref?.();
}
const outcome = await this.vaultService.respond(entry, response, nativeOptions);
await entry.context.assertActive();
this.#assertWindow(sender);
@@ -972,6 +984,9 @@ class PluginHostInteractionService {
let rawText;
try { rawText = await this.clipboard.readText(); }
catch { throw fail("unavailable", "Host clipboard text is unavailable"); }
await entry.context.assertActive();
this.#assertWindow(sender);
if (this.pending.get(entry.id) !== entry) return false;
const text = assertTextBytes(rawText, LIMITS.clipboardBytes);
this.quotaManager.chargeBytes(entry.context.runtimeId, "clipboard", Buffer.byteLength(text));
entry.previewText = text;
+482 -120
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() {
@@ -25,8 +37,9 @@ function loadVendorDetector() {
* Host-owned pooled SSH exec transport for sandboxed plugins.
*
* - Reuses Netcatty's main-process SSH dialer (`portForwardingBridge.startPortForward`
* with `reuseTransport: true` and `bindChannels`), inheriting jump hosts, proxies,
* passphrase prompts, FIDO2, and host-key verification.
* with `reuseTransport: false` and `bindChannels`), inheriting jump hosts, proxies,
* passphrase prompts, FIDO2, and host-key verification while keeping plugin
* connections isolated in this transport's own `(runtimeId, hostId)` pool.
* - Caches live authenticated `ssh2` transports per `(runtimeId, hostId)` with idle
* eviction so periodic monitoring polls execute in ~5-30ms without new SSH handshakes
* or renderer IPC roundtrips.
@@ -41,13 +54,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 +94,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 +282,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 +294,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: false,
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 +586,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();
@@ -270,6 +611,10 @@ class PluginHostSshExecTransport {
});
await assertActive?.();
controller.signal.throwIfAborted();
if (!this.#isEntryHealthy(entry)) {
void this.#closeEntry(entry);
throw fail("unavailable", "Host SSH connection closed before acquisition");
}
entry.activeCount += 1;
acquired = true;
if (entry.idleTimer) {
@@ -330,7 +675,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 });
@@ -351,6 +696,10 @@ class PluginHostSshExecTransport {
await assertActive?.();
controller.signal.throwIfAborted();
if (!this.#isEntryHealthy(entry)) {
void this.#closeEntry(entry);
throw fail("unavailable", "Host SSH connection closed before execution");
}
entry.activeCount += 1;
acquired = true;
@@ -371,10 +720,20 @@ 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"
|| err?.code === "SSH_EXEC_OPEN_PENDING"
|| isDeadlineAbort
) {
void this.#closeEntry(entry);
}
if (err instanceof PluginRpcError) throw err;
@@ -382,7 +741,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 +781,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 +799,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 +817,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 +834,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 +857,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,803 @@
"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();
});
test("PluginHostSshExecTransport dials with reuseTransport: false and reconnects cleanly after idle eviction", async () => {
const observedReuseFlags = [];
let dialCount = 0;
const portForwardingBridge = {
async startPortForward(_event, opts, hooks) {
dialCount += 1;
observedReuseFlags.push(opts.reuseTransport);
const conn = createFakeConn();
await hooks.bindChannels({
conn,
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
chainConnections: [],
});
return { success: true };
},
async stopPortForward(_event, { tunnelId }) {
return { tunnelId, success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
measurePing: async () => 4,
getSender: () => ({ id: 3 }),
idleTtlMs: 25,
});
const first = await transport.exec(createBaseExecArgs({ command: "poll-1" }));
assert.equal(first.stdout, "ok:poll-1");
assert.equal(dialCount, 1);
// Wait for idle eviction to tear down the pooled connection.
for (let i = 0; i < 40 && transport.connections.size > 0; i += 1) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
assert.equal(transport.connections.size, 0, "idle entry should be evicted");
const second = await transport.exec(createBaseExecArgs({ command: "poll-2" }));
assert.equal(second.stdout, "ok:poll-2");
assert.equal(dialCount, 2);
assert.deepEqual(observedReuseFlags, [false, false]);
transport.shutdown();
});
test("SSH_EXEC_OPEN_PENDING evicts the wedged pooled connection so the next retry dials fresh", async () => {
let dialCount = 0;
let execCalls = 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(_event, { tunnelId }) {
return { tunnelId, success: true };
},
};
const transport = new PluginHostSshExecTransport({
portForwardingBridge,
execCommand: async (_conn, command) => {
execCalls += 1;
if (execCalls === 1) {
const err = new Error("SSH exec channel open still pending on this connection");
err.code = "SSH_EXEC_OPEN_PENDING";
throw err;
}
return { stdout: `ok:${command}`, stderr: "", code: 0 };
},
measurePing: async () => 2,
getSender: () => ({ id: 4 }),
});
await assert.rejects(
transport.exec(createBaseExecArgs({ command: "stuck" })),
(err) => err.code === RPC_ERRORS.unavailable,
);
assert.equal(transport.connections.size, 0, "wedged connection must be evicted on SSH_EXEC_OPEN_PENDING");
const recovered = await transport.exec(createBaseExecArgs({ command: "recovered" }));
assert.equal(recovered.stdout, "ok:recovered");
assert.equal(dialCount, 2, "next retry must dial a fresh SSH connection");
transport.shutdown();
});
+39 -9
View File
@@ -4,7 +4,11 @@ const posixPath = require("node:path").posix;
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
const schema = require("./generated/plugin-contract.schema.json");
const fail = (code, message) => new PluginRpcError(RPC_ERRORS[code], message);
const fail = (code, message, cause) => {
const err = new PluginRpcError(RPC_ERRORS[code], message);
if (cause !== undefined) err.cause = cause;
return err;
};
const SFTP_LIMITS = schema.$defs.VaultHostSftpLimits.const;
const S_IFMT = 0o170000;
@@ -127,7 +131,7 @@ class PluginHostSshSftpTransport {
}
settled = true;
if (err || !sftp) {
reject(fail("unavailable", err?.message || "Failed to open SFTP subsystem"));
reject(fail("unavailable", err?.message || "Failed to open SFTP subsystem", err));
return;
}
const evict = () => {
@@ -147,15 +151,33 @@ class PluginHostSshSftpTransport {
return raceWithCallerSignal(opening, callerSignal);
}
#evictSftp(conn) {
const cached = this.sftpByConn.get(conn);
if (!cached) return;
this.sftpByConn.delete(conn);
void cached.then((sftp) => {
try { sftp?.end?.(); } catch { /* ignore */ }
}).catch(() => {});
}
async #withSftp(ctx, operation) {
const lease = await this.sshExecTransport.acquireConnection(ctx);
try {
const sftp = await this.#openSftp(lease.conn, lease.signal);
return await runWithOperationSignal(lease.signal, SFTP_LIMITS.timeoutMs, (opSignal) => operation(sftp, opSignal));
} catch (err) {
const rawCode = err?.cause?.code ?? err?.code;
const isTransportBroken =
rawCode === "ECONNRESET"
|| rawCode === "EPIPE"
|| rawCode === "ETIMEDOUT"
|| err?.code === RPC_ERRORS.deadlineExceeded;
if (isTransportBroken) {
this.#evictSftp(lease.conn);
lease.invalidate();
}
if (err instanceof PluginRpcError) throw err;
if (lease.signal.aborted) throw fail("cancelled", "SFTP operation was cancelled");
if (err?.code === "ECONNRESET" || err?.code === "EPIPE") lease.invalidate();
throw fail("unavailable", err?.message ? String(err.message).slice(0, 256) : "SFTP operation failed");
} finally {
lease.release();
@@ -167,7 +189,7 @@ class PluginHostSshSftpTransport {
return this.#withSftp(ctx, (sftp) => new Promise((resolve, reject) => {
sftp.readdir(p, (err, list) => {
if (err) {
reject(fail(err.code === 2 ? "notFound" : "unavailable", err.message || "Failed to list directory"));
reject(fail(err.code === 2 ? "notFound" : "unavailable", err.message || "Failed to list directory", err));
return;
}
const items = Array.isArray(list) ? list : [];
@@ -193,7 +215,7 @@ class PluginHostSshSftpTransport {
resolve({ exists: false });
return;
}
reject(fail("unavailable", err.message || "Failed to stat remote path"));
reject(fail("unavailable", err.message || "Failed to stat remote path", err));
return;
}
resolve({
@@ -215,6 +237,7 @@ class PluginHostSshSftpTransport {
const chunks = [];
let total = 0;
let truncated = false;
let ended = false;
const onAbort = () => {
try { stream.destroy(); } catch { /* ignore */ }
};
@@ -244,11 +267,17 @@ class PluginHostSshSftpTransport {
});
return;
}
reject(fail(err?.code === 2 ? "notFound" : "unavailable", err?.message || "Failed to read remote file"));
const rpcErr = fail(err?.code === 2 ? "notFound" : "unavailable", err?.message || "Failed to read remote file");
rpcErr.cause = err;
reject(rpcErr);
});
stream.once("close", () => {
signal.removeEventListener("abort", onAbort);
if (!truncated) return;
if (ended) return;
if (!truncated) {
reject(fail("unavailable", "Remote SFTP read closed before completion"));
return;
}
const combined = Buffer.concat(chunks, total);
resolve({
data: encoding === "base64" ? combined.toString("base64") : combined.toString("utf8"),
@@ -258,6 +287,7 @@ class PluginHostSshSftpTransport {
});
});
stream.once("end", () => {
ended = true;
signal.removeEventListener("abort", onAbort);
const combined = Buffer.concat(chunks, total);
resolve({
@@ -288,7 +318,7 @@ class PluginHostSshSftpTransport {
});
stream.once("error", (err) => {
signal.removeEventListener("abort", onAbort);
reject(fail("unavailable", err?.message || "Failed to write remote file"));
reject(fail("unavailable", err?.message || "Failed to write remote file", err));
});
stream.once("close", () => {
signal.removeEventListener("abort", onAbort);
@@ -307,7 +337,7 @@ class PluginHostSshSftpTransport {
return this.#withSftp(ctx, (sftp) => new Promise((resolve, reject) => {
sftp.mkdir(p, (err) => {
if (err) {
reject(fail("unavailable", err.message || "Failed to create remote directory"));
reject(fail("unavailable", err.message || "Failed to create remote directory", err));
return;
}
resolve({ created: true });
+5 -2
View File
@@ -103,7 +103,7 @@ class PluginHostVaultDataBridge {
return true;
}
request(kind, payload, signal) {
request(kind, payload, signal, options = {}) {
if (!ALLOWED_KINDS.has(kind)) {
return Promise.reject(fail("invalidArgument", "Unsupported Vault data request"));
}
@@ -119,6 +119,9 @@ class PluginHostVaultDataBridge {
if (this.pending.size >= MAX_PENDING) {
return Promise.reject(fail("resourceExhausted", "Too many pending Vault data requests"));
}
const requestTimeoutMs = Number.isFinite(options?.timeoutMs) && options.timeoutMs > 0
? Math.min(Math.round(options.timeoutMs), 30_000)
: this.timeoutMs;
const requestId = randomUUID();
const actionToken = randomBytes(24).toString("base64url");
return new Promise((resolve, reject) => {
@@ -143,7 +146,7 @@ class PluginHostVaultDataBridge {
signal?.addEventListener("abort", entry.onAbort, { once: true });
entry.timer = setTimeout(() => {
finish(fail("deadlineExceeded", "Vault data request timed out"));
}, this.timeoutMs);
}, requestTimeoutMs);
entry.timer.unref?.();
this.pending.set(requestId, entry);
try {
+6 -5
View File
@@ -20,7 +20,7 @@ class PluginPermissionDecisionHost {
setReady(sender, ready) {
if (this.closed) throw permissionDenied("Permission UI is closed");
const window = this.getWindows().find((candidate) => candidate?.webContents === sender);
const window = this.getWindows().find((candidate) => candidate && !candidate.isDestroyed?.() && candidate.webContents === sender);
if (!window || window.isDestroyed?.() || sender.isDestroyed?.() || typeof ready !== "boolean") {
throw permissionDenied("Permission UI sender is invalid");
}
@@ -42,14 +42,15 @@ class PluginPermissionDecisionHost {
}
get owner() {
return this.getWindows().find((window) => this.owners.has(window?.webContents)
&& !window.isDestroyed?.() && window.isFocused?.() && window.isVisible?.())?.webContents ?? null;
const win = this.getWindows().find((window) => window && !window.isDestroyed?.()
&& this.owners.has(window.webContents) && window.isFocused?.() && window.isVisible?.());
return win ? win.webContents : null;
}
assertOwner(sender = this.owner) {
const window = this.owners.get(sender)?.window;
if (this.closed || !sender || !window || !this.getWindows().includes(window) || window.webContents !== sender || sender.isDestroyed?.()
|| window.isDestroyed?.() || !window.isFocused?.() || !window.isVisible?.() || this.isLocked()) {
if (this.closed || !sender || !window || window.isDestroyed?.() || !this.getWindows().includes(window) || window.webContents !== sender || sender.isDestroyed?.()
|| !window.isFocused?.() || !window.isVisible?.() || this.isLocked()) {
throw permissionDenied("Permission UI requires a focused unlocked app window");
}
}
+7 -1
View File
@@ -387,6 +387,12 @@ class PluginAISidebarService {
throw new PluginRpcError(RPC_ERRORS.unavailable, "Plugin runtime supervisor is unavailable");
}
const rawDeadline = Number.isSafeInteger(options.deadlineMs)
? options.deadlineMs
: Number.isSafeInteger(options.timeoutMs)
? options.timeoutMs
: TOOL_INVOKE_DEADLINE_MS;
const timeoutMs = Math.max(1, Math.min(300_000, rawDeadline));
const rawResult = await this.runtimeSupervisor.request(
pluginId,
"plugin.ai.invokeTool",
@@ -397,7 +403,7 @@ class PluginAISidebarService {
...(chatSessionId ? { chatSessionId } : {}),
},
{
deadlineMs: Number.isSafeInteger(options.deadlineMs) ? options.deadlineMs : TOOL_INVOKE_DEADLINE_MS,
timeoutMs,
signal: options.signal,
},
);
@@ -275,3 +275,37 @@ test("ai.openSidebar enforces active ai.invoke approval for autoSend: true while
/disabled|denied/i,
);
});
test("PluginAISidebarService.invokeTool forwards timeoutMs to runtimeSupervisor.request", async () => {
const captured = [];
const supervisor = {
async request(pluginId, method, params, options) {
captured.push({ pluginId, method, params, options });
return { ok: true };
},
};
const service = new PluginAISidebarService({
runtimeSupervisor: supervisor,
});
service.registerTools({
viewId: "com.example.db.workbench",
tools: [{ name: "query_schema", description: "Inspect schema", inputSchema: { type: "object", properties: {} }, risk: "read" }],
}, ctx());
await service.invokeTool({
pluginId: manifest.id,
toolName: "query_schema",
args: {},
});
assert.equal(captured.length, 1);
assert.equal(captured[0].options.timeoutMs, 45_000);
await service.invokeTool({
pluginId: manifest.id,
toolName: "query_schema",
args: {},
}, {
deadlineMs: 60_000,
});
assert.equal(captured[1].options.timeoutMs, 60_000);
});
+55 -30
View File
@@ -237,6 +237,24 @@ function createTrustedPluginBridgeSender(options = {}) {
function registerPluginBridge(ipcMain, options) {
const manager = options.manager;
const observeSenderReset = (sender, onReset) => {
const run = () => {
try { onReset(); } catch { /* ignore */ }
};
const onNavigate = (details, _url, isInPlace, isMainFrame) => {
const main = details?.isMainFrame ?? isMainFrame;
const sameDocument = details?.isSameDocument ?? isInPlace;
if (main !== false && sameDocument !== true) run();
};
const onDestroyed = () => {
sender.removeListener?.("render-process-gone", run);
sender.removeListener?.("did-start-navigation", onNavigate);
run();
};
sender.once?.("destroyed", onDestroyed);
sender.on?.("render-process-gone", run);
sender.on?.("did-start-navigation", onNavigate);
};
let githubService;
const githubOwners = new WeakSet();
const githubFor = (activeManager, event) => {
@@ -244,7 +262,7 @@ function registerPluginBridge(ipcMain, options) {
githubService ??= new GitHubInstallService({ manager: activeManager });
if (!githubOwners.has(event.sender)) {
githubOwners.add(event.sender);
event.sender.once?.("destroyed", () => { void githubService.discard(event.sender).catch(() => {}); });
observeSenderReset(event.sender, () => { void githubService.discard(event.sender).catch(() => {}); });
}
return githubService;
};
@@ -349,7 +367,7 @@ function registerPluginBridge(ipcMain, options) {
}
if (!observedTerminalRequestSenders.has(sender)) {
observedTerminalRequestSenders.add(sender);
sender.once?.("destroyed", () => {
observeSenderReset(sender, () => {
for (const controller of requests.values()) controller.abort();
requests.clear();
});
@@ -365,7 +383,7 @@ function registerPluginBridge(ipcMain, options) {
}
if (!observedExtensionRequestSenders.has(sender)) {
observedExtensionRequestSenders.add(sender);
sender.once?.("destroyed", () => {
observeSenderReset(sender, () => {
for (const controller of requests.values()) controller.abort();
requests.clear();
});
@@ -401,7 +419,7 @@ function registerPluginBridge(ipcMain, options) {
}
if (!observedConnectionSenders.has(sender)) {
observedConnectionSenders.add(sender);
sender.once?.("destroyed", () => {
observeSenderReset(sender, () => {
const monitors = connectionMonitorsBySender.get(sender);
for (const monitor of monitors?.values?.() ?? []) monitor.controller.abort();
monitors?.clear?.();
@@ -441,7 +459,7 @@ function registerPluginBridge(ipcMain, options) {
}
if (!observedAuthenticationSenders.has(sender)) {
observedAuthenticationSenders.add(sender);
sender.once?.("destroyed", () => {
observeSenderReset(sender, () => {
for (const pending of challenges.values()) pending.reject(new Error("Plugin authentication window closed"));
challenges.clear();
});
@@ -600,7 +618,7 @@ function registerPluginBridge(ipcMain, options) {
}
if (!observedImporterSelectionSenders.has(sender)) {
observedImporterSelectionSenders.add(sender);
sender.once?.("destroyed", () => {
observeSenderReset(sender, () => {
for (const selection of selections.values()) closeImporterSelection(selection);
selections.clear();
});
@@ -623,7 +641,7 @@ function registerPluginBridge(ipcMain, options) {
}
if (!observedSyncTransferSenders.has(sender)) {
observedSyncTransferSenders.add(sender);
sender.once?.("destroyed", () => {
observeSenderReset(sender, () => {
for (const [transferId, transfer] of [...transfers.entries()]) {
try {
transfer.controller?.abort();
@@ -995,6 +1013,9 @@ function registerPluginBridge(ipcMain, options) {
const result = await extensionProviderService.readSyncObject(payload ?? {}, {
signal: controller.signal,
});
if (controller.signal.aborted) {
throw controller.signal.reason ?? new DOMException("Sync object read cancelled", "AbortError");
}
if (!result?.found || !result.bytes) {
extensionRequestMap(event.sender).delete(requestId);
return { found: false, key: payload?.key, data: null };
@@ -1460,6 +1481,7 @@ function registerPluginBridge(ipcMain, options) {
),
onClose: async () => {
acceptProviderOutput = false;
closedDuringStart = true;
if (sessions.get(sessionId) === sessionOwner) sessions.delete(sessionId);
if (monitors.get(sessionId)?.sessionOwner === sessionOwner) monitors.delete(sessionId);
connectionController.abort(new DOMException("Terminal session closed", "AbortError"));
@@ -1533,30 +1555,33 @@ function registerPluginBridge(ipcMain, options) {
},
});
providerOpened = true;
if (!closedDuringStart) {
sessions.set(opened.sessionId, sessionOwner);
monitors.set(opened.sessionId, { sessionOwner, controller: connectionController });
if (opened.status === "connected") {
// The terminal renderer treats the first delivery as the connection
// readiness boundary. Preserve that boundary for silent protocols
// whose Provider completes open before producing terminal bytes.
await terminalWorkerManager.pushExternalOutput(
opened.sessionId,
"",
pluginConnectionReadyMeta,
sessionOwner,
);
}
void monitorPluginConnection({
sessionId: opened.sessionId,
sessionOwner,
sessions,
monitors,
controller: connectionController,
terminalWorkerManager,
readyPublished: opened.status === "connected",
});
if (closedDuringStart || connectionController.signal.aborted) {
try { await extensionProviderService.control(opened.sessionId, "close", {}, { sessionOwner }); }
catch { extensionProviderService.closeSessionLocal(opened.sessionId, undefined, sessionOwner); }
return opened;
}
sessions.set(opened.sessionId, sessionOwner);
monitors.set(opened.sessionId, { sessionOwner, controller: connectionController });
if (opened.status === "connected") {
// The terminal renderer treats the first delivery as the connection
// readiness boundary. Preserve that boundary for silent protocols
// whose Provider completes open before producing terminal bytes.
await terminalWorkerManager.pushExternalOutput(
opened.sessionId,
"",
pluginConnectionReadyMeta,
sessionOwner,
);
}
void monitorPluginConnection({
sessionId: opened.sessionId,
sessionOwner,
sessions,
monitors,
controller: connectionController,
terminalWorkerManager,
readyPublished: opened.status === "connected",
});
return opened;
} catch (error) {
acceptProviderOutput = false;
+5 -1
View File
@@ -37,7 +37,11 @@ class PluginManager {
#mutate(operation) {
if (this.shuttingDown) return Promise.reject(new Error("Plugin manager is shutting down"));
const result = this.mutationTail.then(operation, operation);
const guarded = () => {
if (this.shuttingDown) return Promise.reject(new Error("Plugin manager is shutting down"));
return operation();
};
const result = this.mutationTail.then(guarded, guarded);
this.mutationTail = result.then(() => undefined, () => undefined);
return result;
}
+10
View File
@@ -318,6 +318,16 @@ class PluginRpcRouter {
signal: controller.signal,
notification: true,
})), controller.signal);
} catch (error) {
// Non-protocol application/authorization errors on a fire-and-forget
// notification (e.g. denied permission or App Lock) must not escalate
// to a fatal protocol violation that terminates and quarantines the plugin.
if (!(error instanceof PluginRpcError)
|| error.code === RPC_ERRORS.parseError
|| error.code === RPC_ERRORS.invalidRequest
|| error.code === RPC_ERRORS.invalidParams) {
throw error;
}
} finally {
clearTimeout(timer);
this.inflightNotifications.delete(controller);
+17
View File
@@ -425,3 +425,20 @@ test("oversized control messages close the peer before dispatch", async () => {
assert.equal(fixture.router.closed, true);
assert.match(fixture.protocolErrors[0].message, /exceeds/);
});
test("notification permission denial does not escalate to a protocol error or close the peer", async () => {
const fixture = createRouter({
notificationHandlers: {
"views.postMessage": async () => {
throw new PluginRpcError(RPC_ERRORS.permissionDenied, "Plugin permission is disabled");
},
},
});
await fixture.router.accept({
jsonrpc: "2.0",
method: "views.postMessage",
params: { viewId: "com.example.demo.view", message: { ok: true } },
});
assert.equal(fixture.protocolErrors.length, 0);
assert.equal(fixture.router.closed, false);
});
+26 -4
View File
@@ -4,7 +4,11 @@ import { PLUGIN_BYTE_STREAM_FEATURE } from "@netcatty/plugin-contract";
export async function connectByteStream({ client, streams, subscriptions, enabledFeatures }, request, cancellationToken, viaHost = false) {
if (!enabledFeatures.includes(PLUGIN_BYTE_STREAM_FEATURE)) throw new PluginError("unsupported", "Byte stream feature is unavailable");
if (viaHost && !enabledFeatures.includes("network.host-byte-streams")) throw new PluginError("unsupported", "Host byte stream feature is unavailable");
const descriptor = await client.request(viaHost ? "network.stream.connectViaHost" : "network.stream.connect", request, { cancellationToken, ...(viaHost ? { deadlineMs: 120_000 } : {}) });
const descriptor = await client.request(
viaHost ? "network.stream.connectViaHost" : "network.stream.connect",
request,
{ cancellationToken, deadlineMs: 120_000 },
);
if (descriptor.cancelled) throw new PluginError("cancelled", "Host connection cancelled");
let readable;
let writable;
@@ -12,12 +16,18 @@ export async function connectByteStream({ client, streams, subscriptions, enable
let closing;
let cancellation;
let connection;
const detachLocal = () => {
cancellation?.dispose();
cancellation = undefined;
if (connection) subscriptions.delete(connection);
};
const close = () => {
closing ??= client.request("network.stream.close", { handleId: descriptor.handleId })
.finally(() => {
cancellation?.dispose();
detachLocal();
try { readable?.cancel(); } catch {}
try { writable?.cancel(); } catch {}
streams.rejectReadable(descriptor.outputStreamId);
if (connection) subscriptions.delete(connection);
});
return closing;
};
@@ -45,7 +55,19 @@ export async function connectByteStream({ client, streams, subscriptions, enable
endpoint: descriptor.endpoint,
...(descriptor.hostBindingToken ? { hostBindingToken: descriptor.hostBindingToken } : {}),
readable: Object.freeze({
id: readable.id, read: () => readable.read(), cancel, dispose: cancel,
id: readable.id,
read: () => readable.read().then(
(chunk) => {
if (chunk === null) detachLocal();
return chunk;
},
(error) => {
detachLocal();
throw error;
},
),
cancel,
dispose: cancel,
}),
writable: Object.freeze({
id: writable.id, write: (bytes) => writable.write(bytes), end: () => writable.end(),
@@ -41,11 +41,24 @@ function closedError(streamId) {
return new PluginError("unavailable", `Plugin stream is closed: ${streamId}`);
}
const MAX_RETIRED_STREAM_IDS = 512;
function rememberRetiredStreamId(set, streamId) {
set.delete(streamId);
set.add(streamId);
while (set.size > MAX_RETIRED_STREAM_IDS) {
const oldest = set.values().next().value;
set.delete(oldest);
}
}
export function createPluginStreamEndpoint(transport, options = {}) {
const maxStreams = options.maxStreams ?? 128;
const incoming = new Map();
const outgoing = new Map();
const pendingIncoming = new Map();
const retiredIncoming = new Set();
const retiredOutgoing = new Set();
let closed = false;
const sendEnvelope = (frame, transfer) => {
@@ -87,10 +100,22 @@ export function createPluginStreamEndpoint(transport, options = {}) {
}
function closeIncoming(state, error, notify = false, refundCancelledCredit = false) {
if (state.closed) return;
if (state.closed) {
// Peer already sent "end", but consumer cancelled/disposed before reading
// EOF null or draining buffered chunks. Refund remaining credit so the
// host can retire its outgoing stream slot.
if (notify && !state.error && (state.currentCreditBytes > 0 || state.queue.length > 0)) {
state.currentCreditBytes += state.queue.reduce((sum, chunk) => sum + chunk.creditBytes, 0);
state.queue.length = 0;
try { releaseCurrent(state); } catch {}
state.currentCreditBytes = 0;
}
return;
}
state.closed = true;
state.error = error ?? null;
incoming.delete(state.streamId);
if (notify) rememberRetiredStreamId(retiredIncoming, state.streamId);
if (error) {
// Discard unread bytes on cancellation/failure and settle their credit
// now. A later read must surface the error without sending more credit.
@@ -216,6 +241,7 @@ export function createPluginStreamEndpoint(transport, options = {}) {
state.terminal = "error";
state.closed = true;
outgoing.delete(state.streamId);
rememberRetiredStreamId(retiredOutgoing, state.streamId);
const failure = new PluginError("data_loss", String(error?.message ?? "Plugin stream failed"));
for (const pending of state.queue.splice(0)) pending.reject(failure);
state.queuedBytes = 0;
@@ -231,7 +257,7 @@ export function createPluginStreamEndpoint(transport, options = {}) {
});
},
cancel() {
if (state.closed) return;
if (state.closed || state.terminalSent) return;
state.closed = true;
state.terminal = "cancel";
const error = new PluginError("cancelled", "Plugin stream was cancelled");
@@ -246,7 +272,10 @@ export function createPluginStreamEndpoint(transport, options = {}) {
});
state.terminalSent = true;
} finally {
if (!state.terminalSent || state.availableBytes === state.windowBytes) outgoing.delete(state.streamId);
if (!state.terminalSent || state.availableBytes === state.windowBytes) {
outgoing.delete(state.streamId);
if (state.terminalSent) rememberRetiredStreamId(retiredOutgoing, state.streamId);
}
}
},
dispose() { this.cancel(); },
@@ -292,6 +321,7 @@ export function createPluginStreamEndpoint(transport, options = {}) {
if (output.terminalSent && output.availableBytes === output.windowBytes) {
output.closed = true;
outgoing.delete(frame.streamId);
rememberRetiredStreamId(retiredOutgoing, frame.streamId);
} else flushOutgoing(output);
return true;
}
@@ -304,8 +334,18 @@ export function createPluginStreamEndpoint(transport, options = {}) {
output.endReject?.(error);
return true;
}
if ((frame.kind === "windowUpdate" || frame.kind === "cancel") && retiredOutgoing.has(frame.streamId)) {
if (frame.kind === "cancel") retiredOutgoing.delete(frame.streamId);
return true;
}
const input = incoming.get(frame.streamId);
if (!input || input.closed) throw new PluginError("data_loss", `Unknown Plugin stream: ${frame.streamId}`);
if (!input || input.closed) {
if (retiredIncoming.has(frame.streamId)) {
if (frame.kind !== "chunk") retiredIncoming.delete(frame.streamId);
return true;
}
throw new PluginError("data_loss", `Unknown Plugin stream: ${frame.streamId}`);
}
if (frame.sequence !== input.nextSequence) {
throw new PluginError("data_loss", `Plugin stream frame is out of order: ${frame.streamId}`);
}
+87 -31
View File
@@ -291,17 +291,24 @@ function createHostClient(transport) {
return new Promise((resolve, reject) => {
const cancellationId = options.cancellationToken ? `browser-${id}` : undefined;
const pendingRequest = { resolve, reject };
pending.set(`${typeof id}:${String(id)}`, pendingRequest);
transport.post({
jsonrpc: "2.0",
id,
method,
...(sanitizedParams === undefined ? {} : { params: sanitizedParams }),
...(cancellationId === undefined ? {} : { cancellationId }),
...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),
});
const pendingKey = `${typeof id}:${String(id)}`;
pending.set(pendingKey, pendingRequest);
try {
transport.post({
jsonrpc: "2.0",
id,
method,
...(sanitizedParams === undefined ? {} : { params: sanitizedParams }),
...(cancellationId === undefined ? {} : { cancellationId }),
...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),
});
} catch (error) {
pending.delete(pendingKey);
reject(new PluginError("unavailable", error instanceof Error ? error.message : "Plugin host transport failed"));
return;
}
pendingRequest.cancellation = options.cancellationToken?.onCancellationRequested(() => {
notify("$/cancelRequest", { cancellationId });
try { notify("$/cancelRequest", { cancellationId }); } catch {}
});
});
}
@@ -791,7 +798,7 @@ function createPluginContext(config, client, runtimeApi) {
}),
};
const aiBase = Object.fromEntries(["openChat", "startTurn", "readTurn", "stopTurn", "closeChat"].map((operation) => [
operation, (params) => client.request(`ai.${operation}`, params, operation === "readTurn" ? { deadlineMs: 65_000 } : {}),
operation, (params) => client.request(`ai.${operation}`, params, { deadlineMs: 65_000 }),
]));
const ai = {
...aiBase,
@@ -821,24 +828,50 @@ function createPluginContext(config, client, runtimeApi) {
...(toolViewId ? { viewId: toolViewId } : {}),
};
});
await client.request("ai.registerTools", {
...(viewId ? { viewId } : {}),
tools: normalizedTools,
});
const prevBucket = runtimeApi.aiToolBuckets.get(scopeKey);
const prevExecutors = new Map();
if (prevBucket) {
for (const name of prevBucket.names) {
if (runtimeApi.aiToolExecutors.get(name)?.scopeKey === scopeKey) {
const existing = runtimeApi.aiToolExecutors.get(name);
if (existing?.scopeKey === scopeKey) {
prevExecutors.set(name, existing);
runtimeApi.aiToolExecutors.delete(name);
}
}
}
const names = normalizedTools.map((toolDef) => toolDef.name);
const token = Symbol("aiToolRegistration");
const displacedExecutors = new Map();
runtimeApi.aiToolBuckets.set(scopeKey, { token, names });
for (const name of names) {
if (runtimeApi.aiToolExecutors.has(name)) {
displacedExecutors.set(name, runtimeApi.aiToolExecutors.get(name));
}
runtimeApi.aiToolExecutors.set(name, { scopeKey, token, executor });
}
try {
await client.request("ai.registerTools", {
...(viewId ? { viewId } : {}),
tools: normalizedTools,
});
} catch (error) {
if (runtimeApi.aiToolBuckets.get(scopeKey)?.token === token) {
if (prevBucket) runtimeApi.aiToolBuckets.set(scopeKey, prevBucket);
else runtimeApi.aiToolBuckets.delete(scopeKey);
for (const name of names) {
if (runtimeApi.aiToolExecutors.get(name)?.token === token) {
runtimeApi.aiToolExecutors.delete(name);
}
}
for (const [name, entry] of displacedExecutors) {
if (!runtimeApi.aiToolExecutors.has(name)) runtimeApi.aiToolExecutors.set(name, entry);
}
for (const [name, entry] of prevExecutors) {
if (!runtimeApi.aiToolExecutors.has(name)) runtimeApi.aiToolExecutors.set(name, entry);
}
}
throw error;
}
let disposed = false;
return Object.freeze({
dispose() {
@@ -908,7 +941,7 @@ function createPluginContext(config, client, runtimeApi) {
read: (params) => client.request("context.selected.read", params),
};
const agent = Object.fromEntries(["listBackends", "selectTargets", "listChats", "openChat", "send", "read", "history", "stop", "closeChat"].map((operation) => [
operation, (params) => client.request(`agent.${operation}`, params, operation === "read" ? { deadlineMs: 65_000 } : {}),
operation, (params) => client.request(`agent.${operation}`, params, { deadlineMs: 65_000 }),
]));
const filesystem = {
readFile: (filePath, options = {}) => client.request("filesystem.readFile", {
@@ -1253,8 +1286,11 @@ export async function startPluginRuntime({
if (message.method === "plugin.deactivate") {
if (!deactivated) {
deactivated = true;
await plugin.deactivate?.();
context?.subscriptions.dispose();
try {
await plugin.deactivate?.();
} finally {
context?.subscriptions.dispose();
}
}
return null;
}
@@ -1580,19 +1616,33 @@ export async function startPluginRuntime({
const cancellationId = message.cancellationId;
const source = new CancellationTokenSource();
if (cancellationId) cancellation.set(cancellationId, source);
const sendRpcFailure = (error) => {
const rpcError = normalizeError(error);
try {
transport.post(makeRpcFailure(message.id, rpcError.code, rpcError.message, rpcError.data));
} catch {}
};
void handleRequest(message, source.token, ports).then(
(result) => {
const safeResult = result === undefined ? null : sanitizeOutboundJsonValue(result, 1);
transport.post({
jsonrpc: "2.0",
id: message.id,
result: safeResult,
});
},
(error) => {
const rpcError = normalizeError(error);
transport.post(makeRpcFailure(message.id, rpcError.code, rpcError.message, rpcError.data));
let safeResult;
try {
safeResult = result === undefined ? null : sanitizeOutboundJsonValue(result, 1);
} catch (error) {
sendRpcFailure(new PluginError(
"internal",
error instanceof Error ? error.message : "Plugin RPC result must be a JSON value",
));
return;
}
try {
transport.post({
jsonrpc: "2.0",
id: message.id,
result: safeResult,
});
} catch {}
},
sendRpcFailure,
).finally(() => {
if (cancellationId) cancellation.delete(cancellationId);
source.dispose();
@@ -1606,6 +1656,8 @@ export async function startPluginRuntime({
for (const source of cancellation.values()) source.cancel();
runtimeApi.commandHandlers.clear();
runtimeApi.providerHandlers.clear();
runtimeApi.aiToolBuckets.clear();
runtimeApi.aiToolExecutors.clear();
runtimeApi.settingsChanged.clear();
runtimeApi.environmentChanged.clear();
runtimeApi.terminalEvents.clear();
@@ -1615,8 +1667,12 @@ export async function startPluginRuntime({
for (const emitter of runtimeApi.viewMessages.values()) emitter.clear();
cancellation.clear();
if (!deactivated) {
await plugin.deactivate?.();
context?.subscriptions.dispose();
deactivated = true;
try {
await plugin.deactivate?.();
} finally {
context?.subscriptions.dispose();
}
}
transport.close();
},
+25 -5
View File
@@ -113,6 +113,7 @@ class RuntimeSupervisor {
this.starting = new Map();
this.startControllers = new Map();
this.stopping = new Map();
this.exitCleanups = new Map();
this.runtimeListeners = new Set();
this.progressListeners = new Set();
this.uncontainedPlugins = new Set();
@@ -232,6 +233,8 @@ class RuntimeSupervisor {
}
const stopping = this.stopping.get(pluginId);
if (stopping) await stopping;
const exitCleanup = this.exitCleanups.get(pluginId);
if (exitCleanup) await exitCleanup;
if (this.shuttingDown) throw new Error("Plugin runtime supervisor is shutting down");
if (this.starting.has(pluginId)) return this.starting.get(pluginId);
if (this.runtimes.has(pluginId)) {
@@ -325,7 +328,13 @@ class RuntimeSupervisor {
});
logger = this.logService?.createLogger(identity, plugin) ?? new PluginLogger();
const routes = this.rpcRegistry.createRoutes(identity);
const onExit = (details) => { void this.#handleExit(pluginId, runtime, identity, details); };
const onExit = (details) => {
const cleanup = this.#handleExit(pluginId, runtime, identity, details).catch(() => {});
this.exitCleanups.set(pluginId, cleanup);
void cleanup.finally(() => {
if (this.exitCleanups.get(pluginId) === cleanup) this.exitCleanups.delete(pluginId);
});
};
const onProtocolError = (error) => {
logger.audit({ operation: "runtime.protocol", authorization: "not-reached", result: "error", errorCode: error?.code });
return logger.write("error", "Plugin protocol violation", { error: error?.message });
@@ -482,14 +491,19 @@ class RuntimeSupervisor {
this.#recordContainmentFailure(identity, error);
return;
}
if (this.shuttingDown) {
try { this.#setRuntimeState(identity, "stopped"); } catch {}
return;
}
if (details.containmentFailed) {
this.#recordContainmentFailure(identity, details.error);
return;
}
if (details.expected || this.shuttingDown) {
if (details.expected) {
this.#setRuntimeState(identity, "stopped");
return;
}
if (this.runtimes.has(pluginId)) return;
await this.#recordFailure(identity, details.error);
}
@@ -538,11 +552,16 @@ class RuntimeSupervisor {
if (starting) {
try { await starting; } catch {}
}
if (plugin && plugin.runtime.quarantinedAt == null && plugin.runtime.status !== "stopped") {
const exitCleanup = this.exitCleanups.get(pluginId);
if (exitCleanup) {
try { await exitCleanup; } catch {}
}
const latestPlugin = this.database.getActivePlugin(pluginId);
if (latestPlugin && latestPlugin.runtime.quarantinedAt == null && latestPlugin.runtime.status !== "stopped" && latestPlugin.runtime.status !== "error") {
this.#setRuntimeState(identity, "stopped", {
pluginId,
pluginVersion: plugin.activeVersion,
kind: plugin.runtime.kind,
pluginVersion: latestPlugin.activeVersion,
kind: latestPlugin.runtime.kind,
});
}
return;
@@ -746,6 +765,7 @@ class RuntimeSupervisor {
await Promise.allSettled([...this.runtimes.keys()].map((pluginId) => this.stop(pluginId)));
await Promise.allSettled([...this.starting.values()]);
await Promise.allSettled([...this.stopping.values()]);
await Promise.allSettled([...this.exitCleanups.values()]);
for (const identity of this.runtimeIdentities.values()) this.#releaseRuntimeResources(identity);
this.resourceMonitors.clear();
this.runtimeListeners.clear();
+7 -2
View File
@@ -8,11 +8,12 @@ const {
const shutdownHandlers = new Set();
let shutdownPromise = null;
let shutdownInFlight = false;
function registerPluginShutdown(handler) {
if (typeof handler !== "function") throw new TypeError("Plugin shutdown handler must be a function");
shutdownHandlers.add(handler);
shutdownPromise = null;
if (!shutdownInFlight) shutdownPromise = null;
return () => {
shutdownHandlers.delete(handler);
};
@@ -30,6 +31,7 @@ function runPluginShutdown(options = {}) {
const timeout = new Promise((resolve) => {
timer = setTimeout(() => resolve({ timedOut: true }), timeoutMs);
});
shutdownInFlight = true;
shutdownPromise = Promise.race([
Promise.allSettled([...shutdownHandlers].map((handler) => Promise.resolve().then(handler)))
.then((results) => {
@@ -38,7 +40,10 @@ function runPluginShutdown(options = {}) {
return { timedOut: false };
}),
timeout,
]).finally(() => clearTimeout(timer));
]).finally(() => {
clearTimeout(timer);
shutdownInFlight = false;
});
return shutdownPromise;
}
+36 -4
View File
@@ -54,12 +54,25 @@ function raceWithSignal(operation, signal) {
});
}
const MAX_RETIRED_STREAM_IDS = 512;
function rememberRetiredStreamId(set, streamId) {
set.delete(streamId);
set.add(streamId);
while (set.size > MAX_RETIRED_STREAM_IDS) {
const oldest = set.values().next().value;
set.delete(oldest);
}
}
class PluginStreamRouter {
constructor(options) {
this.send = options.send;
this.onIncomingStream = options.onIncomingStream ?? (() => false);
this.incoming = new Map();
this.outgoing = new Map();
this.retiredIncoming = new Set();
this.retiredOutgoing = new Set();
this.maxStreams = options.maxStreams ?? PLUGIN_RPC_MAX_PENDING;
this.openTimeoutMs = options.openTimeoutMs ?? PLUGIN_RPC_DEFAULT_TIMEOUT_MS;
this.closed = false;
@@ -93,6 +106,7 @@ class PluginStreamRouter {
openController: new AbortController(),
closed: false,
};
this.retiredIncoming.delete(frame.streamId);
this.incoming.set(frame.streamId, state);
let accepted;
let openTimedOut = false;
@@ -143,6 +157,7 @@ class PluginStreamRouter {
if (outgoing.terminalKind === "end" || outgoing.terminalKind === "cancel") {
if (outgoing.availableBytes === outgoing.maxCreditBytes) {
this.outgoing.delete(frame.streamId);
rememberRetiredStreamId(this.retiredOutgoing, frame.streamId);
}
return;
}
@@ -163,8 +178,20 @@ class PluginStreamRouter {
this.#notifyOutgoingClosed(outgoing, "cancel");
return;
}
if (frame.kind === "cancel" && this.retiredOutgoing.has(frame.streamId)) {
// Peer cancelled while our terminal end/cancel frame was already in flight.
this.retiredOutgoing.delete(frame.streamId);
return;
}
const state = this.incoming.get(frame.streamId);
if (!state || state.closed) throw new Error(`Unknown incoming plugin stream: ${frame.streamId}`);
if (!state || state.closed) {
if (this.retiredIncoming.has(frame.streamId)) {
// Producer had in-flight frames when host cancelled this incoming stream.
if (frame.kind !== "chunk") this.retiredIncoming.delete(frame.streamId);
return;
}
throw new Error(`Unknown incoming plugin stream: ${frame.streamId}`);
}
if (frame.sequence !== state.nextSequence) {
throw new Error(`Out-of-order plugin stream frame: ${frame.streamId}`);
}
@@ -218,9 +245,9 @@ class PluginStreamRouter {
: new Error(`Plugin stream ${frame.kind}: ${frame.streamId}`);
state.openController.abort(abortReason);
try {
if (frame.kind === "cancel" && state.availableBytes < state.windowBytes) {
// The producer has stopped. Return discarded credit once so it can
// retire its terminal state, without releasing more queued writes.
if ((frame.kind === "cancel" || frame.kind === "end") && state.availableBytes < state.windowBytes) {
// The producer has stopped. Return unreturned credit once so it can
// retire its terminal state without leaking an outgoing stream slot.
state.updateSequence += 1;
this.send({ frame: {
streamId: state.streamId, sequence: state.updateSequence,
@@ -284,6 +311,7 @@ class PluginStreamRouter {
terminalKind: null,
onClose: options.onClose,
};
this.retiredOutgoing.delete(streamId);
this.outgoing.set(streamId, state);
try {
this.send(envelope);
@@ -393,6 +421,7 @@ class PluginStreamRouter {
|| state.availableBytes === state.maxCreditBytes
) {
this.outgoing.delete(state.streamId);
if (terminalSent) rememberRetiredStreamId(this.retiredOutgoing, state.streamId);
}
this.#notifyOutgoingClosed(state, kind);
}
@@ -411,6 +440,7 @@ class PluginStreamRouter {
if (state.closed) return;
state.closed = true;
this.incoming.delete(state.streamId);
rememberRetiredStreamId(this.retiredIncoming, state.streamId);
state.openController.abort(reason);
state.updateSequence = Math.max(1, state.updateSequence + 1);
let sendError;
@@ -447,6 +477,8 @@ class PluginStreamRouter {
} catch {}
}
this.incoming.clear();
this.retiredIncoming.clear();
this.retiredOutgoing.clear();
}
}
+46
View File
@@ -496,3 +496,49 @@ test("oversized binary writes fail before consuming stream credit", async () =>
assert.equal(sent.length, 1);
assert.equal(router.outgoing.get("oversized").availableBytes, contract.PLUGIN_STREAM_MAX_WINDOW_BYTES);
});
test("crossing cancel/end frames on retired streams do not throw protocol errors and end refunds remaining credit", async () => {
const sent = [];
const contract = await import("@netcatty/plugin-contract");
let incomingHandle;
const router = new PluginStreamRouter({
send(message) { sent.push(message); },
onIncomingStream(stream) {
incomingHandle = stream;
stream.bind({ onChunk: async () => {}, onClose: () => {} });
return true;
},
});
// 1. Host cancels incoming while producer has in-flight chunk + end frames.
await router.accept({
frame: { streamId: "race-in", sequence: 0, kind: "open", windowBytes: 4096 },
});
await incomingHandle.cancel();
await router.accept({
frame: { streamId: "race-in", sequence: 1, kind: "chunk", data: contract.createJsonStreamChunk({ ok: true }) },
});
await router.accept({
frame: { streamId: "race-in", sequence: 2, kind: "end" },
});
// 2. Host ends outgoing at full credit while peer has an in-flight cancel frame.
const out = await router.openOutgoing("race-out", 4096);
out.end();
await router.accept({
frame: { streamId: "race-out", sequence: 1, kind: "cancel" },
});
// 3. Producer ends incoming stream before consumer calls release() -> host refunds unreturned credit.
sent.length = 0;
await router.accept({
frame: { streamId: "refund-end", sequence: 0, kind: "open", windowBytes: 4096 },
});
await router.accept({
frame: { streamId: "refund-end", sequence: 1, kind: "chunk", data: contract.createJsonStreamChunk({ hello: "world" }) },
});
await router.accept({
frame: { streamId: "refund-end", sequence: 2, kind: "end" },
});
assert.equal(sent.some((msg) => msg.frame?.streamId === "refund-end" && msg.frame?.kind === "windowUpdate"), true);
});
+5 -1
View File
@@ -164,6 +164,7 @@ class UtilityPluginRuntime {
const ready = waitForUtilityReady(this.child, PLUGIN_ACTIVATION_TIMEOUT_MS);
this.child.postMessage({ type: "netcatty-plugin:bootstrap", config });
await ready;
this.connected = true;
this.#assertStarting(signal);
const initialized = await this.router.request("plugin.initialize", {
netcattyVersion: config.netcattyVersion,
@@ -189,10 +190,13 @@ class UtilityPluginRuntime {
async #stop() {
this.stopping = true;
try {
await this.router?.request("plugin.deactivate", {}, { timeoutMs: PLUGIN_DEACTIVATION_TIMEOUT_MS });
if (this.connected) {
await this.router?.request("plugin.deactivate", {}, { timeoutMs: PLUGIN_DEACTIVATION_TIMEOUT_MS });
}
} finally {
const router = this.router;
this.router = null;
this.connected = false;
router?.close();
await this.#terminateAndWait();
}
+3 -3
View File
@@ -1,14 +1,14 @@
{
version = "1.1.97";
version = "1.2.0";
sources = {
x86_64-linux = {
appImageArch = "x86_64";
hash = "sha256-UJKTvsEvHI76aBr+PxmBXsnKBgNbm4QUZD5gY5SqyeY=";
hash = "sha256-75Mt9kDH4zlpLrngxBjOglrrDBgviuAoq5W2jJtXc+Q=";
};
aarch64-linux = {
appImageArch = "arm64";
hash = "sha256-cCZhDymIcZkMKPzwh/x7cjCz78gjZ+dEf3UF7LmjCuk=";
hash = "sha256-ENQ8FTo3ATITTRFvBAvIhKzuGRKxbAKI5HXK3i+91qI=";
};
};
}
+19 -3
View File
@@ -305,8 +305,11 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
view.controlElements.clear();
view.controls.clear();
view.pointerAncestors.clear();
view.unmount();
view.container.remove();
try {
view.unmount();
} finally {
view.container.remove();
}
};
const sendEvent = (view: View, event: HostDrawnViewEvent) => {
view.syncElementIndex();
@@ -757,5 +760,18 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
}
}
});
return { dispose() { subscription.dispose(); for (const id of [...instances.keys()]) close(id); } };
return {
dispose() {
subscription.dispose();
let firstError: unknown;
for (const id of [...instances.keys()]) {
try {
close(id);
} catch (error) {
firstError ??= error;
}
}
if (firstError !== undefined) throw firstError;
},
};
}