mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-12-02 07:11:00 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb7e49c409 | ||
|
|
02be8a2e0a | ||
|
|
ca2cdcbd12 | ||
|
|
f7fed5fd6f | ||
|
|
25aa27bbf8 | ||
|
|
7e44b774f8 | ||
|
|
c5c7cfdae3 | ||
|
|
62085cb3c2 |
No files matched your search
@@ -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 };
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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" });
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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?.();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -37,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.
|
||||
@@ -455,7 +456,7 @@ class PluginHostSshExecTransport {
|
||||
bindAddress: "127.0.0.1",
|
||||
remoteHost: "127.0.0.1",
|
||||
remotePort: 1,
|
||||
reuseTransport: true,
|
||||
reuseTransport: false,
|
||||
sshTcpConnectTimeoutMs,
|
||||
sshAuthReadyTimeoutMs,
|
||||
},
|
||||
@@ -610,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) {
|
||||
@@ -691,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;
|
||||
@@ -722,6 +731,7 @@ class PluginHostSshExecTransport {
|
||||
|| err?.code === "ECONNRESET"
|
||||
|| err?.code === "EPIPE"
|
||||
|| err?.code === "SSH_EXEC_OPEN_TIMEOUT"
|
||||
|| err?.code === "SSH_EXEC_OPEN_PENDING"
|
||||
|| isDeadlineAbort
|
||||
) {
|
||||
void this.#closeEntry(entry);
|
||||
|
||||
@@ -708,3 +708,96 @@ test("post-return abort stops tunnel after early Tunnel not found on both succes
|
||||
|
||||
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();
|
||||
});
|
||||
@@ -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 });
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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}`);
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
},
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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
@@ -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=";
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user