Compare commits

...
Author SHA1 Message Date
陈大猫 1eb4d33102 feat(plugins): forward pointer and wheel events through host-drawn views
Host-drawn Remote DOM surfaces now translate pointerdown, pointermove,
pointerup, pointercancel, and wheel into HostDrawnViewEvent so plugin
HTML canvases can drag, pan, and zoom in the real workbench. The official
SDK dispatches PointerEvent and WheelEvent with surface-relative
coordinates.

Includes host-side pointer capture after pointerdown, move coalescing
with acknowledgedEvent backpressure, pointercancel on surface teardown,
a non-passive wheel listener on the shadow host, and native scrolling
when a scrollable ancestor or host-owned popover panel can consume the
gesture.
2026-11-29 17:40:32 +08:00
陈大猫 d04bf9ce72 fix(terminal): clear full snippet label on autocomplete accept when the name has spaces (#4550)
Fixes #4549
2026-11-29 16:49:21 +08:00
陈大猫 bfe63719d8 feat(terminal): unify 1px focus and magnification borders with deterministic state (#4543) (#4545)
* feat(terminal): unify 1px focus and magnification borders with deterministic state

* fix(terminal): preserve zoom entry animation on unchanged initial ResizeObserver callback

* test(terminal): update browserPanelLifecycle vm stub for setMagnifiedPanesByTab
2026-11-29 14:45:56 +08:00
陈大猫 08f22349c1 fix(plugins): clear stale PluginDataGrid editingCell and blur timer on row removal (#4547) 2026-11-29 14:41:35 +08:00
陈大猫 c846cd6fd8 feat(vault): allow Direct (no proxy) on groups (#4442) (#4546) 2026-11-29 14:34:10 +08:00
Netcatty-Bot 2506b5d1bc Update Nix release metadata for v1.1.95 (#4536) 2026-11-29 12:50:41 +08:00
陈大猫 a24be98a6b fix(rdp): reuse MCS server public key when license request has no cert (#4542)
Related #4540
2026-11-29 12:23:04 +08:00
陈大猫 b08a1398e3 test(plugins): sync Database 0.3.2 brand fixture and list avatar assertions (#4537) 2026-11-29 09:18:47 +08:00
56 changed files with 3810 additions and 238 deletions

No files matched your search

+31 -1
View File
@@ -604,7 +604,37 @@ export function AppSideEffects() {
});
// Window controls - must be before update toast effect which uses openSettingsWindow
const { openSettingsWindow } = useWindowControls();
const { openSettingsWindow, isFullscreen, onFullscreenChanged } = useWindowControls();
// Sync host platform and fullscreen state to DOM so platform-aware chrome
// (such as macOS rounded window corners on outer split-pane focus borders)
// stays accurate across fullscreen transitions without per-pane polling.
useEffect(() => {
const isMac = typeof navigator !== 'undefined' && /Mac/i.test(navigator.platform);
if (isMac) {
document.documentElement.setAttribute('data-platform', 'darwin');
} else {
document.documentElement.removeAttribute('data-platform');
document.documentElement.removeAttribute('data-window-fullscreen');
return undefined;
}
let cancelled = false;
const syncFullscreen = (value: boolean) => {
if (value) {
document.documentElement.setAttribute('data-window-fullscreen', 'true');
} else {
document.documentElement.removeAttribute('data-window-fullscreen');
}
};
void isFullscreen().then((value) => {
if (!cancelled) syncFullscreen(!!value);
});
const unsubscribe = onFullscreenChanged((value) => syncFullscreen(!!value));
return () => {
cancelled = true;
unsubscribe();
};
}, [isFullscreen, onFullscreenChanged]);
const _handleTrayJumpToSession = useEffectEvent((sessionId: string) => {
return handleTrayJumpToSessionImpl(() => ({
sessionId,
@@ -58,6 +58,7 @@ export const isAutoStartProxyReady = (
host.proxyProfileId && !validProxyProfileIds.has(host.proxyProfileId),
);
const missingGroupProxyProfile = Boolean(
!host.directProxy &&
!host.proxyConfig &&
!host.proxyProfileId &&
rawGroupDefaults.proxyProfileId &&
@@ -0,0 +1,167 @@
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
import type { GroupConfig } from "../types.ts";
import GroupDetailsPanel from "./GroupDetailsPanel.tsx";
import { ProxyPanel } from "./host-details/ProxyPanel.tsx";
import { AsidePanel } from "./ui/aside-panel.tsx";
import { Badge } from "./ui/badge.tsx";
import { TooltipProvider } from "./ui/tooltip.tsx";
import { installDomEnvironment } from "./test-support/renderReactDom.tsx";
async function mountGroupDetails(config: GroupConfig | undefined) {
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previous = environment.IS_REACT_ACT_ENVIRONMENT;
const dom = installDomEnvironment();
const previousRaf = globalThis.requestAnimationFrame;
const previousCancelRaf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
environment.IS_REACT_ACT_ENVIRONMENT = true;
let renderer: ReactTestRenderer | undefined;
let saved: GroupConfig | undefined;
await act(async () => {
renderer = create(
<I18nProvider locale="en">
<TooltipProvider>
<GroupDetailsPanel
groupPath={config?.path ?? "corp/local"}
config={config}
availableKeys={[]}
identities={[]}
proxyProfiles={[]}
allHosts={[]}
groups={["corp", "corp/local"]}
groupConfigs={[
{ path: "corp", proxyConfig: { type: "http", host: "corp-proxy.example.com", port: 8080 } },
...(config ? [config] : []),
]}
terminalThemeId="default"
terminalFontSize={14}
onSave={(value) => { saved = value; }}
onCancel={() => {}}
/>
</TooltipProvider>
</I18nProvider>,
);
});
const cleanup = async () => {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
environment.IS_REACT_ACT_ENVIRONMENT = previous;
};
return {
get root() {
return renderer!.root;
},
getSaved: () => saved,
cleanup,
};
}
const findProxySummaryButton = (root: ReactTestRenderer["root"]) =>
root.findAllByType("button").find((button) => {
const badges = button.findAllByType(Badge);
return badges.some((badge) =>
badge.props.children === "HTTP" || badge.props.children === "Direct (no proxy)",
);
});
test("GroupDetailsPanel lets a child group choose Direct (no proxy) and persists directProxy", async () => {
const harness = await mountGroupDetails({
path: "corp/local",
protocol: "ssh",
proxyConfig: { type: "http", host: "old-proxy.example.com", port: 8080 },
});
try {
const proxyButton = findProxySummaryButton(harness.root);
assert.ok(proxyButton, "Proxy summary button should be rendered");
await act(async () => {
proxyButton.props.onClick();
});
const proxyPanel = harness.root.findByType(ProxyPanel);
assert.equal(typeof proxyPanel.props.onSelectDirectProxy, "function");
assert.equal(proxyPanel.props.directProxy, undefined);
await act(async () => {
proxyPanel.props.onSelectDirectProxy!();
});
const updatedPanel = harness.root.findByType(ProxyPanel);
assert.equal(updatedPanel.props.directProxy, true);
assert.equal(updatedPanel.props.proxyConfig, undefined);
assert.equal(updatedPanel.props.selectedProxyProfileId, undefined);
await act(async () => {
updatedPanel.props.onBack();
});
const proxyButtonAfter = findProxySummaryButton(harness.root);
assert.ok(proxyButtonAfter);
const badge = proxyButtonAfter.findByType(Badge);
assert.equal(badge.props.children, "Direct (no proxy)");
await act(async () => {
harness.root.findByType(AsidePanel).props.actions.props.onClick();
});
const saved = harness.getSaved();
assert.ok(saved, "onSave should be called");
assert.equal(saved.directProxy, true);
assert.equal(saved.proxyConfig, undefined);
assert.equal(saved.proxyProfileId, undefined);
} finally {
await harness.cleanup();
}
});
test("GroupDetailsPanel clears directProxy when removed in ProxyPanel so parent proxy applies again", async () => {
const harness = await mountGroupDetails({
path: "corp/local",
directProxy: true,
});
try {
const proxyButton = findProxySummaryButton(harness.root);
assert.ok(proxyButton, "SSH section and Proxy summary should open automatically for directProxy groups");
assert.equal(proxyButton.findByType(Badge).props.children, "Direct (no proxy)");
await act(async () => {
proxyButton.props.onClick();
});
const proxyPanel = harness.root.findByType(ProxyPanel);
assert.equal(proxyPanel.props.directProxy, true);
await act(async () => {
proxyPanel.props.onClearProxy();
});
assert.equal(harness.root.findByType(ProxyPanel).props.directProxy, undefined);
await act(async () => {
harness.root.findByType(ProxyPanel).props.onBack();
});
await act(async () => {
harness.root.findByType(AsidePanel).props.actions.props.onClick();
});
const saved = harness.getSaved();
assert.ok(saved, "onSave should be called");
assert.equal(saved.directProxy, undefined);
assert.equal(saved.proxyConfig, undefined);
assert.equal(saved.proxyProfileId, undefined);
} finally {
await harness.cleanup();
}
});
+5
View File
@@ -33,6 +33,11 @@ test("GroupDetailsPanel keeps the SSH section when X11 forwarding is set", () =>
assert.equal(hasGroupSshFields({ x11Forwarding: false }), true);
});
test("GroupDetailsPanel keeps the SSH section when directProxy is set", () => {
assert.equal(hasGroupSshFields({ directProxy: true }), true);
assert.equal(hasGroupSshFields({ directProxy: false }), false);
});
test("GroupDetailsPanel treats cleared telnet credentials as explicit settings", () => {
assert.equal(hasGroupTelnetFields({ telnetUsername: "" }), true);
assert.equal(hasGroupTelnetFields({ telnetPassword: "" }), true);
+47 -24
View File
@@ -121,6 +121,7 @@ export const hasGroupSshFields = (c: Partial<GroupConfig>): boolean => {
return Boolean(
c.proxyProfileId ||
c.proxyConfig ||
c.directProxy === true ||
c.hostChain ||
c.startupCommand ||
c.startupCommandRunMode !== undefined,
@@ -350,23 +351,29 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
() => proxyProfiles.find((profile) => profile.id === form.proxyProfileId),
[form.proxyProfileId, proxyProfiles],
);
const hasMissingProxyProfile = Boolean(form.proxyProfileId && !selectedProxyProfile);
const hasMissingProxyProfile = Boolean(!form.directProxy && form.proxyProfileId && !selectedProxyProfile);
const hasProxyConfig = Boolean(
form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId,
form.directProxy || form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId,
);
const proxySummaryType = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
: formatProxyConfigType(selectedProxyProfile?.config || form.proxyConfig) || "HTTP";
const proxySummaryLabel = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? selectedProxyProfile.label
: formatProxyConfigEndpoint(form.proxyConfig);
const proxySummaryTooltip = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? `${selectedProxyProfile.label} - ${formatProxyConfigEndpoint(selectedProxyProfile.config)}`
: `${formatProxyConfigType(form.proxyConfig)} ${formatProxyConfigEndpoint(form.proxyConfig)}`;
const proxySummaryType = form.directProxy
? t("hostDetails.proxy.direct")
: hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
: formatProxyConfigType(selectedProxyProfile?.config || form.proxyConfig) || "HTTP";
const proxySummaryLabel = form.directProxy
? t("hostDetails.proxy.directHint")
: hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? selectedProxyProfile.label
: formatProxyConfigEndpoint(form.proxyConfig);
const proxySummaryTooltip = form.directProxy
? `${t("hostDetails.proxy.direct")} - ${t("hostDetails.proxy.directHint")}`
: hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? `${selectedProxyProfile.label} - ${formatProxyConfigEndpoint(selectedProxyProfile.config)}`
: `${formatProxyConfigType(form.proxyConfig)} ${formatProxyConfigEndpoint(form.proxyConfig)}`;
const update = <K extends keyof GroupConfig>(key: K, value: GroupConfig[K] | undefined) => {
setForm((prev) => ({ ...prev, [key]: value }));
@@ -463,6 +470,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -479,6 +487,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -494,6 +503,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -513,6 +523,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -525,7 +536,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
const updateProxyConfig = useCallback(
(field: keyof ProxyConfig, value: ProxyConfig[keyof ProxyConfig]) => {
setForm((prev) => {
const { proxyProfileId: _proxyProfileId, ...rest } = prev;
const { proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
return {
...rest,
proxyConfig: updateProxyConfigField(prev.proxyConfig, field, value),
@@ -537,19 +548,26 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
const clearProxyConfig = useCallback(() => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
return rest;
});
}, []);
const selectProxyProfile = useCallback((profileId: string | undefined) => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
if (!profileId) return rest;
return { ...rest, proxyProfileId: profileId };
});
}, []);
const selectDirectProxy = useCallback(() => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
return { ...rest, directProxy: true };
});
}, []);
// Chain helpers
const chainedHosts = useMemo(() => {
const ids = form.hostChain?.hostIds || [];
@@ -751,7 +769,6 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
setNameError(t("vault.groups.errors.invalidChars"));
return;
}
const newPath = parentGroup ? `${parentGroup}/${trimmedName}` : trimmedName;
if (newPath !== groupPath && groups.includes(newPath)) {
setNameError(t("vault.groups.errors.duplicatePath"));
@@ -772,7 +789,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
const anyProtocolEnabled = sshEnabled || rdpEnabled || vncEnabled || telnetEnabled;
const anyRoutingProtocolEnabled = sshEnabled || rdpEnabled || vncEnabled;
const proxySave = anyProtocolEnabled
const proxySave = anyProtocolEnabled && !form.directProxy
? prepareProxyConfigForSave({
proxyConfig: form.proxyConfig,
proxyProfileId: form.proxyProfileId,
@@ -917,10 +934,14 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
}),
...(finalRdpConfig && { rdpConfig: finalRdpConfig }),
...(finalVncConfig && { vncConfig: finalVncConfig }),
...(anyProtocolEnabled && {
...(form.proxyProfileId !== undefined && { proxyProfileId: form.proxyProfileId }),
...(normalizedProxyConfig !== undefined && { proxyConfig: normalizedProxyConfig }),
}),
...(anyProtocolEnabled && (
form.directProxy === true
? { directProxy: true }
: {
...(form.proxyProfileId !== undefined && { proxyProfileId: form.proxyProfileId }),
...(normalizedProxyConfig !== undefined && { proxyConfig: normalizedProxyConfig }),
}
)),
...(anyRoutingProtocolEnabled && {
...(form.hostChain !== undefined && { hostChain: form.hostChain }),
}),
@@ -954,8 +975,10 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
proxyProfiles={proxyProfiles}
identities={identities}
selectedProxyProfileId={form.proxyProfileId}
directProxy={form.directProxy}
onUpdateProxy={updateProxyConfig}
onSelectProxyProfile={selectProxyProfile}
onSelectDirectProxy={selectDirectProxy}
onClearProxy={clearProxyConfig}
onBack={() => setActiveSubPanel("none")}
onCancel={onCancel}
+5 -1
View File
@@ -63,6 +63,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
proxySummaryType,
proxySummaryLabel,
proxySummaryTooltip,
displayDirectProxy = Boolean(form.directProxy),
proxyInherited = false,
clearProxyConfig,
}) => {
@@ -784,7 +785,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
title={t("hostDetails.proxy")}
className="overflow-hidden"
>
{form.directProxy ? (
{displayDirectProxy ? (
<div className="w-full min-w-0 grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
<button
type="button"
@@ -796,8 +797,10 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
</Badge>
<span className="block min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm">
{t("hostDetails.proxy.directHint")}
{proxyInherited ? ` · ${t("vault.groups.details.inherited")}` : ""}
</span>
</button>
{!proxyInherited && (
<Button
type="button"
variant="ghost"
@@ -808,6 +811,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
>
<X size={14} />
</Button>
)}
</div>
) : form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId || proxyInherited ? (
<div className="w-full min-w-0 grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
@@ -691,6 +691,34 @@ test("HostDetailsPanel direct proxy hides inherited group proxy", () => {
assert.match(markup, /Direct \(no proxy\)/);
assert.doesNotMatch(markup, /group-proxy\.example\.com/);
assert.doesNotMatch(markup, /Inherited from group/);
});
test("HostDetailsPanel displays inherited group directProxy and hides global default proxy", () => {
const previous = getActiveGlobalDefaultProxyProfileId();
try {
publishActiveGlobalDefaultProxyProfileId("global-proxy");
const markup = renderHostDetailsWithGroup(networkSshHost, {
directProxy: true,
});
assert.match(markup, /Direct \(no proxy\)/);
assert.match(markup, /Inherited from group/);
assert.doesNotMatch(markup, /Configure proxy/);
const overridden = renderHostDetailsWithGroup({
...networkSshHost,
proxyConfig: { type: "http", host: "host-proxy.example.com", port: 9090 },
}, {
directProxy: true,
});
assert.match(overridden, /host-proxy\.example\.com/);
assert.doesNotMatch(overridden, /Direct \(no proxy\)/);
assert.doesNotMatch(overridden, /Inherited from group/);
} finally {
publishActiveGlobalDefaultProxyProfileId(previous);
}
});
test("HostDetailsPanel displays inherited group jump hosts", () => {
+6 -3
View File
@@ -517,8 +517,10 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
const hasHostProxyOverride = form.directProxy === true
|| form.proxyProfileId !== undefined
|| form.proxyConfig !== undefined;
const displayDirectProxy = form.directProxy === true
|| (!hasHostProxyOverride && effectiveAuthHost.directProxy === true);
const displayProxyProfileId = resolveDisplayProxyProfileId(form, effectiveAuthHost.proxyProfileId);
const displayProxyConfig = form.directProxy
const displayProxyConfig = displayDirectProxy
? undefined
: (form.proxyConfig ?? effectiveAuthHost.proxyConfig);
const selectedProxyProfile = useMemo(
@@ -527,7 +529,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
);
const hasMissingProxyProfile = Boolean(displayProxyProfileId && !selectedProxyProfile);
const proxyInherited = !hasHostProxyOverride && Boolean(
displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
displayDirectProxy || displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
);
const proxySummaryType = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
@@ -1518,7 +1520,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
proxyProfiles={proxyProfiles}
identities={identities}
selectedProxyProfileId={displayProxyProfileId}
directProxy={form.directProxy}
directProxy={displayDirectProxy}
allowClear={hasHostProxyOverride}
onUpdateProxy={updateProxyConfig}
onSelectProxyProfile={selectProxyProfile}
@@ -1902,6 +1904,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
proxySummaryType={proxySummaryType}
proxySummaryLabel={proxySummaryLabel}
proxySummaryTooltip={proxySummaryTooltip}
displayDirectProxy={displayDirectProxy}
proxyInherited={proxyInherited}
clearProxyConfig={clearProxyConfig}
/>
+12
View File
@@ -226,3 +226,15 @@ test("ProxyPanel offers keychain identities for HTTP and SOCKS5 proxy credential
assert.match(markup, /Proxy login/);
assert.match(markup, /proxy-user/);
});
test("ProxyPanel shows saved proxy selector and enables saving without profiles when directProxy is selected", () => {
const markup = renderPanel({
directProxy: true,
onSelectDirectProxy: () => {},
});
assert.match(markup, /Saved proxy/);
assert.match(markup, /Remove Proxy/);
assert.doesNotMatch(markup, /Proxy host/);
assert.doesNotMatch(markup, /disabled=""/);
});
+85 -57
View File
@@ -137,8 +137,10 @@ import {
} from '../domain/sidePanelLayout';
import { useWorkspaceLayoutPresetState } from '../application/state/useWorkspaceLayoutPresetState';
import {
isPaneMagnificationSelectionValid,
canMagnifyPaneSurface,
pruneMagnifiedPanesByTab,
resolvePaneMagnificationCandidate,
setTabMagnifiedPane,
type PaneMagnificationController,
type PaneMagnificationTarget,
} from '../domain/paneMagnification';
@@ -318,12 +320,11 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
onRemoveSessionFromWorkspace,
}) => {
const { t } = useI18n();
const [magnifiedPane, setMagnifiedPane] = useState<{
tabId: string;
target: PaneMagnificationTarget;
} | null>(null);
const magnifiedPaneRef = useRef(magnifiedPane);
magnifiedPaneRef.current = magnifiedPane;
const [magnifiedPanesByTab, setMagnifiedPanesByTab] = useState<
ReadonlyMap<string, PaneMagnificationTarget>
>(() => new Map());
const magnifiedPanesByTabRef = useRef(magnifiedPanesByTab);
magnifiedPanesByTabRef.current = magnifiedPanesByTab;
const lastInteractedPaneRef = useRef<Map<string, PaneMagnificationTarget>>(new Map());
// Side panel state must be initialized before any callbacks reference its
// setters or refs in their dependency arrays.
@@ -345,8 +346,8 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
}, [sessions]);
useEffect(() => {
setMagnifiedPane((current) => {
if (!current) return current;
setMagnifiedPanesByTab((current) => {
if (current.size === 0) return current;
const terminalPanes = sessions.map((session) => ({
tabId: session.workspaceId ?? session.id,
sessionId: session.id,
@@ -354,9 +355,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const sidePanelPanes = Array.from(sidePanelLayouts.entries()).flatMap(([tabId, layout]) => (
collectSidePanelPanes(layout.root).map((pane) => ({ tabId, paneId: pane.id }))
));
return isPaneMagnificationSelectionValid(current, terminalPanes, sidePanelPanes)
? current
: null;
return pruneMagnifiedPanesByTab(current, terminalPanes, sidePanelPanes);
});
}, [sessions, sidePanelLayouts]);
const terminalRendererCwdBySessionRef = useRef<Map<string, string>>(new Map());
@@ -475,11 +474,18 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
// Stable callback references for Terminal components
const handleCloseSession = useCallback((sessionId: string) => {
setMagnifiedPane((current) => (
current?.target.kind === 'terminal' && current.target.sessionId === sessionId
? null
: current
));
setMagnifiedPanesByTab((current) => {
if (current.size === 0) return current;
let changed = false;
const next = new Map(current);
for (const [tabId, target] of next) {
if (target.kind === 'terminal' && target.sessionId === sessionId) {
next.delete(tabId);
changed = true;
}
}
return changed ? next : current;
});
for (const [tabId, target] of lastInteractedPaneRef.current) {
if (target.kind === 'terminal' && target.sessionId === sessionId) {
lastInteractedPaneRef.current.delete(tabId);
@@ -1773,9 +1779,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const handleCloseSidePanel = useCallback(() => {
const activeTabId = activeTabIdRef.current;
if (!activeTabId) return;
setMagnifiedPane((current) => (
current?.tabId === activeTabId && current.target.kind === 'side-panel'
? null
setMagnifiedPanesByTab((current) => (
current.get(activeTabId)?.kind === 'side-panel'
? setTabMagnifiedPane(current, activeTabId, null)
: current
));
const sessionIdToRefocus = getActiveTerminalSessionId();
@@ -1906,14 +1912,27 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const handleMagnifyTerminalPane = useCallback((tabId: string, sessionId: string) => {
const target: PaneMagnificationTarget = { kind: 'terminal', sessionId };
lastInteractedPaneRef.current.set(tabId, target);
setMagnifiedPane((current) => (
current?.tabId === tabId
&& current.target.kind === 'terminal'
&& current.target.sessionId === sessionId
? null
: { tabId, target }
));
}, []);
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
if (existing?.kind === 'terminal' && existing.sessionId === sessionId) {
return setTabMagnifiedPane(current, tabId, null);
}
const workspace = workspacesRef.current.find((candidate) => candidate.id === tabId);
const workspaceSessionIds = workspace ? collectSessionIds(workspace.root) : [];
const standaloneSession = sessionsRef.current.find((candidate) => (
candidate.id === tabId && !candidate.workspaceId
));
const terminalCount = workspaceSessionIds.length > 0
? workspaceSessionIds.length
: standaloneSession ? 1 : 0;
const layout = sidePanelLayoutsRef.current.get(tabId);
const sidePanelCount = layout ? collectSidePanelPanes(layout.root).length : 0;
if (!canMagnifyPaneSurface(terminalCount, sidePanelCount)) {
return current;
}
return setTabMagnifiedPane(current, tabId, target);
});
}, [sidePanelLayoutsRef]);
const handleMagnifySidePanelPane = useCallback((paneId: string) => {
const tabId = activeTabIdRef.current;
@@ -1929,18 +1948,19 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
tool: pane.tool,
};
lastInteractedPaneRef.current.set(tabId, target);
setMagnifiedPane((current) => (
current?.tabId === tabId
&& current.target.kind === 'side-panel'
&& current.target.paneId === paneId
? null
: { tabId, target }
));
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
if (existing?.kind === 'side-panel' && existing.paneId === paneId) {
return setTabMagnifiedPane(current, tabId, null);
}
return setTabMagnifiedPane(current, tabId, target);
});
}, [sidePanelLayoutsRef]);
const handleRestoreMagnifiedPane = useCallback(() => {
const tabId = activeTabIdRef.current;
setMagnifiedPane((current) => current?.tabId === tabId ? null : current);
if (!tabId) return;
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, tabId, null));
}, []);
useEffect(() => {
@@ -1949,7 +1969,8 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const tabId = activeTabStore.getActiveTabId();
if (!tabId) return null;
const workspace = workspacesRef.current.find((candidate) => candidate.id === tabId);
const hasCurrentMagnification = magnifiedPaneRef.current?.tabId === tabId;
const currentTarget = magnifiedPanesByTabRef.current.get(tabId);
const hasCurrentMagnification = !!currentTarget;
if (workspace?.viewMode === 'focus' && !hasCurrentMagnification) return null;
const workspaceSessionIds = workspace ? collectSessionIds(workspace.root) : [];
const standaloneSession = sessionsRef.current.find((candidate) => (
@@ -1971,7 +1992,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
? [focusedSidePanelPane, ...sidePanelPanes.filter((pane) => pane !== focusedSidePanelPane)]
: sidePanelPanes,
lastTarget: lastInteractedPaneRef.current.get(tabId),
current: magnifiedPaneRef.current,
current: currentTarget ? { tabId, target: currentTarget } : null,
});
return candidate ? { tabId, ...candidate } : null;
};
@@ -1983,19 +2004,23 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
focus: () => {
const target = getTarget();
if (!target || target.focused) return false;
setMagnifiedPane({ tabId: target.tabId, target: target.target });
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, target.tabId, target.target));
return true;
},
restore: () => {
const target = getTarget();
if (!target?.focused) return false;
setMagnifiedPane(null);
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, target.tabId, null));
return true;
},
toggle: () => {
const target = getTarget();
if (!target) return false;
setMagnifiedPane(target.focused ? null : { tabId: target.tabId, target: target.target });
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(
current,
target.tabId,
target.focused ? null : target.target,
));
return true;
},
};
@@ -2029,13 +2054,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const closingPane = layout
? collectSidePanelPanes(layout.root).find((pane) => pane.id === paneId)
: undefined;
setMagnifiedPane((current) => (
current?.tabId === tabId
&& current.target.kind === 'side-panel'
&& current.target.paneId === paneId
? null
: current
));
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
return existing?.kind === 'side-panel' && existing.paneId === paneId
? setTabMagnifiedPane(current, tabId, null)
: current;
});
const closesWholePanel = closeSidePanelPaneForTab(tabId, paneId);
if (closesWholePanel) {
handleCloseSidePanel();
@@ -2063,8 +2087,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const layout = sidePanelLayoutsRef.current.get(tabId);
const pane = layout && collectSidePanelPanes(layout.root).find((item) => item.id === paneId);
if (pane?.tool !== expectedTool) return;
setMagnifiedPane((current) => current?.tabId === tabId && current.target.kind === 'side-panel'
&& current.target.paneId === paneId ? null : current);
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
return existing?.kind === 'side-panel' && existing.paneId === paneId
? setTabMagnifiedPane(current, tabId, null)
: current;
});
closeSidePanelPaneForTab(tabId, paneId);
}, [closeSidePanelPaneForTab, sidePanelLayoutsRef]);
@@ -2151,12 +2179,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
if (!terminal || terminal.hiddenFromTabs || terminal.workspaceId) return false;
tabId = terminal.id;
}
setMagnifiedPane((current) => (
current?.tabId === tabId
&& !(current.target.kind === 'side-panel' && current.target.tool === 'ai')
? null
: current
));
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
return existing && !(existing.kind === 'side-panel' && existing.tool === 'ai')
? setTabMagnifiedPane(current, tabId, null)
: current;
});
activeTabStore.setActiveTabId(tabId);
if (prepareSidePanelTool(tabId, 'ai')) {
startTransition(() => {
@@ -2886,7 +2914,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
lastSidePanelTabRef,
mountedAiTabIds: aiMountedTabIds,
mountedSftpTabIds,
magnifiedPane,
magnifiedPanesByTab,
notesMountedTabIds,
browserMountedTabIds,
notesOpenNoteByTab,
+7 -7
View File
@@ -77,7 +77,7 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
const hasManualProxyCommand = Boolean(proxyConfig?.command?.trim());
const hasManualProxyValue = isCommandProxy ? hasManualProxyCommand : hasManualProxyHost;
const hasInvalidManualProxyPort = !isCommandProxy && hasManualProxyHost && !isValidProxyPort(proxyConfig?.port);
const effectiveProxyConfig = selectedProfile?.config ?? proxyConfig;
const effectiveProxyConfig = directProxy ? undefined : (selectedProfile?.config ?? proxyConfig);
const hasMissingIdentity = hasMissingProxyIdentity(effectiveProxyConfig, identities);
const hasIncompleteIdentity = hasIncompleteProxyIdentity(effectiveProxyConfig, identities);
const hasUnreadableIdentity = hasUnreadableProxyCredential(effectiveProxyConfig, identities);
@@ -92,9 +92,9 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
);
const selectedIdentityValue = selectedIdentity?.id || (hasMissingIdentity ? missingIdentityValue : manualCredentialsValue);
const handleBack = useCallback(() => {
if (hasInvalidManualProxyPort || hasInvalidIdentity) return;
if (!directProxy && (hasInvalidManualProxyPort || hasInvalidIdentity)) return;
onBack();
}, [hasInvalidManualProxyPort, hasInvalidIdentity, onBack]);
}, [directProxy, hasInvalidManualProxyPort, hasInvalidIdentity, onBack]);
return (
<AsidePanel
@@ -153,7 +153,7 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
{t('hostDetails.proxyPanel.missingSaved')}
</div>
)}
{selectedProfile && (
{isUsingProfile && selectedProfile && (
<div className="min-w-0 rounded-md bg-secondary/50 p-2 text-sm">
<div className="flex min-w-0 items-center gap-2">
<Badge variant="secondary" className="text-xs shrink-0">
@@ -165,17 +165,17 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
</div>
</div>
)}
{selectedProfile && hasMissingIdentity && (
{isUsingProfile && selectedProfile && hasMissingIdentity && (
<div className="min-w-0 rounded-md border border-destructive/30 bg-destructive/10 p-2 text-sm text-destructive">
{t('hostDetails.proxyPanel.missingIdentity')}
</div>
)}
{selectedProfile && hasIncompleteIdentity && (
{isUsingProfile && selectedProfile && hasIncompleteIdentity && (
<div className="min-w-0 rounded-md border border-destructive/30 bg-destructive/10 p-2 text-sm text-destructive">
{t('hostDetails.proxyPanel.incompleteIdentity')}
</div>
)}
{selectedProfile && hasUnreadableIdentity && (
{isUsingProfile && selectedProfile && hasUnreadableIdentity && (
<div className="min-w-0 rounded-md border border-destructive/30 bg-destructive/10 p-2 text-sm text-destructive">
{t('hostDetails.proxyPanel.unreadableIdentity')}
</div>
@@ -704,3 +704,897 @@ test('RemoteImageElement renders a transparent placeholder while loading and nev
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginDataGrid clears stale editingCell and pending blur timer when insertedRows shrink or row is deleted', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, {
configurable: true,
writable: true,
value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window],
});
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, {
ResizeObserver: class {
private cb: (entries: unknown[]) => void;
constructor(cb: (entries: unknown[]) => void) { this.cb = cb; }
observe(target: Element) {
this.cb([{ target, borderBoxSize: [{ inlineSize: 800, blockSize: 600 }], contentRect: { width: 800, height: 600 } }]);
}
unobserve() {}
disconnect() {}
},
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 0, y: 0, width: 800, height: 600, top: 0, left: 0, right: 800, bottom: 600, toJSON() {},
});
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const events: Array<Record<string, unknown>> = [];
const makeTree = (insertedRows: Array<Record<string, unknown>>, deletedRowIndices: number[] = []) => ({
children: [
{
id: 'grid',
type: 1,
element: 'div',
attributes: {
'data-plugin-widget': 'data-grid',
'data-plugin-widget-props': JSON.stringify({
columns: [
{ name: 'id', type: 'INTEGER', primaryKey: true },
{ name: 'name', type: 'TEXT' },
],
rows: [[1, 'Alice']],
insertedRows,
deletedRowIndices,
editable: true,
}),
},
children: [],
},
],
});
const root = createRoot(document.getElementById('root')!);
try {
await act(async () => {
root.render(<PluginRemoteSurface tree={makeTree([{ id: null, name: null }])} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
const gridHost = document.querySelector('[data-plugin-widget-node="grid"]') as HTMLElement;
const insertedNameCell = gridHost.querySelector('[role="gridcell"][data-row-index="1"][data-col-name="name"]') as HTMLElement;
assert.ok(insertedNameCell, 'inserted row cell rendered');
await act(async () => {
insertedNameCell.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
});
const input = gridHost.querySelector('[role="gridcell"][data-row-index="1"][data-col-name="name"] input') as HTMLInputElement;
assert.ok(input, 'cell input opened on inserted row');
await act(async () => {
input.dispatchEvent(new dom.window.FocusEvent('blur', { bubbles: false }));
});
// Discard insertedRows immediately after blur and before blurTimeout(0) fires
await act(async () => {
root.render(<PluginRemoteSurface tree={makeTree([])} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
await act(async () => {
await new Promise((r) => setTimeout(r, 25));
});
assert.equal(
events.some((e) => e.widgetEvent === 'cellEdit' && (e.detail as { rowIndex?: number })?.rowIndex === 1),
false,
'discarding inserted row must cancel pending blur cellEdit for removed row',
);
// Re-adding an inserted row must NOT reopen the stale editing input
await act(async () => {
root.render(<PluginRemoteSurface tree={makeTree([{ id: null, name: null }])} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
assert.equal(
gridHost.querySelector('[role="gridcell"][data-row-index="1"][data-col-name="name"] input'),
null,
're-adding inserted row starts clean without stale editingCell input',
);
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginRemoteSurface forwards pointer gestures with capture/coalescing and wheel zoom without breaking scroll or widgets', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'WheelEvent', 'PointerEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, {
ResizeObserver: class {
private cb: (entries: unknown[]) => void;
constructor(cb: (entries: unknown[]) => void) { this.cb = cb; }
observe(target: Element) {
this.cb([{ target, borderBoxSize: [{ inlineSize: 800, blockSize: 600 }], contentRect: { width: 800, height: 600 } }]);
}
unobserve() {}
disconnect() {}
},
PointerEvent: dom.window.MouseEvent,
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, toJSON() {},
});
const capturedPointers: Array<{ target: Element; pointerId: number }> = [];
const releasedPointers: Array<{ target: Element; pointerId: number }> = [];
dom.window.HTMLElement.prototype.setPointerCapture = function (pointerId: number) {
capturedPointers.push({ target: this, pointerId });
};
dom.window.HTMLElement.prototype.releasePointerCapture = function (pointerId: number) {
releasedPointers.push({ target: this, pointerId });
};
const shadows: ShadowRoot[] = [];
const nativeAttach = dom.window.Element.prototype.attachShadow;
dom.window.Element.prototype.attachShadow = function (options) {
const s = nativeAttach.call(this, options);
shadows.push(s as unknown as ShadowRoot);
return s;
};
const makePointerEvent = (
type: string,
opts: { clientX: number; clientY: number; pointerId?: number; button?: number; buttons?: number; pointerType?: string; shiftKey?: boolean; composed?: boolean },
) => {
const evt = new dom.window.MouseEvent(type, {
bubbles: true,
cancelable: true,
composed: opts.composed ?? true,
clientX: opts.clientX,
clientY: opts.clientY,
button: opts.button ?? 0,
buttons: opts.buttons ?? 0,
shiftKey: opts.shiftKey ?? false,
});
if (opts.pointerId !== undefined) Object.defineProperty(evt, 'pointerId', { value: opts.pointerId });
if (opts.pointerType !== undefined) Object.defineProperty(evt, 'pointerType', { value: opts.pointerType });
return evt;
};
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const { createDefinitionValidator } = await import('../../electron/plugins/contractValidator.cjs');
const validateEvent = createDefinitionValidator('HostDrawnViewEvent');
const events: Array<Record<string, unknown>> = [];
const gridProps = {
columns: [{ name: 'id', type: 'int4', primaryKey: true }],
rows: [{ id: 1 }],
editable: false,
};
const tree = {
children: [
{
id: 'stage',
type: 1,
element: 'div',
attributes: { class: 'graph-stage', style: 'overflow:hidden;touch-action:none' },
children: [
{
id: 'node-1',
type: 1,
element: 'button',
attributes: { type: 'button', class: 'graph-node', style: 'touch-action:none' },
children: [{ id: 'n1t', type: 3, data: 'Alpha' }],
},
{
id: 'plain-btn',
type: 1,
element: 'button',
attributes: { type: 'button', class: 'plain-btn' },
children: [{ id: 'pbt', type: 3, data: 'Click me' }],
},
],
},
{
id: 'scroll-box',
type: 1,
element: 'div',
attributes: { class: 'scroll-box', style: 'overflow-y:auto;height:120px' },
children: [
{ id: 'scroll-row', type: 1, element: 'div', attributes: { class: 'scroll-row' }, children: [{ id: 'srt', type: 3, data: 'Item' }] },
],
},
{
id: 'fit-box',
type: 1,
element: 'div',
attributes: { class: 'fit-box', style: 'overflow-y:auto;height:120px' },
children: [
{ id: 'fit-row', type: 1, element: 'div', attributes: { class: 'fit-row' }, children: [{ id: 'frt', type: 3, data: 'Short' }] },
],
},
{
id: 'split',
type: 1,
element: 'div',
attributes: {
'data-plugin-widget': 'split-pane',
'data-plugin-widget-props': JSON.stringify({ direction: 'horizontal', initialSize: 200, minSize: 100, maxSize: 400 }),
},
children: [
{ id: 'pane-node', type: 1, element: 'div', attributes: { class: 'pane-node' }, children: [{ id: 'pn', type: 3, data: 'Pane' }] },
{ id: 'pane-b', type: 1, element: 'div', attributes: {}, children: [{ id: 'pb', type: 3, data: 'Right' }] },
],
},
{
id: 'grid',
type: 1,
element: 'div',
attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(gridProps) },
children: [],
},
],
};
const root = createRoot(document.getElementById('root')!);
const renderSurface = async (settled = true) => {
await act(async () => {
root.render(
<PluginRemoteSurface
tree={tree}
css=""
settled={settled}
onEvent={(e) => {
assert.equal(validateEvent(e), true, `Emitted event must satisfy contract schema: ${JSON.stringify(e)} -> ${JSON.stringify(validateEvent.errors)}`);
events.push(e as unknown as Record<string, unknown>);
}}
/>,
);
});
};
try {
await renderSurface(true);
const mainShadow = shadows[0]!;
const stage = mainShadow.querySelector('.graph-stage') as HTMLElement;
const nodeBtn = mainShadow.querySelector('.graph-node') as HTMLElement;
const plainBtn = mainShadow.querySelector('.plain-btn') as HTMLElement;
const scrollBox = mainShadow.querySelector('.scroll-box') as HTMLElement;
const scrollRow = mainShadow.querySelector('.scroll-row') as HTMLElement;
const fitBox = mainShadow.querySelector('.fit-box') as HTMLElement;
const fitRow = mainShadow.querySelector('.fit-row') as HTMLElement;
const paneNode = mainShadow.querySelector('.pane-node') as HTMLElement;
const splitHandle = mainShadow.querySelector('[data-split-handle]') as HTMLElement;
// 1. Hover pointermove before any pointerdown must NOT forward
await act(async () => {
nodeBtn.dispatchEvent(makePointerEvent('pointermove', { clientX: 150, clientY: 90, pointerId: 3, button: -1, buttons: 0 }));
});
assert.equal(events.length, 0, 'idle hover pointermove must not flood plugin IPC');
// 2. pointerdown -> move (including outside node/surface) -> coalesce -> flush before pointerup
const downEvt = makePointerEvent('pointerdown', { clientX: 140, clientY: 90, pointerId: 7, button: 0, buttons: 1, pointerType: 'mouse' });
await act(async () => {
nodeBtn.dispatchEvent(downEvt);
});
assert.equal(downEvt.defaultPrevented, false, 'pointerdown must not preventDefault so focus/click/text-selection remain intact');
assert.deepEqual(capturedPointers, [{ target: nodeBtn, pointerId: 7 }], 'touch-action:none node engages host pointer capture');
assert.deepEqual(events.at(-1), {
nodeId: 'node-1',
type: 'pointerdown',
x: 40,
y: 40,
pointerId: 7,
button: 0,
buttons: 1,
pointerType: 'mouse',
});
// Unchanged coordinate move is skipped; first changed move forwards immediately (leading edge)
// and rapid subsequent moves outside the surface coalesce and flush right before pointerup.
await act(async () => {
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 140, clientY: 90, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 200, clientY: 130, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse', shiftKey: true }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 215, clientY: 140, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 80, clientY: 20, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 80, clientY: 20, pointerId: 7, button: 0, buttons: 0, pointerType: 'mouse' }));
});
assert.deepEqual(releasedPointers, [{ target: nodeBtn, pointerId: 7 }], 'pointer capture released on pointerup');
assert.deepEqual(events.slice(1), [
{ nodeId: 'node-1', type: 'pointermove', x: 100, y: 80, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse', shiftKey: true },
{ nodeId: 'node-1', type: 'pointermove', x: -20, y: -30, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' },
{ nodeId: 'node-1', type: 'pointerup', x: -20, y: -30, pointerId: 7, button: 0, buttons: 0, pointerType: 'mouse' },
]);
// Moves after pointerup are ignored
const countAfterUp = events.length;
await act(async () => {
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 300, clientY: 300, pointerId: 7, button: -1, buttons: 0 }));
});
assert.equal(events.length, countAfterUp);
// 3. Backpressure via settled={false} holds coalesced pointermove until settled flips true
events.length = 0;
await renderSurface(false);
await act(async () => {
nodeBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 150, clientY: 100, pointerId: 9, button: 0, buttons: 1 }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 190, clientY: 120, pointerId: 9, button: -1, buttons: 1 }));
});
assert.deepEqual(events.map((e) => e.type), ['pointerdown'], 'unsettled move waits for acknowledgement');
await renderSurface(true);
assert.deepEqual(events.map((e) => ({ type: e.type, x: e.x, y: e.y })), [
{ type: 'pointerdown', x: 50, y: 50 },
{ type: 'pointermove', x: 90, y: 70 },
], 'move flushes immediately once settled becomes true');
await act(async () => {
dom.window.dispatchEvent(makePointerEvent('pointercancel', { clientX: 95, clientY: 75, pointerId: 9, button: -1, buttons: 0 }));
});
assert.equal(events.at(-1)?.type, 'pointercancel');
assert.equal(events.at(-1)?.nodeId, 'node-1');
// 4. Plain button does not engage setPointerCapture and still forwards normal click
events.length = 0;
const captureCountBeforePlain = capturedPointers.length;
await act(async () => {
plainBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 120, clientY: 70, pointerId: 11, button: 0, buttons: 1 }));
plainBtn.dispatchEvent(makePointerEvent('pointerup', { clientX: 120, clientY: 70, pointerId: 11, button: 0, buttons: 0 }));
plainBtn.click();
});
assert.equal(capturedPointers.length, captureCountBeforePlain, 'plain button without touch-action:none skips setPointerCapture');
assert.deepEqual(events.map((e) => e.type), ['pointerdown', 'pointerup', 'click']);
// 5. Wheel over non-scrollable remote node prevents default and forwards deltas; rapid ticks coalesce by summing deltas
events.length = 0;
const wheel1 = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 260,
clientY: 190,
deltaX: 0,
deltaY: -120,
deltaMode: 0,
ctrlKey: true,
});
const wheel2 = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 265,
clientY: 195,
deltaX: 4,
deltaY: -60,
deltaMode: 0,
ctrlKey: true,
});
const wheel3 = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 270,
clientY: 200,
deltaX: 6,
deltaY: -40,
deltaMode: 0,
ctrlKey: true,
});
await act(async () => {
stage.dispatchEvent(wheel1);
stage.dispatchEvent(wheel2);
stage.dispatchEvent(wheel3);
});
assert.equal(wheel1.defaultPrevented, true, 'non-scrollable wheel must preventDefault');
assert.equal(wheel2.defaultPrevented, true, 'coalesced wheel tick must also preventDefault');
assert.equal(wheel3.defaultPrevented, true, 'coalesced wheel tick must also preventDefault');
assert.deepEqual([...events], [
{ nodeId: 'stage', type: 'wheel', x: 160, y: 140, deltaX: 0, deltaY: -120, deltaMode: 0, ctrlKey: true },
]);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 40));
});
assert.deepEqual(events.at(-1), {
nodeId: 'stage',
type: 'wheel',
x: 170,
y: 150,
deltaX: 10,
deltaY: -100,
deltaMode: 0,
ctrlKey: true,
});
// 6. Wheel over scrollable overflow container allows native scroll (no preventDefault, no wheel event)
events.length = 0;
Object.defineProperty(scrollBox, 'scrollHeight', { value: 600, configurable: true });
Object.defineProperty(scrollBox, 'clientHeight', { value: 120, configurable: true });
const scrollWheel = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 200,
clientY: 150,
deltaX: 0,
deltaY: 100,
deltaMode: 0,
});
await act(async () => {
scrollRow.dispatchEvent(scrollWheel);
});
assert.equal(scrollWheel.defaultPrevented, false, 'scrollable overflow ancestor must keep native wheel scrolling');
assert.equal(events.length, 0, 'wheel over scrollable overflow ancestor must not forward wheel');
// Non-overflowing overflow:auto container still forwards wheel
Object.defineProperty(fitBox, 'scrollHeight', { value: 120, configurable: true });
Object.defineProperty(fitBox, 'clientHeight', { value: 120, configurable: true });
const fitWheel = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 200,
clientY: 150,
deltaX: 0,
deltaY: -80,
deltaMode: 0,
});
await act(async () => {
fitRow.dispatchEvent(fitWheel);
await new Promise((resolve) => setTimeout(resolve, 35));
});
assert.equal(fitWheel.defaultPrevented, true, 'non-overflowing overflow:auto box forwards wheel');
assert.equal(events.length, 1);
assert.equal(events[0].nodeId, 'fit-row');
assert.equal(events[0].type, 'wheel');
// 7. touch-action:none canvas inside a scrollable surface host still claims wheel zoom
events.length = 0;
const hostDiv = mainShadow.host as HTMLElement;
hostDiv.style.overflowY = 'auto';
Object.defineProperty(hostDiv, 'scrollHeight', { value: 1400, configurable: true });
Object.defineProperty(hostDiv, 'clientHeight', { value: 600, configurable: true });
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 35));
});
const stageWheelInScrollableHost = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 220,
clientY: 160,
deltaX: 0,
deltaY: -90,
deltaMode: 0,
});
await act(async () => {
nodeBtn.dispatchEvent(stageWheelInScrollableHost);
});
assert.equal(stageWheelInScrollableHost.defaultPrevented, true, 'touch-action:none graph node claims wheel even when outer host is scrollable');
assert.equal(events.at(-1)?.type, 'wheel');
assert.equal(events.at(-1)?.nodeId, 'node-1');
// 8. Slotted widget pointer & wheel events are never forwarded as generic plugin events
events.length = 0;
const gridHost = document.querySelector('[data-plugin-widget-host="data-grid"]') as HTMLElement;
const gridCell = gridHost.querySelector('[role="gridcell"]') as HTMLElement;
const widgetWheel = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
composed: true,
clientX: 200,
clientY: 150,
deltaX: 0,
deltaY: 120,
deltaMode: 0,
});
await act(async () => {
gridCell.dispatchEvent(makePointerEvent('pointerdown', { clientX: 200, clientY: 150, pointerId: 21, button: 0, buttons: 1 }));
gridCell.dispatchEvent(makePointerEvent('pointermove', { clientX: 240, clientY: 170, pointerId: 21, button: -1, buttons: 1 }));
gridCell.dispatchEvent(makePointerEvent('pointerup', { clientX: 240, clientY: 170, pointerId: 21, button: 0, buttons: 0 }));
gridCell.dispatchEvent(widgetWheel);
});
assert.equal(widgetWheel.defaultPrevented, false, 'slotted widget wheel must not be intercepted by surface');
assert.equal(
events.some((e) => ['pointerdown', 'pointermove', 'pointerup', 'wheel'].includes(String(e.type))),
false,
'slotted widget pointer and wheel events must not forward as generic surface events',
);
// 9. SplitPane handle drag does not forward generic pointer events, while remote nodes inside its panes do
events.length = 0;
await act(async () => {
splitHandle.dispatchEvent(makePointerEvent('pointerdown', { clientX: 200, clientY: 100, pointerId: 31, button: 0, buttons: 1 }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 250, clientY: 100, pointerId: 31, button: -1, buttons: 1 }));
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 250, clientY: 100, pointerId: 31, button: 0, buttons: 0 }));
});
assert.equal(
events.some((e) => ['pointerdown', 'pointermove', 'pointerup'].includes(String(e.type))),
false,
'split-pane handle must not forward generic pointer events',
);
assert.ok(events.some((e) => e.nodeId === 'split' && e.widgetEvent === 'resizeEnd'), 'split-pane resize still works');
events.length = 0;
await act(async () => {
paneNode.dispatchEvent(makePointerEvent('pointerdown', { clientX: 160, clientY: 110, pointerId: 32, button: 0, buttons: 1 }));
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 160, clientY: 110, pointerId: 32, button: 0, buttons: 0 }));
});
assert.deepEqual(events.map((e) => ({ nodeId: e.nodeId, type: e.type, x: e.x, y: e.y })), [
{ nodeId: 'pane-node', type: 'pointerdown', x: 60, y: 60 },
{ nodeId: 'pane-node', type: 'pointerup', x: 60, y: 60 },
]);
// 10. Unmounting the surface mid-drag emits pointercancel so a retained plugin session does not stay in a drag.
events.length = 0;
await act(async () => {
nodeBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 160, clientY: 110, pointerId: 41, button: 0, buttons: 1, pointerType: 'mouse' }));
});
assert.equal(events[0]?.type, 'pointerdown');
assert.equal(events[0]?.pointerId, 41);
await act(async () => { root.unmount(); });
assert.deepEqual(events.at(-1), {
nodeId: 'node-1',
type: 'pointercancel',
x: 60,
y: 60,
pointerId: 41,
button: -1,
buttons: 0,
});
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginRemoteSurface leaves wheel to a scrollable host-owned popover panel', async () => {
const { JSDOM } = await import('jsdom');
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'WheelEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
const val = key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window];
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, {
ResizeObserver: class {
observe() {}
unobserve() {}
disconnect() {}
},
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, toJSON() {},
});
const shadows: ShadowRoot[] = [];
const nativeAttach = dom.window.Element.prototype.attachShadow;
dom.window.Element.prototype.attachShadow = function (options) {
const s = nativeAttach.call(this, options);
shadows.push(s as unknown as ShadowRoot);
return s;
};
const events: Array<Record<string, unknown>> = [];
const root = createRoot(dom.window.document.getElementById('root')!);
try {
await act(async () => {
root.render(
<PluginRemoteSurface
tree={{
children: [
{
id: 'menu',
type: 1,
element: 'div',
attributes: {
'data-plugin-popover': 'true',
'data-plugin-anchor-x': '40',
'data-plugin-anchor-y': '20',
'data-plugin-popover-width': '240',
'data-plugin-popover-max-height': '160',
open: '',
},
children: [
{
id: 'row',
type: 1,
element: 'button',
attributes: { type: 'button' },
children: [{ id: 'row-t', type: 3, data: 'A tall menu item' }],
},
],
},
],
}}
css=""
settled={true}
onEvent={(e) => { events.push(e as unknown as Record<string, unknown>); }}
/>,
);
});
const popover = dom.window.document.querySelector('[data-plugin-view-popover]') as HTMLElement | null;
assert.ok(popover, 'host-owned popover panel is present');
popover!.style.overflow = 'auto';
Object.defineProperty(popover!, 'scrollHeight', { configurable: true, value: 400 });
Object.defineProperty(popover!, 'clientHeight', { configurable: true, value: 160 });
const popoverShadow = shadows.find((s) => popover!.contains((s as ShadowRoot).host)) ?? shadows.at(-1);
const row = popoverShadow!.querySelector('button') as HTMLElement;
assert.ok(row, 'popover row is present');
const wheel = new dom.window.WheelEvent('wheel', { bubbles: true, cancelable: true, deltaX: 0, deltaY: 80, deltaMode: 0, clientX: 120, clientY: 80 });
await act(async () => { row.dispatchEvent(wheel); });
assert.equal(wheel.defaultPrevented, false, 'scrollable popover panel must keep native wheel scrolling');
assert.equal(events.some((e) => e.type === 'wheel'), false, 'wheel over a scrollable popover panel must not be forwarded');
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginRemoteSurface + hostDom end-to-end round-trip supports node drag, incident edge tracking, background pan, and wheel zoom', async () => {
const dom = new JSDOM('<!doctype html><div id="host-root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLOptionElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'MouseEvent', 'WheelEvent', 'PointerEvent', 'CustomEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, { PointerEvent: dom.window.MouseEvent });
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 40, y: 20, width: 600, height: 400, top: 20, left: 40, right: 640, bottom: 420, toJSON() {},
});
// In Electron the visible host renderer and hidden plugin runtime run in separate
// BrowserWindows. Guard host window capture listeners while forwarding into hostDom
// so plugin-side synthetic dispatches do not loop back into the host in a shared JSDOM.
let forwardingToPlugin = false;
const origAdd = dom.window.addEventListener.bind(dom.window);
const origRemove = dom.window.removeEventListener.bind(dom.window);
const wrappedListeners = new WeakMap<EventListenerOrEventListenerObject, EventListener>();
dom.window.addEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) => {
const capture = typeof options === 'boolean' ? options : Boolean(options?.capture);
if (type === 'pointermove' || type === 'pointerup' || type === 'pointercancel') {
const wrapped: EventListener = (evt) => {
if (capture ? forwardingToPlugin : !forwardingToPlugin) return;
if (typeof listener === 'function') listener(evt);
else listener.handleEvent(evt);
};
wrappedListeners.set(listener, wrapped);
return origAdd(type, wrapped, options);
}
return origAdd(type, listener, options);
}) as typeof dom.window.addEventListener;
dom.window.removeEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions) => {
return origRemove(type, wrappedListeners.get(listener) ?? listener, options);
}) as typeof dom.window.removeEventListener;
const shadows: ShadowRoot[] = [];
const nativeAttach = dom.window.Element.prototype.attachShadow;
dom.window.Element.prototype.attachShadow = function (options) {
const s = nativeAttach.call(this, options);
shadows.push(s as unknown as ShadowRoot);
return s;
};
const { act, useEffect, useRef, useState } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const { createPluginRemoteTree } = await import('../../application/state/pluginRemoteTree');
const { registerHostReactView } = await import('../../packages/plugin-sdk/src/hostReact');
const { createDefinitionValidator } = await import('../../electron/plugins/contractValidator.cjs');
const validateEvent = createDefinitionValidator('HostDrawnViewEvent');
const remoteTree = createPluginRemoteTree();
const hostRoot = createRoot(document.getElementById('host-root')!);
let pluginReceive: (message: unknown) => void = () => {};
let latestEventId = 0;
let latestAck = 0;
const renderHostSurface = () => {
hostRoot.render(
<PluginRemoteSurface
tree={remoteTree.snapshot()}
css=""
settled={latestAck >= latestEventId}
onEvent={(event) => {
const stamped = { ...event, eventId: ++latestEventId };
assert.equal(validateEvent(stamped), true, `Host event failed contract schema: ${JSON.stringify(validateEvent.errors)}`);
forwardingToPlugin = true;
try {
pluginReceive({ kind: 'host-ui.event', instanceId: 'e2e-1', event: stamped });
} finally {
forwardingToPlugin = false;
}
}}
/>,
);
};
const views = {
onDidReceiveMessage(_id: string, listener: (value: unknown) => void) {
pluginReceive = listener;
return { dispose() {} };
},
postMessage(_id: string, value: unknown) {
const msg = value as { kind?: string; mutations?: unknown[]; acknowledgedEvent?: number };
if (msg.kind !== 'host-ui.update') return;
if (Array.isArray(msg.mutations) && msg.mutations.length > 0) {
remoteTree.apply(msg.mutations);
}
if (typeof msg.acknowledgedEvent === 'number') {
latestAck = msg.acknowledgedEvent;
}
renderHostSurface();
},
getState: async () => undefined,
setState: async () => {},
setBadge: async () => {},
};
function MiniGraphCanvas() {
const stageRef = useRef<HTMLDivElement | null>(null);
const [nodePos, setNodePos] = useState({ x: 80, y: 100 });
const fixedPos = { x: 280, y: 100 };
const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 });
const [dragging, setDragging] = useState(false);
const dragRef = useRef<{ kind: 'node' | 'pan'; pointerId: number; startX: number; startY: number; originX: number; originY: number } | null>(null);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const onWheel = (event: WheelEvent) => {
event.preventDefault();
setViewport((prev) => ({
...prev,
zoom: Math.round(prev.zoom * (event.deltaY < 0 ? 1.2 : 0.8) * 100) / 100,
}));
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, []);
// Mirror real canvas window-level drag listeners inside the plugin runtime.
useEffect(() => {
if (!dragging) return;
const onMove = (event: PointerEvent) => {
const drag = dragRef.current;
if (!drag || drag.pointerId !== event.pointerId) return;
if (drag.kind === 'node') {
setNodePos({ x: drag.originX + (event.clientX - drag.startX), y: drag.originY + (event.clientY - drag.startY) });
} else {
setViewport((prev) => ({ ...prev, x: drag.originX + (event.clientX - drag.startX), y: drag.originY + (event.clientY - drag.startY) }));
}
};
const onUp = (event: PointerEvent) => {
if (dragRef.current?.pointerId === event.pointerId) {
dragRef.current = null;
setDragging(false);
}
};
window.addEventListener('pointermove', onMove as unknown as EventListener);
window.addEventListener('pointerup', onUp as unknown as EventListener);
return () => {
window.removeEventListener('pointermove', onMove as unknown as EventListener);
window.removeEventListener('pointerup', onUp as unknown as EventListener);
};
}, [dragging]);
const edgeLen = Math.round(Math.hypot(fixedPos.x - nodePos.x, fixedPos.y - nodePos.y));
return (
<div
className="e2e-stage"
ref={stageRef}
style={{ overflow: 'hidden', touchAction: 'none' }}
onPointerDown={(e) => {
if (e.button !== 0) return;
dragRef.current = { kind: 'pan', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: viewport.x, originY: viewport.y };
setDragging(true);
}}
>
<div className="e2e-world" style={{ transform: `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})` }}>
<div className="e2e-edge" style={{ width: `${edgeLen}px`, transform: `translate(${nodePos.x}px, ${nodePos.y}px)` }} />
<button
type="button"
className="e2e-node"
style={{ touchAction: 'none', transform: `translate(${nodePos.x}px, ${nodePos.y}px)` }}
onPointerDown={(e) => {
if (e.button !== 0) return;
e.stopPropagation();
dragRef.current = { kind: 'node', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: nodePos.x, originY: nodePos.y };
setDragging(true);
}}
>
N1
</button>
</div>
</div>
);
}
const makePointer = (type: string, clientX: number, clientY: number, pointerId: number, button: number, buttons: number) => {
const evt = new dom.window.MouseEvent(type, { bubbles: true, cancelable: true, composed: true, clientX, clientY, button, buttons });
Object.defineProperty(evt, 'pointerId', { value: pointerId });
return evt;
};
const registration = registerHostReactView(views as never, 'com.example.e2e-graph', () => <MiniGraphCanvas />);
try {
await act(async () => {
pluginReceive({ kind: 'host-ui.open', instanceId: 'e2e-1' });
await new Promise((resolve) => setTimeout(resolve, 20));
});
const shadow = shadows[0]!;
const stageEl = shadow.querySelector('.e2e-stage') as HTMLElement;
const worldEl = shadow.querySelector('.e2e-world') as HTMLElement;
const edgeEl = shadow.querySelector('.e2e-edge') as HTMLElement;
const nodeEl = shadow.querySelector('.e2e-node') as HTMLElement;
assert.equal(nodeEl.style.transform, 'translate(80px, 100px)');
assert.equal(edgeEl.style.width, '200px');
// Drag node across the visible host surface (pointermove/up dispatched on host window outside the node)
await act(async () => {
nodeEl.dispatchEvent(makePointer('pointerdown', 120, 120, 1, 0, 1));
await new Promise((resolve) => setTimeout(resolve, 15));
});
await act(async () => {
dom.window.dispatchEvent(makePointer('pointermove', 170, 160, 1, -1, 1));
await new Promise((resolve) => setTimeout(resolve, 15));
});
await act(async () => {
dom.window.dispatchEvent(makePointer('pointerup', 170, 160, 1, 0, 0));
await new Promise((resolve) => setTimeout(resolve, 25));
});
assert.equal(nodeEl.style.transform, 'translate(130px, 140px)', 'visible host shadow DOM node must move by (+50, +40)');
assert.equal(edgeEl.style.width, `${Math.round(Math.hypot(280 - 130, 100 - 140))}px`, 'visible host incident edge must follow node');
// Pan background stage and wheel-zoom
await act(async () => {
stageEl.dispatchEvent(makePointer('pointerdown', 300, 200, 2, 0, 1));
await new Promise((resolve) => setTimeout(resolve, 15));
});
await act(async () => {
dom.window.dispatchEvent(makePointer('pointermove', 340, 230, 2, -1, 1));
await new Promise((resolve) => setTimeout(resolve, 15));
});
await act(async () => {
dom.window.dispatchEvent(makePointer('pointerup', 340, 230, 2, 0, 0));
await new Promise((resolve) => setTimeout(resolve, 25));
});
const wheelEvt = new dom.window.WheelEvent('wheel', { bubbles: true, cancelable: true, clientX: 250, clientY: 180, deltaX: 0, deltaY: -120, deltaMode: 0 });
await act(async () => {
stageEl.dispatchEvent(wheelEvt);
await new Promise((resolve) => setTimeout(resolve, 25));
});
assert.equal(wheelEvt.defaultPrevented, true);
assert.equal(worldEl.style.transform, 'translate(40px, 30px) scale(1.2)', 'visible host shadow DOM world must pan and wheel-zoom');
await act(async () => {
pluginReceive({ kind: 'host-ui.close', instanceId: 'e2e-1' });
});
} finally {
await act(async () => {
registration.dispose();
hostRoot.unmount();
});
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
+523 -11
View File
@@ -19,8 +19,13 @@ export type PluginSurfaceEvent = import('@netcatty/plugin-contract').HostDrawnVi
const MAX_EVENT_VALUE_LENGTH = 131072;
const SCROLL_THROTTLE_MS = 60;
const POINTER_MOVE_THROTTLE_MS = 24;
const POINTER_MOVE_BACKPRESSURE_MAX_MS = 96;
const WHEEL_THROTTLE_MS = 24;
const SURFACE_EVENTS = [
'click', 'dblclick', 'contextmenu',
'pointerdown', 'pointermove', 'pointerup', 'pointercancel',
'wheel',
'input', 'change',
'keydown', 'keyup',
'focusin', 'focusout',
@@ -337,6 +342,163 @@ function readSelectionRange(
return undefined;
}
function readSurfacePoint(
event: MouseEvent,
surfaceEl: HTMLElement | null,
): { x: number; y: number } {
const rect = surfaceEl?.getBoundingClientRect();
const rawX = rect ? event.clientX - rect.left : event.clientX;
const rawY = rect ? event.clientY - rect.top : event.clientY;
return {
x: Number.isFinite(rawX) ? Math.round(rawX) : 0,
y: Number.isFinite(rawY) ? Math.round(rawY) : 0,
};
}
function readModifierKeys(event: MouseEvent | WheelEvent): {
ctrlKey?: true;
metaKey?: true;
altKey?: true;
shiftKey?: true;
} {
return {
...(event.ctrlKey ? { ctrlKey: true as const } : {}),
...(event.metaKey ? { metaKey: true as const } : {}),
...(event.altKey ? { altKey: true as const } : {}),
...(event.shiftKey ? { shiftKey: true as const } : {}),
};
}
function readPointerId(event: Event): number {
const raw = (event as PointerEvent).pointerId;
if (typeof raw === 'number' && Number.isFinite(raw)) {
return Math.max(-2147483648, Math.min(2147483647, Math.trunc(raw)));
}
return 1;
}
function readPointerType(event: Event): 'mouse' | 'pen' | 'touch' | undefined {
const raw = (event as PointerEvent).pointerType;
return raw === 'mouse' || raw === 'pen' || raw === 'touch' ? raw : undefined;
}
function readPointerButton(event: MouseEvent): number {
return typeof event.button === 'number' && Number.isFinite(event.button)
? Math.max(-1, Math.min(32, Math.trunc(event.button)))
: 0;
}
function readPointerButtons(event: MouseEvent): number {
return typeof event.buttons === 'number' && Number.isFinite(event.buttons)
? Math.max(0, Math.min(65535, Math.trunc(event.buttons)))
: 0;
}
function roundWheelDelta(value: number): number {
return Number.isFinite(value) ? Math.round(value * 100) / 100 : 0;
}
function isScrollableOverflowValue(value: string | undefined): boolean {
return value === 'auto' || value === 'scroll' || value === 'overlay';
}
function readOverflowToken(value: string | undefined, axis: 'x' | 'y'): string | undefined {
if (!value) return undefined;
const parts = value.trim().split(/\s+/);
return axis === 'y' ? (parts[1] ?? parts[0]) : parts[0];
}
function readAxisOverflow(
el: HTMLElement,
style: CSSStyleDeclaration | undefined,
axis: 'x' | 'y',
): string | undefined {
// Prefer a scrollable value from computed or inline styles. Some test DOMs
// report the initial `visible` computed overflow even when the element has
// an inline `overflow: auto` shorthand.
const candidates = [
axis === 'y' ? style?.overflowY : style?.overflowX,
axis === 'y' ? el.style.overflowY : el.style.overflowX,
readOverflowToken(style?.overflow, axis),
readOverflowToken(el.style.overflow, axis),
];
for (const value of candidates) {
if (isScrollableOverflowValue(value)) return value;
}
return candidates.find((value) => value && value !== 'visible') ?? candidates[0];
}
function canElementScrollForWheel(
el: HTMLElement,
view: Window & typeof globalThis,
deltaX: number,
deltaY: number,
): boolean {
const style = view.getComputedStyle?.(el);
const canScrollY = deltaY !== 0
&& isScrollableOverflowValue(readAxisOverflow(el, style, 'y'))
&& el.scrollHeight > el.clientHeight + 1;
const canScrollX = deltaX !== 0
&& isScrollableOverflowValue(readAxisOverflow(el, style, 'x'))
&& el.scrollWidth > el.clientWidth + 1;
return canScrollY || canScrollX;
}
/**
* Wheel vs native scroll rule:
* Walk ancestors inside the shadow root (and then the surface's own scroll host
* unless a non-scrollable element declares `touch-action: none` to claim canvas
* gestures). If an ancestor has `overflow: auto|scroll|overlay` with actual
* overflow along the wheel axis, leave the event to native scrolling (existing
* throttled `scroll` events still forward). Otherwise `preventDefault()` so the
* surrounding workbench does not steal the gesture, and forward coalesced `wheel`.
*/
function hasScrollableAncestorForWheel(
target: HTMLElement,
shadow: ShadowRoot,
host: HTMLElement | null,
view: Window & typeof globalThis,
deltaX: number,
deltaY: number,
): boolean {
let current: HTMLElement | null = target;
let hitGestureBoundary = false;
while (current) {
if (canElementScrollForWheel(current, view, deltaX, deltaY)) return true;
const touchAction = view.getComputedStyle?.(current)?.touchAction || current.style.touchAction;
if (touchAction === 'none') {
hitGestureBoundary = true;
break;
}
const parent = current.parentElement;
if (!parent || parent.getRootNode() !== shadow) break;
current = parent;
}
if (!hitGestureBoundary && host && canElementScrollForWheel(host, view, deltaX, deltaY)) {
return true;
}
// Nested popover surfaces live in a portaled PluginViewPopover panel. That
// panel (not the inner overflow-auto host) is often the only element with a
// bounded max-height, so include it when deciding who owns the wheel.
if (!hitGestureBoundary) {
const popover = (host ?? target).closest?.('[data-plugin-view-popover]') as HTMLElement | null;
if (popover && canElementScrollForWheel(popover, view, deltaX, deltaY)) return true;
}
return false;
}
type ActivePointerGesture = {
nodeId: string;
pointerId: number;
capturedElement: HTMLElement | null;
lastSentX: number;
lastSentY: number;
lastMoveSentAt: number;
pendingMove: PluginSurfaceEvent | null;
pendingMoveSince: number;
moveTimer: ReturnType<typeof setTimeout> | null;
};
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadImage, depth = 0 }: { depth?: number; tree: unknown; css: string; settled?: boolean; loadImage?(path: string): Promise<string>; onEvent(event: PluginSurfaceEvent): void }) {
const checkedTree = useMemo(() => {
@@ -373,6 +535,8 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
const surfaceRef = useRef<HTMLDivElement>(null);
const hostRef = useRef<HTMLDivElement>(null);
const onEventRef = useRef(onEvent); onEventRef.current = onEvent;
const settledRef = useRef(settled); settledRef.current = settled;
const flushPendingMovesRef = useRef<(() => void) | null>(null);
const shadowRef = useRef<ShadowRoot | null>(null);
const [shadow, setShadow] = useState<ShadowRoot | null>(null);
const [shadowHost, setShadowHost] = useState<HTMLDivElement | null>(null);
@@ -387,6 +551,10 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
setShadowHost(host);
}, []);
useEffect(() => {
if (settled) flushPendingMovesRef.current?.();
}, [settled]);
const surfaceContextValue = useMemo(
() => ({ css, onEvent, depth, shadowHost }),
[css, onEvent, depth, shadowHost],
@@ -394,8 +562,15 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
useEffect(() => {
if (!shadow) return;
const view = shadow.ownerDocument.defaultView;
const scrollTimers = new Map<string, ReturnType<typeof setTimeout>>();
const pendingScroll = new Map<string, PluginSurfaceEvent>();
const activeGestures = new Map<number, ActivePointerGesture>();
const handledPointerEvents = new WeakSet<Event>();
let windowPointerListenersAttached = false;
let wheelTimer: ReturnType<typeof setTimeout> | null = null;
let pendingWheel: PluginSurfaceEvent | null = null;
let lastWheelSentAt = 0;
const flushScroll = (nodeId: string) => {
scrollTimers.delete(nodeId);
@@ -406,10 +581,203 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
}
};
const flushWheel = () => {
if (wheelTimer !== null) {
clearTimeout(wheelTimer);
wheelTimer = null;
}
const evt = pendingWheel;
pendingWheel = null;
if (!evt || ((evt.deltaX ?? 0) === 0 && (evt.deltaY ?? 0) === 0)) return;
lastWheelSentAt = Date.now();
onEventRef.current(evt);
};
const emitGestureMove = (gesture: ActivePointerGesture, moveEvent: PluginSurfaceEvent, now: number) => {
if (gesture.moveTimer !== null) {
clearTimeout(gesture.moveTimer);
gesture.moveTimer = null;
}
gesture.pendingMove = null;
gesture.pendingMoveSince = 0;
if (moveEvent.x === gesture.lastSentX && moveEvent.y === gesture.lastSentY) return;
gesture.lastSentX = moveEvent.x ?? gesture.lastSentX;
gesture.lastSentY = moveEvent.y ?? gesture.lastSentY;
gesture.lastMoveSentAt = now;
onEventRef.current(moveEvent);
};
const scheduleGestureMoveFlush = (gesture: ActivePointerGesture) => {
if (gesture.moveTimer !== null || !gesture.pendingMove) return;
const now = Date.now();
const throttleWait = Math.max(0, POINTER_MOVE_THROTTLE_MS - (now - gesture.lastMoveSentAt));
const backpressureWait = settledRef.current
? 0
: Math.max(0, POINTER_MOVE_BACKPRESSURE_MAX_MS - (now - gesture.pendingMoveSince));
const delay = Math.max(1, throttleWait, backpressureWait);
gesture.moveTimer = setTimeout(() => {
gesture.moveTimer = null;
if (activeGestures.get(gesture.pointerId) !== gesture || !gesture.pendingMove) return;
const tickNow = Date.now();
const elapsed = tickNow - gesture.lastMoveSentAt;
const waitedEnough = settledRef.current || tickNow - gesture.pendingMoveSince >= POINTER_MOVE_BACKPRESSURE_MAX_MS;
if (elapsed >= POINTER_MOVE_THROTTLE_MS && waitedEnough) {
emitGestureMove(gesture, gesture.pendingMove, tickNow);
} else {
scheduleGestureMoveFlush(gesture);
}
}, delay);
};
const releaseGesture = (gesture: ActivePointerGesture) => {
if (gesture.moveTimer !== null) {
clearTimeout(gesture.moveTimer);
gesture.moveTimer = null;
}
gesture.pendingMove = null;
gesture.pendingMoveSince = 0;
if (gesture.capturedElement) {
try {
gesture.capturedElement.releasePointerCapture?.(gesture.pointerId);
} catch {
// Capture may already have been released natively.
}
gesture.capturedElement = null;
}
activeGestures.delete(gesture.pointerId);
if (activeGestures.size === 0) detachWindowPointerListeners();
};
/**
* Active pointer gestures are tracked at the host surface so plugin drags
* continue after leaving the originating node or surface (plugin-side
* setPointerCapture cannot capture the visible host pointer). Moves skip
* unchanged coordinates, coalesce under POINTER_MOVE_THROTTLE_MS, and adapt
* to host-ui acknowledgedEvent backpressure via `settled`.
*/
const onGesturePointerEvent = (event: Event) => {
if (!view || activeGestures.size === 0 || handledPointerEvents.has(event)) return;
const pointerId = readPointerId(event);
const gesture = activeGestures.get(pointerId);
if (!gesture) return;
handledPointerEvents.add(event);
const isMouseLike = event instanceof view.MouseEvent;
const coords = isMouseLike
? readSurfacePoint(event, surfaceRef.current ?? hostRef.current)
: { x: gesture.lastSentX, y: gesture.lastSentY };
const pointerType = readPointerType(event);
const button = isMouseLike ? readPointerButton(event) : -1;
const buttons = isMouseLike ? readPointerButtons(event) : 0;
const modifiers = isMouseLike ? readModifierKeys(event) : {};
if (event.type === 'pointermove') {
const moveEvent: PluginSurfaceEvent = {
nodeId: gesture.nodeId,
type: 'pointermove',
...coords,
pointerId: gesture.pointerId,
button,
buttons,
...(pointerType ? { pointerType } : {}),
...modifiers,
};
if (gesture.pendingMove === null && coords.x === gesture.lastSentX && coords.y === gesture.lastSentY) {
return;
}
const now = Date.now();
const elapsed = now - gesture.lastMoveSentAt;
const canSendNow =
elapsed >= POINTER_MOVE_THROTTLE_MS
&& (settledRef.current || (gesture.pendingMoveSince > 0 && now - gesture.pendingMoveSince >= POINTER_MOVE_BACKPRESSURE_MAX_MS));
if (canSendNow) {
emitGestureMove(gesture, moveEvent, now);
} else {
gesture.pendingMove = moveEvent;
if (gesture.pendingMoveSince === 0) gesture.pendingMoveSince = now;
scheduleGestureMoveFlush(gesture);
}
return;
}
if (event.type === 'pointerup' && gesture.pendingMove) {
emitGestureMove(gesture, gesture.pendingMove, Date.now());
}
releaseGesture(gesture);
onEventRef.current({
nodeId: gesture.nodeId,
type: event.type as 'pointerup' | 'pointercancel',
...coords,
pointerId: gesture.pointerId,
button,
buttons,
...(pointerType ? { pointerType } : {}),
...modifiers,
});
};
const onWindowBlur = (event: Event) => {
if (!view || event.target !== view || activeGestures.size === 0) return;
for (const gesture of [...activeGestures.values()]) {
const { nodeId, pointerId, lastSentX, lastSentY } = gesture;
releaseGesture(gesture);
onEventRef.current({
nodeId,
type: 'pointercancel',
x: lastSentX,
y: lastSentY,
pointerId,
button: -1,
buttons: 0,
});
}
};
const attachWindowPointerListeners = () => {
if (!view || windowPointerListenersAttached) return;
windowPointerListenersAttached = true;
view.addEventListener('pointermove', onGesturePointerEvent, true);
view.addEventListener('pointerup', onGesturePointerEvent, true);
view.addEventListener('pointercancel', onGesturePointerEvent, true);
view.addEventListener('blur', onWindowBlur, false);
};
const detachWindowPointerListeners = () => {
if (!view || !windowPointerListenersAttached) return;
windowPointerListenersAttached = false;
view.removeEventListener('pointermove', onGesturePointerEvent, true);
view.removeEventListener('pointerup', onGesturePointerEvent, true);
view.removeEventListener('pointercancel', onGesturePointerEvent, true);
view.removeEventListener('blur', onWindowBlur, false);
};
flushPendingMovesRef.current = () => {
const now = Date.now();
for (const gesture of activeGestures.values()) {
if (!gesture.pendingMove) continue;
const elapsed = now - gesture.lastMoveSentAt;
if (elapsed >= POINTER_MOVE_THROTTLE_MS) {
emitGestureMove(gesture, gesture.pendingMove, now);
} else {
if (gesture.moveTimer !== null) {
clearTimeout(gesture.moveTimer);
gesture.moveTimer = null;
}
scheduleGestureMoveFlush(gesture);
}
}
};
const listener = (event: Event) => {
if (!view || !SURFACE_EVENT_SET.has(event.type)) return;
if (event.type === 'pointermove' || event.type === 'pointerup' || event.type === 'pointercancel') {
onGesturePointerEvent(event);
return;
}
const target = event.target;
const view = shadow.ownerDocument.defaultView;
if (!view || !(target instanceof view.HTMLElement) || !SURFACE_EVENT_SET.has(event.type)) return;
if (!(target instanceof view.HTMLElement)) return;
// Closed-shadow events hide their editable target from window capture.
if (event.type === 'focusin') {
@@ -420,8 +788,12 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
}
if (event.type === 'focusout') hostRef.current?.removeAttribute('data-plugin-editing');
// Internal events inside slotted host-rendered widgets are handled by the widget itself.
if (target.closest('[data-plugin-widget-host]')) return;
// Internal events inside slotted host-rendered widgets or split-pane dividers are handled by the widget itself.
if (
target.closest('[data-plugin-widget-host]')
|| target.closest('[data-split-handle]')
|| SLOTTED_WIDGET_KINDS.has(target.dataset.pluginWidget ?? '')
) return;
if (event.type === 'submit') event.preventDefault();
if (event.type === 'contextmenu') event.preventDefault();
@@ -436,6 +808,120 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
?? (event.type === 'keydown' ? (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode : undefined);
if (!nodeId) return;
if (event.type === 'pointerdown') {
if (!(event instanceof view.MouseEvent)) return;
const pointerId = readPointerId(event);
const existing = activeGestures.get(pointerId);
if (existing) releaseGesture(existing);
const coords = readSurfacePoint(event, surfaceRef.current ?? hostRef.current);
const pointerType = readPointerType(event);
const button = readPointerButton(event);
const buttons = readPointerButtons(event);
const modifiers = readModifierKeys(event);
// Engage native pointer capture only on non-control elements that explicitly
// declare `touch-action: none` so text selection, native form controls, and
// normal button click cancellation stay intact. Window capture listeners still
// sustain cross-node/cross-surface drags for every remote node.
let capturedElement: HTMLElement | null = null;
if (!target.matches('input, textarea, select, option')) {
const touchAction = view.getComputedStyle?.(target)?.touchAction || target.style.touchAction;
if (touchAction === 'none') {
try {
target.setPointerCapture?.(pointerId);
capturedElement = target;
} catch {
// Synthetic or unsupported pointer capture environments rely on window listeners.
}
}
}
activeGestures.set(pointerId, {
nodeId,
pointerId,
capturedElement,
lastSentX: coords.x,
lastSentY: coords.y,
lastMoveSentAt: 0,
pendingMove: null,
pendingMoveSince: 0,
moveTimer: null,
});
attachWindowPointerListeners();
onEventRef.current({
nodeId,
type: 'pointerdown',
...coords,
pointerId,
button,
buttons,
...(pointerType ? { pointerType } : {}),
...modifiers,
});
return;
}
if (event.type === 'wheel') {
const wheel = event as WheelEvent;
const deltaX = roundWheelDelta(wheel.deltaX);
const deltaY = roundWheelDelta(wheel.deltaY);
if (deltaX === 0 && deltaY === 0) return;
if (hasScrollableAncestorForWheel(target, shadow, hostRef.current, view, deltaX, deltaY)) {
return;
}
event.preventDefault();
const rawMode = wheel.deltaMode;
const deltaMode = typeof rawMode === 'number' && Number.isFinite(rawMode)
? Math.max(0, Math.min(2, Math.trunc(rawMode)))
: 0;
const coords = readSurfacePoint(wheel, surfaceRef.current ?? hostRef.current);
const modifiers = readModifierKeys(wheel);
const nextWheel: PluginSurfaceEvent = {
nodeId,
type: 'wheel',
...coords,
deltaX,
deltaY,
deltaMode,
...modifiers,
};
const now = Date.now();
if (!pendingWheel && now - lastWheelSentAt >= WHEEL_THROTTLE_MS) {
lastWheelSentAt = now;
onEventRef.current(nextWheel);
return;
}
if (
pendingWheel
&& pendingWheel.nodeId === nodeId
&& pendingWheel.deltaMode === deltaMode
&& Boolean(pendingWheel.ctrlKey) === Boolean(modifiers.ctrlKey)
&& Boolean(pendingWheel.metaKey) === Boolean(modifiers.metaKey)
&& Boolean(pendingWheel.altKey) === Boolean(modifiers.altKey)
&& Boolean(pendingWheel.shiftKey) === Boolean(modifiers.shiftKey)
) {
pendingWheel = {
...pendingWheel,
...coords,
deltaX: roundWheelDelta((pendingWheel.deltaX ?? 0) + deltaX),
deltaY: roundWheelDelta((pendingWheel.deltaY ?? 0) + deltaY),
};
} else {
if (pendingWheel) flushWheel();
pendingWheel = nextWheel;
}
if (wheelTimer === null) {
const delay = Math.max(1, WHEEL_THROTTLE_MS - (Date.now() - lastWheelSentAt));
wheelTimer = setTimeout(flushWheel, delay);
}
return;
}
if (event.type === 'scroll') {
const scrollEvent: PluginSurfaceEvent = {
nodeId,
@@ -463,11 +949,7 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
let pointerCoords: { x: number; y: number } | undefined;
if ((event.type === 'dblclick' || event.type === 'contextmenu') && event instanceof view.MouseEvent) {
const rect = (surfaceRef.current ?? hostRef.current)?.getBoundingClientRect();
pointerCoords = {
x: Math.round(rect ? event.clientX - rect.left : event.clientX),
y: Math.round(rect ? event.clientY - rect.top : event.clientY),
};
pointerCoords = readSurfacePoint(event, surfaceRef.current ?? hostRef.current);
}
const selection =
@@ -488,12 +970,21 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
});
};
for (const event of SURFACE_EVENTS) shadow.addEventListener(event, listener, true);
for (const event of SURFACE_EVENTS) {
shadow.addEventListener(event, listener, event === 'wheel' ? { capture: true, passive: false } : true);
}
// Chromium only treats wheel as cancelable when a non-passive listener is
// registered on a real element. A closed ShadowRoot listener alone can see
// `cancelable: false`, so also listen on the shadow host (no-op targeting;
// the shadow capture listener still owns forwarding).
const shadowHostEl = hostRef.current;
const hostWheelOptions: AddEventListenerOptions = { capture: true, passive: false };
const hostWheelListener = (_event: Event) => {};
shadowHostEl?.addEventListener('wheel', hostWheelListener, hostWheelOptions);
// When a full-bleed plugin view is visible and focus sits on document.body (e.g.
// right after tab switch or drawer close), forward global Cmd/Ctrl+K / Cmd/Ctrl+S
// into the plugin so its Command Palette and Save shortcuts work reliably.
const view = shadow.ownerDocument.defaultView;
const onWindowKeyDown = (event: KeyboardEvent) => {
if (depth !== 0 || event.defaultPrevented) return;
const surfaceEl = surfaceRef.current;
@@ -531,7 +1022,28 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
view?.addEventListener('keydown', onWindowKeyDown, false);
return () => {
flushPendingMovesRef.current = null;
view?.removeEventListener('keydown', onWindowKeyDown, false);
shadowHostEl?.removeEventListener('wheel', hostWheelListener, hostWheelOptions);
// The retained plugin session keeps its SDK DOM when this surface unmounts
// (tab hide). Send pointercancel so plugin drags do not stay stuck.
for (const gesture of [...activeGestures.values()]) {
const { nodeId, pointerId, lastSentX, lastSentY } = gesture;
releaseGesture(gesture);
onEventRef.current({
nodeId,
type: 'pointercancel',
x: lastSentX,
y: lastSentY,
pointerId,
button: -1,
buttons: 0,
});
}
detachWindowPointerListeners();
if (wheelTimer !== null) clearTimeout(wheelTimer);
wheelTimer = null;
pendingWheel = null;
for (const timer of scrollTimers.values()) clearTimeout(timer);
scrollTimers.clear();
pendingScroll.clear();
+2 -2
View File
@@ -1,9 +1,9 @@
[
{
"id": "com.binaricat.netcatty-database",
"version": "0.3.1",
"version": "0.3.2",
"repository": "binaricat/netcatty-database-plugin",
"commit": "84928ba5ca9638e509a11b7a578c400c0a320d06",
"commit": "81c3dd7ad9193b0d3a44df1531daeb6c758b4ee8",
"icon": {
"kind": "package",
"light": "assets/plugin-icon-light.png",
@@ -89,6 +89,22 @@ export function PluginDataGrid({
);
const totalRows = rows.length + insertedRows.length;
useEffect(() => {
if (!editingCell) return;
const colAtIdx = visibleCols[editingCell.colIndex];
const invalidRow =
editingCell.rowIndex < 0 || editingCell.rowIndex >= totalRows || deletedSet.has(editingCell.rowIndex);
const invalidCol = !colAtIdx || colAtIdx.col.name !== editingCell.colName;
if (invalidRow || invalidCol) {
if (blurTimerRef.current !== null) {
clearTimeout(blurTimerRef.current);
blurTimerRef.current = null;
}
editingCellRef.current = null;
setEditingCell(null);
}
}, [editingCell, totalRows, deletedSet, visibleCols]);
const getColWidth = useCallback((col: PluginDataGridColumn): number => {
const custom = colWidths[col.name];
if (custom !== undefined) return custom;
@@ -7,19 +7,27 @@ import { PluginPackageManager } from './PluginPackageManager';
import type { usePluginManager } from '../../../application/state/usePluginManager';
test('state pill exposes actual state, opposite action, focus styling and pending disable without granting permissions', async () => {
const globals = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
const globals = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean; requestAnimationFrame?: typeof requestAnimationFrame };
const previous = globals.IS_REACT_ACT_ENVIRONMENT; globals.IS_REACT_ACT_ENVIRONMENT = true;
const previousRaf = globals.requestAnimationFrame;
globals.requestAnimationFrame ??= (fn) => { fn(0); return 0; };
const calls: unknown[] = [];
const plugin = { id: 'com.test.pill', activeVersion: '1.0.0', enabled: true, manifest: { name: 'Pill' }, runtime: {} } as NetcattyInstalledPlugin;
const plugin = { id: 'com.test.pill', activeVersion: '1.0.0', enabled: true, manifest: { name: 'Pill', engines: { netcatty: '*', api: '*' } }, runtime: {} } as NetcattyInstalledPlugin;
const manager = { available: true, plugins: [plugin], busy: false, setEnabled: async (...args: unknown[]) => { calls.push(args); } } as unknown as ReturnType<typeof usePluginManager>;
let renderer: ReactTestRenderer;
const render = (enabled: boolean, busy = false) => <I18nProvider locale="en"><PluginPackageManager manager={{ ...manager, busy, plugins: [{ ...plugin, enabled }] }} /></I18nProvider>;
try {
await act(async () => { renderer = create(render(true)); });
const pill = () => renderer.root.findAllByType('button').find((node) => node.props['aria-pressed'] !== undefined)!;
const listAvatar = () => renderer.root.findAllByType('button').find((node) => node.props['aria-label'] === 'View details Pill' && typeof node.props.className === 'string' && node.props.className.includes('h-8 w-8'));
const detailLogoSlot = () => renderer.root.findAllByType('div').find((node) => node.props.className === 'flex h-12 w-12 shrink-0 items-center justify-center');
assert.ok(listAvatar(), 'list card renders 32px avatar details button');
assert.doesNotMatch(listAvatar()!.props.className, /\bbg-/, 'list avatar has no extra decorative background');
assert.equal(detailLogoSlot(), undefined, 'list render does not include the 48px detail logo slot');
await act(async () => listAvatar()!.props.onClick());
assert.ok(detailLogoSlot(), 'logo keeps its 48px layout slot without an extra decorative background');
assert.doesNotMatch(detailLogoSlot()!.props.className, /\bbg-/);
assert.equal(pill().props['aria-pressed'], true);
const logoSlot = renderer.root.findAllByType('div').find((node) => node.props.className === 'flex h-12 w-12 shrink-0 items-center justify-center');
assert.ok(logoSlot, 'logo keeps its 48px layout slot without an extra decorative background');
assert.equal(pill().props['aria-label'], 'Disable Pill');
assert.ok(pill().children.includes('Enabled'));
assert.match(pill().props.className, /rounded-full/);
@@ -39,5 +47,9 @@ test('state pill exposes actual state, opposite action, focus styling and pendin
assert.match(pill().props.className, /bg-muted/);
assert.equal(pill().props.style, undefined);
await act(async () => renderer.unmount());
} finally { globals.IS_REACT_ACT_ENVIRONMENT = previous; }
} finally {
globals.IS_REACT_ACT_ENVIRONMENT = previous;
if (previousRaf === undefined) Reflect.deleteProperty(globals, 'requestAnimationFrame');
else globals.requestAnimationFrame = previousRaf;
}
});
@@ -301,7 +301,8 @@ export function getCommandToRecordOnEnter(
/**
* Keystrokes that remove the text a snippet acceptance replaces.
* Line-start keeps the shell kill-line (Ctrl+U, or backspaces on Windows).
* Mid-line and program read-prompts delete only the word being typed.
* Matching label prefixes replace the longest suffix starting at a word boundary.
* Otherwise, mid-line and program read-prompts delete only the word being typed.
* POSIX word delete sends DEL, the tty erase character. Ctrl-H is literal
* input to canonical `read` when erase is ^?, while readline still deletes
* on DEL. Windows line editing keeps backspace.
@@ -313,18 +314,35 @@ export function computeSnippetAcceptClearSequence(options: {
os: string;
promptText: string;
snippetKind?: "snippet" | "script";
snippetLabel?: string;
}): string {
const line = options.line ?? "";
if (line.length === 0) return "";
let matchedLabelSuffix: string | undefined;
if (options.snippetKind !== "script" && options.snippetLabel) {
const label = options.snippetLabel.toLowerCase();
// Scan from the start so the first boundary match is the longest suffix.
for (let start = 0; start < line.length; start += 1) {
if (start > 0 && !/\s/.test(line[start - 1])) continue;
const suffix = line.slice(start);
if (label.startsWith(suffix.toLowerCase())) {
matchedLabelSuffix = suffix;
break;
}
}
}
const { currentWord, wordIndex } = parseCommandLine(line);
const replaceWord = options.snippetKind !== "script"
&& currentWord.length > 0
&& line.endsWith(currentWord)
&& (wordIndex > 0 || isProgramInputPromptText(options.promptText));
const replaceWord = matchedLabelSuffix !== undefined
? matchedLabelSuffix !== line
: options.snippetKind !== "script"
&& currentWord.length > 0
&& line.endsWith(currentWord)
&& (wordIndex > 0 || isProgramInputPromptText(options.promptText));
if (replaceWord) {
const eraseChar = isWindowsShellLineInput(options.os, options.promptText) ? "\b" : "\x7f";
return eraseChar.repeat(Array.from(currentWord).length);
return eraseChar.repeat(Array.from(matchedLabelSuffix ?? currentWord).length);
}
return isWindowsShellLineInput(options.os, options.promptText)
@@ -1340,7 +1340,7 @@ export function useTerminalAutocomplete(
[handleCommandHistoryCleared],
);
/** Accept a snippet: clear the matched word (or the whole line for a script
/** Accept a snippet: clear the matched label or word (or the whole line for a script
* or a shell prompt), then run it via onAcceptSnippet. */
const acceptSnippet = useCallback((snippet: Snippet): boolean => {
const term = termRef.current;
@@ -1358,6 +1358,7 @@ export function useTerminalAutocomplete(
os: hostOsRef.current,
promptText: prompt.promptText,
snippetKind: snippet.kind,
snippetLabel: snippet.label,
});
if (clearSequence) writeToTerminal(clearSequence);
}
@@ -387,6 +387,102 @@ test("snippet accept deletes only the mid-line word (#3622)", () => {
);
});
test("snippet accept clears a whole-line label prefix (#4549)", () => {
for (const snippetKind of [undefined, "snippet"] as const) {
for (const line of ["Check size", "Check si", "check size"]) {
for (const os of ["linux", "windows"]) {
assert.equal(
computeSnippetAcceptClearSequence({
line,
os,
promptText: os === "windows" ? "C:\\Users\\me>" : "user@host:~$ ",
snippetKind,
snippetLabel: "Check size",
}),
os === "windows" ? "\b".repeat(line.length) : "\x15",
);
}
}
}
});
test("snippet accept deletes the longest matching label suffix at a word boundary (#4549)", () => {
for (const os of ["linux", "windows"]) {
for (const suffix of ["Check size", "Check si", "check size", "Check \u{1F680}"]) {
assert.equal(
computeSnippetAcceptClearSequence({
line: `git pull ${suffix}`,
os,
promptText: os === "windows" ? "C:\\Users\\me>" : "user@host:~$ ",
snippetKind: "snippet",
snippetLabel: suffix === "Check \u{1F680}" ? suffix : "Check size",
}),
(os === "windows" ? "\b" : "\x7f").repeat(Array.from(suffix).length),
);
}
}
assert.equal(
computeSnippetAcceptClearSequence({
line: "git pull\tCheck\tsize",
os: "linux",
promptText: "user@host:~$ ",
snippetLabel: "Check\tsize",
}),
"\x7f".repeat("Check\tsize".length),
);
assert.equal(
computeSnippetAcceptClearSequence({
line: "git pull use use",
os: "linux",
promptText: "user@host:~$ ",
snippetLabel: "use use more",
}),
"\x7f".repeat("use use".length),
);
});
test("snippet accept preserves word deletion with a single-word or unmatched label (#3622, #4549)", () => {
for (const snippetLabel of [undefined, "use", "user name", "Check size"]) {
assert.equal(
computeSnippetAcceptClearSequence({
line: "git pull use",
os: "linux",
promptText: "user@host:~$ ",
snippetLabel,
}),
"\x7f".repeat(3),
);
}
for (const line of ["size", "git pull size", "git pull xCheck size"]) {
assert.equal(
computeSnippetAcceptClearSequence({
line,
os: "linux",
promptText: "user@host:~$ ",
snippetLabel: "Check size",
}),
line === "size" ? "\x15" : "\x7f".repeat(4),
);
}
});
test("script snippet accept ignores matching labels and clears the whole line (#4549)", () => {
for (const os of ["linux", "windows"]) {
for (const promptText of ["user@host:~$ ", "Email: "]) {
assert.equal(
computeSnippetAcceptClearSequence({
line: "git pull Check size",
os,
promptText,
snippetKind: "script",
snippetLabel: "Check size",
}),
os === "windows" ? "\b".repeat("git pull Check size".length) : "\x15",
);
}
}
});
test("script snippet accept still clears the whole line (#3622)", () => {
assert.equal(
computeSnippetAcceptClearSequence({
@@ -453,4 +549,4 @@ test("computeAutocompleteAcceptWrite clears with backspaces on a mislabeled Wind
}),
"\b\b\buv run tkauto video sync-fs",
);
});
});
@@ -38,19 +38,21 @@ test('per-pane close button keeps shrink-0 so a narrow pane cannot squeeze it aw
);
});
test('magnified side panels use an inner rounded 1px border in the side panel accent', () => {
test('magnified side panels use an inner rounded 1px theme-accent border and skip zoom animation on tab switch', () => {
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
const chromeStart = source.indexOf('className="absolute inset-3');
const chromeStart = source.indexOf('"absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl [clip-path:inset(0_round_0.375rem)]"');
assert.ok(chromeStart > 0, 'magnified side panel chrome must exist');
const chromeSource = source.slice(chromeStart, source.indexOf('\n >', chromeStart));
const strokeStart = source.indexOf('data-section="pane-magnification-stroke"', chromeStart);
const strokeSource = source.slice(strokeStart, source.indexOf('/>', strokeStart));
assert.match(chromeSource, /overflow-hidden rounded-md bg-background shadow-2xl/);
assert.match(chromeSource, /\[clip-path:inset\(0_round_0\.375rem\)\]/);
assert.match(chromeSource, /animateMagnifiedSidePane && "animate-in fade-in zoom-in-95 duration-150"/);
assert.doesNotMatch(chromeSource, /\b(?:outline|outlineOffset|border|borderColor|borderWidth|borderStyle)\b/);
assert.match(strokeSource, /className="pointer-events-none absolute inset-0 z-50"/);
assert.match(strokeSource, /boxSizing: 'border-box'/);
assert.match(strokeSource, /border: `1px solid \$\{sidePanelTheme\.accent\}`/);
assert.match(strokeSource, /border: '1px solid hsl\(var\(--primary\)\)'/);
assert.match(strokeSource, /borderRadius: 'inherit'/);
});
@@ -1148,10 +1148,32 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
const magnifiedSidePane = activeMagnifiedPane?.target.kind === 'side-panel'
? activeSidePanelPanes.find((pane) => pane.id === activeMagnifiedPane.target.paneId) ?? null
: null;
const sidePaneMagAnimRef = useRef<{
tabId: string | null;
paneId: string | null;
animate: boolean;
}>({
tabId: activeTabId ?? null,
paneId: magnifiedSidePane?.id ?? null,
animate: false,
});
if (
sidePaneMagAnimRef.current.tabId !== (activeTabId ?? null)
|| sidePaneMagAnimRef.current.paneId !== (magnifiedSidePane?.id ?? null)
) {
const sameTab = sidePaneMagAnimRef.current.tabId === (activeTabId ?? null);
const entering = !!magnifiedSidePane && sidePaneMagAnimRef.current.paneId !== magnifiedSidePane.id;
sidePaneMagAnimRef.current = {
tabId: activeTabId ?? null,
paneId: magnifiedSidePane?.id ?? null,
animate: sameTab && entering,
};
}
const animateMagnifiedSidePane = sidePaneMagAnimRef.current.animate;
const paneMagnificationShortcutLabel = getPaneMagnificationShortcutLabel(keyBindings, hotkeyScheme);
const [showMagnificationHint, setShowMagnificationHint] = useState(false);
useEffect(() => {
if (!magnifiedSidePane) {
if (!magnifiedSidePane || !sidePaneMagAnimRef.current.animate) {
setShowMagnificationHint(false);
return undefined;
}
@@ -1583,7 +1605,10 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
data-section="pane-magnification-backdrop"
/>
<div
className="absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl [clip-path:inset(0_round_0.375rem)] animate-in fade-in zoom-in-95 duration-150"
className={cn(
"absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl [clip-path:inset(0_round_0.375rem)]",
animateMagnifiedSidePane && "animate-in fade-in zoom-in-95 duration-150",
)}
style={{
backgroundColor: sidePanelTheme.termBg,
color: sidePanelTheme.termFg,
@@ -1616,7 +1641,7 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
className="pointer-events-none absolute inset-0 z-50"
style={{
boxSizing: 'border-box',
border: `1px solid ${sidePanelTheme.accent}`,
border: '1px solid hsl(var(--primary))',
borderRadius: 'inherit',
}}
/>
@@ -65,9 +65,13 @@ import type { ResolvedAppearance, TerminalAppearanceHostScope } from '../../doma
import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePanelAutoOpen';
import type { SidePanelTool } from '../../domain/sidePanelLayout';
import {
getWorkspacePaneOuterEdges,
PANE_MAGNIFICATION_DURATION_MS,
resolveNextMagnifiedSurfaceBounds,
resolvePaneMagnificationLayoutGeometry,
resolvePaneMagnificationStyle,
shouldAnimatePaneMagnificationTransition,
type MagnifiedSurfaceBounds,
type PaneMagnificationController,
type PaneMagnificationTarget,
} from '../../domain/paneMagnification';
@@ -1560,6 +1564,14 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
}, [deferPaneLayoutUpdate, isFocusedPane, isFocusMode, isSplitViewVisible, isVisible, livePaneLayoutKey]);
const paneLayoutKey = paneLayoutKeyRef.current;
const workspacePaneCount = layoutWorkspace ? collectSessionIds(layoutWorkspace.root).length : 0;
const hasMultipleWorkspacePanes = inActiveWorkspace && !isFocusMode && workspacePaneCount > 1;
const paneOuterEdges = useMemo(
() => (hasMultipleWorkspacePanes
? getWorkspacePaneOuterEdges(layoutWorkspace?.root, session.id)
: { left: false, right: false, top: false, bottom: false }),
[hasMultipleWorkspacePanes, layoutWorkspace?.root, session.id],
);
const isMagnified = isVisible
&& magnifiedPane?.target.kind === 'terminal'
&& magnifiedPane.target.sessionId === session.id
@@ -1567,16 +1579,22 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
const isCoveredByMagnification = isVisible
&& magnifiedPane?.tabId === (activeWorkspaceId ?? session.id)
&& !isMagnified;
const [magnifiedSurfaceBounds, setMagnifiedSurfaceBounds] = useState<{
left: number;
top: number;
width: number;
height: number;
layoutOrigin: { left: number; top: number; width: number; height: number };
} | null>(null);
const [magnifiedSurfaceBounds, setMagnifiedSurfaceBounds] = useState<MagnifiedSurfaceBounds | null>(null);
const prevMagnificationTransitionRef = useRef({
isVisible,
isMagnified,
});
useLayoutEffect(() => {
const prev = prevMagnificationTransitionRef.current;
prevMagnificationTransitionRef.current = { isVisible, isMagnified };
const shouldAnimate = shouldAnimatePaneMagnificationTransition({
wasVisible: prev.isVisible,
isVisible,
wasMagnified: prev.isMagnified,
isMagnified,
});
if (!isMagnified) {
if (!isVisible) {
if (!isVisible || !shouldAnimate) {
setMagnifiedSurfaceBounds(null);
return undefined;
}
@@ -1593,10 +1611,10 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
// the pane is fixed (offsetParent would be null during a quick re-zoom).
const layoutParent = pane?.parentElement;
if (!surface || !layoutParent) return undefined;
const update = () => {
const update = (animate: boolean) => {
const bounds = surface.getBoundingClientRect();
const origin = layoutParent.getBoundingClientRect();
if (pane && pane.style.position !== 'fixed') {
if (animate && pane && pane.style.position !== 'fixed') {
const geometry = {
left: pane.style.left,
top: pane.style.top,
@@ -1611,27 +1629,30 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
pane.getBoundingClientRect();
}
}
setMagnifiedSurfaceBounds({
setMagnifiedSurfaceBounds((current) => resolveNextMagnifiedSurfaceBounds(current, {
left: bounds.left,
top: bounds.top,
width: bounds.width,
height: bounds.height,
layoutOrigin: { left: origin.left, top: origin.top, width: origin.width, height: origin.height },
});
animate,
}));
};
update();
update(shouldAnimate);
if (typeof ResizeObserver === 'undefined') return undefined;
const observer = new ResizeObserver(update);
const observer = new ResizeObserver(() => update(false));
observer.observe(surface);
return () => observer.disconnect();
}, [isMagnified, isVisible]);
const magnifiedDevicePixelRatio = typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1);
const animateMagnification = !isMagnified || (magnifiedSurfaceBounds?.animate ?? true);
const style: React.CSSProperties = resolvePaneMagnificationStyle(
layoutStyle,
isMagnified && !!magnifiedSurfaceBounds,
magnifiedSurfaceBounds,
magnifiedDevicePixelRatio,
magnifiedSurfaceBounds?.layoutOrigin,
animateMagnification,
);
useLayoutEffect(() => {
@@ -1821,6 +1842,10 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
data-session-id={session.id}
data-section="terminal-split-pane"
data-focused={isFocusedPane ? 'true' : undefined}
data-multi-pane={hasMultipleWorkspacePanes ? 'true' : undefined}
data-magnified={magnifiedSurfaceBounds ? 'true' : undefined}
data-workspace-corner-bl={paneOuterEdges.left && paneOuterEdges.bottom ? 'true' : undefined}
data-workspace-corner-br={paneOuterEdges.right && paneOuterEdges.bottom ? 'true' : undefined}
inert={isVisible && !isCoveredByMagnification ? undefined : true}
className={cn(
"absolute bg-background",
@@ -1999,7 +2024,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
className="pointer-events-none absolute inset-0 z-50"
style={{
boxSizing: 'border-box',
border: `1px solid ${sessionAppearanceTheme.colors.cursor}`,
border: '1px solid hsl(var(--primary))',
borderRadius: 'inherit',
}}
/>
@@ -28,6 +28,7 @@ import {
collectSidePanelPanes,
type SidePanelLayout,
} from '../../domain/sidePanelLayout';
import type { PaneMagnificationTarget } from '../../domain/paneMagnification';
type StableRef = React.MutableRefObject<Record<string, any>>;
@@ -54,8 +55,15 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef })
const sftpAuthHostBySessionId = s.sftpAuthHostBySessionId as Map<string, Host>;
const sidePanelOpenTabs = s.sidePanelOpenTabs as Map<string, SidePanelTab>;
const sidePanelLayouts = s.sidePanelLayouts as Map<string, SidePanelLayout>;
const magnifiedPanesByTab = s.magnifiedPanesByTab as ReadonlyMap<string, PaneMagnificationTarget>;
const showHostTreeSidebar = s.showHostTreeSidebar as boolean | undefined;
const activeMagnifiedPane = useMemo(() => {
if (!activeTabId) return null;
const target = magnifiedPanesByTab.get(activeTabId);
return target ? { tabId: activeTabId, target } : null;
}, [activeTabId, magnifiedPanesByTab]);
const activeWorkspace = useMemo(
() => (activeTabId ? workspaceById.get(activeTabId) : undefined),
[activeTabId, workspaceById],
@@ -116,7 +124,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef })
activeSession,
activeWorkspace,
isFocusMode,
hasMagnifiedPane: !!activeWorkspace && activeWorkspace.id === s.magnifiedPane?.tabId,
hasMagnifiedPane: !!activeWorkspace && activeWorkspace.id === activeMagnifiedPane?.tabId,
shouldKeepHiddenWorkspaceLaidOut,
onAddSessionToWorkspace: s.onAddSessionToWorkspace,
onCreateWorkspaceFromSessions: s.onCreateWorkspaceFromSessions,
@@ -574,7 +582,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef })
keys: s.keys,
knownHosts: s.knownHosts,
MessageSquare: s.MessageSquare,
magnifiedPane: s.magnifiedPane,
magnifiedPane: activeMagnifiedPane,
mountedAiTabIds: s.mountedAiTabIds,
mountedSftpTabIds: s.mountedSftpTabIds,
notesMountedTabIds: s.notesMountedTabIds,
@@ -724,7 +732,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef })
isFocusMode,
isSidePanelOpenForCurrentTab,
isTerminalLayerVisible,
s.magnifiedPane,
activeMagnifiedPane,
resizing,
resolveAIExecutorContext,
sessionHostsMap,
+19 -6
View File
@@ -44,6 +44,11 @@ function TerminalLayerViewInner({ ctx }: { ctx: TerminalLayerViewContext }) {
const hostTreeLayoutAnimated = useTerminalHostTreeLayoutTransitionAnimated();
const isBottomDock = ctx.sidePanelPosition === 'bottom';
const workspaceTouchesBottom = !ctx.isComposeBarOpen && !(ctx.isSidePanelOpenForCurrentTab && isBottomDock);
const workspaceTouchesLeft = hostTreeLayoutWidth <= 0
&& !ctx.isFocusMode
&& !(ctx.isSidePanelOpenForCurrentTab && ctx.sidePanelPosition === 'left');
const workspaceTouchesRight = !(ctx.isSidePanelOpenForCurrentTab && ctx.sidePanelPosition === 'right');
return (
<div
@@ -51,12 +56,20 @@ function TerminalLayerViewInner({ ctx }: { ctx: TerminalLayerViewContext }) {
className={`absolute inset-0 bg-background flex min-h-0${isBottomDock ? ' flex-col' : ''}`}
data-section="terminal-workspace"
inert={ctx.isTerminalLayerVisible ? undefined : true}
style={getTerminalLayerViewStyle({
isTerminalLayerVisible: ctx.isTerminalLayerVisible,
hibernateHiddenTabs: ctx.hibernateHiddenTabs,
hostTreeLayoutWidth,
hostTreeLayoutAnimated,
})}
style={{
...getTerminalLayerViewStyle({
isTerminalLayerVisible: ctx.isTerminalLayerVisible,
hibernateHiddenTabs: ctx.hibernateHiddenTabs,
hostTreeLayoutWidth,
hostTreeLayoutAnimated,
}),
'--workspace-corner-bl-radius': workspaceTouchesBottom && workspaceTouchesLeft
? 'var(--window-corner-radius)'
: '0px',
'--workspace-corner-br-radius': workspaceTouchesBottom && workspaceTouchesRight
? 'var(--window-corner-radius)'
: '0px',
} as React.CSSProperties}
>
{/* Keep TerminalLayerSidePanelSection at a stable tree position (first
child) so cycling between side and bottom docks reorders it via flex
@@ -9,20 +9,24 @@ import { renderToStaticMarkup } from "react-dom/server";
import { TerminalLayerWorkspaceSection } from "./TerminalLayerWorkspaceSection.tsx";
test("terminal pane chrome uses an inner rounded 1px border while retaining overflow clipping", () => {
test("terminal pane chrome uses an inner rounded 1px theme-accent border while retaining overflow clipping", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf('TerminalPane.displayName'));
const hostSource = paneSource.slice(0, paneSource.indexOf("<LazyLoadBoundary"));
const strokeSource = paneSource.slice(paneSource.indexOf("{magnifiedSurfaceBounds && ("));
assert.match(hostSource, /^\s*magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl \[clip-path:inset\(0_round_0\.375rem\)\]",$/m);
assert.match(hostSource, /data-multi-pane=\{hasMultipleWorkspacePanes \? 'true' : undefined\}/);
assert.match(hostSource, /data-magnified=\{magnifiedSurfaceBounds \? 'true' : undefined\}/);
assert.match(hostSource, /data-workspace-corner-bl=\{paneOuterEdges\.left && paneOuterEdges\.bottom \? 'true' : undefined\}/);
assert.match(hostSource, /data-workspace-corner-br=\{paneOuterEdges\.right && paneOuterEdges\.bottom \? 'true' : undefined\}/);
assert.match(hostSource, /style=\{style\}/);
assert.doesNotMatch(hostSource, /\b(?:outline|outlineOffset|border|borderColor|borderWidth|borderStyle)\b/);
assert.match(strokeSource, /aria-hidden="true"/);
assert.match(strokeSource, /data-section="pane-magnification-stroke"/);
assert.match(strokeSource, /className="pointer-events-none absolute inset-0 z-50"/);
assert.match(strokeSource, /boxSizing: 'border-box'/);
assert.match(strokeSource, /border: `1px solid \$\{sessionAppearanceTheme\.colors\.cursor\}`/);
assert.match(strokeSource, /border: '1px solid hsl\(var\(--primary\)\)'/);
assert.match(strokeSource, /borderRadius: 'inherit'/);
});
@@ -34,30 +38,31 @@ test("restoring terminal chrome retains its inner 1px border until surface bound
assert.ok(condition);
assert.ok(styleSource);
const resolveStroke = new Function(
"isMagnified", "magnifiedSurfaceBounds", "sessionAppearanceTheme", "magnifiedDevicePixelRatio",
"isMagnified", "magnifiedSurfaceBounds", "magnifiedDevicePixelRatio",
`return ${condition[1]} ? ({${styleSource[1]}}) : null;`,
);
const bounds = { left: 0, top: 80, width: 1200, height: 800 };
const theme = { colors: { cursor: "#0088ff" } };
const bounds = { left: 0, top: 80, width: 1200, height: 800, animate: true };
for (const dpr of [1, 1.25, 1.5, 2, 3]) {
const magnified = resolveStroke(true, bounds, theme, dpr);
const restoring = resolveStroke(false, bounds, theme, dpr);
const magnified = resolveStroke(true, bounds, dpr);
const restoring = resolveStroke(false, bounds, dpr);
assert.deepEqual(restoring, magnified);
assert.equal(restoring.border, `1px solid ${theme.colors.cursor}`);
assert.equal(restoring.border, '1px solid hsl(var(--primary))');
assert.equal(restoring.boxSizing, 'border-box');
assert.equal(restoring.borderRadius, 'inherit');
for (const isMagnified of [false, true]) {
assert.equal(resolveStroke(isMagnified, null, theme, dpr), null);
assert.equal(resolveStroke(isMagnified, null, dpr), null);
}
}
});
test("magnified terminal panes snap overlay bounds to the device-pixel grid", () => {
test("magnified terminal panes snap overlay bounds to the device-pixel grid and skip animation on tab restore", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
assert.match(source, /resolvePaneMagnificationStyle\(\s*layoutStyle,\s*isMagnified && !!magnifiedSurfaceBounds,\s*magnifiedSurfaceBounds,\s*magnifiedDevicePixelRatio,\s*magnifiedSurfaceBounds\?\.layoutOrigin,\s*\)/);
assert.match(source, /resolvePaneMagnificationStyle\(\s*layoutStyle,\s*isMagnified && !!magnifiedSurfaceBounds,\s*magnifiedSurfaceBounds,\s*magnifiedDevicePixelRatio,\s*magnifiedSurfaceBounds\?\.layoutOrigin,\s*animateMagnification,\s*\)/);
assert.match(source, /layoutOrigin: \{ left: origin\.left, top: origin\.top, width: origin\.width, height: origin\.height \}/);
assert.match(source, /const magnifiedDevicePixelRatio = typeof window === 'undefined' \? 1 : \(window\.devicePixelRatio \|\| 1\)/);
assert.match(source, /shouldAnimatePaneMagnificationTransition\(/);
assert.match(source, /resolveNextMagnifiedSurfaceBounds\(current,/);
});
test("percentage zoom entry flushes pixel geometry before applying fixed bounds", () => {
@@ -80,8 +85,8 @@ test("terminal keyboard focus updates the pane selected for magnification", () =
test("closing a magnified terminal clears the overlay selection", () => {
const source = readFileSync(new URL("../TerminalLayer.tsx", import.meta.url), "utf8");
assert.match(source, /isPaneMagnificationSelectionValid\(current, terminalPanes, sidePanelPanes\)/);
assert.match(source, /current\?\.target\.kind === 'terminal' && current\.target\.sessionId === sessionId/);
assert.match(source, /pruneMagnifiedPanesByTab\(current, terminalPanes, sidePanelPanes\)/);
assert.match(source, /target\.kind === 'terminal' && target\.sessionId === sessionId/);
});
test("terminal panes expose focus mode and temporary magnification as separate actions", () => {
@@ -96,8 +101,28 @@ test("terminal panes expose focus mode and temporary magnification as separate a
test("focus mode cannot start temporary magnification but can restore stale magnification", () => {
const source = readFileSync(new URL("../TerminalLayer.tsx", import.meta.url), "utf8");
assert.match(source, /const hasCurrentMagnification = magnifiedPaneRef\.current\?\.tabId === tabId;/);
assert.match(source, /const currentTarget = magnifiedPanesByTabRef\.current\.get\(tabId\);/);
assert.match(source, /const hasCurrentMagnification = !!currentTarget;/);
assert.match(source, /if \(workspace\?\.viewMode === 'focus' && !hasCurrentMagnification\) return null;/);
assert.match(source, /if \(!canMagnifyPaneSurface\(terminalCount, sidePanelCount\)\) \{/);
});
test("workspace focus border CSS uses 1px deterministic state, suppresses on magnified/single panes, and handles macOS corners", () => {
const css = readFileSync(new URL("../../index.css", import.meta.url), "utf8");
// Default dim mode preserved
assert.match(css, /\.workspace-pane:not\(:focus-within\) \.xterm-screen \{\s*opacity: 0\.82;\s*\}/);
// 1px customizable border on multi-pane workspaces only
assert.match(css, /\[data-workspace-focus="border"\] \.workspace-pane\[data-multi-pane="true"\]::after/);
assert.match(css, /border: var\(--workspace-focus-border-width, 1px\) solid transparent;/);
// Deterministic data-focused state (not :focus-within), suppressed while magnified
assert.match(css, /\[data-workspace-focus="border"\] \.workspace-pane\[data-multi-pane="true"\]\[data-focused="true"\]:not\(\[data-magnified="true"\]\)::after/);
assert.match(css, /border-color: var\(--workspace-focus-border-color, hsl\(var\(--primary\)\)\);/);
assert.doesNotMatch(css, /\[data-workspace-focus="border"\] \.workspace-pane:focus-within::after/);
// macOS non-fullscreen rounded window corners
assert.match(css, /:root\[data-platform="darwin"\]:not\(\[data-window-fullscreen="true"\]\) \{\s*--window-corner-radius: 10px;\s*\}/);
assert.match(css, /border-bottom-left-radius: var\(--workspace-corner-bl-radius, 0px\);/);
assert.match(css, /border-bottom-right-radius: var\(--workspace-corner-br-radius, 0px\);/);
});
test("closing a magnified terminal restores its pane instead of ending the session", () => {
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { memo, useEffect, useState, useSyncExternalStore } from 'react';
import React, { memo, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import { createPortal } from 'react-dom';
import { LayoutGrid, Plus } from 'lucide-react';
import { Button } from '../ui/button';
@@ -147,10 +147,34 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext })
&& magnifiedPane.target.kind === 'terminal'
? magnifiedPane
: null;
const activeMagnifiedSessionId = activeMagnifiedTerminal?.target.kind === 'terminal'
? activeMagnifiedTerminal.target.sessionId
: null;
const terminalMagHintRef = useRef<{
tabId: string | null;
sessionId: string | null;
shouldShowHint: boolean;
}>({
tabId: activeTabId ?? null,
sessionId: activeMagnifiedSessionId,
shouldShowHint: false,
});
if (
terminalMagHintRef.current.tabId !== (activeTabId ?? null)
|| terminalMagHintRef.current.sessionId !== activeMagnifiedSessionId
) {
const sameTab = terminalMagHintRef.current.tabId === (activeTabId ?? null);
const entering = !!activeMagnifiedSessionId && terminalMagHintRef.current.sessionId !== activeMagnifiedSessionId;
terminalMagHintRef.current = {
tabId: activeTabId ?? null,
sessionId: activeMagnifiedSessionId,
shouldShowHint: sameTab && entering,
};
}
const paneMagnificationShortcutLabel = getPaneMagnificationShortcutLabel(keyBindings, hotkeyScheme);
const [showMagnificationHint, setShowMagnificationHint] = useState(false);
useEffect(() => {
if (!activeMagnifiedTerminal) {
if (!activeMagnifiedTerminal || !terminalMagHintRef.current.shouldShowHint) {
setShowMagnificationHint(false);
return undefined;
}
@@ -32,7 +32,8 @@ function closePane(tool: 'browser' | 'notes') {
useCallback: (callback: unknown) => callback,
activeTabIdRef: { current: 'terminal' }, sidePanelLayoutsRef: { current: layouts },
collectSidePanelPanes,
setMagnifiedPane: () => {},
setMagnifiedPanesByTab: () => {},
setTabMagnifiedPane: (current: unknown) => current,
closeSidePanelPaneForTab: (tabId: string, paneId: string) => {
const next = closeSidePanelPane(layouts.get(tabId)!, paneId);
assert.ok(next);
+103
View File
@@ -1239,3 +1239,106 @@ test("applyGroupDefaults lets standalone RDP host with inline password inherit a
assert.equal(result.rdpConfig?.username, "Administrator");
});
test("resolveGroupDefaults and applyGroupDefaults let a child group Direct override parent group and global proxies", () => {
const configs: GroupConfig[] = [
{ path: "corp", proxyProfileId: "corp-proxy" },
{ path: "corp/local", directProxy: true },
];
const childDefaults = resolveGroupDefaults("corp/local", configs);
assert.equal(childDefaults.directProxy, true);
assert.equal(childDefaults.proxyProfileId, undefined);
assert.equal(childDefaults.proxyConfig, undefined);
const grandchildDefaults = resolveGroupDefaults("corp/local/lab", configs);
assert.equal(grandchildDefaults.directProxy, true);
assert.equal(grandchildDefaults.proxyProfileId, undefined);
const effective = applyGroupDefaults(
host({ group: "corp/local/lab" }),
grandchildDefaults,
globalProxyOptions,
);
assert.equal(effective.directProxy, true);
assert.equal(effective.proxyProfileId, undefined);
assert.equal(effective.proxyConfig, undefined);
});
test("resolveGroupDefaults lets a child group proxy override a parent group Direct setting", () => {
const configs: GroupConfig[] = [
{ path: "corp", directProxy: true },
{ path: "corp/bastion", proxyProfileId: "bastion-proxy" },
{ path: "corp/custom", proxyConfig: { type: "http", host: "custom.example.com", port: 8080 } },
];
const withProfile = resolveGroupDefaults("corp/bastion", configs);
assert.equal(withProfile.directProxy, undefined);
assert.equal(withProfile.proxyProfileId, "bastion-proxy");
const withCustom = resolveGroupDefaults("corp/custom", configs);
assert.equal(withCustom.directProxy, undefined);
assert.equal(withCustom.proxyConfig?.host, "custom.example.com");
const effective = applyGroupDefaults(host({ group: "corp/bastion" }), withProfile, globalProxyOptions);
assert.equal(effective.directProxy, undefined);
assert.equal(effective.proxyProfileId, "bastion-proxy");
});
test("resolveGroupDefaults prioritizes directProxy when co-present with proxy fields on the same group", () => {
const resolved = resolveGroupDefaults("corp", [
{
path: "corp",
directProxy: true,
proxyProfileId: "stale-profile",
proxyConfig: { type: "http", host: "stale.example.com", port: 8080 },
},
]);
assert.equal(resolved.directProxy, true);
assert.equal(resolved.proxyProfileId, undefined);
assert.equal(resolved.proxyConfig, undefined);
});
test("applyGroupDefaults lets a host choose its own proxy inside a Direct group", () => {
const groupDefaults = resolveGroupDefaults("corp/local", [
{ path: "corp", proxyProfileId: "corp-proxy" },
{ path: "corp/local", directProxy: true },
]);
const hostWithProfile = applyGroupDefaults(
host({ group: "corp/local", proxyProfileId: "host-proxy" }),
groupDefaults,
globalProxyOptions,
);
assert.equal(hostWithProfile.proxyProfileId, "host-proxy");
assert.equal(hostWithProfile.directProxy, undefined);
const customProxy = { type: "socks5" as const, host: "host-proxy.example.com", port: 1080 };
const hostWithCustom = applyGroupDefaults(
host({ group: "corp/local", proxyConfig: customProxy }),
groupDefaults,
globalProxyOptions,
);
assert.deepEqual(hostWithCustom.proxyConfig, customProxy);
assert.equal(hostWithCustom.directProxy, undefined);
assert.equal(hostWithCustom.proxyProfileId, undefined);
});
test("applyGroupDefaults inherits group directProxy for vnc/rdp hosts and skips global default", () => {
const groupDefaults = resolveGroupDefaults("corp/local", [
{ path: "corp", proxyProfileId: "corp-proxy" },
{ path: "corp/local", directProxy: true },
]);
for (const protocol of ["rdp", "vnc"] as const) {
const result = applyGroupDefaults(
host({ group: "corp/local", protocol }),
groupDefaults,
globalProxyOptions,
);
assert.equal(result.directProxy, true);
assert.equal(result.proxyProfileId, undefined);
assert.equal(result.proxyConfig, undefined);
}
});
+30 -5
View File
@@ -183,7 +183,20 @@ export function resolveGroupDefaults(
}
}
const groupSetsDirectProxy = config.directProxy === true;
if (groupSetsDirectProxy) {
delete merged.proxyProfileId;
delete merged.proxyConfig;
merged.directProxy = true;
}
for (const [key, value] of Object.entries(config)) {
if (key === 'directProxy') {
continue;
}
if (groupSetsDirectProxy && (key === 'proxyProfileId' || key === 'proxyConfig')) {
continue;
}
if (
key === 'proxyProfileId' &&
typeof value === 'string' &&
@@ -217,9 +230,11 @@ export function resolveGroupDefaults(
}
if (key === 'proxyProfileId') {
delete merged.proxyConfig;
delete merged.directProxy;
}
if (key === 'proxyConfig') {
delete merged.proxyProfileId;
delete merged.directProxy;
}
merged[key] = value;
}
@@ -243,7 +258,7 @@ export function resolveGroupDefaults(
const INHERITABLE_KEYS: (keyof GroupConfig)[] = [
'username', 'password', 'savePassword', 'authMethod', 'identityId', 'identityFileId', 'identityFilePaths',
'port', 'protocol', 'deviceType', 'agentForwarding', 'x11Forwarding', 'proxyProfileId', 'proxyConfig', 'hostChain', 'startupCommand', 'startupCommandRunMode',
'port', 'protocol', 'deviceType', 'agentForwarding', 'x11Forwarding', 'proxyProfileId', 'proxyConfig', 'directProxy', 'hostChain', 'startupCommand', 'startupCommandRunMode',
'legacyAlgorithms', 'skipEcdsaHostKey', 'algorithms',
'environmentVariables', 'charset', 'moshEnabled', 'moshServerPath',
'etEnabled', 'etPort',
@@ -297,6 +312,7 @@ const REMOTE_DESKTOP_INHERITABLE_KEYS = new Set<keyof GroupConfig>([
'hostChain',
'proxyProfileId',
'proxyConfig',
'directProxy',
]);
const STANDALONE_REMOTE_DESKTOP_SKIP_KEYS = new Set<string>([
@@ -460,6 +476,13 @@ export function applyGroupDefaults(
if (host.proxyConfig !== undefined || !groupDefaults.proxyProfileId) continue;
}
if (key === 'proxyConfig' && (host.proxyProfileId !== undefined || hostHasUsableProxyProfile)) continue;
if (key === 'directProxy') {
if (
groupDefaults.directProxy !== true ||
Boolean(host.proxyProfileId) ||
host.proxyConfig !== undefined
) continue;
}
const hostValue = (effective as unknown as Record<string, unknown>)[key];
const groupValue = (groupDefaults as unknown as Record<string, unknown>)[key];
const emptyStringIsOverride = EMPTY_STRING_OVERRIDES_GROUP_DEFAULT.has(key);
@@ -471,9 +494,6 @@ export function applyGroupDefaults(
(effective as unknown as Record<string, unknown>)[key] = groupValue;
}
}
// Explicit direct beats a host proxy, the nearest group proxy, and the
// global default. Clearing the host setting leaves directProxy unset and
// still inherits.
const isPluginHost = typeof host.protocol === 'string' && host.protocol.startsWith('plugin:');
if (!isLocalShellHost && !isSerialHost && !isPluginHost) {
const isStandaloneRdp = host.protocol === 'rdp';
@@ -506,7 +526,12 @@ export function applyGroupDefaults(
}
}
}
if (host.directProxy === true) return withoutInheritedProxy(effective);
// Explicit direct (on the host or inherited from the nearest group) beats
// parent group proxies and the global default. Clearing the setting leaves
// directProxy unset and still inherits.
if (host.directProxy === true || effective.directProxy === true) {
return withoutInheritedProxy(effective);
}
if (!effective.proxyConfig && !effective.proxyProfileId) {
const globalProxyProfileId = resolveGlobalProxyProfileId(options);
if (globalProxyProfileId) effective.proxyProfileId = globalProxyProfileId;
+5
View File
@@ -529,6 +529,11 @@ export interface GroupConfig {
x11Forwarding?: boolean;
proxyProfileId?: string;
proxyConfig?: ProxyConfig;
/**
* Explicit direct connection default for hosts in this group. Overrides
* parent group proxies and the global default proxy. Absent means inherit.
*/
directProxy?: boolean;
hostChain?: HostChainConfig;
startupCommand?: string;
startupCommandRunMode?: MultiLineRunMode;
+163
View File
@@ -2,14 +2,20 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import {
canMagnifyPaneSurface,
getAvailablePaneMagnificationController,
getPaneMagnificationShortcutLabel,
getWorkspacePaneOuterEdges,
isPaneMagnificationSelectionValid,
PANE_MAGNIFICATION_DURATION_MS,
pruneMagnifiedPanesByTab,
resolveNextMagnifiedSurfaceBounds,
resolvePaneMagnificationCandidate,
resolvePaneMagnificationLayoutGeometry,
resolvePaneMagnificationStyle,
resolveTwoPaneMagnificationStyle,
setTabMagnifiedPane,
shouldAnimatePaneMagnificationTransition,
snapCssRectToDevicePixels,
type PaneMagnificationController,
} from './paneMagnification.ts';
@@ -299,3 +305,160 @@ test('keeps a valid magnified pane focused and rejects a single-pane surface', (
current: null,
}), null);
});
test('canMagnifyPaneSurface disables magnification for a lone terminal without a side panel', () => {
assert.equal(canMagnifyPaneSurface(0, 0), false);
assert.equal(canMagnifyPaneSurface(1, 0), false);
assert.equal(canMagnifyPaneSurface(0, 1), false);
assert.equal(canMagnifyPaneSurface(1, 1), true);
assert.equal(canMagnifyPaneSurface(2, 0), true);
});
test('getWorkspacePaneOuterEdges identifies bottom-left and bottom-right corner panes in nested splits', () => {
const root = {
id: 'root',
type: 'split' as const,
direction: 'vertical' as const,
children: [
{ id: 'left', type: 'pane' as const, sessionId: 's-left' },
{
id: 'right-col',
type: 'split' as const,
direction: 'horizontal' as const,
children: [
{ id: 'top-right', type: 'pane' as const, sessionId: 's-top-right' },
{ id: 'bottom-right', type: 'pane' as const, sessionId: 's-bottom-right' },
],
},
],
};
assert.deepEqual(getWorkspacePaneOuterEdges(root, 's-left'), {
left: true,
right: false,
top: true,
bottom: true,
});
assert.deepEqual(getWorkspacePaneOuterEdges(root, 's-top-right'), {
left: false,
right: true,
top: true,
bottom: false,
});
assert.deepEqual(getWorkspacePaneOuterEdges(root, 's-bottom-right'), {
left: false,
right: true,
top: false,
bottom: true,
});
assert.deepEqual(getWorkspacePaneOuterEdges(root, 'missing'), {
left: false,
right: false,
top: false,
bottom: false,
});
});
test('shouldAnimatePaneMagnificationTransition skips zoom animation on tab-switch restore', () => {
// User triggers magnify on active visible tab -> animate
assert.equal(shouldAnimatePaneMagnificationTransition({
wasVisible: true,
isVisible: true,
wasMagnified: false,
isMagnified: true,
}), true);
// User triggers restore on active visible tab -> animate
assert.equal(shouldAnimatePaneMagnificationTransition({
wasVisible: true,
isVisible: true,
wasMagnified: true,
isMagnified: false,
}), true);
// Switching back to an already-magnified tab -> no animation
assert.equal(shouldAnimatePaneMagnificationTransition({
wasVisible: false,
isVisible: true,
wasMagnified: false,
isMagnified: true,
}), false);
// Switching away from a magnified tab -> no animation
assert.equal(shouldAnimatePaneMagnificationTransition({
wasVisible: true,
isVisible: false,
wasMagnified: true,
isMagnified: false,
}), false);
});
test('resolvePaneMagnificationStyle omits transition properties when animate is false', () => {
const original = { left: '0px', top: '0px', width: '500px', height: '400px' };
const surface = { left: 0, top: 40, width: 1000, height: 800 };
const origin = { left: 0, top: 40, width: 1000, height: 800 };
const snapped = resolvePaneMagnificationStyle(original, true, surface, 1, origin, false);
assert.equal(snapped.position, 'fixed');
assert.equal(snapped.zIndex, 50);
assert.equal(snapped.transitionProperty, undefined);
assert.equal(snapped.transitionDuration, undefined);
assert.equal(snapped.transitionTimingFunction, undefined);
assert.equal(snapped.left, '12px');
assert.equal(snapped.top, '12px');
assert.equal(snapped.width, '976px');
assert.equal(snapped.height, '776px');
});
test('per-tab magnification map preserves independent tab states and prunes closed panes', () => {
let byTab = new Map();
byTab = new Map(setTabMagnifiedPane(byTab, 'tab-a', { kind: 'terminal', sessionId: 's1' }));
byTab = new Map(setTabMagnifiedPane(byTab, 'tab-b', { kind: 'side-panel', paneId: 'p1', tool: 'sftp' }));
assert.deepEqual(byTab.get('tab-a'), { kind: 'terminal', sessionId: 's1' });
assert.deepEqual(byTab.get('tab-b'), { kind: 'side-panel', paneId: 'p1', tool: 'sftp' });
const pruned = pruneMagnifiedPanesByTab(
byTab,
[{ tabId: 'tab-a', sessionId: 's1' }],
[],
);
assert.deepEqual(pruned.get('tab-a'), { kind: 'terminal', sessionId: 's1' });
assert.equal(pruned.has('tab-b'), false);
const cleared = setTabMagnifiedPane(pruned, 'tab-a', null);
assert.equal(cleared.size, 0);
});
test('resolveNextMagnifiedSurfaceBounds preserves entry animation on unchanged initial ResizeObserver callback', () => {
const initial = {
left: 0,
top: 40,
width: 1200,
height: 800,
layoutOrigin: { left: 0, top: 40, width: 1200, height: 800 },
animate: true,
};
// Unchanged resize notification with animate=false must preserve initial animate=true reference
const afterInitialObserver = resolveNextMagnifiedSurfaceBounds(initial, {
...initial,
layoutOrigin: { ...initial.layoutOrigin },
animate: false,
});
assert.equal(afterInitialObserver, initial);
assert.equal(afterInitialObserver.animate, true);
// Real surface resize updates bounds with animate=false
const resized = resolveNextMagnifiedSurfaceBounds(initial, {
...initial,
width: 1400,
layoutOrigin: { ...initial.layoutOrigin, width: 1400 },
animate: false,
});
assert.equal(resized.width, 1400);
assert.equal(resized.animate, false);
// Restoring from hidden tab (current=null) applies animate=false immediately
const restored = resolveNextMagnifiedSurfaceBounds(null, {
...initial,
animate: false,
});
assert.equal(restored.animate, false);
});
+172 -7
View File
@@ -1,4 +1,5 @@
import type React from 'react';
import type { WorkspaceNode } from './models';
export type PaneMagnificationState = 'unavailable' | 'focusable' | 'focused';
@@ -13,6 +14,161 @@ export type PaneMagnificationTarget =
| { kind: 'terminal'; sessionId: string }
| { kind: 'side-panel'; paneId: string; tool: string };
export type WorkspacePaneOuterEdges = {
left: boolean;
right: boolean;
top: boolean;
bottom: boolean;
};
/**
* Pure threshold check matching resolvePaneMagnificationCandidate:
* a surface with fewer than 2 total panes (e.g. a single terminal with no side
* panel) is already full-size and must not magnify.
*/
export function canMagnifyPaneSurface(
terminalPaneCount: number,
sidePanelPaneCount: number,
): boolean {
return terminalPaneCount + sidePanelPaneCount >= 2;
}
/**
* Determine which outer edges of the workspace split tree a terminal session
* touches, so focus borders can match the host window's rounded corners on
* macOS without clipping while keeping interior split edges crisp.
*/
export function getWorkspacePaneOuterEdges(
root: WorkspaceNode | null | undefined,
sessionId: string,
): WorkspacePaneOuterEdges {
const empty: WorkspacePaneOuterEdges = { left: false, right: false, top: false, bottom: false };
if (!root) return empty;
const walk = (node: WorkspaceNode, edges: WorkspacePaneOuterEdges): WorkspacePaneOuterEdges | null => {
if (node.type === 'pane') {
return node.sessionId === sessionId ? edges : null;
}
const count = node.children.length;
for (let index = 0; index < count; index += 1) {
const child = node.children[index];
const childEdges: WorkspacePaneOuterEdges = node.direction === 'vertical'
? {
left: edges.left && index === 0,
right: edges.right && index === count - 1,
top: edges.top,
bottom: edges.bottom,
}
: {
left: edges.left,
right: edges.right,
top: edges.top && index === 0,
bottom: edges.bottom && index === count - 1,
};
const found = walk(child, childEdges);
if (found) return found;
}
return null;
};
return walk(root, { left: true, right: true, top: true, bottom: true }) ?? empty;
}
/**
* Animate magnification/restore only when the pane stays visible across the
* state transition (user action on the active tab). Returning to an already
* magnified tab must snap directly without replaying a zoom animation.
*/
export function shouldAnimatePaneMagnificationTransition({
wasVisible,
isVisible,
wasMagnified,
isMagnified,
}: {
wasVisible: boolean;
isVisible: boolean;
wasMagnified: boolean;
isMagnified: boolean;
}): boolean {
return wasVisible && isVisible && wasMagnified !== isMagnified;
}
export type MagnifiedSurfaceBounds = {
left: number;
top: number;
width: number;
height: number;
layoutOrigin: { left: number; top: number; width: number; height: number };
animate: boolean;
};
/**
* Merge a magnified surface measurement into existing state while ignoring
* ResizeObserver notifications whose geometry has not actually changed (most
* notably the initial observation callback delivered right after observe(),
* which would otherwise overwrite `animate: true` and cancel user-triggered
* zoom animations).
*/
export function resolveNextMagnifiedSurfaceBounds(
current: MagnifiedSurfaceBounds | null,
next: MagnifiedSurfaceBounds,
): MagnifiedSurfaceBounds {
if (
!next.animate
&& current
&& current.left === next.left
&& current.top === next.top
&& current.width === next.width
&& current.height === next.height
&& current.layoutOrigin.left === next.layoutOrigin.left
&& current.layoutOrigin.top === next.layoutOrigin.top
&& current.layoutOrigin.width === next.layoutOrigin.width
&& current.layoutOrigin.height === next.layoutOrigin.height
) {
return current;
}
return next;
}
export function setTabMagnifiedPane(
current: ReadonlyMap<string, PaneMagnificationTarget>,
tabId: string,
target: PaneMagnificationTarget | null,
): ReadonlyMap<string, PaneMagnificationTarget> {
const existing = current.get(tabId);
if (!target) {
if (!existing) return current;
const next = new Map(current);
next.delete(tabId);
return next;
}
const sameTarget = existing && existing.kind === target.kind && (
existing.kind === 'terminal'
? target.kind === 'terminal' && existing.sessionId === target.sessionId
: target.kind === 'side-panel' && existing.paneId === target.paneId && existing.tool === target.tool
);
if (sameTarget) return current;
const next = new Map(current);
next.set(tabId, target);
return next;
}
export function pruneMagnifiedPanesByTab(
current: ReadonlyMap<string, PaneMagnificationTarget>,
terminalPanes: Array<{ tabId: string; sessionId: string }>,
sidePanelPanes: Array<{ tabId: string; paneId: string }>,
): ReadonlyMap<string, PaneMagnificationTarget> {
if (current.size === 0) return current;
let changed = false;
const next = new Map<string, PaneMagnificationTarget>();
for (const [tabId, target] of current) {
if (isPaneMagnificationSelectionValid({ tabId, target }, terminalPanes, sidePanelPanes)) {
next.set(tabId, target);
} else {
changed = true;
}
}
return changed ? next : current;
}
export function isPaneMagnificationSelectionValid(
selection: { tabId: string; target: PaneMagnificationTarget },
terminalPanes: Array<{ tabId: string; sessionId: string }>,
@@ -42,7 +198,7 @@ export function resolvePaneMagnificationCandidate({
lastTarget?: PaneMagnificationTarget;
current: { tabId: string; target: PaneMagnificationTarget } | null;
}): { target: PaneMagnificationTarget; focused: boolean } | null {
if (terminalSessionIds.length + sidePanelPanes.length < 2) return null;
if (!canMagnifyPaneSurface(terminalSessionIds.length, sidePanelPanes.length)) return null;
const targetIsValid = (target: PaneMagnificationTarget) => (
target.kind === 'terminal'
? terminalSessionIds.includes(target.sessionId)
@@ -140,15 +296,24 @@ export function resolvePaneMagnificationStyle(
surfaceBounds?: { left: number; top: number; width: number; height: number } | null,
devicePixelRatio = 1,
layoutOrigin?: { left: number; top: number; width?: number; height?: number },
animate = true,
): React.CSSProperties {
// Keep the fixed overlay and transition while restoring too, so the split
// container cannot clip the pane before it has finished shrinking.
const transition: React.CSSProperties = surfaceBounds ? {
transitionProperty: 'left, top, width, height',
transitionDuration: `${PANE_MAGNIFICATION_DURATION_MS}ms`,
transitionTimingFunction: 'ease-out',
zIndex: 50,
} : {};
// When restoring magnification after a tab switch (`animate = false`), skip
// transition properties so the pane snaps immediately before paint.
const transition: React.CSSProperties = surfaceBounds ? (
animate
? {
transitionProperty: 'left, top, width, height',
transitionDuration: `${PANE_MAGNIFICATION_DURATION_MS}ms`,
transitionTimingFunction: 'ease-out',
zIndex: 50,
}
: {
zIndex: 50,
}
) : {};
// Margins compensate for the containing-block switch without animating or
// transforming the terminal and its descendants. Local split offsets then
// keep the same viewport origin when fixed positioning starts or ends.
+52
View File
@@ -47,6 +47,58 @@ describe('vaultGroupAgentOps', () => {
assert.equal(effective.proxyConfig?.host, 'parent-gw.test');
});
it('supports setting and clearing directProxy on groups consistently with Group Details', () => {
const proxyOptions = { validProxyProfileIds: new Set(['proxy-1']), globalProxyProfileId: 'proxy-1' };
const initialState = {
groups: ['prod', 'prod/web'],
configs: [
{ path: 'prod', proxyConfig: { type: 'http' as const, host: 'parent-gw.test', port: 3128 } },
{ path: 'prod/web', proxyProfileId: 'proxy-1' },
],
hosts,
managedSources: [],
};
const setDirect = upsertGroup(initialState, 'prod/web', '{"directProxy":true}', [], proxyProfiles);
assert.equal(setDirect.ok, true);
if (!setDirect.ok) return;
assert.equal(setDirect.config?.directProxy, true);
assert.equal(setDirect.config?.proxyProfileId, undefined);
assert.equal(setDirect.config?.proxyConfig, undefined);
const directEffective = applyGroupDefaults(
hosts[0], resolveGroupDefaults('prod/web', setDirect.state.configs, proxyOptions), proxyOptions,
);
assert.equal(directEffective.directProxy, true);
assert.equal(directEffective.proxyProfileId, undefined);
assert.equal(directEffective.proxyConfig, undefined);
const replacedWithProfile = upsertGroup(setDirect.state, 'prod/web', '{"proxyProfileId":"proxy-1"}', [], proxyProfiles);
assert.equal(replacedWithProfile.ok, true);
if (!replacedWithProfile.ok) return;
assert.equal(replacedWithProfile.config?.directProxy, undefined);
assert.equal(replacedWithProfile.config?.proxyProfileId, 'proxy-1');
const clearedViaEmptyProfile = upsertGroup(setDirect.state, 'prod/web', '{"proxyProfileId":""}', [], proxyProfiles);
assert.equal(clearedViaEmptyProfile.ok, true);
if (!clearedViaEmptyProfile.ok) return;
assert.equal(clearedViaEmptyProfile.config?.directProxy, undefined);
assert.equal(clearedViaEmptyProfile.config?.proxyProfileId, undefined);
const inheritedAgain = applyGroupDefaults(
hosts[0], resolveGroupDefaults('prod/web', clearedViaEmptyProfile.state.configs, proxyOptions), proxyOptions,
);
assert.equal(inheritedAgain.proxyConfig?.host, 'parent-gw.test');
const clearedViaFalse = upsertGroup(setDirect.state, 'prod/web', '{"directProxy":false}', [], proxyProfiles);
assert.equal(clearedViaFalse.ok, true);
if (!clearedViaFalse.ok) return;
assert.equal(clearedViaFalse.config?.directProxy, undefined);
assert.equal(
upsertGroup(initialState, 'prod/web', '{"directProxy":true,"proxyProfileId":"proxy-1"}', [], proxyProfiles).ok,
false,
);
});
it('rejects missing identities, proxy profiles, and jump hosts', () => {
const state = { groups: ['prod'], configs: [], hosts, managedSources: [] };
assert.equal(upsertGroup(state, 'prod', '{"identityId":"missing"}', [], proxyProfiles).ok, false);
+21 -1
View File
@@ -144,8 +144,18 @@ export function patchGroupConfig(
next.authMethod = undefined;
}
}
if (Object.hasOwn(defaults, 'proxyProfileId')) {
const hasProxyProfileId = Object.hasOwn(defaults, 'proxyProfileId');
const hasDirectProxy = Object.hasOwn(defaults, 'directProxy');
let parsedDirectProxy: boolean | undefined;
if (hasDirectProxy) {
parsedDirectProxy = bool(defaults.directProxy);
if (parsedDirectProxy === undefined) return { ok: false, error: 'directProxy must be true or false.' };
}
if (hasProxyProfileId) {
const proxyProfileId = String(defaults.proxyProfileId ?? '');
if (proxyProfileId && parsedDirectProxy === true) {
return { ok: false, error: 'directProxy and proxyProfileId cannot both be set.' };
}
if (proxyProfileId && !proxyProfiles.some((profile) => profile.id === proxyProfileId)) {
return { ok: false, error: `Proxy profile "${proxyProfileId}" was not found.` };
}
@@ -153,6 +163,16 @@ export function patchGroupConfig(
// group proxy (or the global default) applies, instead of blocking it.
next.proxyProfileId = proxyProfileId || undefined;
next.proxyConfig = undefined;
next.directProxy = undefined;
}
if (hasDirectProxy) {
if (parsedDirectProxy) {
next.directProxy = true;
next.proxyProfileId = undefined;
next.proxyConfig = undefined;
} else {
next.directProxy = undefined;
}
}
if (Object.hasOwn(defaults, 'jumpHostIds')) {
let ids: unknown = defaults.jumpHostIds;
+28
View File
@@ -456,6 +456,34 @@ test("CSV round-trips explicit direct proxy mode and still treats an empty Proxy
assert.equal(literal.hosts[1]?.directProxy, undefined);
});
test("CSV export writes direct for hosts inheriting group directProxy and preserves host proxy overrides", () => {
const groupProxy = { type: "socks5" as const, host: "group.example.com", port: 1080 };
const hostProxy = { type: "http" as const, host: "host.example.com", port: 8080 };
const hosts: Host[] = [
{ ...hostDefaults, id: "child-direct", label: "Child Direct", hostname: "child.example.com", group: "Corp/Local" },
{
...hostDefaults,
id: "child-override",
label: "Child Override",
hostname: "override.example.com",
group: "Corp/Local",
proxyConfig: hostProxy,
},
];
const { csv } = exportHostsToCsvWithStats(hosts, {
groupConfigs: [
{ path: "Corp", proxyConfig: groupProxy },
{ path: "Corp/Local", directProxy: true },
],
});
const lines = csv.replace(/^\uFEFF/, "").trimEnd().split("\r\n");
const proxyIndex = lines[0].split(",").indexOf("Proxy");
const proxyCell = (line: string) => line.split(",")[proxyIndex];
assert.equal(proxyCell(lines[1]), "direct");
assert.equal(proxyCell(lines[2]), "http://host.example.com:8080");
assert.equal(csv.includes("group.example.com"), false);
});
test("CSV export keeps an empty Proxy cell when only the global default is set", () => {
publishActiveGlobalDefaultProxyProfileId("global-proxy");
try {
+1 -1
View File
@@ -262,7 +262,7 @@ const TOOL_INPUT_FIELDS = Object.freeze({
"vault.group.list": {},
"vault.group.create": {
path: { type: "string", description: "New group path, for example prod/web." },
defaults: { type: "string", optional: true, description: "JSON object of group defaults: username, identityId, proxyProfileId, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort." },
defaults: { type: "string", optional: true, description: "JSON object of group defaults: username, identityId, proxyProfileId, directProxy, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort." },
},
"vault.group.update": {
path: { type: "string", description: "Existing group path." },
@@ -4293,6 +4293,11 @@
"reset",
"dblclick",
"contextmenu",
"pointerdown",
"pointermove",
"pointerup",
"pointercancel",
"wheel",
"scroll",
"widget"
]
@@ -4343,6 +4348,39 @@
"y": {
"type": "number"
},
"pointerId": {
"type": "integer",
"minimum": -2147483648,
"maximum": 2147483647
},
"button": {
"type": "integer",
"minimum": -1,
"maximum": 32
},
"buttons": {
"type": "integer",
"minimum": 0,
"maximum": 65535
},
"pointerType": {
"enum": [
"mouse",
"pen",
"touch"
]
},
"deltaX": {
"type": "number"
},
"deltaY": {
"type": "number"
},
"deltaMode": {
"type": "integer",
"minimum": 0,
"maximum": 2
},
"scrollTop": {
"type": "number",
"minimum": 0
@@ -196,9 +196,26 @@ test("extended surface and widget events validate schema and bound detail payloa
const f = fixture(); await open(f);
await f.host.event("instance-1", { nodeId: "1", type: "contextmenu", x: 42, y: 84 }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "dblclick", x: 10, y: 20 }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "pointerdown", x: 120, y: 80, pointerId: 1, button: 0, buttons: 1, pointerType: "mouse" }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "pointermove", x: 165, y: 95, pointerId: 1, button: -1, buttons: 1, pointerType: "mouse", shiftKey: true }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "pointerup", x: 165, y: 95, pointerId: 1, button: 0, buttons: 0, pointerType: "mouse" }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "pointercancel", x: -10, y: 40, pointerId: 1, button: -1, buttons: 0 }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "wheel", x: 200, y: 150, deltaX: 0, deltaY: -120.5, deltaMode: 0, ctrlKey: true }, f.sender);
assert.equal(f.notifications.at(-1)[2].message.event.type, "wheel");
assert.equal(f.notifications.at(-1)[2].message.event.deltaY, -120.5);
await f.host.event("instance-1", { nodeId: "1", type: "scroll", scrollTop: 100, scrollLeft: 0, clientHeight: 400, clientWidth: 600 }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "widget", widgetEvent: "execute", detail: { value: "SELECT 1;", currentStatement: "SELECT 1" } }, f.sender);
assert.equal(f.notifications.at(-1)[2].message.event.widgetEvent, "execute");
for (const invalid of [
{ nodeId: "1", type: "pointerdown", pointerId: 1.5 },
{ nodeId: "1", type: "pointerdown", button: -2 },
{ nodeId: "1", type: "pointerdown", buttons: -1 },
{ nodeId: "1", type: "pointerdown", pointerType: "stylus" },
{ nodeId: "1", type: "wheel", deltaMode: 3 },
{ nodeId: "1", type: "wheel", deltaY: -100, unknownField: true },
]) {
await assert.rejects(f.host.event("instance-1", invalid, f.sender), /Invalid plugin view event/);
}
await assert.rejects(
f.host.event("instance-1", { nodeId: "1", type: "widget", widgetEvent: "change", detail: { value: "x".repeat(260 * 1024) } }, f.sender),
/exceeds limits/,
+31 -5
View File
@@ -796,6 +796,16 @@ html[data-theme-transition] *::after {
border-right: var(--terminal-workspace-sidebar-border, none);
}
/* Host window corner radius for split-pane focus borders touching the outer
window edge. Non-fullscreen macOS windows have native rounded corners;
Linux/Windows and fullscreen windows stay square. */
:root {
--window-corner-radius: 0px;
}
:root[data-platform="darwin"]:not([data-window-fullscreen="true"]) {
--window-corner-radius: 10px;
}
/* Dim terminal text in unfocused workspace panes (default) */
.workspace-pane:not(:focus-within) .xterm-screen {
opacity: 0.82;
@@ -805,21 +815,37 @@ html[data-theme-transition] *::after {
.workspace-pane[data-menu-open] .xterm-screen {
opacity: 1;
}
/* Border-style focus indicator (opt-in via data attribute) */
/* Border-style focus indicator (opt-in via data attribute).
Driven by deterministic workspace focus state (data-focused) rather than
DOM :focus-within so dialogs, settings, and app switches do not drop the
indicator. Suppressed for single-pane workspaces and magnified panes (which
render their own independent 1px magnification stroke). */
[data-workspace-focus="border"] .workspace-pane:not(:focus-within) .xterm-screen {
opacity: 1;
}
[data-workspace-focus="border"] .workspace-pane::after {
[data-workspace-focus="border"] .workspace-pane[data-multi-pane="true"]::after {
content: "";
position: absolute;
inset: 0;
border: 2px solid transparent;
box-sizing: border-box;
border: var(--workspace-focus-border-width, 1px) solid transparent;
border-radius: inherit;
pointer-events: none;
transition: border-color 120ms ease;
z-index: 40;
}
[data-workspace-focus="border"] .workspace-pane:focus-within::after {
border-color: hsl(var(--primary));
[data-workspace-focus="border"] .workspace-pane[data-multi-pane="true"][data-workspace-corner-bl="true"]:not([data-magnified="true"])::after {
border-bottom-left-radius: var(--workspace-corner-bl-radius, 0px);
}
[data-workspace-focus="border"] .workspace-pane[data-multi-pane="true"][data-workspace-corner-br="true"]:not([data-magnified="true"])::after {
border-bottom-right-radius: var(--workspace-corner-br-radius, 0px);
}
[data-workspace-focus="border"] .workspace-pane[data-multi-pane="true"][data-focused="true"]:not([data-magnified="true"])::after {
border-color: var(--workspace-focus-border-color, hsl(var(--primary)));
}
[data-workspace-focus="border"] .workspace-pane[data-magnified="true"]::after {
border-color: transparent;
transition: none;
}
/* ── Streamdown code block overrides ── */
@@ -1212,7 +1212,7 @@
"defaults": {
"type": "string",
"optional": true,
"description": "JSON object of group defaults: username, identityId, proxyProfileId, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort."
"description": "JSON object of group defaults: username, identityId, proxyProfileId, directProxy, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort."
}
},
"policy": {
@@ -1284,7 +1284,7 @@
"defaults": {
"type": "string",
"optional": true,
"description": "JSON object of group defaults: username, identityId, proxyProfileId, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort."
"description": "JSON object of group defaults: username, identityId, proxyProfileId, directProxy, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort."
}
},
"policy": {
@@ -307,6 +307,7 @@ const SAFE_GROUP_CONFIG_KEYS = [
'deviceType',
'agentForwarding',
'proxyProfileId',
'directProxy',
'hostChain',
'startupCommandRunMode',
'loginScriptId',
+3 -3
View File
@@ -1,14 +1,14 @@
{
version = "1.1.94";
version = "1.1.95";
sources = {
x86_64-linux = {
appImageArch = "x86_64";
hash = "sha256-aGZRSKTQQdBsdrP26HWvqEc1W9hKJHBrbEpy/H+jRP8=";
hash = "sha256-jtkRQ4I+ZF1ihy/JE8L8c4Nj7Chy65K808y/a4fXwLE=";
};
aarch64-linux = {
appImageArch = "arm64";
hash = "sha256-xOF4Rs0vfvmzVPE2vn2QYEFEzy5nPSYriru4Vmbwc2c=";
hash = "sha256-z1qYYw/E7fkHTGGvIaTc2VGzBkQgZFEvxR7H+iBUlLc=";
};
};
}
+1
View File
@@ -9,6 +9,7 @@ Self-contained WebAssembly build of [Devolutions/IronRDP](https://github.com/Dev
2. `0002-load-balance-info-and-shell.patch` — Exposes `load_balance_info`, `alternate_shell`, and `work_dir` extensions on `SessionBuilder` for JumpServer Razor and RDS Connection Broker routing.
3. `0003-rdpdr-drives-and-multimonitor.patch` — Adds `WasmDriveBackend` for MS-RDPEFS drive redirection (`rdpdr_drives`, `rdpdr_request_callback`, `rdpdr_response`, `rdpdr_add_drive`, `rdpdr_remove_drive`, composing cleanly with audio and printer redirection) and MS-RDPEDISP multi-monitor layout extensions (`set_monitor_layout`, `display_control_caps_callback`).
4. `0004-standard-rdp-security.patch` — Fixes `ConferenceCreateRequest` GCC `connectPDU` PER length encoding, raises `ServerSecurityData` certificate size limits, and adds Standard RDP Security (MS-RDPBCGR 5.3) with 40/56/128-bit RC4 (standard & salted MAC, 4096-packet key update) and FIPS (3DES-EDE3-CBC + HMAC-SHA1) across Slow-Path, Fast-Path, and Deactivation-Reactivation, plus `security_info_callback`.
5. `0005-license-request-fallback-public-key.patch` — Reuses the server public key from Standard RDP Server Security Data when the Server License Request omits its certificate, for both new and cached license responses.
## Rebuilding
+7 -7
View File
@@ -298,13 +298,13 @@ export interface InitOutput {
readonly sessionbuilder_webSocketProtocols: (a: number, b: any) => number;
readonly sessionterminationinfo_reason: (a: number) => [number, number];
readonly setup: (a: number, b: number) => void;
readonly wasm_bindgen__convert__closures_____invoke__h0870fb11242d97da: (a: number, b: number, c: any, d: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__hc8af3a46fbf9a387: (a: number, b: number, c: any) => [number, number];
readonly wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48: (a: number, b: number, c: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_69: (a: number, b: number, c: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_70: (a: number, b: number, c: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__hda0c6eb1ba57bb78: (a: number, b: number) => void;
readonly wasm_bindgen__convert__closures_____invoke__hed1c9475885aec45: (a: number, b: number) => void;
readonly wasm_bindgen__convert__closures_____invoke__h7fd80c0d0f68485d: (a: number, b: number, c: any, d: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__h9b3b88103f98b444: (a: number, b: number, c: any) => [number, number];
readonly wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74: (a: number, b: number, c: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_69: (a: number, b: number, c: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_70: (a: number, b: number, c: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__h43f4169ee688cf51: (a: number, b: number) => void;
readonly wasm_bindgen__convert__closures_____invoke__h4a921f6235159135: (a: number, b: number) => void;
readonly __wbindgen_malloc: (a: number, b: number) => number;
readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
readonly __wbindgen_exn_store: (a: number) => void;
+27 -27
View File
@@ -1238,7 +1238,7 @@ function __wbg_get_imports() {
const a = state0.a;
state0.a = 0;
try {
return wasm_bindgen__convert__closures_____invoke__h0870fb11242d97da(a, state0.b, arg0, arg1);
return wasm_bindgen__convert__closures_____invoke__h7fd80c0d0f68485d(a, state0.b, arg0, arg1);
} finally {
state0.a = a;
}
@@ -1493,33 +1493,33 @@ function __wbg_get_imports() {
return ret;
},
__wbindgen_generic_0000000000000001: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 3876, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hc8af3a46fbf9a387);
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 3867, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h9b3b88103f98b444);
return ret;
},
__wbindgen_generic_0000000000000002: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("CloseEvent")], shim_idx: 1111, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48);
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("CloseEvent")], shim_idx: 1113, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74);
return ret;
},
__wbindgen_generic_0000000000000003: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 1111, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_69);
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 1113, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_69);
return ret;
},
__wbindgen_generic_0000000000000004: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("MessageEvent")], shim_idx: 1111, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_70);
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("MessageEvent")], shim_idx: 1113, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_70);
return ret;
},
__wbindgen_generic_0000000000000005: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1103, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hda0c6eb1ba57bb78);
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1105, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h43f4169ee688cf51);
return ret;
},
__wbindgen_generic_0000000000000006: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1112, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hed1c9475885aec45);
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1114, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h4a921f6235159135);
return ret;
},
__wbindgen_generic_0000000000000007: function(arg0) {
@@ -1548,35 +1548,35 @@ function __wbg_get_imports() {
};
}
function wasm_bindgen__convert__closures_____invoke__hda0c6eb1ba57bb78(arg0, arg1) {
wasm.wasm_bindgen__convert__closures_____invoke__hda0c6eb1ba57bb78(arg0, arg1);
function wasm_bindgen__convert__closures_____invoke__h43f4169ee688cf51(arg0, arg1) {
wasm.wasm_bindgen__convert__closures_____invoke__h43f4169ee688cf51(arg0, arg1);
}
function wasm_bindgen__convert__closures_____invoke__hed1c9475885aec45(arg0, arg1) {
wasm.wasm_bindgen__convert__closures_____invoke__hed1c9475885aec45(arg0, arg1);
function wasm_bindgen__convert__closures_____invoke__h4a921f6235159135(arg0, arg1) {
wasm.wasm_bindgen__convert__closures_____invoke__h4a921f6235159135(arg0, arg1);
}
function wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48(arg0, arg1, arg2) {
wasm.wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48(arg0, arg1, arg2);
function wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74(arg0, arg1, arg2) {
wasm.wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74(arg0, arg1, arg2);
}
function wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_69(arg0, arg1, arg2) {
wasm.wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_69(arg0, arg1, arg2);
function wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_69(arg0, arg1, arg2) {
wasm.wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_69(arg0, arg1, arg2);
}
function wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_70(arg0, arg1, arg2) {
wasm.wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_70(arg0, arg1, arg2);
function wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_70(arg0, arg1, arg2) {
wasm.wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_70(arg0, arg1, arg2);
}
function wasm_bindgen__convert__closures_____invoke__hc8af3a46fbf9a387(arg0, arg1, arg2) {
const ret = wasm.wasm_bindgen__convert__closures_____invoke__hc8af3a46fbf9a387(arg0, arg1, arg2);
function wasm_bindgen__convert__closures_____invoke__h9b3b88103f98b444(arg0, arg1, arg2) {
const ret = wasm.wasm_bindgen__convert__closures_____invoke__h9b3b88103f98b444(arg0, arg1, arg2);
if (ret[1]) {
throw takeFromExternrefTable0(ret[0]);
}
}
function wasm_bindgen__convert__closures_____invoke__h0870fb11242d97da(arg0, arg1, arg2, arg3) {
wasm.wasm_bindgen__convert__closures_____invoke__h0870fb11242d97da(arg0, arg1, arg2, arg3);
function wasm_bindgen__convert__closures_____invoke__h7fd80c0d0f68485d(arg0, arg1, arg2, arg3) {
wasm.wasm_bindgen__convert__closures_____invoke__h7fd80c0d0f68485d(arg0, arg1, arg2, arg3);
}
Binary file not shown.
+7 -7
View File
@@ -79,13 +79,13 @@ export const sessionbuilder_username: (a: number, b: number, c: number) => numbe
export const sessionbuilder_webSocketProtocols: (a: number, b: any) => number;
export const sessionterminationinfo_reason: (a: number) => [number, number];
export const setup: (a: number, b: number) => void;
export const wasm_bindgen__convert__closures_____invoke__h0870fb11242d97da: (a: number, b: number, c: any, d: any) => void;
export const wasm_bindgen__convert__closures_____invoke__hc8af3a46fbf9a387: (a: number, b: number, c: any) => [number, number];
export const wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48: (a: number, b: number, c: any) => void;
export const wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_69: (a: number, b: number, c: any) => void;
export const wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_70: (a: number, b: number, c: any) => void;
export const wasm_bindgen__convert__closures_____invoke__hda0c6eb1ba57bb78: (a: number, b: number) => void;
export const wasm_bindgen__convert__closures_____invoke__hed1c9475885aec45: (a: number, b: number) => void;
export const wasm_bindgen__convert__closures_____invoke__h7fd80c0d0f68485d: (a: number, b: number, c: any, d: any) => void;
export const wasm_bindgen__convert__closures_____invoke__h9b3b88103f98b444: (a: number, b: number, c: any) => [number, number];
export const wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74: (a: number, b: number, c: any) => void;
export const wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_69: (a: number, b: number, c: any) => void;
export const wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_70: (a: number, b: number, c: any) => void;
export const wasm_bindgen__convert__closures_____invoke__h43f4169ee688cf51: (a: number, b: number) => void;
export const wasm_bindgen__convert__closures_____invoke__h4a921f6235159135: (a: number, b: number) => void;
export const __wbindgen_malloc: (a: number, b: number) => number;
export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
export const __wbindgen_exn_store: (a: number) => void;
+2 -1
View File
@@ -32,7 +32,8 @@
"0001-session-responsiveness.patch",
"0002-load-balance-info-and-shell.patch",
"0003-rdpdr-drives-and-multimonitor.patch",
"0004-standard-rdp-security.patch"
"0004-standard-rdp-security.patch",
"0005-license-request-fallback-public-key.patch"
]
}
}
@@ -3690,6 +3690,11 @@
"reset",
"dblclick",
"contextmenu",
"pointerdown",
"pointermove",
"pointerup",
"pointercancel",
"wheel",
"scroll",
"widget"
]
@@ -3740,6 +3745,39 @@
"y": {
"type": "number"
},
"pointerId": {
"type": "integer",
"minimum": -2147483648,
"maximum": 2147483647
},
"button": {
"type": "integer",
"minimum": -1,
"maximum": 32
},
"buttons": {
"type": "integer",
"minimum": 0,
"maximum": 65535
},
"pointerType": {
"enum": [
"mouse",
"pen",
"touch"
]
},
"deltaX": {
"type": "number"
},
"deltaY": {
"type": "number"
},
"deltaMode": {
"type": "integer",
"minimum": 0,
"maximum": 2
},
"scrollTop": {
"type": "number",
"minimum": 0
@@ -1492,3 +1492,26 @@ test("settings accept host-owned groups but reject custom rendering and settings
assert.equal(view({ id: "com.example.contract-test.view", title: "Custom", location }), true, JSON.stringify(view.errors));
}
});
test("HostDrawnViewEvent accepts pointer and wheel fields while rejecting out-of-range or unknown fields", () => {
const validate = validator("HostDrawnViewEvent");
for (const valid of [
{ nodeId: "stage", type: "pointerdown", x: 120, y: 80, pointerId: 1, button: 0, buttons: 1, pointerType: "mouse" },
{ nodeId: "stage", type: "pointermove", x: -12, y: 240, pointerId: 1, button: -1, buttons: 1, shiftKey: true },
{ nodeId: "stage", type: "pointerup", x: 140, y: 90, pointerId: 1, button: 0, buttons: 0, pointerType: "touch" },
{ nodeId: "stage", type: "pointercancel", x: 140, y: 90, pointerId: 2, button: -1, buttons: 0, pointerType: "pen" },
{ nodeId: "stage", type: "wheel", x: 200, y: 150, deltaX: 12.5, deltaY: -120, deltaMode: 0, ctrlKey: true },
]) {
assert.equal(validate(valid), true, JSON.stringify(validate.errors));
}
for (const invalid of [
{ nodeId: "stage", type: "pointerdown", pointerId: 1.5 },
{ nodeId: "stage", type: "pointerdown", button: -2 },
{ nodeId: "stage", type: "pointerdown", buttons: 70000 },
{ nodeId: "stage", type: "pointerdown", pointerType: "unknown" },
{ nodeId: "stage", type: "wheel", deltaMode: 3 },
{ nodeId: "stage", type: "wheel", deltaY: -100, extra: 1 },
]) {
assert.equal(validate(invalid), false, JSON.stringify(invalid));
}
});
@@ -272,7 +272,7 @@ export type HostConfirmRequest = {
export type HostDrawnViewEvent = {
nodeId: string;
type: "click" | "input" | "change" | "keydown" | "keyup" | "focusin" | "focusout" | "compositionstart" | "compositionupdate" | "compositionend" | "dismiss" | "submit" | "reset" | "dblclick" | "contextmenu" | "scroll" | "widget";
type: "click" | "input" | "change" | "keydown" | "keyup" | "focusin" | "focusout" | "compositionstart" | "compositionupdate" | "compositionend" | "dismiss" | "submit" | "reset" | "dblclick" | "contextmenu" | "pointerdown" | "pointermove" | "pointerup" | "pointercancel" | "wheel" | "scroll" | "widget";
value?: string;
checked?: boolean;
eventId?: number;
@@ -285,6 +285,13 @@ export type HostDrawnViewEvent = {
values?: Array<string>;
x?: number;
y?: number;
pointerId?: number;
button?: number;
buttons?: number;
pointerType?: "mouse" | "pen" | "touch";
deltaX?: number;
deltaY?: number;
deltaMode?: number;
scrollTop?: number;
scrollLeft?: number;
clientHeight?: number;
+133 -2
View File
@@ -107,6 +107,91 @@ function subscribeControlPropertyMutations(container: HTMLElement, onMutation: (
const MAX_PLUGIN_CSS_LENGTH = 131072;
const MAX_PLUGIN_EVENT_VALUE_LENGTH = 131072;
function createForwardedPointerEvent(
win: (Window & typeof globalThis) | null,
eventType: 'pointerdown' | 'pointermove' | 'pointerup' | 'pointercancel',
event: HostDrawnViewEvent,
pointerId: number,
): Event {
const pointerType = event.pointerType ?? 'mouse';
const button = typeof event.button === 'number' && Number.isFinite(event.button)
? Math.trunc(event.button)
: (eventType === 'pointermove' || eventType === 'pointercancel' ? -1 : 0);
const buttons = typeof event.buttons === 'number' && Number.isFinite(event.buttons)
? Math.trunc(event.buttons)
: 0;
const init: PointerEventInit = {
bubbles: true,
cancelable: eventType !== 'pointercancel',
composed: true,
clientX: event.x ?? 0,
clientY: event.y ?? 0,
button,
buttons,
ctrlKey: Boolean(event.ctrlKey),
metaKey: Boolean(event.metaKey),
altKey: Boolean(event.altKey),
shiftKey: Boolean(event.shiftKey),
pointerId,
pointerType,
isPrimary: true,
};
const PointerCtor = win?.PointerEvent ?? (typeof PointerEvent === 'function' ? PointerEvent : undefined);
const MouseCtor = win?.MouseEvent ?? MouseEvent;
const created = PointerCtor ? new PointerCtor(eventType, init) : new MouseCtor(eventType, init);
// JSDOM either omits PointerEvent or aliases it to MouseEvent, which drops pointer* fields.
if ((created as PointerEvent).pointerId !== pointerId) {
Object.defineProperty(created, 'pointerId', { value: pointerId, configurable: true });
}
if ((created as PointerEvent).pointerType !== pointerType) {
Object.defineProperty(created, 'pointerType', { value: pointerType, configurable: true });
}
if ((created as PointerEvent).isPrimary !== true) {
Object.defineProperty(created, 'isPrimary', { value: true, configurable: true });
}
return created;
}
function createForwardedWheelEvent(
win: (Window & typeof globalThis) | null,
event: HostDrawnViewEvent,
): Event {
const deltaX = typeof event.deltaX === 'number' && Number.isFinite(event.deltaX) ? event.deltaX : 0;
const deltaY = typeof event.deltaY === 'number' && Number.isFinite(event.deltaY) ? event.deltaY : 0;
const deltaMode = typeof event.deltaMode === 'number' && Number.isFinite(event.deltaMode) ? Math.trunc(event.deltaMode) : 0;
const init: WheelEventInit = {
bubbles: true,
cancelable: true,
composed: true,
clientX: event.x ?? 0,
clientY: event.y ?? 0,
deltaX,
deltaY,
deltaZ: 0,
deltaMode,
ctrlKey: Boolean(event.ctrlKey),
metaKey: Boolean(event.metaKey),
altKey: Boolean(event.altKey),
shiftKey: Boolean(event.shiftKey),
};
const WheelCtor = win?.WheelEvent ?? (typeof WheelEvent === 'function' ? WheelEvent : undefined);
const MouseCtor = win?.MouseEvent ?? MouseEvent;
const created = WheelCtor ? new WheelCtor('wheel', init) : new MouseCtor('wheel', init);
if ((created as WheelEvent).deltaX !== deltaX) {
Object.defineProperty(created, 'deltaX', { value: deltaX, configurable: true });
}
if ((created as WheelEvent).deltaY !== deltaY) {
Object.defineProperty(created, 'deltaY', { value: deltaY, configurable: true });
}
if ((created as WheelEvent).deltaZ !== 0) {
Object.defineProperty(created, 'deltaZ', { value: 0, configurable: true });
}
if ((created as WheelEvent).deltaMode !== deltaMode) {
Object.defineProperty(created, 'deltaMode', { value: deltaMode, configurable: true });
}
return created;
}
function matchShortcutFromKeyEvent(event: HostDrawnViewEvent, isTextControl: boolean): string | null {
const key = event.key ?? '';
if (key === 'Escape' && !event.metaKey && !event.ctrlKey && !event.altKey) return 'escape';
@@ -144,6 +229,7 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
acknowledgedEvent: number;
sentAck: number;
controls: Map<string, string>;
pointerAncestors: Map<number, Element[]>;
};
const instances = new Map<string, View>();
const close = (id: string) => {
@@ -156,14 +242,58 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
view.elementsById.clear();
view.controlElements.clear();
view.controls.clear();
view.pointerAncestors.clear();
view.unmount();
view.container.remove();
};
const sendEvent = (view: View, event: HostDrawnViewEvent) => {
view.syncElementIndex();
const element = view.elementsById.get(event.nodeId);
if (!element || !(element instanceof HTMLElement)) return;
const eventType = event.type;
const lookedUp = view.elementsById.get(event.nodeId);
if (
eventType === 'pointerdown'
|| eventType === 'pointermove'
|| eventType === 'pointerup'
|| eventType === 'pointercancel'
) {
const pointerId = typeof event.pointerId === 'number' && Number.isFinite(event.pointerId)
? Math.trunc(event.pointerId)
: 1;
let target: HTMLElement | null = lookedUp instanceof HTMLElement && lookedUp.isConnected ? lookedUp : null;
if (eventType === 'pointerdown') {
if (!target) return;
const chain: Element[] = [];
let cur: Element | null = target;
while (cur && view.container.contains(cur)) {
chain.push(cur);
if (cur === view.container) break;
cur = cur.parentElement;
}
view.pointerAncestors.set(pointerId, chain);
} else {
if (!target) {
const chain = view.pointerAncestors.get(pointerId);
if (chain) {
const surviving = chain.find((node): node is HTMLElement => node instanceof HTMLElement && node.isConnected);
target = surviving ?? (view.container.isConnected ? view.container : null);
}
}
if (eventType === 'pointerup' || eventType === 'pointercancel') {
view.pointerAncestors.delete(pointerId);
}
if (!target) return;
}
const win = target.ownerDocument?.defaultView as (Window & typeof globalThis) | null;
target.dispatchEvent(createForwardedPointerEvent(win, eventType, event, pointerId));
return;
}
const element = lookedUp;
if (!element || !(element instanceof HTMLElement)) return;
if (eventType === 'wheel') {
const win = element.ownerDocument?.defaultView as (Window & typeof globalThis) | null;
element.dispatchEvent(createForwardedWheelEvent(win, event));
return;
}
if (eventType === 'dismiss') { element.dispatchEvent(new Event('netcatty-dismiss')); return; }
if (eventType === 'widget') {
const widgetEvent = new CustomEvent('netcatty-widget-event', {
@@ -391,6 +521,7 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
acknowledgedEvent: 0,
sentAck: 0,
controls: new Map(),
pointerAncestors: new Map(),
};
instances.set(id, view);
domObserver.observe(container, { childList: true, subtree: true });
+216 -1
View File
@@ -573,7 +573,6 @@ test('PluginBiChart serializes props and forwards datumClick, exportSvg, exportP
postMessage() {},
getState: async () => undefined,
setState: async () => {},
setBadge: async () => {},
};
const received: Record<string, unknown> = {};
@@ -650,3 +649,219 @@ test('registerHostReactView still completes initial loading for components that
dom.window.close();
}
});
test('hostDom dispatches pointer drag, pan, cancel, and wheel zoom events into a React graph fixture', async () => {
const dom = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLOptionElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'MouseEvent', 'WheelEvent', 'CustomEvent']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
const { act, useEffect, useRef, useState } = await import('react');
const { remoteId } = await import('@remote-dom/core/elements');
const { registerHostReactView } = await import('./hostReact.js');
let receive: (value: JsonValue) => void = () => {};
const messages: Array<Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>> = [];
const views = {
onDidReceiveMessage(_id: string, listener: (value: JsonValue) => void) { receive = listener; return { dispose() {} }; },
postMessage(_id: string, value: JsonValue) { messages.push(value as unknown as Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>); },
getState: async () => undefined,
setState: async () => {},
setBadge: async () => {},
};
const log: Array<Record<string, unknown>> = [];
function GraphFixture() {
const stageRef = useRef<HTMLDivElement | null>(null);
const [nodeA, setNodeA] = useState({ x: 100, y: 100 });
const nodeB = { x: 300, y: 100 };
const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 });
const [showHandle, setShowHandle] = useState(true);
const dragRef = useRef<
| { kind: 'node'; pointerId: number; startX: number; startY: number; originX: number; originY: number }
| { kind: 'pan'; pointerId: number; startX: number; startY: number; originX: number; originY: number }
| null
>(null);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const onWheel = (event: WheelEvent) => {
event.preventDefault();
log.push({
type: 'wheel',
clientX: event.clientX,
clientY: event.clientY,
deltaX: event.deltaX,
deltaY: event.deltaY,
deltaMode: event.deltaMode,
ctrlKey: event.ctrlKey,
});
setViewport((prev) => ({
...prev,
zoom: Math.round(prev.zoom * (event.deltaY < 0 ? 1.25 : 0.8) * 100) / 100,
}));
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, []);
const dx = nodeB.x - nodeA.x;
const dy = nodeB.y - nodeA.y;
const edgeLength = Math.round(Math.hypot(dx, dy));
const edgeAngle = Math.round((Math.atan2(dy, dx) * 180) / Math.PI);
return (
<div
id="graph-stage"
ref={stageRef}
onPointerDown={(e) => {
if (e.button !== 0) return;
log.push({ type: 'stage-down', pointerId: e.pointerId, clientX: e.clientX, clientY: e.clientY, buttons: e.buttons });
dragRef.current = { kind: 'pan', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: viewport.x, originY: viewport.y };
}}
onPointerMove={(e) => {
const drag = dragRef.current;
if (!drag || drag.pointerId !== e.pointerId) return;
log.push({ type: 'move', pointerId: e.pointerId, clientX: e.clientX, clientY: e.clientY, shiftKey: e.shiftKey });
if (drag.kind === 'node') {
setNodeA({ x: drag.originX + (e.clientX - drag.startX), y: drag.originY + (e.clientY - drag.startY) });
} else {
setViewport((prev) => ({ ...prev, x: drag.originX + (e.clientX - drag.startX), y: drag.originY + (e.clientY - drag.startY) }));
}
}}
onPointerUp={(e) => {
if (dragRef.current?.pointerId === e.pointerId) {
log.push({ type: 'up', pointerId: e.pointerId, clientX: e.clientX, clientY: e.clientY });
dragRef.current = null;
}
}}
onPointerCancel={(e) => {
if (dragRef.current?.pointerId === e.pointerId) {
log.push({ type: 'cancel', pointerId: e.pointerId });
dragRef.current = null;
}
}}
>
<div id="graph-world" style={{ transform: `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})` }}>
<div
id="edge-ab"
style={{ width: `${edgeLength}px`, transform: `translate(${nodeA.x}px, ${nodeA.y}px) rotate(${edgeAngle}deg)` }}
/>
<button
id="node-a"
type="button"
style={{ transform: `translate(${nodeA.x}px, ${nodeA.y}px)` }}
onPointerDown={(e) => {
if (e.button !== 0) return;
e.stopPropagation();
log.push({ type: 'node-down', pointerId: e.pointerId, clientX: e.clientX, clientY: e.clientY, button: e.button, buttons: e.buttons });
dragRef.current = { kind: 'node', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: nodeA.x, originY: nodeA.y };
}}
>
Node A
</button>
{showHandle && (
<button
id="ephemeral-handle"
type="button"
onPointerDown={(e) => {
e.stopPropagation();
dragRef.current = { kind: 'node', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: nodeA.x, originY: nodeA.y };
setShowHandle(false);
}}
>
Handle
</button>
)}
</div>
</div>
);
}
const registration = registerHostReactView(views, 'com.example.graph', () => <GraphFixture />);
try {
await act(async () => {
receive({ kind: 'host-ui.open', instanceId: 'graph-1' });
await new Promise((resolve) => setTimeout(resolve, 20));
});
const stage = document.getElementById('graph-stage')!;
const world = document.getElementById('graph-world')!;
const edge = document.getElementById('edge-ab')!;
const nodeAEl = document.getElementById('node-a')!;
const ephemeralHandle = document.getElementById('ephemeral-handle')!;
assert.equal(nodeAEl.style.transform, 'translate(100px, 100px)');
assert.equal(edge.style.width, '200px');
// 1. Node drag: node moves by (+60, +80) and incident edge recomputes length and start transform
const nodeAId = remoteId(nodeAEl);
await act(async () => {
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 1, type: 'pointerdown', nodeId: nodeAId, x: 100, y: 100, pointerId: 4, button: 0, buttons: 1, pointerType: 'mouse' } });
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 2, type: 'pointermove', nodeId: nodeAId, x: 160, y: 180, pointerId: 4, button: -1, buttons: 1, shiftKey: true } });
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 3, type: 'pointerup', nodeId: nodeAId, x: 160, y: 180, pointerId: 4, button: 0, buttons: 0 } });
// Subsequent move after pointerup must not drag the node further
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 4, type: 'pointermove', nodeId: nodeAId, x: 260, y: 260, pointerId: 4, button: -1, buttons: 0 } });
await new Promise((resolve) => setTimeout(resolve, 20));
});
assert.equal(nodeAEl.style.transform, 'translate(160px, 180px)', 'node transform must move by pointer delta');
const expectedLen = Math.round(Math.hypot(300 - 160, 100 - 180));
const expectedAngle = Math.round((Math.atan2(100 - 180, 300 - 160) * 180) / Math.PI);
assert.equal(edge.style.width, `${expectedLen}px`, 'incident edge length must follow dragged node');
assert.equal(edge.style.transform, `translate(160px, 180px) rotate(${expectedAngle}deg)`, 'incident edge origin/angle must follow dragged node');
assert.deepEqual(log.slice(0, 3), [
{ type: 'node-down', pointerId: 4, clientX: 100, clientY: 100, button: 0, buttons: 1 },
{ type: 'move', pointerId: 4, clientX: 160, clientY: 180, shiftKey: true },
{ type: 'up', pointerId: 4, clientX: 160, clientY: 180 },
]);
assert.equal(messages.at(-1)?.acknowledgedEvent, 4);
// 2. Stage pan + pointercancel + wheel zoom
const stageId = remoteId(stage);
await act(async () => {
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 5, type: 'pointerdown', nodeId: stageId, x: 200, y: 200, pointerId: 5, button: 0, buttons: 1 } });
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 6, type: 'pointermove', nodeId: stageId, x: 245, y: 175, pointerId: 5, button: -1, buttons: 1 } });
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 7, type: 'pointercancel', nodeId: stageId, x: 245, y: 175, pointerId: 5, button: -1, buttons: 0 } });
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 8, type: 'wheel', nodeId: stageId, x: 210, y: 140, deltaX: 5, deltaY: -120, deltaMode: 0, ctrlKey: true } });
await new Promise((resolve) => setTimeout(resolve, 20));
});
assert.equal(world.style.transform, 'translate(45px, -25px) scale(1.25)', 'stage pan and wheel zoom must update viewport transform');
assert.deepEqual(log.at(-1), {
type: 'wheel',
clientX: 210,
clientY: 140,
deltaX: 5,
deltaY: -120,
deltaMode: 0,
ctrlKey: true,
});
assert.equal(log.some((entry) => entry.type === 'cancel' && entry.pointerId === 5), true);
// 3. Unmounting the originating pointerdown node mid-gesture still delivers pointermove/pointerup to surviving ancestors
const handleId = remoteId(ephemeralHandle);
await act(async () => {
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 9, type: 'pointerdown', nodeId: handleId, x: 10, y: 10, pointerId: 6, button: 0, buttons: 1 } });
});
assert.equal(document.getElementById('ephemeral-handle'), null, 'ephemeral handle unmounted on pointerdown');
await act(async () => {
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 10, type: 'pointermove', nodeId: handleId, x: 35, y: 20, pointerId: 6, button: -1, buttons: 1 } });
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 11, type: 'pointerup', nodeId: handleId, x: 35, y: 20, pointerId: 6, button: 0, buttons: 0 } });
await new Promise((resolve) => setTimeout(resolve, 20));
});
assert.equal(nodeAEl.style.transform, 'translate(185px, 190px)', 'pointermove after target unmount must still bubble to surviving stage');
assert.equal(log.some((entry) => entry.type === 'up' && entry.pointerId === 6), true, 'pointerup after target unmount must terminate drag cleanly');
await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'graph-1' }); });
} finally {
await act(async () => { registration.dispose(); });
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
dom.window.close();
}
});
+5 -2
View File
@@ -116,8 +116,9 @@ run_host_tests() {
echo "Running IronRDP host unit tests (ironrdp-pdu, ironrdp-connector, ironrdp-web)..."
(
cd "${SRC_DIR}"
cargo test -p ironrdp-pdu --lib --locked -- crypto:: gcc::
cargo test -p ironrdp-pdu --lib --locked -- crypto:: gcc:: server_license::
cargo test -p ironrdp-connector --lib --locked
cargo test -p ironrdp-testsuite-core --test integration_tests_core --locked -- pdu::server_license connector::license_exchange
# Run host-compatible unit tests (RDPDR drive PDU marshalling, multi-monitor
# layout validation, load_balance_info, audio/printer/drive channel
# attachment, RDCleanPath, file-transfer marshalling). Clipboard JS bridge
@@ -214,7 +215,8 @@ package_output() {
"0001-session-responsiveness.patch",
"0002-load-balance-info-and-shell.patch",
"0003-rdpdr-drives-and-multimonitor.patch",
"0004-standard-rdp-security.patch"
"0004-standard-rdp-security.patch",
"0005-license-request-fallback-public-key.patch"
]
}
}
@@ -232,6 +234,7 @@ Self-contained WebAssembly build of [Devolutions/IronRDP](https://github.com/Dev
2. \`0002-load-balance-info-and-shell.patch\` — Exposes \`load_balance_info\`, \`alternate_shell\`, and \`work_dir\` extensions on \`SessionBuilder\` for JumpServer Razor and RDS Connection Broker routing.
3. \`0003-rdpdr-drives-and-multimonitor.patch\` — Adds \`WasmDriveBackend\` for MS-RDPEFS drive redirection (\`rdpdr_drives\`, \`rdpdr_request_callback\`, \`rdpdr_response\`, \`rdpdr_add_drive\`, \`rdpdr_remove_drive\`, composing cleanly with audio and printer redirection) and MS-RDPEDISP multi-monitor layout extensions (\`set_monitor_layout\`, \`display_control_caps_callback\`).
4. \`0004-standard-rdp-security.patch\` — Fixes \`ConferenceCreateRequest\` GCC \`connectPDU\` PER length encoding, raises \`ServerSecurityData\` certificate size limits, and adds Standard RDP Security (MS-RDPBCGR 5.3) with 40/56/128-bit RC4 (standard & salted MAC, 4096-packet key update) and FIPS (3DES-EDE3-CBC + HMAC-SHA1) across Slow-Path, Fast-Path, and Deactivation-Reactivation, plus \`security_info_callback\`.
5. \`0005-license-request-fallback-public-key.patch\` — Reuses the server public key from Standard RDP Server Security Data when the Server License Request omits its certificate, for both new and cached license responses.
## Rebuilding
@@ -0,0 +1,537 @@
diff --git a/crates/ironrdp-connector/src/connection.rs b/crates/ironrdp-connector/src/connection.rs
index 35c546e3..3e1329c7 100644
--- a/crates/ironrdp-connector/src/connection.rs
+++ b/crates/ironrdp-connector/src/connection.rs
@@ -491,6 +491,8 @@ pub struct ClientConnector {
pending_standard_security: Option<gcc::ServerSecurityData>,
/// Active Standard RDP Security cipher context once `SecurityExchange` has completed.
standard_rdp_security: Option<StandardRdpSecurity>,
+ /// DER public key retained from the Standard RDP Security exchange for licensing.
+ fallback_server_public_key: Option<Vec<u8>>,
}
impl ClientConnector {
@@ -521,6 +523,7 @@ impl ClientConnector {
license_rng: Arc::new(DefaultLicenseRng),
pending_standard_security: None,
standard_rdp_security: None,
+ fallback_server_public_key: None,
}
}
@@ -1955,6 +1958,14 @@ impl ClientConnector {
)
.map_err(|err| reason_err!("SecurityExchange", "{err}"))?;
+ let certificate = decode::<rdp::server_license::ServerCertificate>(&server_security.server_cert)
+ .map_err(ConnectorError::decode)?;
+ self.fallback_server_public_key = Some(
+ certificate
+ .get_server_security_public_key()
+ .map_err(|err| crate::custom_err!("SecurityExchange", err))?,
+ );
+
info!(
method = ?security.info().encryption_method,
level = ?security.info().encryption_level,
@@ -2016,6 +2027,7 @@ impl ClientConnector {
// the phase. Without a message channel nothing is read and we go
// straight to licensing, as before.
let license_exchange = LicenseExchangeSequence {
+ fallback_server_public_key: self.fallback_server_public_key.take(),
rng: Arc::clone(&self.license_rng),
..LicenseExchangeSequence::new(
io_channel_id,
diff --git a/crates/ironrdp-connector/src/license_exchange.rs b/crates/ironrdp-connector/src/license_exchange.rs
index 3ff98dfa..0f0ca536 100644
--- a/crates/ironrdp-connector/src/license_exchange.rs
+++ b/crates/ironrdp-connector/src/license_exchange.rs
@@ -65,6 +65,8 @@ pub struct LicenseExchangeSequence {
pub hardware_id: [u32; 4],
pub license_cache: Arc<dyn LicenseCache>,
pub rng: Arc<dyn LicenseRng>,
+ /// DER public key from Server Security Data, used only if the license request omits its certificate.
+ pub fallback_server_public_key: Option<Vec<u8>>,
}
// Use RefUnwindSafe so that types that embed LicenseCache remain UnwindSafe
@@ -139,6 +141,7 @@ impl LicenseExchangeSequence {
hardware_id,
license_cache,
rng: Arc::new(DefaultLicenseRng),
+ fallback_server_public_key: None,
}
}
}
@@ -206,6 +209,7 @@ impl Sequence for LicenseExchangeSequence {
if let Some(info) = license_info {
match server_license::ClientLicenseInfo::from_server_license_request(
&license_request,
+ self.fallback_server_public_key.as_deref(),
&client_random,
&premaster_secret,
self.hardware_id,
@@ -237,6 +241,7 @@ impl Sequence for LicenseExchangeSequence {
let hwid = self.hardware_id;
match server_license::ClientNewLicenseRequest::from_server_license_request(
&license_request,
+ self.fallback_server_public_key.as_deref(),
&client_random,
&premaster_secret,
&self.username,
diff --git a/crates/ironrdp-fuzzing/src/oracles/mod.rs b/crates/ironrdp-fuzzing/src/oracles/mod.rs
index 2e2a089b..fcfc8348 100644
--- a/crates/ironrdp-fuzzing/src/oracles/mod.rs
+++ b/crates/ironrdp-fuzzing/src/oracles/mod.rs
@@ -185,6 +185,7 @@ pub fn pdu_decode(data: &[u8]) {
{
let _ = server_license::ClientNewLicenseRequest::from_server_license_request(
&license_request,
+ None,
&[0; 32],
&[0; 48],
"user",
@@ -192,6 +193,7 @@ pub fn pdu_decode(data: &[u8]) {
);
let _ = server_license::ClientLicenseInfo::from_server_license_request(
&license_request,
+ None,
&[0; 32],
&[0; 48],
[0; 4],
diff --git a/crates/ironrdp-pdu/src/rdp/server_license/client_license_info.rs b/crates/ironrdp-pdu/src/rdp/server_license/client_license_info.rs
index 782a6330..6efc617b 100644
--- a/crates/ironrdp-pdu/src/rdp/server_license/client_license_info.rs
+++ b/crates/ironrdp-pdu/src/rdp/server_license/client_license_info.rs
@@ -44,15 +44,17 @@ impl ClientLicenseInfo {
pub fn from_server_license_request(
license_request: &ServerLicenseRequest,
+ fallback_server_public_key: Option<&[u8]>,
client_random: &[u8],
premaster_secret: &[u8],
hardware_data: [u32; 4],
license_info: Vec<u8>,
) -> Result<(Self, LicenseEncryptionData), ServerLicenseError> {
- let public_key = license_request.get_public_key()?
+ let license_public_key = license_request.get_public_key()?;
+ let public_key = license_public_key.as_deref().or(fallback_server_public_key)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData,
"attempted to retrieve the server public key from a server license request message that does not have a certificate"))?;
- let encrypted_premaster_secret = encrypt_with_public_key(premaster_secret, &public_key)?;
+ let encrypted_premaster_secret = encrypt_with_public_key(premaster_secret, public_key)?;
let master_secret = compute_master_secret(
premaster_secret,
diff --git a/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/mod.rs b/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/mod.rs
index 9f0b0d4b..e5e1ed49 100644
--- a/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/mod.rs
+++ b/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/mod.rs
@@ -65,16 +65,18 @@ impl ClientNewLicenseRequest {
pub fn from_server_license_request(
license_request: &ServerLicenseRequest,
+ fallback_server_public_key: Option<&[u8]>,
client_random: &[u8],
premaster_secret: &[u8],
client_username: &str,
client_machine_name: &str,
) -> Result<(Self, LicenseEncryptionData), ServerLicenseError> {
- let public_key = license_request.get_public_key()?
+ let license_public_key = license_request.get_public_key()?;
+ let public_key = license_public_key.as_deref().or(fallback_server_public_key)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData,
"attempted to retrieve the server public key from a server license request message that does not have a certificate"))?;
- let encrypted_premaster_secret = encrypt_with_public_key(premaster_secret, &public_key)?;
+ let encrypted_premaster_secret = encrypt_with_public_key(premaster_secret, public_key)?;
let master_secret = compute_master_secret(
premaster_secret,
diff --git a/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/tests.rs b/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/tests.rs
index ac8eb9cd..ad8158dd 100644
--- a/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/tests.rs
+++ b/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/tests.rs
@@ -325,6 +325,7 @@ fn client_new_license_request_creates_correctly() {
LicensePdu::ServerLicenseRequest(license_request) => {
let (client_new_license_request, encryption_data) = ClientNewLicenseRequest::from_server_license_request(
license_request,
+ None,
CLIENT_RANDOM_BUFFER.as_ref(),
PREMASTER_SECRET_BUFFER.as_ref(),
CLIENT_USERNAME,
diff --git a/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/mod.rs b/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/mod.rs
index 7b8bdbc8..b30b1cb4 100644
--- a/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/mod.rs
+++ b/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/mod.rs
@@ -218,6 +218,25 @@ impl ServerCertificate {
const FIXED_PART_SIZE: usize = CERT_VERSION_FIELD_SIZE;
+ /// Extracts the DER public key from a Server Security Data certificate.
+ pub fn get_server_security_public_key(&self) -> Result<Vec<u8>, ServerLicenseError> {
+ use pkcs1::der::Encode as _;
+
+ if let CertificateType::Proprietary(certificate) = &self.certificate {
+ // MCS proprietary RSA integers are little-endian and the modulus includes eight padding bytes.
+ let mut modulus = certificate.public_key.modulus.clone();
+ modulus.truncate(modulus.len().saturating_sub(8));
+ modulus.reverse();
+ let public_exponent = certificate.public_key.public_exponent.to_be_bytes();
+ return Ok(pkcs1::RsaPublicKey {
+ modulus: pkcs1::UintRef::new(&modulus)?,
+ public_exponent: pkcs1::UintRef::new(&public_exponent)?,
+ }
+ .to_der()?);
+ }
+ self.get_public_key()
+ }
+
pub fn get_public_key(&self) -> Result<Vec<u8>, ServerLicenseError> {
use pkcs1::der::Encode as _;
use x509_cert::der::Decode as _;
diff --git a/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/tests.rs b/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/tests.rs
index c5aa22ab..1189f75c 100644
--- a/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/tests.rs
+++ b/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/tests.rs
@@ -638,3 +638,202 @@ fn buffer_length_is_correct_for_x509_certificate_chain() {
assert_eq!(CERT_CHAIN.size(), chain_buffer.len());
}
+
+// oracle: regression Netcatty #4540; encryption is raw RSA with little-endian premaster and eight padding bytes.
+#[test]
+fn license_responses_reuse_the_fallback_public_key_without_a_certificate() {
+ use crate::rdp::server_license::{ClientLicenseInfo, ClientNewLicenseRequest};
+
+ let LicensePdu::ServerLicenseRequest(mut request) =
+ decode::<LicensePdu>(&encode_vec(&*SERVER_LICENSE_REQUEST).unwrap()).unwrap()
+ else {
+ panic!("expected a Server License Request");
+ };
+ let public_key = request.get_public_key().unwrap().unwrap();
+ request.server_certificate = None;
+ // RSA maps the integer one to one for any valid key, so this checks ciphertext independently of the encryptor.
+ let mut premaster = [0; 48];
+ premaster[0] = 1;
+ let mut expected_ciphertext = vec![0; 256 + 8];
+ expected_ciphertext[0] = 1;
+
+ let (new_request, _) = ClientNewLicenseRequest::from_server_license_request(
+ &request,
+ Some(&public_key),
+ &[0x11; 32],
+ &premaster,
+ "user",
+ "machine",
+ )
+ .unwrap();
+ assert_eq!(new_request.encrypted_premaster_secret, expected_ciphertext);
+ let (info, _) = ClientLicenseInfo::from_server_license_request(
+ &request,
+ Some(&public_key),
+ &[0x11; 32],
+ &premaster,
+ [0; 4],
+ vec![0x33; 16],
+ )
+ .unwrap();
+ assert_eq!(info.encrypted_premaster_secret, expected_ciphertext);
+}
+
+// oracle: regression Netcatty #4540; absence of both keys retains the existing missing-certificate error.
+#[test]
+fn license_responses_without_a_certificate_or_fallback_still_fail() {
+ use crate::rdp::server_license::{ClientLicenseInfo, ClientNewLicenseRequest};
+
+ let LicensePdu::ServerLicenseRequest(mut request) =
+ decode::<LicensePdu>(&encode_vec(&*SERVER_LICENSE_REQUEST).unwrap()).unwrap()
+ else {
+ panic!("expected a Server License Request");
+ };
+ request.server_certificate = None;
+ let error = "IO error: attempted to retrieve the server public key from a server license request message that does not have a certificate";
+ assert_eq!(
+ ClientNewLicenseRequest::from_server_license_request(
+ &request,
+ None,
+ &[0x11; 32],
+ &[0x22; 48],
+ "user",
+ "machine",
+ )
+ .unwrap_err()
+ .to_string(),
+ error
+ );
+ assert_eq!(
+ ClientLicenseInfo::from_server_license_request(
+ &request,
+ None,
+ &[0x11; 32],
+ &[0x22; 48],
+ [0; 4],
+ vec![0x33; 16],
+ )
+ .unwrap_err()
+ .to_string(),
+ error
+ );
+}
+
+// oracle: regression Netcatty #4540; the license certificate takes precedence over a fallback key.
+#[test]
+fn license_responses_ignore_fallback_when_the_license_certificate_is_present() {
+ use crate::rdp::server_license::{ClientLicenseInfo, ClientNewLicenseRequest};
+
+ let LicensePdu::ServerLicenseRequest(request) = &*SERVER_LICENSE_REQUEST else {
+ panic!("expected a Server License Request");
+ };
+ // An invalid fallback would fail DER decoding if it were used.
+ assert!(
+ ClientNewLicenseRequest::from_server_license_request(
+ request,
+ Some(&[0]),
+ &[0x11; 32],
+ &[0x22; 48],
+ "user",
+ "machine",
+ )
+ .is_ok()
+ );
+ assert!(
+ ClientLicenseInfo::from_server_license_request(
+ request,
+ Some(&[0]),
+ &[0x11; 32],
+ &[0x22; 48],
+ [0; 4],
+ vec![0x33; 16],
+ )
+ .is_ok()
+ );
+}
+
+// oracle: regression Netcatty #4540; a malformed license certificate must not trigger fallback.
+#[test]
+fn license_responses_do_not_hide_invalid_certificates_with_the_fallback() {
+ use crate::rdp::server_license::{ClientLicenseInfo, ClientNewLicenseRequest};
+
+ let LicensePdu::ServerLicenseRequest(mut request) =
+ decode::<LicensePdu>(&encode_vec(&*SERVER_LICENSE_REQUEST).unwrap()).unwrap()
+ else {
+ panic!("expected a Server License Request");
+ };
+ let public_key = request.get_public_key().unwrap().unwrap();
+ request.server_certificate = Some(ServerCertificate {
+ issued_permanently: true,
+ certificate: CertificateType::X509(X509CertificateChain {
+ certificate_array: vec![vec![0]],
+ }),
+ });
+ assert!(matches!(
+ ClientNewLicenseRequest::from_server_license_request(
+ &request,
+ Some(&public_key),
+ &[0x11; 32],
+ &[0x22; 48],
+ "user",
+ "machine",
+ ),
+ Err(ServerLicenseError::InvalidX509Certificate { .. })
+ ));
+ assert!(matches!(
+ ClientLicenseInfo::from_server_license_request(
+ &request,
+ Some(&public_key),
+ &[0x11; 32],
+ &[0x22; 48],
+ [0; 4],
+ vec![0x33; 16],
+ ),
+ Err(ServerLicenseError::InvalidX509Certificate { .. })
+ ));
+}
+
+// oracle: regression Netcatty #4540; Python pow(int.from_bytes([0x22] * 48, "little"), 65537, n),
+// with n from the proprietary MCS certificate's little-endian modulus (MS-RDPBCGR 4.1.4).
+#[test]
+fn license_fallback_preserves_the_proprietary_mcs_public_key() {
+ use crate::rdp::server_license::{ClientLicenseInfo, ClientNewLicenseRequest};
+
+ let certificate = ServerCertificate {
+ issued_permanently: true,
+ certificate: CertificateType::Proprietary(decode(&encode_vec(&*PROPRIETARY_CERTIFICATE).unwrap()).unwrap()),
+ };
+ let public_key = certificate.get_server_security_public_key().unwrap();
+ let LicensePdu::ServerLicenseRequest(mut request) =
+ decode::<LicensePdu>(&encode_vec(&*SERVER_LICENSE_REQUEST).unwrap()).unwrap()
+ else {
+ panic!("expected a Server License Request");
+ };
+ request.server_certificate = None;
+ let expected_ciphertext = [
+ 0x97, 0xc6, 0x48, 0x9e, 0x02, 0x1c, 0x44, 0xb2, 0x67, 0x54, 0xd4, 0xbe, 0x10, 0x5a, 0x13, 0xfa, 0x9b, 0x02,
+ 0xc9, 0x65, 0xcf, 0xfe, 0x2b, 0x2f, 0x4d, 0xe2, 0x06, 0xee, 0x7c, 0xeb, 0x58, 0x4c, 0xef, 0x70, 0xc8, 0x06,
+ 0xad, 0x9b, 0xa2, 0x23, 0x4c, 0xd0, 0xe0, 0xa4, 0x34, 0x90, 0x90, 0xdc, 0xd5, 0x13, 0x85, 0x4d, 0x75, 0x25,
+ 0x62, 0x14, 0x4d, 0x66, 0x9f, 0xd6, 0x41, 0xb3, 0x2b, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ ];
+ let (new_request, _) = ClientNewLicenseRequest::from_server_license_request(
+ &request,
+ Some(&public_key),
+ &[0x11; 32],
+ &[0x22; 48],
+ "user",
+ "machine",
+ )
+ .unwrap();
+ assert_eq!(new_request.encrypted_premaster_secret, expected_ciphertext);
+ let (info, _) = ClientLicenseInfo::from_server_license_request(
+ &request,
+ Some(&public_key),
+ &[0x11; 32],
+ &[0x22; 48],
+ [0; 4],
+ vec![0x33; 16],
+ )
+ .unwrap();
+ assert_eq!(info.encrypted_premaster_secret, expected_ciphertext);
+}
diff --git a/crates/ironrdp-testsuite-core/tests/connector/license_exchange.rs b/crates/ironrdp-testsuite-core/tests/connector/license_exchange.rs
index bb5022e3..5d6c4caf 100644
--- a/crates/ironrdp-testsuite-core/tests/connector/license_exchange.rs
+++ b/crates/ironrdp-testsuite-core/tests/connector/license_exchange.rs
@@ -52,10 +52,17 @@ impl LicenseCache for StoredLicense {
}
/// Enters the licensing exchange and answers a Server License Request.
-fn answer_license_request(mut connector: ClientConnector) -> (Vec<u8>, LicenseEncryptionData) {
+fn answer_license_request(connector: ClientConnector) -> (Vec<u8>, LicenseEncryptionData) {
+ answer_license_request_with_certificate(connector, true)
+}
+
+fn answer_license_request_with_certificate(
+ mut connector: ClientConnector,
+ include_certificate: bool,
+) -> (Vec<u8>, LicenseEncryptionData) {
// A Server License Request on the I/O channel, carrying a proprietary certificate with a 512-bit key.
let server_license_request = {
- let license = LicensePdu::ServerLicenseRequest(ServerLicenseRequest {
+ let mut request = ServerLicenseRequest {
license_header: LicenseHeader {
security_header: BasicSecurityHeader {
flags: BasicSecurityHeaderFlags::LICENSE_PKT,
@@ -83,7 +90,11 @@ fn answer_license_request(mut connector: ClientConnector) -> (Vec<u8>, LicenseEn
}),
// The connector looks a license up once per scope, so a stored license needs one to be found.
scope_list: vec![Scope("microsoft.com".to_owned())],
- });
+ };
+ if !include_certificate {
+ request.server_certificate = None;
+ }
+ let license = LicensePdu::ServerLicenseRequest(request);
encode_vec(&X224(McsMessage::SendDataIndication(SendDataIndication {
initiator_id: USER_CHANNEL_ID,
@@ -208,3 +219,80 @@ fn each_connection_gets_new_values_from_the_default_rng() {
second_encryption_data.premaster_secret
);
}
+
+// oracle: regression Netcatty #4540; MCS carries the key that an encrypted session's license request may omit.
+#[rstest::rstest]
+#[case::new_license(false)]
+#[case::cached_license(true)]
+fn licensing_reuses_the_standard_security_public_key(#[case] cached_license: bool) {
+ use ironrdp_pdu::gcc::{ConferenceCreateResponse, EncryptionLevel, EncryptionMethod, ServerSecurityData};
+ use ironrdp_pdu::mcs::ConnectResponse;
+ use ironrdp_pdu::nego::SecurityProtocol;
+ use ironrdp_pdu::x224::X224Data;
+ use ironrdp_testsuite_core::{gcc::SERVER_GCC_WITHOUT_OPTIONAL_FIELDS, mcs::CONNECT_RESPONSE};
+
+ let mut connector = connector();
+ connector.config.enable_standard_rdp_security = true;
+ if cached_license {
+ connector.config.license_cache = Some(Arc::new(StoredLicense(vec![0x33; 16])));
+ }
+ connector.state = ClientConnectorState::BasicSettingsExchangeSendInitial {
+ selected_protocol: SecurityProtocol::empty(),
+ };
+ let mut output = WriteBuf::new();
+ connector.step(&[], None, &mut output).unwrap();
+ output.clear();
+
+ let certificate = ServerCertificate {
+ issued_permanently: true,
+ certificate: CertificateType::Proprietary(ProprietaryCertificate {
+ public_key: RsaPublicKey {
+ public_exponent: 0x0001_0001,
+ modulus: [vec![0xff; 64], vec![0; 8]].concat(),
+ },
+ signature: vec![0; 72],
+ }),
+ };
+ let mut gcc_blocks = SERVER_GCC_WITHOUT_OPTIONAL_FIELDS.clone();
+ gcc_blocks.security = ServerSecurityData {
+ encryption_method: EncryptionMethod::BIT_128,
+ encryption_level: EncryptionLevel::ClientCompatible,
+ server_random: Some([0x44; 32]),
+ server_cert: encode_vec(&certificate).unwrap(),
+ };
+ let response = ConnectResponse {
+ conference_create_response: ConferenceCreateResponse::new(0x79f3, gcc_blocks).unwrap(),
+ ..CONNECT_RESPONSE.clone()
+ };
+ let response = encode_vec(&X224(X224Data {
+ data: Cow::Owned(encode_vec(&response).unwrap()),
+ }))
+ .unwrap();
+ connector.step(&response, None, &mut output).unwrap();
+
+ // Channel joins carry no security data; enter Security Exchange with the MCS data just received.
+ connector.state = ClientConnectorState::SecurityExchange {
+ io_channel_id: IO_CHANNEL_ID,
+ user_channel_id: USER_CHANNEL_ID,
+ };
+ connector.step(&[], None, &mut output).unwrap();
+ let (response, _) = answer_license_request_with_certificate(connector, false);
+ let mut cursor = ReadCursor::new(&response);
+ let header = LicenseHeader::decode(&mut cursor).unwrap();
+ let encrypted_premaster = match header.preamble_message_type {
+ PreambleType::NewLicenseRequest => {
+ assert!(!cached_license);
+ ClientNewLicenseRequest::decode(header, &mut cursor)
+ .unwrap()
+ .encrypted_premaster_secret
+ }
+ PreambleType::LicenseInfo => {
+ assert!(cached_license);
+ ironrdp_pdu::rdp::server_license::ClientLicenseInfo::decode(header, &mut cursor)
+ .unwrap()
+ .encrypted_premaster_secret
+ }
+ _ => panic!("expected a client licensing response"),
+ };
+ assert_eq!(encrypted_premaster.len(), 64 + 8);
+}
diff --git a/crates/ironrdp-testsuite-core/tests/pdu/server_license.rs b/crates/ironrdp-testsuite-core/tests/pdu/server_license.rs
index 59b6b05c..04aff362 100644
--- a/crates/ironrdp-testsuite-core/tests/pdu/server_license.rs
+++ b/crates/ironrdp-testsuite-core/tests/pdu/server_license.rs
@@ -35,6 +35,7 @@ impl LicenseResponse {
match self {
Self::NewLicenseRequest => ClientNewLicenseRequest::from_server_license_request(
license_request,
+ None,
&client_random,
&premaster_secret,
"user",
@@ -43,6 +44,7 @@ impl LicenseResponse {
.is_ok(),
Self::LicenseInfo => ClientLicenseInfo::from_server_license_request(
license_request,
+ None,
&client_random,
&premaster_secret,
[0; 4],