From 883fdaf114b63001687b9b5c7e2d7dfaec1e0083 Mon Sep 17 00:00:00 2001 From: Netcatty-Bot Date: Thu, 26 Nov 2026 00:31:31 +0800 Subject: [PATCH 01/24] Update Nix release metadata for v1.1.91 (#4404) --- nix/release.nix | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nix/release.nix b/nix/release.nix index cc8a35d1d..f060c0f8c 100644 --- a/nix/release.nix +++ b/nix/release.nix @@ -1,14 +1,14 @@ { - version = "1.1.90"; + version = "1.1.91"; sources = { x86_64-linux = { appImageArch = "x86_64"; - hash = "sha256-oa/T3Zey0FHsH+SOt4C1H4CT6aZRJta+x4x/11EAOJE="; + hash = "sha256-+JUalTjinzIH2sIovwtwhEP6IaaYPZDgfPoj0rVDOsM="; }; aarch64-linux = { appImageArch = "arm64"; - hash = "sha256-r5hr3+gpIGrv9XJ7PQkHCdhOd2COkhELMHlnr3xIG7A="; + hash = "sha256-kDwH7pLgaPoC/4AqoQhlZDo8/dbEL9Il2H+mPlUgu64="; }; }; } From 3026be2dc9064636258d7f1ae8c04ec2fa933ec7 Mon Sep 17 00:00:00 2001 From: Radwan Selo <133098464+RadwanSelo@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:29:30 +0900 Subject: [PATCH 02/24] fix(ssh): show the target's label and each hop's address in chain progress (#4413) When connecting through "Proxy via Hosts", the connection dialog named jump hops by their label but the final target by its raw address ("Chain 2 of 2: 192.168.1.10"), and the address line under the heading always showed the target's address, whichever hop was connecting ("Chain 1 of 3: Bastion A" above "SSH 192.168.1.10:22"). Longer chains made this more confusing. - Name the final hop by its vault label (falling back to its address when unlabeled). Direct connections are unchanged. - Send each hop's host:port with chain progress events and show it under the heading for jump hops; the final hop keeps the target's protocol-aware address line (Mosh/ET ports). - Applies to terminal sessions and the host "Test connection" dialog. - Share the host:port formatting for chain hops in chainProgress.cjs. --- application/state/useHostConnectionTest.ts | 5 +- application/state/useTerminalBackend.ts | 2 +- components/Terminal.tsx | 1 + .../terminal/TerminalConnectionDialog.test.ts | 64 ++++++++++++++++++- .../terminal/TerminalConnectionDialog.tsx | 23 ++++++- .../runtime/createTerminalSessionStarters.ts | 7 +- .../createTerminalSessionStarters.types.ts | 4 +- .../bridges/sshBridge.authRetryExit.test.cjs | 44 +++++++++++++ electron/bridges/sshBridge.cjs | 9 ++- electron/bridges/sshBridge/chainProgress.cjs | 44 +++++++++++++ .../bridges/sshBridge/chainProgress.test.cjs | 46 +++++++++++++ electron/bridges/sshBridge/startSession.cjs | 63 ++++++++++-------- electron/preload.cjs | 4 +- types/global/netcatty-bridge-sync.d.ts | 5 +- 14 files changed, 284 insertions(+), 37 deletions(-) create mode 100644 electron/bridges/sshBridge/chainProgress.cjs create mode 100644 electron/bridges/sshBridge/chainProgress.test.cjs diff --git a/application/state/useHostConnectionTest.ts b/application/state/useHostConnectionTest.ts index edb1a1519..6558ae064 100644 --- a/application/state/useHostConnectionTest.ts +++ b/application/state/useHostConnectionTest.ts @@ -15,6 +15,8 @@ export type ChainProgress = { currentHop: number; totalHops: number; currentHostLabel: string; + /** host:port of the hop being connected; absent from older progress events. */ + currentHostAddress?: string; connectionPhase: string; } | null; @@ -117,13 +119,14 @@ export function useHostConnectionTest(input: HostConnectionTestInput) { // Subscribe to chain progress for the active attempt. useEffect(() => { - const unsub = backend.onChainProgress?.((sessionId, hop, total, label, phase, phaseError) => { + const unsub = backend.onChainProgress?.((sessionId, hop, total, label, phase, phaseError, address) => { if (sessionId !== sessionIdRef.current) return; if (total > 1) { setChainProgress({ currentHop: hop, totalHops: total, currentHostLabel: label, + currentHostAddress: address, connectionPhase: phase, }); } diff --git a/application/state/useTerminalBackend.ts b/application/state/useTerminalBackend.ts index 78c821ff0..5f218ad69 100644 --- a/application/state/useTerminalBackend.ts +++ b/application/state/useTerminalBackend.ts @@ -419,7 +419,7 @@ export const useTerminalBackend = () => { return bridge.getTelnetEchoMode(sessionId); }, []); - const onChainProgress = useCallback((cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void) => { + const onChainProgress = useCallback((cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string, address?: string) => void) => { const bridge = netcattyBridge.get(); return bridge?.onChainProgress?.(cb); }, []); diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 5b9c3c8fa..984e2ee6c 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -1020,6 +1020,7 @@ const TerminalComponent: React.FC = ({ currentHop: number; totalHops: number; currentHostLabel: string; + currentHostAddress?: string; connectionPhase: string; } | null>(null); const [isConnectionAwaitingUserInput, setIsConnectionAwaitingUserInput] = useState(false); diff --git a/components/terminal/TerminalConnectionDialog.test.ts b/components/terminal/TerminalConnectionDialog.test.ts index f17ae97dd..70e871bd9 100644 --- a/components/terminal/TerminalConnectionDialog.test.ts +++ b/components/terminal/TerminalConnectionDialog.test.ts @@ -5,7 +5,7 @@ import { renderToStaticMarkup } from "react-dom/server"; import { I18nProvider } from "../../application/i18n/I18nProvider.tsx"; import type { Host } from "../../types.ts"; -import { TerminalConnectionDialog } from "./TerminalConnectionDialog.tsx"; +import { TerminalConnectionDialog, resolveChainProgressAddressLine } from "./TerminalConnectionDialog.tsx"; const host: Host = { id: "host-1", @@ -193,6 +193,68 @@ test("keeps connection log padding inside the scrollable content", () => { assert.match(markup, /class="[^"]*p-2\.5[^"]*pb-4[^"]*pr-4/); }); +test("chain progress shows the current jump hop's address, not the target's", () => { + const markup = renderDialog({ + host: { ...host, label: "Prod DB", hostname: "10.0.0.5" }, + chainProgress: { + currentHop: 2, + totalHops: 3, + currentHostLabel: "Bastion B", + currentHostAddress: "b.example.com:2201", + }, + }); + + assert.match(markup, /Chain 2 of 3: <\/span>Bastion B<\/span>/); + assert.match(markup, /SSH b\.example\.com:2201/); + assert.equal(markup.includes("10.0.0.5"), false); +}); + +test("chain progress shows the target's label and address on the final hop", () => { + const markup = renderDialog({ + host: { ...host, label: "Prod DB", hostname: "10.0.0.5" }, + chainProgress: { + currentHop: 3, + totalHops: 3, + currentHostLabel: "Prod DB", + currentHostAddress: "10.0.0.5:22", + }, + }); + + assert.match(markup, /Chain 3 of 3: <\/span>Prod DB<\/span>/); + assert.match(markup, /SSH 10\.0\.0\.5:22/); +}); + +test("chain progress address line keeps the target's protocol on the final hop", () => { + const t = (key: string) => ({ + "terminal.connection.protocol.ssh": "SSH", + "terminal.connection.protocol.et": "ET", + }[key] ?? key); + const etInfo = { i18nKey: "terminal.connection.protocol.et", showPort: true, port: 2022 }; + const target = { hostname: "10.0.0.5" }; + + // Jump hop: always SSH with the hop's own address. + assert.equal( + resolveChainProgressAddressLine( + { currentHop: 1, totalHops: 2, currentHostAddress: "bastion.example.com:22" }, + target, etInfo, t, + ), + "SSH bastion.example.com:22", + ); + // Final hop: the target's protocol and port (ET 2022, not the SSH port). + assert.equal( + resolveChainProgressAddressLine( + { currentHop: 2, totalHops: 2, currentHostAddress: "10.0.0.5:22" }, + target, etInfo, t, + ), + "ET 10.0.0.5:2022", + ); + // Older progress events without an address fall back to the target. + assert.equal( + resolveChainProgressAddressLine({ currentHop: 1, totalHops: 2 }, target, etInfo, t), + "ET 10.0.0.5:2022", + ); +}); + test("shows the ET server port (not the SSH port) for an ET host with a custom etPort", () => { const markup = renderDialog({ host: { ...host, etEnabled: true, port: 22, etPort: 9022 }, diff --git a/components/terminal/TerminalConnectionDialog.tsx b/components/terminal/TerminalConnectionDialog.tsx index 6e1e59f1d..bdee750b2 100644 --- a/components/terminal/TerminalConnectionDialog.tsx +++ b/components/terminal/TerminalConnectionDialog.tsx @@ -28,8 +28,29 @@ export interface ChainProgress { currentHop: number; totalHops: number; currentHostLabel: string; + /** host:port of the hop being connected; falls back to the target's address. */ + currentHostAddress?: string; } +/** + * Address line under the "Chain X of Y" heading. Jump hops are always SSH, so + * they show the hop's own address; the final hop keeps the target's + * protocol-aware line (Mosh/ET/Telnet ports differ from the SSH port). + */ +export const resolveChainProgressAddressLine = ( + chainProgress: Pick, + host: Pick, + protocolInfo: { i18nKey: string; showPort: boolean; port: number }, + t: (key: string) => string, +): string => { + const isJumpHop = chainProgress.currentHop < chainProgress.totalHops; + if (isJumpHop && chainProgress.currentHostAddress) { + return `${t('terminal.connection.protocol.ssh')} ${chainProgress.currentHostAddress}`; + } + const address = protocolInfo.showPort ? formatHostPort(host.hostname, protocolInfo.port) : host.hostname; + return `${t(protocolInfo.i18nKey)} ${address}`; +}; + export interface TerminalConnectionDialogProps { host: Host; status: 'connecting' | 'connected' | 'disconnected'; @@ -304,7 +325,7 @@ export const TerminalConnectionDialog: React.FC = className="text-[10px] font-mono truncate" style={{ color: 'color-mix(in srgb, var(--terminal-ui-fg, var(--foreground)) 58%, transparent)' }} > - {t(protocolInfo.i18nKey)} {protocolInfo.showPort ? formatHostPort(host.hostname, protocolInfo.port) : host.hostname} + {resolveChainProgressAddressLine(chainProgress, host, protocolInfo, t)} ) : ( diff --git a/components/terminal/runtime/createTerminalSessionStarters.ts b/components/terminal/runtime/createTerminalSessionStarters.ts index a7e956c46..0179cf6c1 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.ts @@ -41,6 +41,7 @@ import { resolveBridgeSshAgentAuth, resolveHostAuth } from "../../../domain/sshA import { connectionTotpFields } from "../../../domain/totpConfig"; import { requiresFidoSshAgentAuth } from "../../../domain/fidoSsh"; import { + formatHostPort, hostRestrictsExtraSshChannels, resolveHostKeepalive, resolveTelnetPassword, @@ -642,12 +643,15 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex totalHops, currentHostLabel: jumpHosts[0]?.label || jumpHosts[0]?.hostname || ctx.host.hostname, + currentHostAddress: jumpHosts[0]?.hostname + ? formatHostPort(jumpHosts[0].hostname, jumpHosts[0].port || 22) + : undefined, connectionPhase: 'connecting', }); } { - const unsub = ctx.terminalBackend.onChainProgress((sid, hop, total, label, status, error) => { + const unsub = ctx.terminalBackend.onChainProgress((sid, hop, total, label, status, error, address) => { // P1: Only process events for this session if (sid !== ctx.sessionId) return; // Disconnect/reconnect can leave two SSH starts sharing this UI @@ -660,6 +664,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex currentHop: hop, totalHops: total, currentHostLabel: label, + currentHostAddress: address, connectionPhase: status, }); } diff --git a/components/terminal/runtime/createTerminalSessionStarters.types.ts b/components/terminal/runtime/createTerminalSessionStarters.types.ts index d30c4550c..2b7b46784 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.types.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.types.ts @@ -95,7 +95,7 @@ export type TerminalBackendApi = { error?: string; }>; onChainProgress: ( - cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void, + cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string, address?: string) => void, ) => (() => void) | undefined; onConnectionReuseFallback?: ( cb: (sessionId: string, sourceSessionId?: string) => void, @@ -126,6 +126,8 @@ type ChainProgressState = { currentHop: number; totalHops: number; currentHostLabel: string; + /** host:port of the hop being connected; absent from older progress events. */ + currentHostAddress?: string; connectionPhase: string; } | null; diff --git a/electron/bridges/sshBridge.authRetryExit.test.cjs b/electron/bridges/sshBridge.authRetryExit.test.cjs index e65ea560e..631734c17 100644 --- a/electron/bridges/sshBridge.authRetryExit.test.cjs +++ b/electron/bridges/sshBridge.authRetryExit.test.cjs @@ -1562,6 +1562,50 @@ test("jump-host auth failure does not emit exit before encrypted-key retry succe ); }); +test("chain progress names every hop by its label and reports each hop's address", async (t) => { + const { bridge } = loadBridgeWithAuthRetryMocks(t, { + connectEvents: ["ready", "ready", "ready"], + encryptedKeys: [], + }); + const ipcMain = makeIpcMain(); + bridge.init({ sessions: new Map(), electronModule: {} }); + bridge.registerHandlers(ipcMain); + const start = ipcMain.handlers.get("netcatty:start"); + const sender = makeSender(); + + const result = await start( + { sender }, + { + sessionId: "chain-label-session", + hostname: "10.0.0.5", + hostLabel: "Prod DB", + username: "alice", + port: 22, + knownHosts: [], + jumpHosts: [ + { hostname: "a.example.com", username: "alice", port: 22, label: "Bastion A" }, + { hostname: "b.example.com", username: "alice", port: 2201 }, + ], + }, + ); + + assert.deepEqual(result, { sessionId: "chain-label-session" }); + const progress = sender.sent + .filter((message) => message.channel === "netcatty:chain:progress") + .map((message) => message.payload); + const hopSummary = (hop) => [ + ...new Set(progress.filter((p) => p.hop === hop).map((p) => `${p.label} @ ${p.address}`)), + ]; + + assert.ok(progress.every((p) => p.total === 3)); + assert.deepEqual(hopSummary(1), ["Bastion A @ a.example.com:22"]); + // An unlabeled jump host keeps its host:port label. + assert.deepEqual(hopSummary(2), ["b.example.com:2201 @ b.example.com:2201"]); + // The final target is named by its label, not its raw IP. + assert.deepEqual(hopSummary(3), ["Prod DB @ 10.0.0.5:22"]); + assert.ok(progress.some((p) => p.hop === 3 && p.status === "connected")); +}); + test("jump-host auth failure is attributed to the failing jump host", async (t) => { const { bridge } = loadBridgeWithAuthRetryMocks(t, { connectEvents: ["auth-error"], diff --git a/electron/bridges/sshBridge.cjs b/electron/bridges/sshBridge.cjs index 5e07032bc..27b4ac423 100644 --- a/electron/bridges/sshBridge.cjs +++ b/electron/bridges/sshBridge.cjs @@ -64,6 +64,10 @@ const { } = require("./sshAlgorithms.cjs"); const { enableSshNoDelay, enableTcpNoDelay } = require("./tcpNoDelay.cjs"); const { createSshPingLatencyProbe } = require("./sshBridge/sshPingLatency.cjs"); +const { + formatChainHopAddress, + resolveChainHopAddress, +} = require("./sshBridge/chainProgress.cjs"); const { configureTerminalSessionDataEmitter, } = require("./emitTerminalSessionData.cjs"); @@ -376,7 +380,8 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target const sendProgress = (hop, total, label, status, error) => { if (!sender.isDestroyed()) { - sender.send("netcatty:chain:progress", { sessionId, hop, total, label, status, error }); + const address = resolveChainHopAddress(jumpHosts, targetHost, targetPort, hop); + sender.send("netcatty:chain:progress", { sessionId, hop, total, label, status, error, address }); } }; @@ -388,7 +393,7 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target const jump = jumpHosts[i]; const isFirst = i === 0; const isLast = i === jumpHosts.length - 1; - const hopLabel = jump.label || (jump.hostname.includes(':') && !jump.hostname.startsWith('[') ? `[${jump.hostname}]:${jump.port || 22}` : `${jump.hostname}:${jump.port || 22}`); + const hopLabel = jump.label || formatChainHopAddress(jump.hostname, jump.port); sendProgress(i + 1, totalHops + 1, hopLabel, 'connecting'); diff --git a/electron/bridges/sshBridge/chainProgress.cjs b/electron/bridges/sshBridge/chainProgress.cjs new file mode 100644 index 000000000..2ae122ffe --- /dev/null +++ b/electron/bridges/sshBridge/chainProgress.cjs @@ -0,0 +1,44 @@ +"use strict"; + +/** + * Helpers for `netcatty:chain:progress` events sent while connecting through + * jump hosts. Each event names the hop being connected (`label`) and its + * network address (`address`), so the connection dialog can show + * "Chain 2 of 3: Prod DB" with the matching "SSH 10.0.0.5:22" below it. + */ + +/** Format `host:port`, bracketing bare IPv6 literals (`[::1]:22`). */ +function formatChainHopAddress(hostname, port) { + const host = String(hostname || ""); + const display = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; + return `${display}:${port || 22}`; +} + +/** + * Address of the 1-based `hop` in a chain of `jumpHosts` followed by the + * final target. Hops past the jump hosts are the target. + */ +function resolveChainHopAddress(jumpHosts, targetHostname, targetPort, hop) { + const jumps = Array.isArray(jumpHosts) ? jumpHosts : []; + const jump = hop >= 1 && hop <= jumps.length ? jumps[hop - 1] : null; + if (jump) return formatChainHopAddress(jump.hostname, jump.port); + return formatChainHopAddress(targetHostname, targetPort); +} + +/** + * Label for the final target in chain progress. Jump hops already show their + * vault label; the target should too, instead of its raw address. Direct + * (single-hop) connections keep the address, which the dialog does not use + * as a chain heading. + */ +function resolveChainTargetLabel(options, hasJumpHosts) { + const hostname = options?.hostname || ""; + if (!hasJumpHosts) return hostname; + return options?.hostLabel || options?.label || hostname; +} + +module.exports = { + formatChainHopAddress, + resolveChainHopAddress, + resolveChainTargetLabel, +}; diff --git a/electron/bridges/sshBridge/chainProgress.test.cjs b/electron/bridges/sshBridge/chainProgress.test.cjs new file mode 100644 index 000000000..e64bf9b7b --- /dev/null +++ b/electron/bridges/sshBridge/chainProgress.test.cjs @@ -0,0 +1,46 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + formatChainHopAddress, + resolveChainHopAddress, + resolveChainTargetLabel, +} = require("./chainProgress.cjs"); + +test("formatChainHopAddress formats host:port and brackets bare IPv6", () => { + assert.equal(formatChainHopAddress("10.0.0.5", 22), "10.0.0.5:22"); + assert.equal(formatChainHopAddress("bastion.example.com", 2222), "bastion.example.com:2222"); + assert.equal(formatChainHopAddress("10.0.0.5"), "10.0.0.5:22"); + assert.equal(formatChainHopAddress("fd00::5", 22), "[fd00::5]:22"); + assert.equal(formatChainHopAddress("[fd00::5]", 22), "[fd00::5]:22"); +}); + +test("resolveChainHopAddress maps each hop of a long chain to its own address", () => { + const jumps = [ + { hostname: "a.example.com", port: 22 }, + { hostname: "b.example.com", port: 2201 }, + { hostname: "fd00::c" }, + ]; + assert.equal(resolveChainHopAddress(jumps, "10.0.0.5", 22, 1), "a.example.com:22"); + assert.equal(resolveChainHopAddress(jumps, "10.0.0.5", 22, 2), "b.example.com:2201"); + assert.equal(resolveChainHopAddress(jumps, "10.0.0.5", 22, 3), "[fd00::c]:22"); + // The hop after the last jump host is the target. + assert.equal(resolveChainHopAddress(jumps, "10.0.0.5", 22, 4), "10.0.0.5:22"); + // A direct connection only has the target. + assert.equal(resolveChainHopAddress(undefined, "10.0.0.5", 2222, 1), "10.0.0.5:2222"); +}); + +test("resolveChainTargetLabel names a chained target by its label, not its address", () => { + assert.equal( + resolveChainTargetLabel({ hostname: "10.0.0.5", hostLabel: "Prod DB" }, true), + "Prod DB", + ); + assert.equal(resolveChainTargetLabel({ hostname: "10.0.0.5", label: "Prod DB" }, true), "Prod DB"); + // Unlabeled target falls back to its address. + assert.equal(resolveChainTargetLabel({ hostname: "10.0.0.5", hostLabel: "" }, true), "10.0.0.5"); + // Direct connections keep the address (unchanged behavior). + assert.equal( + resolveChainTargetLabel({ hostname: "10.0.0.5", hostLabel: "Prod DB" }, false), + "10.0.0.5", + ); +}); diff --git a/electron/bridges/sshBridge/startSession.cjs b/electron/bridges/sshBridge/startSession.cjs index aa2b08384..ffffc40c3 100644 --- a/electron/bridges/sshBridge/startSession.cjs +++ b/electron/bridges/sshBridge/startSession.cjs @@ -31,6 +31,10 @@ const { buildRemoteShellExitPayload, normalizeRemoteExitSignal, } = require("./remoteShellExit.cjs"); +const { + resolveChainHopAddress, + resolveChainTargetLabel, +} = require("./chainProgress.cjs"); const { looksLikeSkOpenSshMaterial } = require("../sshAuthHelper.cjs"); const SSH_TCP_CONNECT_TIMEOUT_MS = 20000; @@ -1521,7 +1525,13 @@ function createStartSessionApi(ctx) { const sendProgress = (hop, total, label, status, error) => { if (!sender.isDestroyed()) { - sender.send("netcatty:chain:progress", { sessionId, hop, total, label, status, error }); + const address = resolveChainHopAddress( + options.jumpHosts, + options.hostname, + options.port, + hop, + ); + sender.send("netcatty:chain:progress", { sessionId, hop, total, label, status, error, address }); } }; @@ -1557,6 +1567,9 @@ function createStartSessionApi(ctx) { const hasJumpHosts = jumpHosts.length > 0; const hasProxy = !!options.proxy; const totalHops = jumpHosts.length + 1; // +1 for final target + // Name the final hop by its vault label (like the jump hops) instead of + // its raw address; the address is sent separately per hop. + const targetProgressLabel = resolveChainTargetLabel(options, hasJumpHosts); // Build base connection options for final target const keepalivePolicy = resolveConnectionKeepalivePolicy(options); @@ -1708,10 +1721,10 @@ function createStartSessionApi(ctx) { bootEpoch: options.bootEpoch, logPrefix: "[SSH]", onPassphrasePromptShown: () => sendProgress( - totalHops, totalHops, options.hostname, "auth-attempt", "waiting for user input...", + totalHops, totalHops, targetProgressLabel, "auth-attempt", "waiting for user input...", ), onPassphrasePromptResolved: () => sendProgress( - totalHops, totalHops, options.hostname, "auth-attempt", "user responded", + totalHops, totalHops, targetProgressLabel, "auth-attempt", "user responded", ), onLoaded: (loaded) => { log("Loaded identity file", { keyPath: loaded.keyPath, encrypted: !!loaded.passphrase }); @@ -1737,10 +1750,10 @@ function createStartSessionApi(ctx) { bootEpoch: options.bootEpoch, logPrefix: "[SSH]", onPassphrasePromptShown: () => sendProgress( - totalHops, totalHops, options.hostname, "auth-attempt", "waiting for user input...", + totalHops, totalHops, targetProgressLabel, "auth-attempt", "waiting for user input...", ), onPassphrasePromptResolved: () => sendProgress( - totalHops, totalHops, options.hostname, "auth-attempt", "user responded", + totalHops, totalHops, targetProgressLabel, "auth-attempt", "user responded", ), }) : null; @@ -2057,7 +2070,7 @@ function createStartSessionApi(ctx) { // Log rejection of previous method if (lastTriedMethod && !partialSuccess) { - sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', `${lastTriedMethod} rejected`); + sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', `${lastTriedMethod} rejected`); if ( lastTriedMethod === "password" && passwordAttemptSawKeyboardInteractive && @@ -2081,7 +2094,7 @@ function createStartSessionApi(ctx) { if (methodsLeft === null && !attemptedMethodIds.has("none")) { attemptedMethodIds.add("none"); lastTriedMethod = "none"; - sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', 'none (no credentials)'); + sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'none (no credentials)'); return callback("none"); } @@ -2218,7 +2231,7 @@ function createStartSessionApi(ctx) { // Only log safe identifier, not the full agent object which may contain private keys const agentType = typeof method.agent === "string" ? "path" : "NetcattyAgent"; log("Trying agent auth", { id: method.id, agentType }); - sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', 'SSH agent'); + sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'SSH agent'); return method.agent === connectOpts.agent ? callback("agent") : callback({ @@ -2235,7 +2248,7 @@ function createStartSessionApi(ctx) { : method.id === "publickey-user" ? "configured key" : method.id; - sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', keyLabel); + sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', keyLabel); return callback({ type: "publickey", username: connectOpts.username, @@ -2244,7 +2257,7 @@ function createStartSessionApi(ctx) { }); } else if (method.type === "password") { log("Trying password auth", { id: method.id }); - sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', 'password'); + sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'password'); passwordAttemptSawKeyboardInteractive = availableMethods.includes("keyboard-interactive"); return callback({ type: "password", @@ -2253,7 +2266,7 @@ function createStartSessionApi(ctx) { }); } else if (method.type === "keyboard-interactive") { log("Trying keyboard-interactive auth", { id: method.id }); - sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', 'keyboard-interactive'); + sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'keyboard-interactive'); // Return string instead of object - ssh2 requires a prompt function // for keyboard-interactive objects. Returning the string lets ssh2 // use its default handling and trigger the keyboard-interactive event. @@ -2262,7 +2275,7 @@ function createStartSessionApi(ctx) { } log("All auth methods exhausted"); - sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', 'all methods exhausted'); + sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'all methods exhausted'); return callback(false); }; @@ -2313,7 +2326,7 @@ function createStartSessionApi(ctx) { delete connectOpts.host; delete connectOpts.port; - sendProgress(totalHops, totalHops, options.hostname, 'connecting'); + sendProgress(totalHops, totalHops, targetProgressLabel, 'connecting'); } else if (hasProxy) { sendProgress(1, 1, options.hostname, 'connecting'); connectionSocket = await createProxySocket( @@ -2391,7 +2404,7 @@ function createStartSessionApi(ctx) { elapsedMs: Date.now() - connectionStartedAt, authReadyTimeoutMs, }); - sendProgress(totalHops, totalHops, options.hostname, 'tcp-connected'); + sendProgress(totalHops, totalHops, targetProgressLabel, 'tcp-connected'); enableSshNoDelay(conn); }); }); @@ -2405,7 +2418,7 @@ function createStartSessionApi(ctx) { hostname: options.hostname, elapsedMs: Date.now() - connectionStartedAt, }); - sendProgress(totalHops, totalHops, options.hostname, 'authenticating'); + sendProgress(totalHops, totalHops, targetProgressLabel, 'authenticating'); }); conn.on("banner", (message) => { @@ -2436,7 +2449,7 @@ function createStartSessionApi(ctx) { } } - sendProgress(totalHops, totalHops, options.hostname, 'authenticated'); + sendProgress(totalHops, totalHops, targetProgressLabel, 'authenticated'); if (testMode) { // Headless connection test: authentication succeeded. Report the @@ -2462,7 +2475,7 @@ function createStartSessionApi(ctx) { return; } - sendProgress(totalHops, totalHops, options.hostname, 'shell'); + sendProgress(totalHops, totalHops, targetProgressLabel, 'shell'); let establishedOwnerSession = null; const sendTerminalMessage = (data) => { @@ -2525,12 +2538,12 @@ function createStartSessionApi(ctx) { if (options.x11Forwarding && /x11/i.test(err.message || "")) { sendTerminalMessage("\r\n[X11] Could not enable X11 forwarding. Make sure X11 forwarding is allowed on the server and xauth is installed.\r\n"); } - sendProgress(totalHops, totalHops, options.hostname, 'error', `Failed to open shell: ${err.message}`); + sendProgress(totalHops, totalHops, targetProgressLabel, 'error', `Failed to open shell: ${err.message}`); reject(err); return; } - sendProgress(totalHops, totalHops, options.hostname, 'connected'); + sendProgress(totalHops, totalHops, targetProgressLabel, 'connected'); // Create the shared reference-counted descriptor for this // connection now that the owning channel is open, then wire the @@ -2667,7 +2680,7 @@ function createStartSessionApi(ctx) { } const visibleError = userVisibleSshErrorMessage(err, options); - sendProgress(totalHops, totalHops, options.hostname, 'error', visibleError); + sendProgress(totalHops, totalHops, targetProgressLabel, 'error', visibleError); const suppressPreShellAuthExit = Boolean(options._suppressPreShellAuthExit && isAuthError); if (suppressPreShellAuthExit) { log("suppressing pre-shell auth exit for wrapper-managed retry", { @@ -2712,7 +2725,7 @@ function createStartSessionApi(ctx) { authReadyTimeoutMs, }); const contents = event.sender; - sendProgress(totalHops, totalHops, options.hostname, 'error', err.message); + sendProgress(totalHops, totalHops, targetProgressLabel, 'error', err.message); safeSendSessionExit({ safeSend, electronModule, sessions }, contents, sessionId, { sessionId, exitCode: 1, error: err.message, reason: "timeout" }); sessionLogStreamManager.stopStream(sessionId, ownerLogStreamToken); sessions.get(sessionId)?.zmodemSentry?.cancel(); @@ -2743,7 +2756,7 @@ function createStartSessionApi(ctx) { transportError: ownsCurrentSession ? currentSession?._transportError : undefined, }); if (!settled) { - sendProgress(totalHops, totalHops, options.hostname, 'error', `Connection to ${options.hostname} closed unexpectedly`); + sendProgress(totalHops, totalHops, targetProgressLabel, 'error', `Connection to ${options.hostname} closed unexpectedly`); } // This handler owns teardown for the *owner* session only. ssh2 // fires conn "close" before the owner's stream "close" on a @@ -2844,14 +2857,14 @@ function createStartSessionApi(ctx) { getAuthBanner: () => authBanner, shouldSkipAutoFill: () => shouldSkipKiPasswordAutoFill(authPhase), onAutoFill: (kind) => sendProgress( - totalHops, totalHops, options.hostname, 'auth-attempt', + totalHops, totalHops, targetProgressLabel, 'auth-attempt', kind === 'totp' ? 'using authenticator code' : 'using saved password', ), onPromptShown: () => sendProgress( - totalHops, totalHops, options.hostname, 'auth-attempt', 'waiting for user input...', + totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'waiting for user input...', ), onUserResponded: () => sendProgress( - totalHops, totalHops, options.hostname, 'auth-attempt', 'user responded', + totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'user responded', ), })); diff --git a/electron/preload.cjs b/electron/preload.cjs index 82c39baa5..7b153051e 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -493,11 +493,11 @@ ipcRenderer.on("netcatty:exit", (_event, payload) => { // Chain progress events (for jump host connections) ipcRenderer.on("netcatty:chain:progress", (_event, payload) => { - const { sessionId, hop, total, label, status, error } = payload; + const { sessionId, hop, total, label, status, error, address } = payload; // Notify all registered chain progress listeners chainProgressListeners.forEach((cb) => { try { - cb(sessionId, hop, total, label, status, error); + cb(sessionId, hop, total, label, status, error, address); } catch (err) { console.error("Chain progress callback failed", err); } diff --git a/types/global/netcatty-bridge-sync.d.ts b/types/global/netcatty-bridge-sync.d.ts index 0306b4e6c..86953de56 100644 --- a/types/global/netcatty-bridge-sync.d.ts +++ b/types/global/netcatty-bridge-sync.d.ts @@ -310,8 +310,9 @@ declare global { onLanguageChanged?(cb: (language: string) => void): () => void; // Chain progress listener for jump host connections - // Callback receives: (sessionId: string, currentHop: number, totalHops: number, hostLabel: string, status: string, error?: string) - onChainProgress?(cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void): () => void; + // Callback receives: (sessionId: string, currentHop: number, totalHops: number, hostLabel: string, status: string, error?: string, address?: string) + // `address` is the current hop's host:port, so the UI can show the hop being connected. + onChainProgress?(cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string, address?: string) => void): () => void; // Fired when a requested SSH connection reuse cannot be honored and the // session falls back to a regular fresh connection. From d556e5c5dedb841a8006c98bebb8cf7489c0185d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:21:06 +0800 Subject: [PATCH 03/24] fix(mcp): recognize short decorative tokens before idle prompts (#4420) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Leading theme glyphs such as ⚡ made the POSIX and Powerline idle-prompt whitelists miss, so terminal_execute waited out the default 30s probe and returned SHELL_READINESS_UNKNOWN. Strip a 1-4 character decorative prefix for recognition only; keep the original prompt text for suffix matching. Related #4354 --- electron/bridges/ai/shellUtils.cjs | 27 ++++++++++++------- electron/bridges/ai/shellUtils.test.cjs | 36 +++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 10 deletions(-) diff --git a/electron/bridges/ai/shellUtils.cjs b/electron/bridges/ai/shellUtils.cjs index e003a6292..eb3c89a84 100644 --- a/electron/bridges/ai/shellUtils.cjs +++ b/electron/bridges/ai/shellUtils.cjs @@ -169,22 +169,29 @@ function isDefaultCmdPromptLine(line) { return CMD_PROMPT_PATTERN.test(String(line || "").replace(/\s+$/, "")); } +function stripLeadingDecorativeToken(line) { + // Optional short decorative token, stripped only for recognition (#4354). + return line.replace(/^\s*[^\s\w\p{L}\p{N}@:#$\\\/>\[\]().]{1,4}\s+/u, ""); +} + function isDefaultPosixPromptLine(line) { const normalized = String(line || "").replace(/\s+$/, ""); // Optional virtualenv / conda / BT-panel style env name prefix: "(name) " // before the shell prompt. Recognition only; callers still return the full // prompt line so suffix matching sees the visible prefix (#3947). const withoutEnvPrefix = normalized.replace(/^\([^()\n\r]+\)\s+/, ""); - return ( - POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) || - BRACKET_TIME_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) || - PAREN_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) || - ALPINE_PROMPT_PATTERN.test(withoutEnvPrefix) || - MACOS_ROOT_PROMPT_PATTERN.test(withoutEnvPrefix) || - ZSH_PROMPT_PATTERN.test(withoutEnvPrefix) || - POWERLEVEL10K_PROMPT_PATTERN.test(withoutEnvPrefix) || - POWERLINE_PROMPT_PATTERN.test(withoutEnvPrefix) || - OH_MY_ZSH_ROBBYRUSSELL_PROMPT_PATTERN.test(withoutEnvPrefix) + return [withoutEnvPrefix, stripLeadingDecorativeToken(withoutEnvPrefix)].some( + (prompt) => ( + POSIX_PROMPT_PATTERN.test(prompt) || + BRACKET_TIME_POSIX_PROMPT_PATTERN.test(prompt) || + PAREN_POSIX_PROMPT_PATTERN.test(prompt) || + ALPINE_PROMPT_PATTERN.test(prompt) || + MACOS_ROOT_PROMPT_PATTERN.test(prompt) || + ZSH_PROMPT_PATTERN.test(prompt) || + POWERLEVEL10K_PROMPT_PATTERN.test(prompt) || + POWERLINE_PROMPT_PATTERN.test(prompt) || + OH_MY_ZSH_ROBBYRUSSELL_PROMPT_PATTERN.test(prompt) + ), ); } diff --git a/electron/bridges/ai/shellUtils.test.cjs b/electron/bridges/ai/shellUtils.test.cjs index ca97b8cc8..c5b01266d 100644 --- a/electron/bridges/ai/shellUtils.test.cjs +++ b/electron/bridges/ai/shellUtils.test.cjs @@ -454,6 +454,42 @@ test("Powerline recognition preserves existing idle prompt recognition", () => { assert.equal(extractTrailingIdlePrompt(twoLinePrompt), twoLinePrompt); }); +test("isDefaultPosixPromptLine matches short decorative prefixes and keeps the full prompt", () => { + for (const prompt of [ + "root@testhost:~# ", + " root@testhost \uE0B0 ~ \uE0B0 ", + "\u26A1 root@testhost:~# ", + "\u26A1 root@testhost:~#", + " \u26A1 root@testhost:~# ", + "\u26A1\uFE0F root@testhost:~# ", + "\u26A1\uFE0E root@testhost:~# ", + " \u26A1 root@testhost \uE0B0 ~ \uE0B0 ", + "(venv) \u26A1 root@testhost:~# ", + "\u26A1\u26A1\u26A1\u26A1 root@testhost:~# ", + "\u{1F680}\u{1F680}\u{1F680}\u{1F680} root@testhost:~# ", + ]) { + assert.equal(isDefaultPosixPromptLine(prompt), true, prompt); + assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt); + } +}); + +test("decorative prefix recognition rejects pending input and non-decorative prefixes", () => { + for (const line of [ + "\u26A1 root@testhost:~# echo hi", + " \u26A1 root@testhost \uE0B0 ~ \uE0B0 ls", + "OK root@testhost:~# ", + "yes root@testhost:~# ", + "git:(main) root@testhost:~# ", + "\u26A1\u26A1\u26A1\u26A1\u26A1 root@testhost:~# ", + "\u{1F680}\u{1F680}\u{1F680}\u{1F680}\u{1F680} root@testhost:~# ", + ...["\u00E9", "\u4E2D", "\u0661", "_", "@", ":", "#", "$", "\\", "/", ">", "[", "]", "(", ")", "."] + .map(prefix => `${prefix} root@testhost:~# `), + ]) { + assert.equal(isDefaultPosixPromptLine(line), false, line); + assert.equal(extractTrailingIdlePrompt(`welcome\r\n${line}`), "", line); + } +}); + test("trackSessionIdlePrompt and getFreshIdlePrompt accept a Powerlevel10k ❯ prompt", () => { const session = {}; trackSessionIdlePrompt(session, "Last login...\r\n~ ❯ "); From ac8869884f19c2b00ca3a26cd1d63636737b4cd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:59:12 +0800 Subject: [PATCH 04/24] fix(vault): normalize Host Details group paths only when the group changes (#4427) * fix(vault): normalize changed Host Details group paths Preserve unchanged legacy group paths to avoid changing connection defaults. Fixes #4426 * fix(vault): normalize explicitly selected trimmed group paths Related #4426 --- .../HostDetailsPanel.groupPath.test.tsx | 160 ++++++++++++++++++ components/HostDetailsPanel.tsx | 43 +++-- components/LocalShellHostDetailsPanel.tsx | 10 +- components/SerialHostDetailsPanel.tsx | 6 +- domain/hostGroupPathMutations.test.ts | 34 ++++ domain/hostGroupPathMutations.ts | 10 ++ 6 files changed, 243 insertions(+), 20 deletions(-) create mode 100644 components/HostDetailsPanel.groupPath.test.tsx diff --git a/components/HostDetailsPanel.groupPath.test.tsx b/components/HostDetailsPanel.groupPath.test.tsx new file mode 100644 index 000000000..fba77e539 --- /dev/null +++ b/components/HostDetailsPanel.groupPath.test.tsx @@ -0,0 +1,160 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; +import React from 'react'; +import { act, create, type ReactTestRenderer } from 'react-test-renderer'; +import { I18nProvider } from '../application/i18n/I18nProvider'; +import type { Host } from '../domain/models'; +import HostDetailsPanel from './HostDetailsPanel'; +import { HostDetailsConnectionSections } from './HostDetailsConnectionSections'; +import { LocalShellHostDetailsPanel } from './LocalShellHostDetailsPanel'; +import { SerialHostDetailsPanel } from './SerialHostDetailsPanel'; +import { installDomEnvironment } from './test-support/renderReactDom'; +import { AsidePanelFooter } from './ui/aside-panel'; +import { Button } from './ui/button'; +import { Combobox } from './ui/combobox'; +import { Input } from './ui/input'; +import { TooltipProvider } from './ui/tooltip'; + +type PanelKind = 'ssh' | 'local' | 'serial'; +const host: Host = { + id: 'existing', label: 'Web', hostname: 'web.example.com', username: 'root', + password: 'test-password', authMethod: 'password', tags: [], os: 'linux', + protocol: 'ssh', group: 'prod / web', +}; + +async function withPanel( + kind: PanelKind, + initialData: Host | undefined, + run: (editor: { + renderer: ReactTestRenderer; + save: () => Promise; + created: string[]; + }) => Promise, + groups: string[] = [], +) { + 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); + let renderer: ReactTestRenderer | undefined; + let saved: Host | undefined; + const created: string[] = []; + const common = { onSave: (value: Host) => { saved = value; }, onCancel() {}, groups, layout: 'inline' as const }; + try { + await act(async () => { + renderer = create( + {kind === 'ssh' ? created.push(path)} /> + : kind === 'local' ? + : } + ); + }); + await run({ + renderer: renderer!, created, + save: async () => { + saved = undefined; + await act(async () => { + const buttons = renderer!.root.findByType(AsidePanelFooter).findAllByType(Button); + await buttons[buttons.length - 1].props.onClick(); + }); + assert.ok(saved, 'the panel must call onSave'); + return saved; + }, + }); + } finally { + if (renderer) await act(async () => { renderer!.unmount(); }); + globalThis.requestAnimationFrame = previousRaf; + globalThis.cancelAnimationFrame = previousCancelRaf; + dom.cleanup(); + } +} + +function groupPicker(renderer: ReactTestRenderer, kind: PanelKind) { + return renderer.root.findAllByType(Combobox).find((picker) => + kind === 'ssh' ? picker.props.createText === 'Create Group' : picker.props.placeholder === 'Select Group', + )!; +} + +for (const kind of ['ssh', 'local', 'serial'] as const) { + const initialData = { ...host, protocol: kind, ...(kind === 'serial' ? { hostname: 'COM3' } : {}) }; + test(`${kind} Host Details keeps the exact stored group on a label-only edit`, async () => { + for (const group of ['prod / web', ' prod / web ', ' prod/web ']) { + await withPanel(kind, { ...initialData, group }, async ({ renderer, save }) => { + await act(async () => { + renderer.root.findAllByType(Input).find((input) => input.props.value === host.label)! + .props.onChange({ target: { value: 'Updated label' } }); + }); + const saved = await save(); + assert.equal(saved.label, 'Updated label'); + assert.equal(saved.group, group); + }); + } + }); + + test(`${kind} Host Details normalizes an explicitly selected trimmed-equivalent group`, async () => { + for (const group of [' prod/web ', ' prod / web ']) { + await withPanel(kind, { ...initialData, group }, async ({ renderer, save }) => { + await act(async () => { groupPicker(renderer, kind).props.onValueChange(group.trim()); }); + assert.equal((await save()).group, 'prod/web'); + }, [group.trim()]); + } + }); + + test(`${kind} Host Details normalizes a changed group and allows clearing it`, async () => { + await withPanel(kind, initialData, async ({ renderer, save }) => { + const picker = groupPicker(renderer, kind); + await act(async () => { picker.props.onValueChange(host.group); }); + assert.equal((await save()).group, host.group, 'reselecting the original group preserves it'); + for (const [value, expected] of [[' stage / / web ', 'stage/web'], ['', '']]) { + await act(async () => { picker.props.onValueChange(value); }); + assert.equal((await save()).group, expected); + } + }); + }); +} + +for (const kind of ['ssh', 'local'] as const) { + test(`${kind} Host Details normalizes a new host's group`, async () => { + await withPanel(kind, undefined, async ({ renderer, save }) => { + await act(async () => { + if (kind === 'ssh') { + const { update } = renderer.root.findByType(HostDetailsConnectionSections).props; + update('hostname', 'web.example.com'); + update('password', 'test-password'); + } + groupPicker(renderer, kind).props.onValueChange('prod / web'); + }); + assert.equal((await save()).group, 'prod/web'); + }); + }); +} + +test('Create Group normalizes paths before creation and selection, including the Combobox follow-up', async () => { + const values = ['prod / web', 'prod//web', 'prod\\web', ' prod / web ', '/ prod / / web //']; + for (const groups of [[], ['prod/web']]) { + await withPanel('ssh', host, async ({ renderer, save, created }) => { + for (const value of values) { + const picker = groupPicker(renderer, 'ssh'); + await act(async () => { picker.props.onCreateNew(value); }); + assert.equal(groupPicker(renderer, 'ssh').props.value, 'prod/web'); + // Combobox calls both callbacks with the original input when creating. + await act(async () => { picker.props.onValueChange(value); }); + assert.equal(groupPicker(renderer, 'ssh').props.value, 'prod/web'); + assert.equal((await save()).group, 'prod/web'); + } + assert.deepEqual(created, groups.length ? [] : values.map(() => 'prod/web')); + await act(async () => { groupPicker(renderer, 'ssh').props.onCreateNew(' / / \\ '); }); + assert.equal(created.length, groups.length ? 0 : values.length); + }, groups); + } +}); + +test('new-group sub-panel passes both parent and name through the same creation handler', () => { + const source = readFileSync(new URL('./HostDetailsPanel.tsx', import.meta.url), 'utf8'); + assert.match(source, /createAndSelectGroup\(`\$\{newGroupParent\}\/\$\{newGroupName\}`\)/); + assert.match(source, /onSave=\{handleCreateGroup\}/); + assert.match(source, /onCreateNew=\{createAndSelectGroup\}/); +}); diff --git a/components/HostDetailsPanel.tsx b/components/HostDetailsPanel.tsx index 636e19cad..e09e6b401 100644 --- a/components/HostDetailsPanel.tsx +++ b/components/HostDetailsPanel.tsx @@ -14,6 +14,7 @@ import React, { useEffect, useMemo, useState, useCallback, useRef } from "react" import { useI18n } from "../application/i18n/I18nProvider"; import { useApplicationBackend, type SshAgentStatus } from "../application/state/useApplicationBackend"; import { applyGroupDefaults, resolveGroupDefaults, resolveGroupTerminalThemeId } from "../domain/groupConfig"; +import { normalizeGroupTargetPath, resolveHostGroupForSave } from "../domain/hostGroupPathMutations"; import { getEffectiveHostDistro, normalizePrimaryTelnetState, @@ -281,6 +282,8 @@ const HostDetailsPanel: React.FC = ({ }, [form.agentForwarding, form.identityAgent, form.hostname, form.port, form.username, checkSshAgent]); const [groupInputValue, setGroupInputValue] = useState(form.group || ""); + const originalGroupRef = useRef(initialData ? initialData.group || "" : undefined); + const createdGroupInputRef = useRef(null); const initialHostId = initialData?.id; @@ -315,6 +318,8 @@ const HostDetailsPanel: React.FC = ({ }, [initialData, snippets]); useEffect(() => { + originalGroupRef.current = initialData ? initialData.group || "" : undefined; + createdGroupInputRef.current = null; if (!initialData) return; const normalized = normalizePrimaryTelnetState(initialData); setForm( @@ -578,7 +583,11 @@ const HostDetailsPanel: React.FC = ({ } const normalizedProxyConfig = proxySave.normalizedProxyConfig; let finalLabel = form.label?.trim() || hostname; - const finalGroup = groupInputValue.trim() || form.group || ""; + const finalGroup = resolveHostGroupForSave( + groupInputValue.trim() || form.group || "", + originalGroupRef.current, + groupInputValue !== originalGroupRef.current, + ); const targetManagedSource = managedSources .filter(s => finalGroup === s.groupName || finalGroup.startsWith(s.groupName + "/")) @@ -761,14 +770,18 @@ const HostDetailsPanel: React.FC = ({ } }; - const handleCreateGroup = () => { - if (!newGroupName.trim()) return; - const fullPath = newGroupParent - ? `${newGroupParent}/${newGroupName.trim()}` - : newGroupName.trim(); - onCreateGroup?.(fullPath); + const createAndSelectGroup = (value: string) => { + const fullPath = normalizeGroupTargetPath(value); + if (!fullPath) return; + createdGroupInputRef.current = value; + if (!groups.includes(fullPath)) onCreateGroup?.(fullPath); setGroupInputValue(fullPath); update("group", fullPath); + }; + + const handleCreateGroup = () => { + if (!newGroupName.trim()) return; + createAndSelectGroup(`${newGroupParent}/${newGroupName}`); setNewGroupName(""); setNewGroupParent(""); setActiveSubPanel("none"); @@ -1117,16 +1130,18 @@ const HostDetailsPanel: React.FC = ({ options={groupOptions} value={form.group || ""} onValueChange={(val) => { - update("group", val); - setGroupInputValue(val); + // Creation also calls onValueChange with the raw input. Keep that + // path normalized while preserving a reselected legacy group. + const groupPath = val === createdGroupInputRef.current + ? normalizeGroupTargetPath(val) + : resolveHostGroupForSave(val, originalGroupRef.current, val !== originalGroupRef.current); + createdGroupInputRef.current = null; + update("group", groupPath); + setGroupInputValue(groupPath); }} placeholder={t("hostDetails.group.placeholder")} allowCreate={true} - onCreateNew={(val) => { - onCreateGroup?.(val); - update("group", val); - setGroupInputValue(val); - }} + onCreateNew={createAndSelectGroup} createText="Create Group" triggerClassName="flex-1 h-10" /> diff --git a/components/LocalShellHostDetailsPanel.tsx b/components/LocalShellHostDetailsPanel.tsx index 17292cb1a..7a2a2766b 100644 --- a/components/LocalShellHostDetailsPanel.tsx +++ b/components/LocalShellHostDetailsPanel.tsx @@ -5,12 +5,13 @@ * into vault groups next to their SSH hosts (issue #3615). */ import { Save, TerminalSquare, X } from 'lucide-react'; -import React, { useMemo, useState } from 'react'; +import React, { useMemo, useRef, useState } from 'react'; import { useI18n } from '../application/i18n/I18nProvider'; import { useDiscoveredShells } from '../lib/useDiscoveredShells'; import { detectLocalOs } from '../lib/localShell'; import type { Host } from '../domain/models'; import { createLocalShellHost } from '../domain/localShellHost'; +import { resolveHostGroupForSave } from '../domain/hostGroupPathMutations'; import { Button } from './ui/button'; import { Combobox, ComboboxOption } from './ui/combobox'; @@ -68,6 +69,7 @@ export const LocalShellHostDetailsPanel: React.FC discoveredShells.find((candidate) => candidate.id === shell), @@ -128,12 +130,12 @@ export const LocalShellHostDetailsPanel: React.FC(initialData.tags || []); const [group, setGroup] = useState(initialData.group || ''); + const originalGroupRef = useRef(initialData.group || ''); const [notes, setNotes] = useState(initialData.notes ?? ''); const handleSave = () => { @@ -136,7 +138,7 @@ export const SerialHostDetailsPanel: React.FC { + for (const value of dirtyPaths) { + assert.equal(normalizeGroupTargetPath(value), 'prod/web'); + assert.equal(resolveHostGroupForSave(value), 'prod/web', 'new host'); + assert.equal(resolveHostGroupForSave(value, ''), 'prod/web', 'previously ungrouped host'); + assert.equal(resolveHostGroupForSave(value, 'staging'), 'prod/web', 'changed group'); + } +}); + +test('Host Details preserves unchanged stored paths on unrelated edits', () => { + for (const storedGroup of [...dirtyPaths, '', ' ']) { + const value = storedGroup.trim() || storedGroup || ''; + assert.equal(resolveHostGroupForSave(value, storedGroup), storedGroup); + assert.equal(resolveHostGroupForSave(storedGroup, storedGroup), storedGroup); + } +}); + +test('Host Details normalizes an explicitly changed group equivalent after trimming', () => { + for (const storedGroup of [' prod/web ', ' prod / web ']) { + assert.equal(resolveHostGroupForSave(storedGroup.trim(), storedGroup, true), 'prod/web'); + } +}); + +test('Host Details allows changed paths to normalize to ungrouped', () => { + for (const value of ['', ' / / \\ ']) { + assert.equal(resolveHostGroupForSave(value, 'prod / web'), ''); + assert.equal(resolveHostGroupForSave(value), ''); + } +}); + const snippets: Snippet[] = [{ id: 'script-a', label: 'A', diff --git a/domain/hostGroupPathMutations.ts b/domain/hostGroupPathMutations.ts index 8e56ff89f..be9e71ba1 100644 --- a/domain/hostGroupPathMutations.ts +++ b/domain/hostGroupPathMutations.ts @@ -9,6 +9,16 @@ export function normalizeGroupTargetPath(value: string): string { .join('/'); } +// Undefined means a new host; existing ungrouped hosts use ''. Preserve legacy +// paths on unrelated edits so their exact-path connection defaults do not change. +// Compare the raw field before save-time trimming to determine groupChanged. +export function resolveHostGroupForSave(value: string, originalGroup?: string, groupChanged = false): string { + if (!groupChanged && originalGroup !== undefined && (value === originalGroup || value === originalGroup.trim())) { + return originalGroup; + } + return normalizeGroupTargetPath(value); +} + export function normalizeGroupTargetPaths(values: Iterable): string[] { return Array.from(new Set( [...values].map(normalizeGroupTargetPath).filter(Boolean), From f4a087e890af82de82bf143cee90981c5be13571 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:52:27 +0800 Subject: [PATCH 05/24] feat(plugins): add host-rendered IDE primitives, STARTTLS/SSH bindings, file/secret APIs, and pooled image rasterizer (#4437) - Add host-rendered native IDE primitives (PluginCodeEditor/Monaco, PluginDataGrid/@tanstack/react-virtual, PluginSplitPane, PluginErCanvas) with Shadow DOM slot projection (zero iframes, zero plugin JS in renderer) - Expand Remote DOM budgets, expose full 22 Netcatty semantic CSS tokens, add dblclick/contextmenu/scroll/selection events, cursor-anchored PluginPopover, database theme icon, and full-bleed chrome flag - Add dynamic user-approved TCP/TLS byte streams (incl. localhost opt-in blocking internal control ports), in-band STARTTLS upgrade with cert fingerprint confirmation, durable revocable Vault SSH host bindings, plugin-owned encrypted secrets, native ui.openFile/saveFile streaming handles, 4 MiB clipboard, and prefix-filtered storage.keys - Optimize plugin view image pipeline with pooled sandboxed rasterizer window (auto-destroyed on idle/error/dispose), LRU version+hash cache in PluginViewResources, transient failure eviction in HostDrawnViewHost, renderer-side session deduplication, and RemoteImageElement cache + retry - Temporarily enable plugin host by default in hostBootstrap.cjs (marked TODO(revert), opt-out via NETCATTY_PLUGIN_DEV=0) --- .../pluginContributionEnvironment.test.ts | 8 + .../state/pluginContributionEnvironment.ts | 21 +- application/state/pluginViewSession.ts | 19 +- application/state/usePluginHostActions.ts | 77 ++- components/plugins/PluginContributionIcon.tsx | 10 + components/plugins/PluginHostActionHost.tsx | 92 ++- components/plugins/PluginHostDrawnPage.tsx | 33 +- .../plugins/PluginRemoteSurface.test.tsx | 218 ++++++- components/plugins/PluginRemoteSurface.tsx | 348 ++++++++++- components/plugins/PluginViewPopover.tsx | 250 +++++++- .../plugins/primitives/PluginCodeEditor.tsx | 29 + .../primitives/PluginCodeEditorInner.tsx | 409 +++++++++++++ .../plugins/primitives/PluginDataGrid.tsx | 548 +++++++++++++++++ .../plugins/primitives/PluginErCanvas.tsx | 484 +++++++++++++++ .../plugins/primitives/PluginSplitPane.tsx | 198 +++++++ .../primitives/PluginWidgetRenderer.tsx | 55 ++ .../plugins/primitives/sqlStatement.test.ts | 37 ++ components/plugins/primitives/sqlStatement.ts | 164 ++++++ components/plugins/primitives/types.ts | 117 ++++ domain/pluginRemoteTreePolicy.cjs | 66 ++- domain/pluginRemoteTreePolicy.test.cjs | 21 +- domain/pluginViewStylePolicy.cjs | 17 +- domain/pluginViewStylePolicy.test.cjs | 8 +- electron/plugins/byteStreamBroker.cjs | 290 +++++++-- electron/plugins/byteStreamBroker.test.cjs | 126 ++++ electron/plugins/byteStreamEndpoint.cjs | 86 ++- electron/plugins/byteStreamService.cjs | 258 +++++++- electron/plugins/constants.cjs | 4 +- .../plugins/contributionIconRasterizer.cjs | 144 ++++- .../contributionIconRasterizer.test.cjs | 50 ++ .../generated/plugin-contract.schema.json | 549 ++++++++++++++++-- electron/plugins/hostBootstrap.cjs | 7 +- electron/plugins/hostBootstrap.test.cjs | 22 +- .../hostByteStreamAuthorization.test.cjs | 50 ++ electron/plugins/hostDrawnViewHost.cjs | 14 +- electron/plugins/hostDrawnViewHost.test.cjs | 35 +- electron/plugins/hostInteractionService.cjs | 383 +++++++++++- .../plugins/hostInteractionService.test.cjs | 108 +++- electron/plugins/hostRpcRegistry.cjs | 24 +- electron/plugins/hostRpcRegistry.test.cjs | 27 + electron/plugins/hostService.cjs | 3 +- electron/plugins/hostVaultService.cjs | 175 +++++- electron/plugins/permissionResources.cjs | 2 +- electron/plugins/quotaManager.cjs | 25 +- electron/plugins/runtime/byteStreamClient.mjs | 8 + electron/plugins/runtime/runtimePeer.mjs | 159 ++++- electron/plugins/secretStore.cjs | 16 + electron/plugins/secretStore.test.cjs | 15 + electron/plugins/secureCapabilities.cjs | 9 + electron/plugins/secureCapabilities.test.cjs | 26 + electron/plugins/viewResourceService.cjs | 84 ++- electron/plugins/viewResourceService.test.cjs | 28 + packages/plugin-cli/src/byteStreams.test.ts | 3 +- .../schema/plugin-contract.schema.json | 549 ++++++++++++++++-- packages/plugin-contract/src/contract.test.ts | 2 +- .../src/generated/plugin-contract-limits.ts | 6 +- .../src/generated/plugin-contract.ts | 130 ++++- packages/plugin-sdk/src/hostDom.ts | 76 ++- packages/plugin-sdk/src/hostReact.test.tsx | 104 ++++ packages/plugin-sdk/src/hostReact.ts | 363 +++++++++++- packages/plugin-sdk/src/index.test.ts | 6 + packages/plugin-sdk/src/index.ts | 78 ++- scripts/generate-plugin-contract.mjs | 2 +- 63 files changed, 6954 insertions(+), 321 deletions(-) create mode 100644 components/plugins/primitives/PluginCodeEditor.tsx create mode 100644 components/plugins/primitives/PluginCodeEditorInner.tsx create mode 100644 components/plugins/primitives/PluginDataGrid.tsx create mode 100644 components/plugins/primitives/PluginErCanvas.tsx create mode 100644 components/plugins/primitives/PluginSplitPane.tsx create mode 100644 components/plugins/primitives/PluginWidgetRenderer.tsx create mode 100644 components/plugins/primitives/sqlStatement.test.ts create mode 100644 components/plugins/primitives/sqlStatement.ts create mode 100644 components/plugins/primitives/types.ts diff --git a/application/state/pluginContributionEnvironment.test.ts b/application/state/pluginContributionEnvironment.test.ts index 845a2677c..db518773d 100644 --- a/application/state/pluginContributionEnvironment.test.ts +++ b/application/state/pluginContributionEnvironment.test.ts @@ -7,12 +7,20 @@ test('plugin theme tokens come from the themed app surface style', () => { assert.deepEqual(selectPluginThemeTokens({ '--background': '220 10% 10%', '--foreground': '0 0% 98%', + '--card': '220 10% 12%', '--primary': '210 90% 55%', + '--destructive': '0 84% 60%', + '--radius': '0.5rem', + '--font-mono': '"JetBrains Mono", monospace', colorScheme: 'dark', '--unknown-plugin-token': 'ignored', }), { '--background': '220 10% 10%', '--foreground': '0 0% 98%', + '--card': '220 10% 12%', '--primary': '210 90% 55%', + '--destructive': '0 84% 60%', + '--radius': '0.5rem', + '--font-mono': '"JetBrains Mono", monospace', }); }); diff --git a/application/state/pluginContributionEnvironment.ts b/application/state/pluginContributionEnvironment.ts index bc5edf409..690b8093f 100644 --- a/application/state/pluginContributionEnvironment.ts +++ b/application/state/pluginContributionEnvironment.ts @@ -1,11 +1,26 @@ export const PLUGIN_THEME_TOKEN_NAMES = Object.freeze([ '--background', '--foreground', - '--muted', - '--muted-foreground', - '--border', + '--card', + '--card-foreground', + '--popover', + '--popover-foreground', '--primary', '--primary-foreground', + '--secondary', + '--secondary-foreground', + '--muted', + '--muted-foreground', + '--accent', + '--accent-foreground', + '--destructive', + '--destructive-foreground', + '--border', + '--input', + '--ring', + '--radius', + '--font-sans', + '--font-mono', ] as const); export function selectPluginThemeTokens( diff --git a/application/state/pluginViewSession.ts b/application/state/pluginViewSession.ts index 991c74cd1..c4beb0d70 100644 --- a/application/state/pluginViewSession.ts +++ b/application/state/pluginViewSession.ts @@ -38,14 +38,23 @@ export class PluginViewSessions { void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => { if (disposed) void bridge.closeHostDrawnPluginView?.(id).catch(() => {}); }).catch(() => dispose(true)); + const imageCache = new Map>(); return { viewId: request.viewId, scope: request.scopeId, - image: async (path: string) => { - if (disposed || !bridge.getPluginViewResource) throw new Error('Plugin image unavailable'); - const result = await bridge.getPluginViewResource({ instanceId: id, path }); - if (disposed) throw new Error('Plugin view closed'); - return result.url; + image: (path: string) => { + if (disposed || !bridge.getPluginViewResource) return Promise.reject(new Error('Plugin image unavailable')); + const existing = imageCache.get(path); + if (existing) return existing; + const pending = bridge.getPluginViewResource({ instanceId: id, path }).then((result) => { + if (disposed) throw new Error('Plugin view closed'); + return result.url; + }).catch((error) => { + if (imageCache.get(path) === pending) imageCache.delete(path); + throw error; + }); + imageCache.set(path, pending); + return pending; }, get idle() { return users === 0; }, getSnapshot: () => state, diff --git a/application/state/usePluginHostActions.ts b/application/state/usePluginHostActions.ts index 52aad9eb2..415344a7b 100644 --- a/application/state/usePluginHostActions.ts +++ b/application/state/usePluginHostActions.ts @@ -24,9 +24,17 @@ type Review = { completionToken?: string; }; +function isHostActionRequestKind(kind: string): boolean { + return kind.startsWith('vault.') + || kind === 'network.stream.connectViaHost' + || kind === 'network.stream.confirm' + || kind === 'network.stream.tlsConfirm'; +} + export function usePluginHostActions() { const [review, setReview] = useState(null); const [selectedIds, setSelectedIds] = useState([]); + const [remember, setRemember] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState(false); const current = useRef(null); @@ -44,9 +52,19 @@ export function usePluginHostActions() { const assertCurrent = useCallback((entry: Review) => { if (current.current !== entry || Date.now() >= entry.prompt.expiresAt) throw new Error('Host action expired'); + if (entry.prompt.request.kind === 'network.stream.confirm' || entry.prompt.request.kind === 'network.stream.tlsConfirm') { + const lock = getAppAppLockRuntime(); + if (lock && lock.initialized && lock.locked) throw new Error('App is locked'); + return; + } const vault = getVault(); const target = entry.prompt.vaultTarget; - if (target && resources.current.resolve(target.resourceId, target.revision) !== entry.host) throw new Error('Selected host changed'); + if (entry.prompt.durableHostId) { + const liveHost = vault.hosts.find((candidate) => candidate.id === entry.prompt.durableHostId); + if (!liveHost || liveHost !== entry.host) throw new Error('Saved SSH host changed or was removed'); + } else if (target && resources.current.resolve(target.resourceId, target.revision) !== entry.host) { + throw new Error('Selected host changed'); + } if ((entry.prompt.request.kind === 'vault.requestConnect' || entry.prompt.request.kind === 'network.stream.connectViaHost') && (vault.groupConfigs !== entry.groups || vault.snippets !== entry.snippets)) { throw new Error('Saved connection settings changed'); } @@ -71,7 +89,7 @@ export function usePluginHostActions() { assertCurrent(entry); const request = entry.prompt.request; const target = entry.prompt.vaultTarget; - if (request.kind === 'network.stream.connectViaHost' && target && entry.host) { + if (request.kind === 'network.stream.connectViaHost' && entry.host && (target || entry.prompt.durableHostId)) { const vault = getVault(); const settings = getAppSettingsRuntime(); if (!settings || !bridge.openPluginHostStream) throw new Error('Host stream unavailable'); @@ -83,7 +101,15 @@ export function usePluginHostActions() { || latest.hosts !== vault.hosts || latest.knownHosts !== vault.knownHosts || getAppSettingsRuntime()?.terminalSettings !== settings.terminalSettings) throw new Error('Connection settings changed'); }; assertPrepared(); - await executePluginHostAction({ kind: 'connect', target }, { + if (entry.prompt.durableHostId) { + entry.claimed = true; + await bridge.openPluginHostStream!({ + response: { requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action: 'commit' }, + connectionOptions, + }); + return; + } + await executePluginHostAction({ kind: 'connect', target: target! }, { getVault, resources: resources.current, assertCurrent: assertPrepared, authorizeCommit: async () => { assertPrepared(); }, connect: async () => { @@ -126,12 +152,35 @@ export function usePluginHostActions() { const unsubscribe = bridge.onPluginInteraction((event) => { if ('closed' in event) { if (current.current?.prompt.requestId !== event.requestId) return; - current.current = null; setReview(null); setBusy(false); responding.current = false; + current.current = null; setReview(null); setRemember(false); setBusy(false); responding.current = false; return; } - if (!event.request.kind.startsWith('vault.') && event.request.kind !== 'network.stream.connectViaHost') return; + if (!isHostActionRequestKind(event.request.kind)) return; const prompt = event as VaultHostPrompt; try { + if (prompt.request.kind === 'network.stream.confirm' || prompt.request.kind === 'network.stream.tlsConfirm') { + const entry: Review = { + prompt, candidates: [], candidateRevisions: new Map(), customGroups: [], + groups: [], snippets: [], managedSources: [], scriptsRun: false, claimed: false, + }; + current.current = entry; setSelectedIds([]); setRemember(false); setBusy(false); setError(false); responding.current = false; + setReview(entry); + return; + } + if (prompt.phase === 'commit' && prompt.autoCommit && prompt.durableHostId && prompt.request.kind === 'network.stream.connectViaHost') { + const vault = getVault(); + const host = vault.hosts.find((candidate) => candidate.id === prompt.durableHostId); + if (!host) throw new Error('Saved SSH host no longer exists'); + const entry: Review = { + prompt, candidates: [], candidateRevisions: new Map(), customGroups: vault.customGroups, + host, groups: vault.groupConfigs, snippets: vault.snippets, managedSources: vault.managedSources, + scriptsRun: false, claimed: false, + }; + current.current = entry; setSelectedIds([]); setRemember(false); setBusy(true); setError(false); responding.current = false; + setReview(null); + void execute(entry); + return; + } if (prompt.phase === 'commit') { const entry = current.current; if (!entry || entry.prompt.requestId !== prompt.requestId || entry.prompt.request.kind !== prompt.request.kind) throw new Error('Host review is unavailable'); @@ -150,7 +199,10 @@ export function usePluginHostActions() { scriptsRun: host ? pluginHostRunsSavedScripts(host, vault.groupConfigs, vault.snippets) : false, claimed: false, }; - current.current = entry; setSelectedIds([]); setBusy(false); setError(false); responding.current = false; + const defaultRemember = prompt.request.kind === 'network.stream.connectViaHost' + && 'durable' in prompt.request + && prompt.request.durable === true; + current.current = entry; setSelectedIds([]); setRemember(defaultRemember); setBusy(false); setError(false); responding.current = false; if (prompt.request.kind === 'vault.requestConnect' && prompt.permissionMode === 'allow') { setReview(null); void bridge.respondPluginInteraction?.({ requestId: prompt.requestId, actionToken: prompt.actionToken, @@ -168,7 +220,7 @@ export function usePluginHostActions() { }; }, [execute, fail, getVault]); - const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields) => { + const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields, rememberOverride?: boolean) => { const entry = current.current; if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return; responding.current = true; setBusy(true); setError(false); @@ -181,17 +233,24 @@ export function usePluginHostActions() { resources.current.resolve(id, revision); return resources.current.metadata(id); }) : undefined; + const includeRemember = action === 'submit' && ( + request.kind === 'network.stream.connectViaHost' + || request.kind === 'network.stream.confirm' + || request.kind === 'network.stream.tlsConfirm' + ); + const effectiveRemember = rememberOverride ?? remember; await netcattyBridge.require().respondPluginInteraction?.({ requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action, ...(selected === undefined ? {} : { resources: selected }), ...(draft === undefined ? {} : { draft }), ...(request.kind === 'vault.requestConnect' && action === 'submit' ? { scriptsRun: entry.scriptsRun } : {}), + ...(includeRemember && effectiveRemember ? { remember: true } : {}), }); } catch { await fail(entry); } finally { if (current.current === entry && entry.prompt.phase === 'request') { responding.current = false; setBusy(false); } } - }, [assertCurrent, fail, selectedIds]); + }, [assertCurrent, fail, remember, selectedIds]); - return { review, selectedIds, setSelectedIds, busy, error, respond }; + return { review, selectedIds, setSelectedIds, remember, setRemember, busy, error, respond }; } diff --git a/components/plugins/PluginContributionIcon.tsx b/components/plugins/PluginContributionIcon.tsx index a855d5e6a..e072f54ea 100644 --- a/components/plugins/PluginContributionIcon.tsx +++ b/components/plugins/PluginContributionIcon.tsx @@ -3,18 +3,23 @@ import { Box, Code, Command, + Database, FileText, Folder, Globe, + HardDrive, Key, + Layers, LayoutPanelLeft, List, Network, Palette, Play, Puzzle, + Server, Settings, Shield, + Sparkles, Table, Terminal, Wrench, @@ -30,17 +35,22 @@ const THEME_ICONS: Readonly> = Object.freeze({ box: Box, code: Code, command: Command, + database: Database, file: FileText, folder: Folder, globe: Globe, + 'hard-drive': HardDrive, key: Key, + layers: Layers, 'layout-panel': LayoutPanelLeft, list: List, network: Network, palette: Palette, play: Play, + server: Server, settings: Settings, shield: Shield, + sparkles: Sparkles, table: Table, terminal: Terminal, wrench: Wrench, diff --git a/components/plugins/PluginHostActionHost.tsx b/components/plugins/PluginHostActionHost.tsx index db8bc6086..d1ae7b3af 100644 --- a/components/plugins/PluginHostActionHost.tsx +++ b/components/plugins/PluginHostActionHost.tsx @@ -15,13 +15,27 @@ export function PluginHostActionHost() { const request = entry.prompt.request; const selection = request.kind === 'vault.selectHosts'; const stream = request.kind === 'network.stream.connectViaHost'; + const directStreamConfirm = request.kind === 'network.stream.confirm'; + const tlsConfirm = request.kind === 'network.stream.tlsConfirm'; const connection = request.kind === 'vault.requestConnect' || stream; const effective = entry.host ? applyGroupDefaults(entry.host, entry.host.group ? resolveGroupDefaults(entry.host.group, entry.groups) : {}) : undefined; const protocol = effective ? resolveEffectiveTerminalProtocol(effective) : undefined; + const dialogTitle = selection + ? t('plugins.hostActions.select') + : directStreamConfirm + ? 'Confirm Network Connection' + : tlsConfirm + ? 'Verify TLS Certificate' + : connection + ? t('plugins.hostActions.connect') + : entry.host + ? t('plugins.hostActions.edit') + : t('plugins.hostActions.create'); + return { if (!open) void state.respond('cancel'); }}> - {t(selection ? 'plugins.hostActions.select' : connection ? 'plugins.hostActions.connect' : entry.host ? 'plugins.hostActions.edit' : 'plugins.hostActions.create')} + {dialogTitle} {entry.prompt.pluginId} · {entry.prompt.pluginVersion} {selection ? <> @@ -29,17 +43,89 @@ export function PluginHostActionHost() {

{request.title}

{state.selectedIds.length > 50 &&

{t('plugins.hostActions.selectionLimit')}

} 50} onSelect={(host) => state.setSelectedIds((ids) => ids.includes(host.id) ? ids.filter((id) => id !== host.id) : [...ids, host.id])} onSelectionChange={state.setSelectedIds} onConfirm={() => { if (!state.busy && state.selectedIds.length <= 50) void state.respond('submit'); }} /> - : connection && effective ? <> + : directStreamConfirm ?
+
+

Destination Endpoint

+

{request.endpoint}

+

+ {request.transport.toUpperCase()} · {request.host}:{request.port} + {request.isLocal ? ' · Local / Private Network' : ''} +

+
+

+ This plugin is requesting a direct {request.transport.toUpperCase()} connection to this endpoint. Netcatty's internal control ports remain blocked. +

+ +
: tlsConfirm ?
+

+ The server certificate could not be verified ({request.reason}). +

+
+
+ Endpoint: + {request.endpoint} +
+ {request.subject &&
+ Subject: + {request.subject} +
} + {request.issuer &&
+ Issuer: + {request.issuer} +
} + {request.validTo &&
+ Valid Until: + {request.validTo} +
} +
+ SHA-256 Fingerprint: + + {request.fingerprint256} + +
+
+ +
: connection && effective ? <>

{effective.label}

{protocol !== 'local' && effective.username ? `${effective.username}@` : ''}{effective.hostname}{protocol !== 'local' && effective.port ? `:${effective.port}` : ''} ({protocol})

{protocol === 'local' &&

{t('plugins.hostActions.localExecution')}

} - {stream ? <>

{request.endpoint}

{t('plugins.hostActions.streamNote')}

: <> + {stream ? <> +

{request.endpoint}

+

{t('plugins.hostActions.streamNote')}

+ + : <>

{t(entry.scriptsRun ? 'plugins.hostActions.scriptsRun' : 'plugins.hostActions.noScripts')}

{t('plugins.hostActions.connectionNote')}

} : request.kind === 'vault.requestHostDraft' ? void state.respond('submit', draft)} /> : null} {state.error &&

{t('plugins.hostActions.failed')}

} + {directStreamConfirm && } + {tlsConfirm && } {connection && }
diff --git a/components/plugins/PluginHostDrawnPage.tsx b/components/plugins/PluginHostDrawnPage.tsx index 0871b670e..3feb38245 100644 --- a/components/plugins/PluginHostDrawnPage.tsx +++ b/components/plugins/PluginHostDrawnPage.tsx @@ -7,14 +7,39 @@ export type PluginHostDrawnPageProps = Parameters pluginId: string; }; +type MinimalTreeNode = { + type?: number; + attributes?: Record; + children?: MinimalTreeNode[]; +}; + +function hasFullBleedChrome(tree: unknown): boolean { + if (!tree || typeof tree !== 'object') return false; + const children = (tree as { children?: MinimalTreeNode[] }).children; + if (!Array.isArray(children)) return false; + // Check root and immediate child (hostDom wraps React trees in a mountRoot div). + const check = (nodes: MinimalTreeNode[], depth: number): boolean => { + for (const node of nodes) { + if (node?.type !== 1) continue; + if (node.attributes?.['data-plugin-chrome'] === 'full-bleed') return true; + if (depth < 2 && Array.isArray(node.children) && check(node.children, depth + 1)) return true; + } + return false; + }; + return check(children, 0); +} + export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) { const view = useHostDrawnPluginView(props); if (!view.visible) return null; if (view.loading) return

{props.loadingLabel}

; - return
+ const fullBleed = hasFullBleedChrome(view.tree); + return
-
- -
+ {!fullBleed && ( +
+ +
+ )}
; } diff --git a/components/plugins/PluginRemoteSurface.test.tsx b/components/plugins/PluginRemoteSurface.test.tsx index dd57fc2cb..8dfd6be2c 100644 --- a/components/plugins/PluginRemoteSurface.test.tsx +++ b/components/plugins/PluginRemoteSurface.test.tsx @@ -31,7 +31,7 @@ test('plugin surface forwards its own input and contains malformed updates and r assert.deepEqual(events, [{ nodeId: '2', type: 'click' }]); const input = captured!.querySelector('input')!; input.value = 'typed'; await act(async () => { input.dispatchEvent(new dom.window.Event('input', { bubbles: true })); }); - assert.deepEqual(events.at(-1), { nodeId: '4', type: 'input', value: 'typed' }); + assert.deepEqual(events.at(-1), { nodeId: '4', type: 'input', value: 'typed', selectionStart: 5, selectionEnd: 5 }); await act(async () => { document.getElementById('host')!.dispatchEvent(new dom.window.Event('input', { bubbles: true })); }); assert.equal(events.length, 2); await act(async () => { root.render( {}} />); }); @@ -254,3 +254,219 @@ test('PluginRemoteSurface avoids JSON/form hook work on text and plain elements Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); } }); + +test('PluginRemoteSurface forwards dblclick, contextmenu, throttled scroll, cursor popover, and host-rendered widgets', async () => { + const dom = new JSDOM('
', { url: 'http://localhost', pretendToBeVisual: true }); + const saved = new Map(); + for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', '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 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 } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { PluginRemoteSurface } = await import('./PluginRemoteSurface'); + + const events: Array> = []; + const gridProps = { + columns: [ + { name: 'id', type: 'int4', primaryKey: true }, + { name: 'name', type: 'varchar', nullable: true }, + ], + rows: [ + { id: 1, name: 'Alice' }, + { id: 2, name: null }, + ], + dirtyCells: { '0:name': 'Alicia' }, + editable: true, + }; + const erProps = { + tables: [ + { name: 'users', columns: [{ name: 'id', type: 'int', isPk: true }] }, + { name: 'orders', columns: [{ name: 'id', type: 'int', isPk: true }, { name: 'user_id', type: 'int', isFk: true }] }, + ], + relations: [{ fromTable: 'orders', fromColumn: 'user_id', toTable: 'users', toColumn: 'id' }], + }; + const tree = { + children: [ + { + id: 'scroller', + type: 1, + element: 'div', + attributes: { class: 'list' }, + children: [{ id: 'item', type: 1, element: 'button', attributes: { type: 'button' }, children: [{ id: 'it', type: 3, data: 'Row' }] }], + }, + { + id: 'ctx-popover', + type: 1, + element: 'div', + attributes: { + 'data-plugin-popover': 'true', + 'data-plugin-anchor-x': '120', + 'data-plugin-anchor-y': '80', + 'data-plugin-popover-width': '260', + 'data-plugin-popover-max-height': '320', + open: '', + }, + children: [{ id: 'pop-item', type: 1, element: 'span', attributes: {}, children: [{ id: 'pt', type: 3, data: 'Menu' }] }], + }, + { + id: 'split', + type: 1, + element: 'div', + attributes: { + 'data-plugin-widget': 'split-pane', + 'data-plugin-widget-props': JSON.stringify({ direction: 'horizontal', initialSize: 220, minSize: 120, maxSize: 400 }), + }, + children: [ + { id: 'pane-a', type: 1, element: 'div', attributes: {}, children: [{ id: 'pa', type: 3, data: 'Left' }] }, + { 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: [], + }, + { + id: 'er', + type: 1, + element: 'div', + attributes: { 'data-plugin-widget': 'er-canvas', 'data-plugin-widget-props': JSON.stringify(erProps) }, + children: [], + }, + ], + }; + + const root = createRoot(document.getElementById('root')!); + try { + await act(async () => { + root.render( events.push(e as unknown as Record)} />); + }); + + const mainShadow = shadows[0]; + assert.ok(mainShadow, 'main shadow mounted'); + + // 1. dblclick & contextmenu with surface-relative coordinates + preventDefault + const btn = mainShadow.querySelector('button')!; + const ctxEvent = new dom.window.MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 250, clientY: 170 }); + await act(async () => { + btn.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true, cancelable: true, clientX: 180, clientY: 90 })); + btn.dispatchEvent(ctxEvent); + }); + assert.equal(ctxEvent.defaultPrevented, true, 'contextmenu must call preventDefault'); + assert.deepEqual(events[0], { nodeId: 'item', type: 'dblclick', x: 80, y: 40 }); + assert.deepEqual(events[1], { nodeId: 'item', type: 'contextmenu', x: 150, y: 120 }); + + // 2. throttled scroll + const scroller = mainShadow.querySelector('.list') as HTMLElement; + scroller.scrollTop = 140; + scroller.scrollLeft = 20; + await act(async () => { + scroller.dispatchEvent(new dom.window.Event('scroll', { bubbles: false })); + await new Promise((resolve) => setTimeout(resolve, 90)); + }); + const scrollEvt = events.find((e) => e.type === 'scroll'); + assert.ok(scrollEvt, 'scroll event emitted'); + assert.equal(scrollEvt!.scrollTop, 140); + assert.equal(scrollEvt!.scrollLeft, 20); + + // 3. cursor-anchored popover positioned within surface bounds with custom width & maxHeight + const popoverEl = document.querySelector('[data-plugin-view-popover]') as HTMLElement | null; + assert.ok(popoverEl, 'cursor-anchored popover rendered'); + assert.equal(popoverEl!.style.width, '260px'); + assert.equal(popoverEl!.style.maxHeight, '320px'); + assert.equal(popoverEl!.style.left, '220px'); // surface.left (100) + anchorX (120) + + // 4. SplitPane rendered inside shadow root with two panes and drag handle + const splitEl = mainShadow.querySelector('[data-plugin-widget="split-pane"]') as HTMLElement | null; + assert.ok(splitEl, 'split-pane rendered in shadow root'); + assert.equal(splitEl!.querySelectorAll('[data-split-pane]').length, 2); + const handle = splitEl!.querySelector('[data-split-handle]') as HTMLElement; + await act(async () => { + handle.dispatchEvent(new dom.window.MouseEvent('pointerdown', { bubbles: true, clientX: 220 })); + dom.window.dispatchEvent(new dom.window.MouseEvent('pointermove', { bubbles: true, clientX: 280 })); + dom.window.dispatchEvent(new dom.window.MouseEvent('pointerup', { bubbles: true, clientX: 280 })); + }); + assert.deepEqual( + events.find((e) => e.nodeId === 'split' && e.widgetEvent === 'resizeEnd'), + { nodeId: 'split', type: 'widget', widgetEvent: 'resizeEnd', detail: { size: 280, collapsed: false } }, + ); + + // 5. DataGrid slotted in Light DOM: renders dirty cell, NULL pill, inline edit & sort + const gridHost = document.querySelector('[data-plugin-widget-host="data-grid"]') as HTMLElement | null; + assert.ok(gridHost, 'data-grid slotted in shadow host Light DOM'); + assert.ok(gridHost!.textContent?.includes('Alicia'), 'dirty cell value rendered'); + assert.ok(gridHost!.textContent?.includes('NULL'), 'NULL pill rendered'); + const nameHeaderBtn = gridHost!.querySelector('[data-col-name="name"] button') as HTMLButtonElement; + await act(async () => { nameHeaderBtn.click(); }); + assert.deepEqual( + events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'sortChange'), + { nodeId: 'grid', type: 'widget', widgetEvent: 'sortChange', detail: { column: 'name', direction: 'asc' } }, + ); + const cell = gridHost!.querySelector('[role="gridcell"][data-row-index="0"][data-col-name="name"]') as HTMLElement; + await act(async () => { + cell.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true })); + }); + const editorInput = cell.querySelector('input') as HTMLInputElement; + assert.ok(editorInput, 'double-click opens inline cell editor'); + await act(async () => { + const setter = Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, 'value')!.set!; + setter.call(editorInput, 'Bob'); + editorInput.dispatchEvent(new dom.window.Event('input', { bubbles: true })); + }); + await act(async () => { + editorInput.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); + }); + assert.deepEqual( + events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'cellEdit'), + { nodeId: 'grid', type: 'widget', widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'name', value: 'Bob', isNull: false } }, + ); + + // 6. ER Canvas slotted in Light DOM: renders tables + FK curve + emits tableClick + const erHost = document.querySelector('[data-plugin-widget-host="er-canvas"]') as HTMLElement | null; + assert.ok(erHost, 'er-canvas slotted in shadow host Light DOM'); + const usersCard = erHost!.querySelector('[data-er-table="users"]') as Element | null; + assert.ok(usersCard, 'users table card rendered'); + await act(async () => { + usersCard!.dispatchEvent(new dom.window.MouseEvent('pointerdown', { bubbles: true, button: 0, clientX: 10, clientY: 10 })); + dom.window.dispatchEvent(new dom.window.MouseEvent('pointerup', { bubbles: true, button: 0, clientX: 10, clientY: 10 })); + }); + assert.deepEqual( + events.find((e) => e.nodeId === 'er' && e.widgetEvent === 'tableClick'), + { nodeId: 'er', type: 'widget', widgetEvent: 'tableClick', detail: { table: 'users' } }, + ); + } 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'); + } +}); diff --git a/components/plugins/PluginRemoteSurface.tsx b/components/plugins/PluginRemoteSurface.tsx index 56ff40bff..44cd3804b 100644 --- a/components/plugins/PluginRemoteSurface.tsx +++ b/components/plugins/PluginRemoteSurface.tsx @@ -1,6 +1,9 @@ -import React, { createContext, memo, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import React, { createContext, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { LazyLoadBoundary } from '../ui/lazy-load-boundary'; import { PluginViewPopover } from './PluginViewPopover'; +import { PluginSplitPane } from './primitives/PluginSplitPane'; +import { parseWidgetPropsJson, PluginSlottedWidget, type SlottedWidgetKind } from './primitives/PluginWidgetRenderer'; +import type { PluginSplitPaneWidgetProps } from './primitives/types'; import { createPortal } from 'react-dom'; import { validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs'; import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs'; @@ -9,16 +12,44 @@ type RemoteElementNode = { id: string; type: 1; element: string; attributes: Record; children: RemoteNode[]; }; type RemoteNode = { id: string; type: 3; data: string } | { id: string; type: 8; data: string } | RemoteElementNode; + export type PluginSurfaceEvent = import('@netcatty/plugin-contract').HostDrawnViewEvent; + +const MAX_EVENT_VALUE_LENGTH = 131072; +const SCROLL_THROTTLE_MS = 60; +const SURFACE_EVENTS = [ + 'click', 'dblclick', 'contextmenu', + 'input', 'change', + 'keydown', 'keyup', + 'focusin', 'focusout', + 'compositionstart', 'compositionupdate', 'compositionend', + 'submit', 'reset', + 'scroll', +] as const; +const SURFACE_EVENT_SET = new Set(SURFACE_EVENTS); +const SLOTTED_WIDGET_KINDS = new Set(['code-editor', 'data-grid', 'er-canvas']); + const ATTRIBUTE_NAMES: Record = { class: 'className', for: 'htmlFor', readonly: 'readOnly', tabindex: 'tabIndex', maxlength: 'maxLength', minlength: 'minLength', colspan: 'colSpan', rowspan: 'rowSpan', autocomplete: 'autoComplete' }; const BOOLEAN_ATTRIBUTES = new Set(['checked', 'disabled', 'readonly', 'required', 'multiple', 'selected', 'open']); const preventFormSubmit = (event: React.FormEvent) => event.preventDefault(); -const SurfaceContext = createContext<{ css: string; onEvent(event: PluginSurfaceEvent): void; depth: number }>({ css: '', onEvent: () => {}, depth: 0 }); +const SurfaceContext = createContext<{ + css: string; + onEvent(event: PluginSurfaceEvent): void; + depth: number; + shadowHost: HTMLDivElement | null; +}>({ css: '', onEvent: () => {}, depth: 0, shadowHost: null }); + function remoteText(nodes: RemoteNode[]): string { return nodes.map((node) => (node.type === 3 ? node.data : node.type === 1 ? remoteText(node.children) : '')).join(''); } +function parseOptionalNumber(raw: string | undefined): number | undefined { + if (raw === undefined || raw === '') return undefined; + const parsed = Number(raw); + return Number.isFinite(parsed) ? parsed : undefined; +} + const ResourceLoader = createContext<((path: string) => Promise) | undefined>(undefined); function buildRemoteElementProps(node: RemoteElementNode): Record { @@ -41,17 +72,166 @@ const RemotePopoverElement = memo(function RemotePopoverElement({ node, settled const loadImage = useContext(ResourceLoader); if (surface.depth >= 1) return null; const attrs = node.attributes; - return surface.onEvent({ nodeId: node.id, type: 'dismiss' })}>; + return ( + surface.onEvent({ nodeId: node.id, type: 'dismiss' })} + > + + + ); }); +const RemoteSplitPaneElement = memo(function RemoteSplitPaneElement({ node, settled }: { node: RemoteElementNode; settled: boolean }): React.ReactNode { + const surface = useContext(SurfaceContext); + const parsed = useMemo( + () => parseWidgetPropsJson(node.attributes['data-plugin-widget-props']), + [node.attributes['data-plugin-widget-props']], + ); + const elementChildren = node.children.filter((child) => child.type === 1 || (child.type === 3 && child.data.length > 0)); + const firstChild = elementChildren[0] ? renderRemoteNode(elementChildren[0], settled) : null; + const secondChild = elementChildren[1] ? renderRemoteNode(elementChildren[1], settled) : null; + const emit = useCallback( + (widgetEvent: string, detail?: Record) => { + surface.onEvent({ + nodeId: node.id, + type: 'widget', + widgetEvent, + detail: detail as PluginSurfaceEvent['detail'], + }); + }, + [surface.onEvent, node.id], + ); + return ( + + ); +}); + +const RemoteSlottedWidgetElement = memo(function RemoteSlottedWidgetElement({ node, kind }: { node: RemoteElementNode; kind: SlottedWidgetKind }): React.ReactNode { + const surface = useContext(SurfaceContext); + const slotName = `nc-widget-${node.id}`; + const emit = useCallback( + (widgetEvent: string, detail?: Record) => { + surface.onEvent({ + nodeId: node.id, + type: 'widget', + widgetEvent, + detail: detail as PluginSurfaceEvent['detail'], + }); + }, + [surface.onEvent, node.id], + ); + + const wrapperProps = buildRemoteElementProps(node); + const origRef = wrapperProps.ref as ((el: HTMLElement | null) => void) | undefined; + const hasExplicitStyle = Object.hasOwn(node.attributes, 'style'); + wrapperProps.ref = (el: HTMLElement | null) => { + origRef?.(el); + if (el && !hasExplicitStyle) { + el.setAttribute('style', 'display:flex;flex-direction:column;width:100%;height:100%;min-width:0;min-height:0;overflow:hidden'); + } + }; + + return ( + <> + {React.createElement( + 'div', + wrapperProps, + React.createElement('slot', { name: slotName, style: { display: 'contents' } }), + )} + {surface.shadowHost && createPortal( +
+ +
, + surface.shadowHost, + )} + + ); +}); + +const resolvedImageCache = new WeakMap<(path: string) => Promise, Map>(); +const IMAGE_RETRY_DELAYS_MS = [200, 600] as const; + +function getCachedImageUrl(loader: ((path: string) => Promise) | undefined, imagePath: string | undefined): string | undefined { + if (!loader || !imagePath) return undefined; + return resolvedImageCache.get(loader)?.get(imagePath); +} + +function setCachedImageUrl(loader: (path: string) => Promise, imagePath: string, url: string) { + let map = resolvedImageCache.get(loader); + if (!map) { + map = new Map(); + resolvedImageCache.set(loader, map); + } + if (map.size >= 256) { + const oldest = map.keys().next().value; + if (oldest !== undefined) map.delete(oldest); + } + map.set(imagePath, url); +} + const RemoteImageElement = memo(function RemoteImageElement({ node }: { node: RemoteElementNode }): React.ReactNode { const loadImage = useContext(ResourceLoader); const imagePath = node.attributes.src?.slice(6); - const [imageUrl, setImageUrl] = useState(); + const [imageUrl, setImageUrl] = useState(() => getCachedImageUrl(loadImage, imagePath)); useEffect(() => { - let cancelled = false; setImageUrl(undefined); - if (imagePath && loadImage) void loadImage(imagePath).then((url) => { if (!cancelled) setImageUrl(url); }).catch(() => {}); - return () => { cancelled = true; }; + let cancelled = false; + let retryTimer: ReturnType | undefined; + const cached = getCachedImageUrl(loadImage, imagePath); + if (cached) { + setImageUrl(cached); + return () => { cancelled = true; }; + } + setImageUrl(undefined); + if (imagePath && loadImage) { + const attemptLoad = (attempt: number) => { + void loadImage(imagePath).then((url) => { + if (cancelled) return; + setCachedImageUrl(loadImage, imagePath, url); + setImageUrl(url); + }).catch(() => { + if (cancelled) return; + const delay = IMAGE_RETRY_DELAYS_MS[attempt]; + if (delay !== undefined) { + retryTimer = setTimeout(() => { if (!cancelled) attemptLoad(attempt + 1); }, delay); + } + }); + }; + attemptLoad(0); + } + return () => { + cancelled = true; + if (retryTimer !== undefined) clearTimeout(retryTimer); + }; }, [imagePath, loadImage]); const props = buildRemoteElementProps(node); props.src = imageUrl; @@ -111,12 +291,40 @@ function renderRemoteNode(node: RemoteNode, settled: boolean): React.ReactNode { if (node.type === 3) return node.data; if (node.type === 8) return null; if (node.attributes['data-plugin-popover'] === 'true') return ; + const widgetKind = node.attributes['data-plugin-widget']; + if (widgetKind === 'split-pane') return ; + if (widgetKind && SLOTTED_WIDGET_KINDS.has(widgetKind)) { + return ; + } if (node.element === 'img') return ; if (node.element === 'select') return ; if (node.element === 'input' || node.element === 'textarea') return ; return ; } +function readSelectionRange( + target: HTMLElement, + view: Window & typeof globalThis, +): { selectionStart: number; selectionEnd: number } | undefined { + const isTextInput = + target instanceof view.HTMLTextAreaElement + || (target instanceof view.HTMLInputElement && ['text', 'search', 'url', 'tel', 'password', ''].includes(target.type)); + if (!isTextInput) return undefined; + try { + const start = target.selectionStart; + const end = target.selectionEnd; + if (typeof start === 'number' && typeof end === 'number' && Number.isFinite(start) && Number.isFinite(end)) { + return { + selectionStart: Math.max(0, Math.min(MAX_EVENT_VALUE_LENGTH, Math.floor(start))), + selectionEnd: Math.max(0, Math.min(MAX_EVENT_VALUE_LENGTH, Math.floor(end))), + }; + } + } catch { + // Non-selectable input types throw InvalidStateError. + } + return undefined; +} + /** 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; onEvent(event: PluginSurfaceEvent): void }) { const checked = useMemo(() => { @@ -125,20 +333,24 @@ export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadIm return { tree: tree as { children: RemoteNode[] }, css: validatePluginStylesheet(css) }; } catch { return null; } }, [tree, css]); - const checkedCss = checked?.css; - const surfaceContextValue = useMemo( - () => (checkedCss !== undefined ? { css: checkedCss, onEvent, depth } : null), - [checkedCss, onEvent, depth], + if (!checked) return

Unable to display plugin view.

; + return ( + Unable to display plugin view.

}> + + + +
); - if (!checked || !surfaceContextValue) return

Unable to display plugin view.

; - return Unable to display plugin view.

}>
; } -function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled }: { settled: boolean; tree: { children: RemoteNode[] }; css: string; onEvent(event: PluginSurfaceEvent): void }) { +function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: { settled: boolean; depth: number; tree: { children: RemoteNode[] }; css: string; onEvent(event: PluginSurfaceEvent): void }) { + const surfaceRef = useRef(null); const hostRef = useRef(null); const onEventRef = useRef(onEvent); onEventRef.current = onEvent; const shadowRef = useRef(null); const [shadow, setShadow] = useState(null); + const [shadowHost, setShadowHost] = useState(null); + useLayoutEffect(() => { const host = hostRef.current; if (!host) return; @@ -146,32 +358,118 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled }: { settled const root = shadowRef.current ?? host.attachShadow({ mode: 'closed' }); shadowRef.current = root; setShadow(root); + setShadowHost(host); }, []); + + const surfaceContextValue = useMemo( + () => ({ css, onEvent, depth, shadowHost }), + [css, onEvent, depth, shadowHost], + ); + useEffect(() => { if (!shadow) return; + const scrollTimers = new Map>(); + const pendingScroll = new Map(); + + const flushScroll = (nodeId: string) => { + scrollTimers.delete(nodeId); + const evt = pendingScroll.get(nodeId); + if (evt) { + pendingScroll.delete(nodeId); + onEventRef.current(evt); + } + }; + const listener = (event: Event) => { const target = event.target; const view = shadow.ownerDocument.defaultView; - if (!view || !(target instanceof view.HTMLElement) || !['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset'].includes(event.type)) return; + if (!view || !(target instanceof view.HTMLElement) || !SURFACE_EVENT_SET.has(event.type)) return; + // Closed-shadow events hide their editable target from window capture. - if (event.type === 'focusin') hostRef.current?.toggleAttribute('data-plugin-editing', target.matches('input, textarea, select, [contenteditable]')); + if (event.type === 'focusin') { + hostRef.current?.toggleAttribute( + 'data-plugin-editing', + target.matches('input, textarea, select, [contenteditable]') || Boolean(target.closest('.monaco-editor')), + ); + } 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; + if (event.type === 'submit') event.preventDefault(); + if (event.type === 'contextmenu') event.preventDefault(); + const nodeId = target.dataset.netcattyRemoteNode; if (!nodeId) return; + + if (event.type === 'scroll') { + const scrollEvent: PluginSurfaceEvent = { + nodeId, + type: 'scroll' as PluginSurfaceEvent['type'], + scrollTop: Math.max(0, Math.round(target.scrollTop)), + scrollLeft: Math.max(0, Math.round(target.scrollLeft)), + clientHeight: Math.max(0, Math.round(target.clientHeight)), + clientWidth: Math.max(0, Math.round(target.clientWidth)), + }; + pendingScroll.set(nodeId, scrollEvent); + if (!scrollTimers.has(nodeId)) { + scrollTimers.set(nodeId, setTimeout(() => flushScroll(nodeId), SCROLL_THROTTLE_MS)); + } + return; + } + const value = target instanceof view.HTMLInputElement || target instanceof view.HTMLTextAreaElement || target instanceof view.HTMLSelectElement ? target.value : undefined; const values = target instanceof view.HTMLSelectElement && target.multiple ? [...target.selectedOptions].map((option) => option.value) : undefined; const checkedValue = target instanceof view.HTMLInputElement && ['checkbox', 'radio'].includes(target.type) ? target.checked : undefined; - if (value !== undefined && value.length > 8192) return; + if (value !== undefined && value.length > MAX_EVENT_VALUE_LENGTH) return; + const keyboard = event instanceof view.KeyboardEvent && event.key.length <= 64 - ? { key: event.key, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey } : {}; - onEventRef.current({ nodeId, type: event.type as PluginSurfaceEvent['type'], ...(value === undefined ? {} : { value }), ...(checkedValue === undefined ? {} : { checked: checkedValue }), ...keyboard, ...(values ? { values } : {}), ...(event instanceof view.CompositionEvent ? { data: event.data.slice(0, 8192) } : {}) }); + ? { key: event.key, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey } + : {}; + + 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), + }; + } + + const selection = + event.type === 'input' || event.type === 'change' || event.type === 'keyup' || event.type === 'keydown' + ? readSelectionRange(target, view) + : undefined; + + onEventRef.current({ + nodeId, + type: event.type as PluginSurfaceEvent['type'], + ...(value === undefined ? {} : { value }), + ...(checkedValue === undefined ? {} : { checked: checkedValue }), + ...keyboard, + ...(pointerCoords ?? {}), + ...(selection ?? {}), + ...(values ? { values } : {}), + ...(event instanceof view.CompositionEvent ? { data: event.data.slice(0, 8192) } : {}), + }); + }; + + for (const event of SURFACE_EVENTS) shadow.addEventListener(event, listener, true); + return () => { + for (const timer of scrollTimers.values()) clearTimeout(timer); + scrollTimers.clear(); + pendingScroll.clear(); + for (const event of SURFACE_EVENTS) shadow.removeEventListener(event, listener, true); }; - for (const event of ['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset']) shadow.addEventListener(event, listener, true); - return () => { for (const event of ['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset']) shadow.removeEventListener(event, listener, true); }; }, [shadow]); - return
-
- {shadow && createPortal(<>{tree.children.map((node) => renderRemoteNode(node, settled))}, shadow)} -
; + + return ( + +
+
+ {shadow && createPortal(<>{tree.children.map((node) => renderRemoteNode(node, settled))}, shadow)} +
+ + ); } diff --git a/components/plugins/PluginViewPopover.tsx b/components/plugins/PluginViewPopover.tsx index 1d4bcd6ac..aa282f84d 100644 --- a/components/plugins/PluginViewPopover.tsx +++ b/components/plugins/PluginViewPopover.tsx @@ -1,41 +1,235 @@ import React, { useLayoutEffect, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; +const MIN_POPOVER_WIDTH = 160; +const MAX_POPOVER_WIDTH = 480; +const DEFAULT_POPOVER_WIDTH = 240; +const MIN_POPOVER_HEIGHT = 80; +const MAX_POPOVER_HEIGHT = 420; + +export interface PluginViewPopoverProps { + anchor?: string; + anchorX?: number; + anchorY?: number; + width?: number; + maxHeight?: number; + open: boolean; + dismiss(): void; + children: React.ReactNode; +} + /** Geometry and dismissal belong to the host; content belongs to the plugin. */ -export function PluginViewPopover({ anchor, open, dismiss, children }: { - anchor: string; open: boolean; dismiss(): void; children: React.ReactNode; -}) { +export function PluginViewPopover({ + anchor, + anchorX, + anchorY, + width: requestedWidth, + maxHeight: requestedMaxHeight, + open, + dismiss, + children, +}: PluginViewPopoverProps) { const marker = useRef(null); const panel = useRef(null); - const dismissRef = useRef(dismiss); dismissRef.current = dismiss; - const [position, setPosition] = useState<{ left: number; top: number; width: number } | null>(null); + const dismissRef = useRef(dismiss); + dismissRef.current = dismiss; + + const [position, setPosition] = useState<{ + left: number; + top: number; + width: number; + maxHeight: number; + } | null>(null); + useLayoutEffect(() => { - if (!open || !marker.current) { setPosition(null); return; } + if (!open || !marker.current) { + setPosition(null); + return; + } const root = marker.current.getRootNode() as ShadowRoot; - const target = root.getElementById(anchor); - if (!(target instanceof marker.current.ownerDocument.defaultView!.HTMLElement)) return; - const doc = target.ownerDocument; const win = doc.defaultView!; + const doc = marker.current.ownerDocument; + const win = doc.defaultView!; + const surface = root.host instanceof win.HTMLElement + ? root.host.closest('[data-plugin-remote-surface]') + : null; + + const hasCursorCoords = + typeof anchorX === 'number' && Number.isFinite(anchorX) + && typeof anchorY === 'number' && Number.isFinite(anchorY); + + const target = anchor ? root.getElementById(anchor) : null; + const targetEl = target instanceof win.HTMLElement ? target : null; + if (!hasCursorCoords && !targetEl) { + setPosition(null); + return; + } + + const resolveSurfaceBounds = () => { + const vp = { + left: 8, + top: 8, + right: Math.max(8, win.innerWidth - 8), + bottom: Math.max(8, win.innerHeight - 8), + }; + if (!surface) return vp; + const sr = surface.getBoundingClientRect(); + if (sr.width <= 0 || sr.height <= 0) return vp; + return { + left: Math.max(vp.left, sr.left + 4), + top: Math.max(vp.top, sr.top + 4), + right: Math.min(vp.right, sr.right - 4), + bottom: Math.min(vp.bottom, sr.bottom - 4), + }; + }; + const update = () => { - const bounds = target.getBoundingClientRect(); - if (!bounds.width || !bounds.height) { setPosition(null); dismissRef.current(); return; } - const width = Math.min(360, Math.max(220, bounds.width), win.innerWidth - 16); - setPosition({ left: Math.max(8, Math.min(bounds.left, win.innerWidth - width - 8)), top: Math.max(8, Math.min(bounds.bottom + 4, win.innerHeight - 248)), width }); + const clip = resolveSurfaceBounds(); + const availableW = Math.max(MIN_POPOVER_WIDTH, clip.right - clip.left); + const availableH = Math.max(MIN_POPOVER_HEIGHT, clip.bottom - clip.top); + const boundedMaxHeight = Math.min( + availableH, + Math.max( + MIN_POPOVER_HEIGHT, + Math.min( + MAX_POPOVER_HEIGHT, + typeof requestedMaxHeight === 'number' && Number.isFinite(requestedMaxHeight) + ? Math.round(requestedMaxHeight) + : MAX_POPOVER_HEIGHT, + ), + ), + ); + + let width: number; + let rawLeft: number; + let rawTop: number; + let anchorTop: number; + + if (hasCursorCoords) { + const sr = surface?.getBoundingClientRect(); + const originLeft = sr && sr.width > 0 ? sr.left : 0; + const originTop = sr && sr.height > 0 ? sr.top : 0; + const desiredW = + typeof requestedWidth === 'number' && Number.isFinite(requestedWidth) + ? requestedWidth + : DEFAULT_POPOVER_WIDTH; + width = Math.min(availableW, Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(desiredW)))); + rawLeft = originLeft + anchorX!; + rawTop = originTop + anchorY! + 2; + anchorTop = originTop + anchorY!; + } else { + const bounds = targetEl!.getBoundingClientRect(); + if (!bounds.width || !bounds.height) { + setPosition(null); + dismissRef.current(); + return; + } + const desiredW = + typeof requestedWidth === 'number' && Number.isFinite(requestedWidth) + ? requestedWidth + : Math.min(360, Math.max(220, bounds.width)); + width = Math.min(availableW, Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(desiredW)))); + rawLeft = bounds.left; + rawTop = bounds.bottom + 4; + anchorTop = bounds.top; + } + + const left = Math.max(clip.left, Math.min(rawLeft, clip.right - width)); + const measuredHeight = panel.current?.getBoundingClientRect().height || 0; + const estimatedHeight = measuredHeight > 0 ? Math.min(measuredHeight, boundedMaxHeight) : Math.min(240, boundedMaxHeight); + + let top = rawTop; + let effectiveMaxHeight = boundedMaxHeight; + const spaceBelow = clip.bottom - rawTop; + const spaceAbove = anchorTop - 4 - clip.top; + + if (spaceBelow < estimatedHeight && spaceAbove > spaceBelow) { + effectiveMaxHeight = Math.min(boundedMaxHeight, Math.max(MIN_POPOVER_HEIGHT, Math.floor(spaceAbove))); + top = Math.max(clip.top, anchorTop - 4 - Math.min(estimatedHeight, effectiveMaxHeight)); + } else { + effectiveMaxHeight = Math.min(boundedMaxHeight, Math.max(MIN_POPOVER_HEIGHT, Math.floor(spaceBelow))); + top = Math.max(clip.top, Math.min(rawTop, clip.bottom - Math.min(estimatedHeight, effectiveMaxHeight))); + } + + setPosition({ left: Math.round(left), top: Math.round(top), width: Math.round(width), maxHeight: Math.round(effectiveMaxHeight) }); + }; + + const dismissNow = () => { + setPosition(null); + dismissRef.current(); + }; + const key = (event: KeyboardEvent) => { + if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + dismissNow(); + targetEl?.focus(); + } + }; + const outside = (event: PointerEvent) => { + const path = event.composedPath(); + if (targetEl && path.includes(targetEl)) return; + if (panel.current && path.includes(panel.current)) return; + dismissNow(); }; - const dismissNow = () => { setPosition(null); dismissRef.current(); }; - const key = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); dismissNow(); target.focus(); } }; - const outside = (event: PointerEvent) => { if (!event.composedPath().includes(target) && (!panel.current || !event.composedPath().includes(panel.current))) dismissNow(); }; const blocked = () => [...doc.querySelectorAll('[role=dialog][aria-modal=true]:not([data-plugin-dialog])')].some((dialog) => { - const rect = dialog.getBoundingClientRect(); return rect.width > 0 && rect.height > 0; + const rect = dialog.getBoundingClientRect(); + return rect.width > 0 && rect.height > 0; }); - if (blocked()) { dismissNow(); return; } - const dialogs = new win.MutationObserver(() => { if (blocked()) dismissNow(); }); - dialogs.observe(doc.body, { subtree: true, childList: true, attributes: true, attributeFilter: ['aria-modal', 'hidden', 'data-state'] }); - const resize = new win.ResizeObserver(update); resize.observe(target); update(); - win.addEventListener('resize', update); doc.addEventListener('scroll', update, true); - doc.addEventListener('keydown', key, true); doc.addEventListener('pointerdown', outside, true); - return () => { dialogs.disconnect(); resize.disconnect(); win.removeEventListener('resize', update); doc.removeEventListener('scroll', update, true); doc.removeEventListener('keydown', key, true); doc.removeEventListener('pointerdown', outside, true); }; - }, [anchor, open]); - return <>
} + > + + +
+ )} + > + + + + ); +} diff --git a/components/plugins/primitives/PluginCodeEditorInner.tsx b/components/plugins/primitives/PluginCodeEditorInner.tsx new file mode 100644 index 000000000..e796be33d --- /dev/null +++ b/components/plugins/primitives/PluginCodeEditorInner.tsx @@ -0,0 +1,409 @@ +import Editor, { loader, type Monaco, type OnMount, useMonaco } from '@monaco-editor/react'; +import { Loader2 } from 'lucide-react'; +import React, { useCallback, useEffect, useId, useRef } from 'react'; +import { useClipboardBackend } from '@/application/state/useClipboardBackend'; +import { + buildMonacoPasteEdits, + pasteForMonacoEditorCommand, + readClipboardTextWithFallbacks, +} from '@/infrastructure/monaco/monacoClipboardPaste'; +import { useNetcattyMonacoTheme } from '@/infrastructure/monaco/useNetcattyMonacoTheme'; +import { extractCurrentSqlStatement, extractSqlTableAliases } from './sqlStatement'; +import type { + PluginCodeEditorCompletionSchema, + PluginCodeEditorDiagnostic, + PluginCodeEditorWidgetProps, + PluginWidgetEventCallback, +} from './types'; + +const viteEnv = (import.meta.env ?? { BASE_URL: '/', DEV: false }) as { BASE_URL?: string; DEV?: boolean }; +const monacoBasePath = viteEnv.DEV + ? './node_modules/monaco-editor/min/vs' + : `${viteEnv.BASE_URL ?? '/'}monaco/vs`; +loader.config({ paths: { vs: monacoBasePath } }); + +const DEFAULT_SQL_KEYWORDS = [ + 'SELECT', 'FROM', 'WHERE', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'SET', 'DELETE', + 'CREATE', 'ALTER', 'DROP', 'TABLE', 'INDEX', 'VIEW', 'JOIN', 'LEFT JOIN', 'RIGHT JOIN', + 'INNER JOIN', 'FULL OUTER JOIN', 'ON', 'GROUP BY', 'ORDER BY', 'HAVING', 'LIMIT', + 'OFFSET', 'DISTINCT', 'AS', 'AND', 'OR', 'NOT', 'IN', 'IS NULL', 'IS NOT NULL', + 'BETWEEN', 'LIKE', 'ILIKE', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'UNION', 'UNION ALL', + 'WITH', 'EXPLAIN', 'ANALYZE', 'BEGIN', 'COMMIT', 'ROLLBACK', 'RETURNING', 'PRIMARY KEY', + 'FOREIGN KEY', 'REFERENCES', 'DEFAULT', 'CASCADE', 'COUNT', 'SUM', 'AVG', 'MIN', 'MAX', +]; + +const SEVERITY_MAP: Record, number> = { + hint: 1, + info: 2, + warning: 4, + error: 8, +}; + +export interface PluginCodeEditorInnerProps extends PluginCodeEditorWidgetProps { + onWidgetEvent: PluginWidgetEventCallback; +} + +export default function PluginCodeEditorInner({ + value = '', + language = 'sql', + readOnly = false, + placeholder, + lineNumbers = 'on', + minimap = false, + wordWrap = 'off', + completionSchema, + diagnostics, + height = '100%', + onWidgetEvent, +}: PluginCodeEditorInnerProps) { + const monaco = useMonaco(); + const themeName = useNetcattyMonacoTheme(monaco ?? undefined); + const { readClipboardText: readClipboardTextFromBridge } = useClipboardBackend(); + const editorId = useId(); + const modelPath = `inmemory://netcatty-plugin-editor/${editorId.replace(/[^a-zA-Z0-9_-]/g, '_')}.${language}`; + + const editorRef = useRef[0] | null>(null); + const monacoRef = useRef(null); + const disposablesRef = useRef>([]); + const onWidgetEventRef = useRef(onWidgetEvent); + onWidgetEventRef.current = onWidgetEvent; + const schemaRef = useRef(completionSchema); + schemaRef.current = completionSchema; + const lastEmittedValueRef = useRef(value); + const changeTimerRef = useRef | null>(null); + const selectionTimerRef = useRef | null>(null); + const readClipboardRef = useRef<() => Promise>(() => Promise.resolve(null)); + + const readClipboardText = useCallback(async (): Promise => ( + readClipboardTextWithFallbacks({ + readNavigator: navigator.clipboard?.readText + ? () => navigator.clipboard.readText() + : undefined, + readBridge: readClipboardTextFromBridge, + }) + ), [readClipboardTextFromBridge]); + readClipboardRef.current = readClipboardText; + + // Sync external value changes without disrupting cursor when value echoes local edits. + useEffect(() => { + const editor = editorRef.current; + if (!editor) return; + if (value === lastEmittedValueRef.current) return; + const model = editor.getModel(); + if (!model || model.getValue() === value) { + lastEmittedValueRef.current = value; + return; + } + lastEmittedValueRef.current = value; + model.setValue(value); + }, [value]); + + // Sync diagnostics markers cleanly. + useEffect(() => { + const editor = editorRef.current; + const monacoInstance = monacoRef.current ?? monaco; + if (!editor || !monacoInstance) return; + const model = editor.getModel(); + if (!model) return; + const markers = (diagnostics ?? []).map((diag) => ({ + startLineNumber: Math.max(1, Math.floor(diag.line || 1)), + startColumn: Math.max(1, Math.floor(diag.column || 1)), + endLineNumber: Math.max(1, Math.floor(diag.endLine ?? diag.line ?? 1)), + endColumn: Math.max(1, Math.floor(diag.endColumn ?? (diag.column ? diag.column + 1 : 2))), + message: diag.message, + severity: SEVERITY_MAP[diag.severity ?? 'error'] ?? 8, + })); + monacoInstance.editor.setModelMarkers(model, 'netcatty-plugin-diagnostics', markers); + }, [diagnostics, monaco]); + + // Register local schema-aware CompletionItemProvider scoped to this editor's model URI. + useEffect(() => { + if (!monaco) return; + if (!['sql', 'pgsql', 'mysql'].includes(language)) return; + const disposable = monaco.languages.registerCompletionItemProvider(language, { + triggerCharacters: ['.', ' '], + provideCompletionItems(model, position) { + if (model.uri.toString() !== modelPath) return { suggestions: [] }; + const word = model.getWordUntilPosition(position); + const range = { + startLineNumber: position.lineNumber, + endLineNumber: position.lineNumber, + startColumn: word.startColumn, + endColumn: word.endColumn, + }; + const linePrefix = model.getLineContent(position.lineNumber).slice(0, position.column - 1); + const dotMatch = /["`]?([a-zA-Z_][\w$]*)["`]?\.\s*[\w$]*$/u.exec(linePrefix); + const schema = schemaRef.current; + const tables = schema?.tables ?? []; + const suggestions: Parameters[1] extends { + provideCompletionItems: (...args: never[]) => infer R; + } + ? R extends { suggestions: infer S } + ? S + : never + : never = [] as never; + const list = suggestions as Array<{ + label: string; + kind: number; + insertText: string; + detail?: string; + sortText?: string; + range: typeof range; + }>; + + if (dotMatch) { + const qualifier = dotMatch[1].toLowerCase(); + const aliases = extractSqlTableAliases(model.getValue()); + const resolvedTableName = aliases.get(qualifier) ?? qualifier; + // Match either schema.table or table/alias.column + for (const tbl of tables) { + if (tbl.schema && tbl.schema.toLowerCase() === qualifier) { + list.push({ + label: tbl.name, + kind: monaco.languages.CompletionItemKind.Struct, + insertText: tbl.name, + detail: `${tbl.schema} table`, + sortText: `0_${tbl.name}`, + range, + }); + } + if (tbl.name.toLowerCase() === resolvedTableName.toLowerCase()) { + for (const col of tbl.columns ?? []) { + list.push({ + label: col.name, + kind: monaco.languages.CompletionItemKind.Field, + insertText: col.name, + detail: col.type ? `${tbl.name}.${col.name} (${col.type})` : `${tbl.name}.${col.name}`, + sortText: `0_${col.name}`, + range, + }); + } + } + } + return { suggestions: list as never }; + } + + const seenColumns = new Set(); + for (const tbl of tables) { + const label = tbl.schema ? `${tbl.schema}.${tbl.name}` : tbl.name; + list.push({ + label, + kind: monaco.languages.CompletionItemKind.Struct, + insertText: label, + detail: tbl.schema ? `Table (${tbl.schema})` : 'Table', + sortText: `1_${tbl.name}`, + range, + }); + if (tbl.schema) { + list.push({ + label: tbl.name, + kind: monaco.languages.CompletionItemKind.Struct, + insertText: tbl.name, + detail: `Table (${tbl.schema})`, + sortText: `1_${tbl.name}`, + range, + }); + } + for (const col of tbl.columns ?? []) { + const key = `${col.name}:${tbl.name}`; + if (seenColumns.has(key)) continue; + seenColumns.add(key); + list.push({ + label: col.name, + kind: monaco.languages.CompletionItemKind.Field, + insertText: col.name, + detail: col.type ? `${tbl.name} (${col.type})` : tbl.name, + sortText: `2_${col.name}`, + range, + }); + } + } + + for (const fn of schema?.functions ?? []) { + list.push({ + label: fn.name, + kind: monaco.languages.CompletionItemKind.Function, + insertText: fn.insertText ?? `${fn.name}()`, + detail: fn.detail ?? 'Function', + sortText: `3_${fn.name}`, + range, + }); + } + + const keywords = schema?.keywords?.length ? schema.keywords : DEFAULT_SQL_KEYWORDS; + for (const kw of keywords) { + list.push({ + label: kw, + kind: monaco.languages.CompletionItemKind.Keyword, + insertText: kw, + detail: 'Keyword', + sortText: `4_${kw}`, + range, + }); + } + + return { suggestions: list as never }; + }, + }); + return () => disposable.dispose(); + }, [language, modelPath, monaco]); + + useEffect(() => () => { + if (changeTimerRef.current) clearTimeout(changeTimerRef.current); + if (selectionTimerRef.current) clearTimeout(selectionTimerRef.current); + for (const d of disposablesRef.current.splice(0)) { + try { d.dispose(); } catch {} + } + editorRef.current = null; + }, []); + + const handleMount: OnMount = useCallback((editor, monacoInstance) => { + for (const d of disposablesRef.current.splice(0)) { + try { d.dispose(); } catch {} + } + editorRef.current = editor; + monacoRef.current = monacoInstance; + + const emitExecute = () => { + const model = editor.getModel(); + if (!model) return; + const fullValue = model.getValue(); + const sel = editor.getSelection(); + const selectedText = sel && !sel.isEmpty() ? model.getValueInRange(sel) : ''; + const cursorOffset = sel ? model.getOffsetAt(sel.getPosition()) : 0; + const currentStatement = selectedText.trim() + ? selectedText.trim() + : extractCurrentSqlStatement(fullValue, cursorOffset); + onWidgetEventRef.current('execute', { + value: fullValue, + selectedText, + currentStatement, + }); + }; + + const emitFormat = () => { + const model = editor.getModel(); + if (!model) return; + onWidgetEventRef.current('format', { value: model.getValue() }); + }; + + const handlePaste = async () => { + const text = await readClipboardRef.current(); + if (text === null) { + editor.trigger('keyboard', 'editor.action.clipboardPasteAction', null); + return; + } + if (!text) return; + const selections = editor.getSelections(); + if (!selections || selections.length === 0) return; + editor.executeEdits('netcatty-plugin-paste', buildMonacoPasteEdits(text, selections)); + editor.focus(); + }; + + disposablesRef.current.push( + editor.addAction({ + id: 'netcatty.pluginCodeEditor.execute', + label: 'Run Query', + keybindings: [monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.Enter], + run: emitExecute, + }), + editor.addAction({ + id: 'netcatty.pluginCodeEditor.formatAlt', + label: 'Format Query', + keybindings: [ + monacoInstance.KeyMod.Shift | monacoInstance.KeyMod.Alt | monacoInstance.KeyCode.KeyF, + monacoInstance.KeyMod.Shift | monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyF, + ], + run: emitFormat, + }), + editor.addAction({ + id: 'netcatty.pluginCodeEditor.paste', + label: 'Paste', + keybindings: [monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyV], + run: () => { + void pasteForMonacoEditorCommand({ + activeElement: document.activeElement, + readClipboardText: () => readClipboardRef.current(), + pasteIntoEditor: () => handlePaste(), + }); + }, + }), + editor.onDidChangeCursorSelection(() => { + if (selectionTimerRef.current) clearTimeout(selectionTimerRef.current); + selectionTimerRef.current = setTimeout(() => { + const model = editor.getModel(); + const sel = editor.getSelection(); + if (!model || !sel) return; + const selectionStart = model.getOffsetAt(sel.getStartPosition()); + const selectionEnd = model.getOffsetAt(sel.getEndPosition()); + const selectedText = sel.isEmpty() ? '' : model.getValueInRange(sel); + onWidgetEventRef.current('selection', { selectionStart, selectionEnd, selectedText }); + }, 60); + }), + ); + + requestAnimationFrame(() => editor.layout()); + }, []); + + const handleChange = useCallback((nextValue: string | undefined) => { + const next = nextValue ?? ''; + lastEmittedValueRef.current = next; + if (changeTimerRef.current) clearTimeout(changeTimerRef.current); + changeTimerRef.current = setTimeout(() => { + onWidgetEventRef.current('change', { value: next }); + }, 80); + }, []); + + const resolvedHeight = typeof height === 'number' ? `${height}px` : height; + + return ( +
+ + +
+ )} + options={{ + readOnly, + contextmenu: false, + minimap: { enabled: minimap }, + fontFamily: '"JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace', + fontSize: 13, + fontLigatures: true, + lineNumbers, + wordWrap, + scrollBeyondLastLine: false, + automaticLayout: true, + tabSize: 2, + insertSpaces: true, + folding: true, + renderLineHighlight: 'line', + padding: { top: 8, bottom: 8 }, + bracketPairColorization: { enabled: true }, + quickSuggestions: { other: true, comments: false, strings: false }, + suggestOnTriggerCharacters: true, + }} + /> + {placeholder && !value ? ( + + ) : null} +
+ ); +} diff --git a/components/plugins/primitives/PluginDataGrid.tsx b/components/plugins/primitives/PluginDataGrid.tsx new file mode 100644 index 000000000..d885c4917 --- /dev/null +++ b/components/plugins/primitives/PluginDataGrid.tsx @@ -0,0 +1,548 @@ +import { useVirtualizer } from '@tanstack/react-virtual'; +import { ArrowDown, ArrowUp, ArrowUpDown, KeyRound, Loader2 } from 'lucide-react'; +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import type { + PluginDataGridColumn, + PluginDataGridRow, + PluginDataGridWidgetProps, + PluginWidgetEventCallback, +} from './types'; + +const ROW_HEIGHT = 30; +const HEADER_HEIGHT = 34; +const GUTTER_WIDTH = 64; +const DEFAULT_COL_WIDTH = 156; +const MIN_COL_WIDTH = 68; +const MAX_COL_WIDTH = 640; + +export interface PluginDataGridProps extends PluginDataGridWidgetProps { + onWidgetEvent: PluginWidgetEventCallback; +} + +function readCellValue(row: PluginDataGridRow, col: PluginDataGridColumn, colIndex: number): unknown { + if (Array.isArray(row)) return row[colIndex]; + if (row && typeof row === 'object') return row[col.name]; + return undefined; +} + +function formatCellDisplay(value: unknown): string { + if (value === null || value === undefined) return ''; + if (typeof value === 'string') return value; + if (typeof value === 'number' || typeof value === 'boolean') return String(value); + try { + return JSON.stringify(value); + } catch { + return String(value); + } +} + +function isNumericColumn(col: PluginDataGridColumn, value: unknown): boolean { + if (typeof value === 'number') return true; + if (!col.type) return false; + return /\b(int|bigint|smallint|tinyint|decimal|numeric|float|double|real|number|serial)\b/i.test(col.type); +} + +export function PluginDataGrid({ + columns = [], + rows = [], + dirtyCells, + deletedRowIndices, + insertedRows = [], + selectedRowIndices, + sort = null, + editable = false, + loading = false, + emptyMessage = 'No rows returned', + onWidgetEvent, +}: PluginDataGridProps) { + const scrollRef = useRef(null); + const editInputRef = useRef(null); + + const [colWidths, setColWidths] = useState>({}); + const [activeCell, setActiveCell] = useState<{ rowIndex: number; colIndex: number } | null>(null); + const [editingCell, setEditingCell] = useState<{ + rowIndex: number; + colIndex: number; + colName: string; + draft: string; + } | null>(null); + const [lastSelectedRow, setLastSelectedRow] = useState(null); + + const deletedSet = useMemo(() => new Set(deletedRowIndices ?? []), [deletedRowIndices]); + const selectedSet = useMemo(() => new Set(selectedRowIndices ?? []), [selectedRowIndices]); + const totalRows = rows.length + insertedRows.length; + + const getColWidth = useCallback((col: PluginDataGridColumn): number => { + const custom = colWidths[col.name]; + if (custom !== undefined) return custom; + if (typeof col.width === 'number' && Number.isFinite(col.width)) { + return Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.round(col.width))); + } + return DEFAULT_COL_WIDTH; + }, [colWidths]); + + const rowVirtualizer = useVirtualizer({ + count: totalRows, + getScrollElement: () => scrollRef.current, + estimateSize: () => ROW_HEIGHT, + overscan: 8, + initialRect: { width: 960, height: 420 }, + }); + + const colVirtualizer = useVirtualizer({ + horizontal: true, + count: columns.length, + getScrollElement: () => scrollRef.current, + estimateSize: (index) => (columns[index] ? getColWidth(columns[index]) : DEFAULT_COL_WIDTH), + overscan: 4, + initialRect: { width: 960, height: 420 }, + }); + + useEffect(() => { + colVirtualizer.measure(); + }, [colWidths, columns, colVirtualizer]); + + useEffect(() => { + if (editingCell) { + const focusInput = () => { + editInputRef.current?.focus(); + editInputRef.current?.select(); + }; + if (typeof requestAnimationFrame === 'function') { + requestAnimationFrame(focusInput); + } else { + focusInput(); + } + } + }, [editingCell?.rowIndex, editingCell?.colIndex]); + + const getRowAt = useCallback((rowIndex: number): { row: PluginDataGridRow; isInserted: boolean } | null => { + if (rowIndex < rows.length) return { row: rows[rowIndex], isInserted: false }; + const insertedIdx = rowIndex - rows.length; + if (insertedIdx >= 0 && insertedIdx < insertedRows.length) { + return { row: insertedRows[insertedIdx], isInserted: true }; + } + return null; + }, [rows, insertedRows]); + + const getEffectiveValue = useCallback((rowIndex: number, col: PluginDataGridColumn, colIndex: number) => { + const dirtyKey = `${rowIndex}:${col.name}`; + const isDirty = Boolean(dirtyCells && Object.prototype.hasOwnProperty.call(dirtyCells, dirtyKey)); + const entry = getRowAt(rowIndex); + const rawValue = entry ? readCellValue(entry.row, col, colIndex) : undefined; + return { + value: isDirty ? dirtyCells![dirtyKey] : rawValue, + isDirty, + isInserted: entry?.isInserted ?? false, + }; + }, [dirtyCells, getRowAt]); + + const commitEdit = useCallback((cell: { rowIndex: number; colIndex: number; colName: string; draft: string }, asNull = false) => { + setEditingCell(null); + onWidgetEvent('cellEdit', { + rowIndex: cell.rowIndex, + colName: cell.colName, + value: asNull ? null : cell.draft, + isNull: asNull, + }); + }, [onWidgetEvent]); + + const beginEdit = useCallback((rowIndex: number, colIndex: number) => { + if (!editable || deletedSet.has(rowIndex)) return; + const col = columns[colIndex]; + if (!col) return; + const { value } = getEffectiveValue(rowIndex, col, colIndex); + setActiveCell({ rowIndex, colIndex }); + setEditingCell({ + rowIndex, + colIndex, + colName: col.name, + draft: value === null || value === undefined ? '' : formatCellDisplay(value), + }); + }, [editable, deletedSet, columns, getEffectiveValue]); + + const toggleRowSelection = useCallback((rowIndex: number, shiftKey: boolean) => { + const next = new Set(selectedSet); + if (shiftKey && lastSelectedRow !== null) { + const lo = Math.min(lastSelectedRow, rowIndex); + const hi = Math.max(lastSelectedRow, rowIndex); + for (let i = lo; i <= hi; i += 1) next.add(i); + } else if (next.has(rowIndex)) { + next.delete(rowIndex); + } else { + next.add(rowIndex); + } + setLastSelectedRow(rowIndex); + onWidgetEvent('rowSelect', { selectedRowIndices: [...next].sort((a, b) => a - b) }); + }, [selectedSet, lastSelectedRow, onWidgetEvent]); + + const toggleSelectAll = useCallback(() => { + if (totalRows === 0) return; + const allSelected = selectedSet.size >= totalRows; + const next = allSelected ? [] : Array.from({ length: totalRows }, (_, i) => i); + onWidgetEvent('rowSelect', { selectedRowIndices: next }); + }, [totalRows, selectedSet.size, onWidgetEvent]); + + const handleSortClick = useCallback((col: PluginDataGridColumn) => { + if (col.sortable === false) return; + const nextDirection = sort?.column === col.name && sort.direction === 'asc' ? 'desc' : 'asc'; + onWidgetEvent('sortChange', { column: col.name, direction: nextDirection }); + }, [sort, onWidgetEvent]); + + const startResizeColumn = useCallback((event: React.PointerEvent, col: PluginDataGridColumn) => { + event.preventDefault(); + event.stopPropagation(); + const startX = event.clientX; + const startWidth = getColWidth(col); + const target = event.currentTarget; + try { target.setPointerCapture(event.pointerId); } catch {} + const onMove = (moveEvent: PointerEvent) => { + const nextWidth = Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.round(startWidth + (moveEvent.clientX - startX)))); + setColWidths((prev) => (prev[col.name] === nextWidth ? prev : { ...prev, [col.name]: nextWidth })); + }; + const onUp = () => { + try { target.releasePointerCapture(event.pointerId); } catch {} + window.removeEventListener('pointermove', onMove); + window.removeEventListener('pointerup', onUp); + window.removeEventListener('pointercancel', onUp); + }; + window.addEventListener('pointermove', onMove); + window.addEventListener('pointerup', onUp); + window.addEventListener('pointercancel', onUp); + }, [getColWidth]); + + const handleCellContextMenu = useCallback(( + event: React.MouseEvent, + rowIndex: number, + colName: string, + ) => { + event.preventDefault(); + event.stopPropagation(); + const surface = scrollRef.current?.closest('[data-plugin-remote-surface]'); + const rect = surface?.getBoundingClientRect(); + const x = Math.round(rect ? event.clientX - rect.left : event.clientX); + const y = Math.round(rect ? event.clientY - rect.top : event.clientY); + onWidgetEvent('cellContextMenu', { rowIndex, colName, x, y }); + }, [onWidgetEvent]); + + const handleGridKeyDown = useCallback((event: React.KeyboardEvent) => { + if (editingCell || !activeCell || columns.length === 0 || totalRows === 0) return; + const { rowIndex, colIndex } = activeCell; + if (event.key === 'ArrowDown' && rowIndex + 1 < totalRows) { + event.preventDefault(); + setActiveCell({ rowIndex: rowIndex + 1, colIndex }); + rowVirtualizer.scrollToIndex(rowIndex + 1); + } else if (event.key === 'ArrowUp' && rowIndex > 0) { + event.preventDefault(); + setActiveCell({ rowIndex: rowIndex - 1, colIndex }); + rowVirtualizer.scrollToIndex(rowIndex - 1); + } else if (event.key === 'ArrowRight' && colIndex + 1 < columns.length) { + event.preventDefault(); + setActiveCell({ rowIndex, colIndex: colIndex + 1 }); + colVirtualizer.scrollToIndex(colIndex + 1); + } else if (event.key === 'ArrowLeft' && colIndex > 0) { + event.preventDefault(); + setActiveCell({ rowIndex, colIndex: colIndex - 1 }); + colVirtualizer.scrollToIndex(colIndex - 1); + } else if (event.key === 'Enter' && editable) { + event.preventDefault(); + beginEdit(rowIndex, colIndex); + } + }, [editingCell, activeCell, columns.length, totalRows, rowVirtualizer, colVirtualizer, editable, beginEdit]); + + const virtualRows = rowVirtualizer.getVirtualItems(); + const virtualCols = colVirtualizer.getVirtualItems(); + const totalWidth = GUTTER_WIDTH + colVirtualizer.getTotalSize(); + const totalHeight = rowVirtualizer.getTotalSize(); + const allSelected = totalRows > 0 && selectedSet.size >= totalRows; + + return ( +
+ {loading && ( +
+ + + Loading... + +
+ )} + +
+ {columns.length === 0 ? ( +
+ {emptyMessage} +
+ ) : ( +
+ {/* Sticky Header */} +
+
+ + # +
+ +
+ {virtualCols.map((vCol) => { + const col = columns[vCol.index]; + if (!col) return null; + const isSorted = sort?.column === col.name; + const sortable = col.sortable !== false; + return ( +
+ + {sortable && ( + + {isSorted ? ( + sort.direction === 'asc' ? : + ) : ( + + )} + + )} +
startResizeColumn(e, col)} + className="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/60" + /> +
+ ); + })} +
+
+ + {/* Virtualized Rows Body */} + {totalRows === 0 ? ( +
+ {emptyMessage} +
+ ) : ( +
+ {virtualRows.map((vRow) => { + const rowIndex = vRow.index; + const entry = getRowAt(rowIndex); + if (!entry) return null; + const isDeleted = deletedSet.has(rowIndex); + const isSelected = selectedSet.has(rowIndex); + const isInserted = entry.isInserted; + + const rowBg = isDeleted + ? 'bg-destructive/10 text-destructive/80 line-through' + : isInserted + ? 'bg-emerald-500/10' + : isSelected + ? 'bg-primary/10' + : rowIndex % 2 === 1 + ? 'bg-muted/20' + : 'bg-background'; + + return ( +
+ {/* Sticky Gutter */} +
handleCellContextMenu(e, rowIndex, columns[0]?.name ?? '')} + > + {}} + onClick={(e) => { + e.stopPropagation(); + toggleRowSelection(rowIndex, e.shiftKey); + }} + className="h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer" + /> + + {isInserted ? '+' : rowIndex + 1} + +
+ + {/* Virtualized Cells */} +
+ {virtualCols.map((vCol) => { + const colIndex = vCol.index; + const col = columns[colIndex]; + if (!col) return null; + const { value, isDirty } = getEffectiveValue(rowIndex, col, colIndex); + const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === colIndex; + const isActive = activeCell?.rowIndex === rowIndex && activeCell?.colIndex === colIndex; + const isNull = value === null || value === undefined; + const numeric = !isNull && isNumericColumn(col, value); + + return ( +
{ + setActiveCell({ rowIndex, colIndex }); + onWidgetEvent('cellSelect', { + rowIndex, + colName: col.name, + value: value === undefined ? null : value, + }); + }} + onDoubleClick={() => beginEdit(rowIndex, colIndex)} + onContextMenu={(e) => handleCellContextMenu(e, rowIndex, col.name)} + > + {isEditing ? ( +
e.stopPropagation()} + onDoubleClick={(e) => e.stopPropagation()} + > + setEditingCell({ ...editingCell, draft: e.target.value })} + onKeyDown={(e) => { + e.stopPropagation(); + if (e.key === 'Enter') { + e.preventDefault(); + commitEdit(editingCell, false); + } else if (e.key === 'Escape') { + e.preventDefault(); + setEditingCell(null); + } else if (e.key === 'Tab') { + e.preventDefault(); + commitEdit(editingCell, false); + const nextCol = e.shiftKey ? colIndex - 1 : colIndex + 1; + if (nextCol >= 0 && nextCol < columns.length) { + beginEdit(rowIndex, nextCol); + } + } + }} + onBlur={() => { + // Delay slightly so clicking the inline NULL button wins over blur. + const snapshot = editingCell; + setTimeout(() => { + setEditingCell((curr) => { + if (curr && curr.rowIndex === snapshot.rowIndex && curr.colIndex === snapshot.colIndex) { + onWidgetEvent('cellEdit', { + rowIndex: curr.rowIndex, + colName: curr.colName, + value: curr.draft, + isNull: false, + }); + return null; + } + return curr; + }); + }, 0); + }} + className="h-6 min-w-0 flex-1 rounded border border-primary bg-background px-1.5 font-mono text-[12px] text-foreground outline-none" + /> + {col.nullable !== false && ( + + )} +
+ ) : isNull ? ( + + NULL + + ) : typeof value === 'boolean' ? ( + + {value ? 'true' : 'false'} + + ) : ( + + {formatCellDisplay(value)} + + )} +
+ ); + })} +
+
+ ); + })} +
+ )} +
+ )} +
+
+ ); +} diff --git a/components/plugins/primitives/PluginErCanvas.tsx b/components/plugins/primitives/PluginErCanvas.tsx new file mode 100644 index 000000000..e281153c9 --- /dev/null +++ b/components/plugins/primitives/PluginErCanvas.tsx @@ -0,0 +1,484 @@ +import { Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react'; +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import type { + PluginErCanvasWidgetProps, + PluginErTable, + PluginWidgetEventCallback, +} from './types'; + +const CARD_WIDTH = 236; +const CARD_HEADER_HEIGHT = 34; +const CARD_ROW_HEIGHT = 24; +const CARD_FOOTER_PADDING = 8; +const GRID_GAP_X = 76; +const GRID_GAP_Y = 56; +const MIN_ZOOM = 0.25; +const MAX_ZOOM = 2.5; + +export interface PluginErCanvasProps extends PluginErCanvasWidgetProps { + onWidgetEvent: PluginWidgetEventCallback; +} + +function tableKey(table: Pick): string { + return table.schema ? `${table.schema}.${table.name}` : table.name; +} + +function cardHeight(table: PluginErTable): number { + return CARD_HEADER_HEIGHT + Math.max(1, table.columns.length) * CARD_ROW_HEIGHT + CARD_FOOTER_PADDING; +} + +function computeInitialPositions(tables: PluginErTable[]): Record { + const result: Record = {}; + const colsPerRow = Math.max(1, Math.min(4, Math.ceil(Math.sqrt(tables.length || 1)))); + const colY = Array.from({ length: colsPerRow }, () => 40); + + tables.forEach((table, index) => { + const key = tableKey(table); + if (typeof table.x === 'number' && Number.isFinite(table.x) && typeof table.y === 'number' && Number.isFinite(table.y)) { + result[key] = { x: table.x, y: table.y }; + return; + } + const colIdx = index % colsPerRow; + const x = 40 + colIdx * (CARD_WIDTH + GRID_GAP_X); + const y = colY[colIdx]; + result[key] = { x, y }; + colY[colIdx] = y + cardHeight(table) + GRID_GAP_Y; + }); + + return result; +} + +export function PluginErCanvas({ + tables = [], + relations = [], + onWidgetEvent, +}: PluginErCanvasProps) { + const containerRef = useRef(null); + const [positions, setPositions] = useState>(() => computeInitialPositions(tables)); + const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 }); + const [selectedTable, setSelectedTable] = useState(null); + const [hoveredRelation, setHoveredRelation] = useState(null); + const [panning, setPanning] = useState(false); + + const tableSignature = useMemo( + () => tables.map((t) => `${tableKey(t)}:${t.x ?? ''}:${t.y ?? ''}`).join('|'), + [tables], + ); + + useEffect(() => { + setPositions((prev) => { + const defaults = computeInitialPositions(tables); + const next: Record = {}; + for (const tbl of tables) { + const key = tableKey(tbl); + next[key] = prev[key] ?? defaults[key]; + } + return next; + }); + }, [tableSignature, tables]); + + const tableLookup = useMemo(() => { + const byKey = new Map(); + const byName = new Map(); + for (const tbl of tables) { + byKey.set(tableKey(tbl), tbl); + if (!byName.has(tbl.name)) byName.set(tbl.name, tbl); + } + return { byKey, byName }; + }, [tables]); + + const resolveTable = useCallback((ref: string): PluginErTable | undefined => ( + tableLookup.byKey.get(ref) ?? tableLookup.byName.get(ref) + ), [tableLookup]); + + const fitToView = useCallback(() => { + const el = containerRef.current; + if (!el || tables.length === 0) { + setViewport({ x: 0, y: 0, zoom: 1 }); + return; + } + const rect = el.getBoundingClientRect(); + if (!rect.width || !rect.height) return; + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const tbl of tables) { + const pos = positions[tableKey(tbl)] ?? { x: 0, y: 0 }; + minX = Math.min(minX, pos.x); + minY = Math.min(minY, pos.y); + maxX = Math.max(maxX, pos.x + CARD_WIDTH); + maxY = Math.max(maxY, pos.y + cardHeight(tbl)); + } + const contentW = Math.max(1, maxX - minX); + const contentH = Math.max(1, maxY - minY); + const pad = 48; + const zoom = Math.max( + MIN_ZOOM, + Math.min(1.15, Math.min((rect.width - pad * 2) / contentW, (rect.height - pad * 2) / contentH)), + ); + const x = (rect.width - contentW * zoom) / 2 - minX * zoom; + const y = (rect.height - contentH * zoom) / 2 - minY * zoom; + setViewport({ x, y, zoom }); + }, [tables, positions]); + + useEffect(() => { + if (typeof requestAnimationFrame !== 'function') { + fitToView(); + return; + } + const frame = requestAnimationFrame(fitToView); + return () => cancelAnimationFrame(frame); + }, [tableSignature]); + + const handleWheel = useCallback((event: React.WheelEvent) => { + event.preventDefault(); + const el = containerRef.current; + if (!el) return; + const rect = el.getBoundingClientRect(); + const mouseX = event.clientX - rect.left; + const mouseY = event.clientY - rect.top; + const factor = event.deltaY < 0 ? 1.1 : 0.9; + setViewport((prev) => { + const nextZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, prev.zoom * factor)); + const scale = nextZoom / prev.zoom; + return { + zoom: nextZoom, + x: mouseX - (mouseX - prev.x) * scale, + y: mouseY - (mouseY - prev.y) * scale, + }; + }); + }, []); + + const handleCanvasPointerDown = useCallback((event: React.PointerEvent) => { + if (event.button !== 0) return; + if ((event.target as Element).closest?.('[data-er-table]')) return; + event.preventDefault(); + const startX = event.clientX; + const startY = event.clientY; + const initialX = viewport.x; + const initialY = viewport.y; + setPanning(true); + const onMove = (moveEvent: PointerEvent) => { + setViewport((prev) => ({ + ...prev, + x: initialX + (moveEvent.clientX - startX), + y: initialY + (moveEvent.clientY - startY), + })); + }; + const onUp = () => { + setPanning(false); + window.removeEventListener('pointermove', onMove); + window.removeEventListener('pointerup', onUp); + window.removeEventListener('pointercancel', onUp); + }; + window.addEventListener('pointermove', onMove); + window.addEventListener('pointerup', onUp); + window.addEventListener('pointercancel', onUp); + }, [viewport.x, viewport.y]); + + const startCardDrag = useCallback((event: React.PointerEvent, table: PluginErTable) => { + if (event.button !== 0) return; + event.stopPropagation(); + const key = tableKey(table); + const startX = event.clientX; + const startY = event.clientY; + const origin = positions[key] ?? { x: 0, y: 0 }; + const zoom = viewport.zoom; + let moved = false; + + const onMove = (moveEvent: PointerEvent) => { + const dx = moveEvent.clientX - startX; + const dy = moveEvent.clientY - startY; + if (Math.abs(dx) > 3 || Math.abs(dy) > 3) moved = true; + if (!moved) return; + setPositions((prev) => ({ + ...prev, + [key]: { x: Math.round(origin.x + dx / zoom), y: Math.round(origin.y + dy / zoom) }, + })); + }; + + const onUp = () => { + window.removeEventListener('pointermove', onMove); + window.removeEventListener('pointerup', onUp); + window.removeEventListener('pointercancel', onUp); + if (!moved) { + setSelectedTable(key); + onWidgetEvent('tableClick', { + table: table.name, + ...(table.schema ? { schema: table.schema } : {}), + }); + } + }; + + window.addEventListener('pointermove', onMove); + window.addEventListener('pointerup', onUp); + window.addEventListener('pointercancel', onUp); + }, [positions, viewport.zoom, onWidgetEvent]); + + const zoomBy = useCallback((factor: number) => { + const el = containerRef.current; + const rect = el?.getBoundingClientRect(); + const cx = rect ? rect.width / 2 : 300; + const cy = rect ? rect.height / 2 : 200; + setViewport((prev) => { + const nextZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, prev.zoom * factor)); + const scale = nextZoom / prev.zoom; + return { + zoom: nextZoom, + x: cx - (cx - prev.x) * scale, + y: cy - (cy - prev.y) * scale, + }; + }); + }, []); + + const resetLayout = useCallback(() => { + setPositions(computeInitialPositions(tables)); + requestAnimationFrame(fitToView); + }, [tables, fitToView]); + + return ( +
+ {/* Floating Canvas Controls */} +
+ + + {Math.round(viewport.zoom * 100)}% + + +
+ + +
+ + {tables.length === 0 ? ( +
+ No tables to visualize +
+ ) : ( + + + + + + + + + + + + + {/* Foreign Key Bezier Curves */} + {relations.map((rel, idx) => { + const fromTable = resolveTable(rel.fromTable); + const toTable = resolveTable(rel.toTable); + if (!fromTable || !toTable) return null; + const fromKey = tableKey(fromTable); + const toKey = tableKey(toTable); + const fromPos = positions[fromKey] ?? { x: 0, y: 0 }; + const toPos = positions[toKey] ?? { x: 0, y: 0 }; + const fromColIdx = Math.max(0, fromTable.columns.findIndex((c) => c.name === rel.fromColumn)); + const toColIdx = Math.max(0, toTable.columns.findIndex((c) => c.name === rel.toColumn)); + const y1 = fromPos.y + CARD_HEADER_HEIGHT + fromColIdx * CARD_ROW_HEIGHT + CARD_ROW_HEIGHT / 2; + const y2 = toPos.y + CARD_HEADER_HEIGHT + toColIdx * CARD_ROW_HEIGHT + CARD_ROW_HEIGHT / 2; + const fromCenter = fromPos.x + CARD_WIDTH / 2; + const toCenter = toPos.x + CARD_WIDTH / 2; + const goRight = toCenter >= fromCenter; + const x1 = goRight ? fromPos.x + CARD_WIDTH : fromPos.x; + const x2 = goRight ? toPos.x : toPos.x + CARD_WIDTH; + const dx = Math.max(48, Math.abs(x2 - x1) * 0.45); + const c1x = goRight ? x1 + dx : x1 - dx; + const c2x = goRight ? x2 - dx : x2 + dx; + const highlighted = hoveredRelation === idx || selectedTable === fromKey || selectedTable === toKey; + const stroke = highlighted ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))'; + + return ( + ${toKey}.${rel.toColumn}:${idx}`} + onPointerEnter={() => setHoveredRelation(idx)} + onPointerLeave={() => setHoveredRelation(null)} + > + + + + + {rel.name && highlighted && ( + + {rel.name} + + )} + + ); + })} + + {/* Table Cards */} + {tables.map((table) => { + const key = tableKey(table); + const pos = positions[key] ?? { x: 0, y: 0 }; + const height = cardHeight(table); + const isSelected = selectedTable === key; + + return ( + startCardDrag(e, table)} + className="cursor-pointer" + filter="url(#nc-er-shadow)" + > + + {/* Header band */} + + + + {table.schema ? `${table.schema}.${table.name}` : table.name} + + + {/* Columns */} + {table.columns.map((col, colIdx) => { + const rowY = CARD_HEADER_HEIGHT + colIdx * CARD_ROW_HEIGHT; + const badgeOffset = (col.isPk ? 26 : 0) + (col.isFk ? 26 : 0); + return ( + + {colIdx > 0 && ( + + )} + {col.isPk && ( + + + + PK + + + )} + {col.isFk && ( + + + + FK + + + )} + + {col.name.length > 18 ? `${col.name.slice(0, 17)}…` : col.name} + + + {`${col.type}${col.nullable ? '?' : ''}`.slice(0, 14)} + + + ); + })} + + ); + })} + + + )} +
+ ); +} diff --git a/components/plugins/primitives/PluginSplitPane.tsx b/components/plugins/primitives/PluginSplitPane.tsx new file mode 100644 index 000000000..eee7b6287 --- /dev/null +++ b/components/plugins/primitives/PluginSplitPane.tsx @@ -0,0 +1,198 @@ +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import type { PluginSplitPaneWidgetProps, PluginWidgetEventCallback } from './types'; + +export interface PluginSplitPaneProps extends PluginSplitPaneWidgetProps { + firstChild: React.ReactNode; + secondChild: React.ReactNode; + nodeId: string; + className?: string; + inlineStyle?: string; + onWidgetEvent: PluginWidgetEventCallback; +} + +/** + * 60fps host-managed 2-child split container rendered inside the shadow root so + * child plugin trees keep full plugin CSS scoping and can nest freely. + */ +export function PluginSplitPane({ + direction = 'horizontal', + initialSize = 260, + minSize = 120, + maxSize = 900, + collapsible = false, + collapsed: controlledCollapsed, + firstChild, + secondChild, + nodeId, + className, + inlineStyle, + onWidgetEvent, +}: PluginSplitPaneProps) { + const containerRef = useRef(null); + const clampSize = useCallback( + (raw: number) => Math.max(minSize, Math.min(maxSize, Math.round(raw))), + [minSize, maxSize], + ); + + const [size, setSize] = useState(() => clampSize(initialSize)); + const [collapsed, setCollapsed] = useState(Boolean(controlledCollapsed)); + const [dragging, setDragging] = useState(false); + const [hovered, setHovered] = useState(false); + const sizeRef = useRef(size); + sizeRef.current = size; + + useEffect(() => { + if (controlledCollapsed !== undefined) setCollapsed(controlledCollapsed); + }, [controlledCollapsed]); + + const isHorizontal = direction !== 'vertical'; + + const handlePointerDown = useCallback((event: React.PointerEvent) => { + event.preventDefault(); + event.stopPropagation(); + const target = event.currentTarget; + const startCoord = isHorizontal ? event.clientX : event.clientY; + const startSize = collapsed ? minSize : sizeRef.current; + setDragging(true); + try { target.setPointerCapture(event.pointerId); } catch {} + + let latestSize = startSize; + let latestCollapsed = collapsed; + + const onMove = (moveEvent: PointerEvent) => { + const containerRect = containerRef.current?.getBoundingClientRect(); + const maxFromContainer = containerRect + ? Math.max(minSize, (isHorizontal ? containerRect.width : containerRect.height) - 64) + : maxSize; + const effectiveMax = Math.min(maxSize, maxFromContainer); + const delta = (isHorizontal ? moveEvent.clientX : moveEvent.clientY) - startCoord; + const raw = startSize + delta; + if (collapsible && raw < minSize * 0.5) { + latestCollapsed = true; + setCollapsed(true); + } else { + latestCollapsed = false; + latestSize = Math.max(minSize, Math.min(effectiveMax, Math.round(raw))); + setCollapsed(false); + setSize(latestSize); + } + }; + + const onUp = () => { + setDragging(false); + try { target.releasePointerCapture(event.pointerId); } catch {} + window.removeEventListener('pointermove', onMove); + window.removeEventListener('pointerup', onUp); + window.removeEventListener('pointercancel', onUp); + onWidgetEvent('resizeEnd', { + size: latestCollapsed ? 0 : latestSize, + collapsed: latestCollapsed, + }); + }; + + window.addEventListener('pointermove', onMove); + window.addEventListener('pointerup', onUp); + window.addEventListener('pointercancel', onUp); + }, [isHorizontal, collapsed, minSize, maxSize, collapsible, onWidgetEvent]); + + const handleDoubleClick = useCallback(() => { + if (!collapsible) return; + const nextCollapsed = !collapsed; + setCollapsed(nextCollapsed); + onWidgetEvent('resizeEnd', { + size: nextCollapsed ? 0 : sizeRef.current, + collapsed: nextCollapsed, + }); + }, [collapsible, collapsed, onWidgetEvent]); + + const setContainerRef = useCallback((el: HTMLDivElement | null) => { + containerRef.current = el; + if (!el) return; + if (inlineStyle) { + el.setAttribute('style', `${inlineStyle};display:flex;flex-direction:${isHorizontal ? 'row' : 'column'};width:100%;height:100%;min-width:0;min-height:0;overflow:hidden`); + } + }, [inlineStyle, isHorizontal]); + + const dividerActive = dragging || hovered; + + return ( +
+
+ {firstChild} +
+ +
setHovered(true)} + onPointerLeave={() => setHovered(false)} + style={{ + position: 'relative', + flex: isHorizontal ? '0 0 5px' : '0 0 5px', + cursor: isHorizontal ? 'col-resize' : 'row-resize', + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + background: 'transparent', + zIndex: 5, + touchAction: 'none', + }} + > +
+
+ +
+ {secondChild} +
+
+ ); +} diff --git a/components/plugins/primitives/PluginWidgetRenderer.tsx b/components/plugins/primitives/PluginWidgetRenderer.tsx new file mode 100644 index 000000000..7789c2bdd --- /dev/null +++ b/components/plugins/primitives/PluginWidgetRenderer.tsx @@ -0,0 +1,55 @@ +import React, { useMemo } from 'react'; +import { LazyLoadBoundary } from '../../ui/lazy-load-boundary'; +import { PluginCodeEditor } from './PluginCodeEditor'; +import { PluginDataGrid } from './PluginDataGrid'; +import { PluginErCanvas } from './PluginErCanvas'; +import type { + PluginCodeEditorWidgetProps, + PluginDataGridWidgetProps, + PluginErCanvasWidgetProps, + PluginWidgetEventCallback, +} from './types'; + +export type SlottedWidgetKind = 'code-editor' | 'data-grid' | 'er-canvas'; + +export function parseWidgetPropsJson(raw: string | undefined): T { + if (!raw) return {} as T; + try { + const parsed = JSON.parse(raw); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + return parsed as T; + } + } catch { + // Policy already validates widget props; fall back to empty props defensively. + } + return {} as T; +} + +export function PluginSlottedWidget({ + kind, + rawProps, + onWidgetEvent, +}: { + kind: SlottedWidgetKind; + rawProps: string | undefined; + onWidgetEvent: PluginWidgetEventCallback; +}) { + const parsedProps = useMemo(() => parseWidgetPropsJson>(rawProps), [rawProps]); + + return ( + Unable to render plugin widget.
} + > + {kind === 'code-editor' && ( + + )} + {kind === 'data-grid' && ( + + )} + {kind === 'er-canvas' && ( + + )} + + ); +} diff --git a/components/plugins/primitives/sqlStatement.test.ts b/components/plugins/primitives/sqlStatement.test.ts new file mode 100644 index 000000000..1a194ae89 --- /dev/null +++ b/components/plugins/primitives/sqlStatement.test.ts @@ -0,0 +1,37 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { extractCurrentSqlStatement, extractSqlTableAliases } from './sqlStatement'; + +test('extractCurrentSqlStatement splits statements respecting strings, comments, and PG dollar quotes', () => { + const sql = [ + "-- first query; not a split", + "SELECT 'semi;colon' AS a;", + "CREATE FUNCTION f() RETURNS text AS $$ BEGIN RETURN 'x;y'; END; $$ LANGUAGE plpgsql;", + "SELECT /* block; comment */ * FROM orders WHERE id = 1", + ].join('\n'); + + const firstIdx = sql.indexOf("SELECT 'semi"); + assert.equal(extractCurrentSqlStatement(sql, firstIdx + 5), "-- first query; not a split\nSELECT 'semi;colon' AS a"); + + const fnIdx = sql.indexOf("RETURN 'x;y'"); + assert.equal( + extractCurrentSqlStatement(sql, fnIdx), + "CREATE FUNCTION f() RETURNS text AS $$ BEGIN RETURN 'x;y'; END; $$ LANGUAGE plpgsql", + ); + + const lastIdx = sql.indexOf('FROM orders'); + assert.equal( + extractCurrentSqlStatement(sql, lastIdx), + 'SELECT /* block; comment */ * FROM orders WHERE id = 1', + ); +}); + +test('extractSqlTableAliases resolves table names and aliases across FROM and JOIN clauses', () => { + const sql = 'SELECT o.id, u.email FROM public.orders AS o INNER JOIN users u ON u.id = o.user_id WHERE o.status = 1'; + const aliases = extractSqlTableAliases(sql); + assert.equal(aliases.get('o'), 'orders'); + assert.equal(aliases.get('orders'), 'orders'); + assert.equal(aliases.get('u'), 'users'); + assert.equal(aliases.get('users'), 'users'); + assert.equal(aliases.has('where'), false); +}); diff --git a/components/plugins/primitives/sqlStatement.ts b/components/plugins/primitives/sqlStatement.ts new file mode 100644 index 000000000..ceb9ded02 --- /dev/null +++ b/components/plugins/primitives/sqlStatement.ts @@ -0,0 +1,164 @@ +/** + * Pure SQL statement and alias helpers used by PluginCodeEditor. + * Runs synchronously in the host renderer with zero IPC overhead. + */ + +export function extractCurrentSqlStatement(sql: string, cursorOffset: number): string { + if (!sql) return ''; + const clampedCursor = Math.max(0, Math.min(cursorOffset, sql.length)); + const statements: Array<{ start: number; end: number; text: string }> = []; + + let start = 0; + let i = 0; + let inSingle = false; + let inDouble = false; + let inBacktick = false; + let inLineComment = false; + let inBlockComment = false; + let dollarTag: string | null = null; + + while (i < sql.length) { + const ch = sql[i]; + const next = sql[i + 1]; + + if (inLineComment) { + if (ch === '\n') inLineComment = false; + i += 1; + continue; + } + if (inBlockComment) { + if (ch === '*' && next === '/') { + inBlockComment = false; + i += 2; + continue; + } + i += 1; + continue; + } + if (dollarTag !== null) { + if (sql.startsWith(dollarTag, i)) { + i += dollarTag.length; + dollarTag = null; + continue; + } + i += 1; + continue; + } + if (inSingle) { + if (ch === "'" && next === "'") { + i += 2; + continue; + } + if (ch === '\\' && next !== undefined) { + i += 2; + continue; + } + if (ch === "'") inSingle = false; + i += 1; + continue; + } + if (inDouble) { + if (ch === '"' && next === '"') { + i += 2; + continue; + } + if (ch === '"') inDouble = false; + i += 1; + continue; + } + if (inBacktick) { + if (ch === '`' && next === '`') { + i += 2; + continue; + } + if (ch === '`') inBacktick = false; + i += 1; + continue; + } + + if (ch === '-' && next === '-') { + inLineComment = true; + i += 2; + continue; + } + if (ch === '/' && next === '*') { + inBlockComment = true; + i += 2; + continue; + } + if (ch === "'") { + inSingle = true; + i += 1; + continue; + } + if (ch === '"') { + inDouble = true; + i += 1; + continue; + } + if (ch === '`') { + inBacktick = true; + i += 1; + continue; + } + if (ch === '$') { + const match = /^\$[a-zA-Z0-9_]*\$/u.exec(sql.slice(i)); + if (match) { + dollarTag = match[0]; + i += dollarTag.length; + continue; + } + } + if (ch === ';') { + const raw = sql.slice(start, i); + if (raw.trim().length > 0) { + statements.push({ start, end: i + 1, text: raw.trim() }); + } + start = i + 1; + i += 1; + continue; + } + i += 1; + } + + const tail = sql.slice(start); + if (tail.trim().length > 0) { + statements.push({ start, end: sql.length, text: tail.trim() }); + } + + if (statements.length === 0) return sql.trim(); + + for (const stmt of statements) { + if (clampedCursor >= stmt.start && clampedCursor <= stmt.end) { + return stmt.text; + } + } + // If cursor sits in trailing whitespace after a semicolon, return the preceding statement. + let chosen = statements[0]; + for (const stmt of statements) { + if (stmt.start <= clampedCursor) chosen = stmt; + } + return chosen.text; +} + +/** Extract simple `FROM/JOIN [schema.]table [AS] alias` bindings for dot-completion. */ +export function extractSqlTableAliases(sql: string): Map { + const aliases = new Map(); + const pattern = /\b(?:from|join|update|into)\s+(?:["`]?([a-zA-Z_][\w$]*)["`]?\.)?["`]?([a-zA-Z_][\w$]*)["`]?(?:\s+(?:as\s+)?["`]?([a-zA-Z_][\w$]*)["`]?)?/giu; + const reserved = new Set([ + 'where', 'on', 'set', 'values', 'inner', 'left', 'right', 'full', 'outer', + 'cross', 'join', 'group', 'order', 'having', 'limit', 'offset', 'union', + 'select', 'from', 'as', 'using', 'returning', + ]); + let match: RegExpExecArray | null; + while ((match = pattern.exec(sql)) !== null) { + const tableName = match[2]; + const alias = match[3]; + if (!tableName) continue; + aliases.set(tableName.toLowerCase(), tableName); + if (alias && !reserved.has(alias.toLowerCase())) { + aliases.set(alias.toLowerCase(), tableName); + } + } + return aliases; +} diff --git a/components/plugins/primitives/types.ts b/components/plugins/primitives/types.ts new file mode 100644 index 000000000..d7e6beecc --- /dev/null +++ b/components/plugins/primitives/types.ts @@ -0,0 +1,117 @@ +export type PluginWidgetEventCallback = ( + widgetEvent: string, + detail?: Record, +) => void; + +export interface PluginCodeEditorCompletionColumn { + name: string; + type?: string; +} + +export interface PluginCodeEditorCompletionTable { + name: string; + schema?: string; + columns?: PluginCodeEditorCompletionColumn[]; +} + +export interface PluginCodeEditorCompletionFunction { + name: string; + detail?: string; + insertText?: string; +} + +export interface PluginCodeEditorCompletionSchema { + tables?: PluginCodeEditorCompletionTable[]; + functions?: PluginCodeEditorCompletionFunction[]; + keywords?: string[]; +} + +export interface PluginCodeEditorDiagnostic { + line: number; + column: number; + endLine?: number; + endColumn?: number; + message: string; + severity?: 'error' | 'warning' | 'info' | 'hint'; +} + +export interface PluginCodeEditorWidgetProps { + value?: string; + language?: 'sql' | 'pgsql' | 'mysql' | 'json' | 'plaintext'; + readOnly?: boolean; + placeholder?: string; + lineNumbers?: 'on' | 'off' | 'relative'; + minimap?: boolean; + wordWrap?: 'on' | 'off' | 'wordWrapColumn' | 'bounded'; + completionSchema?: PluginCodeEditorCompletionSchema; + diagnostics?: PluginCodeEditorDiagnostic[]; + height?: number | string; +} + +export interface PluginDataGridColumn { + name: string; + type?: string; + primaryKey?: boolean; + nullable?: boolean; + width?: number; + sortable?: boolean; +} + +export interface PluginDataGridSort { + column: string; + direction: 'asc' | 'desc'; +} + +export type PluginDataGridRow = Record | unknown[]; + +export interface PluginDataGridWidgetProps { + columns?: PluginDataGridColumn[]; + rows?: PluginDataGridRow[]; + rowKeyField?: string; + dirtyCells?: Record; + deletedRowIndices?: number[]; + insertedRows?: PluginDataGridRow[]; + selectedRowIndices?: number[]; + sort?: PluginDataGridSort | null; + editable?: boolean; + loading?: boolean; + emptyMessage?: string; +} + +export interface PluginSplitPaneWidgetProps { + direction?: 'horizontal' | 'vertical'; + initialSize?: number; + minSize?: number; + maxSize?: number; + collapsible?: boolean; + collapsed?: boolean; +} + +export interface PluginErColumn { + name: string; + type: string; + isPk?: boolean; + isFk?: boolean; + nullable?: boolean; +} + +export interface PluginErTable { + name: string; + schema?: string; + columns: PluginErColumn[]; + x?: number; + y?: number; +} + +export interface PluginErRelation { + fromTable: string; + fromColumn: string; + toTable: string; + toColumn: string; + name?: string; +} + +export interface PluginErCanvasWidgetProps { + tables?: PluginErTable[]; + relations?: PluginErRelation[]; +} diff --git a/domain/pluginRemoteTreePolicy.cjs b/domain/pluginRemoteTreePolicy.cjs index 1f8da3e4b..58e2b5eac 100644 --- a/domain/pluginRemoteTreePolicy.cjs +++ b/domain/pluginRemoteTreePolicy.cjs @@ -8,11 +8,17 @@ const ELEMENTS = new Set(["form", "img", "div", "span", "p", "h1", "h2", "h3", " const VOID_ELEMENTS = new Set(["br", "hr", "img", "input"]); const ATTRIBUTES = new Set(["lang", "dir", "anchor", "src", "alt", "width", "height", "class", "id", "title", "role", "style", "name", "placeholder", "value", "checked", "disabled", "readonly", "required", "multiple", "selected", "type", "for", "tabindex", "min", "max", "step", "minlength", "maxlength", "rows", "cols", "colspan", "rowspan", "scope", "open", "autocomplete"]); const INPUT_TYPES = new Set(["text", "search", "email", "url", "tel", "number", "password", "checkbox", "radio", "range", "date", "time", "datetime-local", "color", "button"]); +const ALLOWED_WIDGETS = new Set(["code-editor", "data-grid", "split-pane", "er-canvas"]); +const FORBIDDEN_JSON_KEYS = new Set(["__proto__", "constructor", "prototype"]); const NAME = /^[a-zA-Z0-9_-]{1,80}$/u; -const MAX_NODES = 1024; -const MAX_DEPTH = 24; -const MAX_VALUE = 8192; -const MAX_RECORDS = 2048; +const MAX_NODES = 4096; +const MAX_DEPTH = 32; +const MAX_VALUE = 131072; +const MAX_WIDGET_PROPS_VALUE = 768 * 1024; +const MAX_TEXT_SIZE = 1024 * 1024; +const MAX_RECORDS = 4096; +const MAX_BATCH_BYTES = 1024 * 1024; +const MAX_WIDGET_PROPS_DEPTH = 12; function validateId(value, root = false) { if (typeof value !== "string" || (root && value === "~" ? false : !NAME.test(value))) throw new TypeError("Invalid view node ID"); } @@ -20,10 +26,39 @@ function record(value) { return value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null); } +function validateSafeJsonValue(value, depth = 0) { + if (depth > MAX_WIDGET_PROPS_DEPTH) throw new TypeError("Widget props exceed depth limit"); + if (value === null || typeof value === "boolean" || typeof value === "string") return; + if (typeof value === "number") { + if (!Number.isFinite(value)) throw new TypeError("Invalid numeric value in widget props"); + return; + } + if (Array.isArray(value)) { + for (const item of value) validateSafeJsonValue(item, depth + 1); + return; + } + if (typeof value === "object") { + for (const [k, v] of Object.entries(value)) { + if (FORBIDDEN_JSON_KEYS.has(k)) throw new TypeError("Forbidden key in widget props"); + validateSafeJsonValue(v, depth + 1); + } + return; + } + throw new TypeError("Invalid value in widget props"); +} +function validateWidgetProps(raw) { + let parsed; + try { parsed = JSON.parse(raw); } catch { throw new TypeError("Invalid plugin widget props JSON"); } + if (!record(parsed)) throw new TypeError("Plugin widget props must be a JSON object"); + validateSafeJsonValue(parsed, 0); +} function validateAttribute(element, name, value) { if (typeof name !== "string" || !/^[a-z][a-z0-9-]{0,79}$/u.test(name) || (!ATTRIBUTES.has(name) && !/^aria-[a-z0-9-]+$/u.test(name) && !/^data-[a-z0-9-]+$/u.test(name))) throw new TypeError("Forbidden view attribute"); if (value === null) return; - if (typeof value !== "string" || value.length > MAX_VALUE || value.includes("\0")) throw new TypeError("Invalid view attribute value"); + const maxLen = name === "data-plugin-widget-props" ? MAX_WIDGET_PROPS_VALUE : MAX_VALUE; + if (typeof value !== "string" || value.length > maxLen || value.includes("\0")) throw new TypeError("Invalid view attribute value"); + if (name === "data-plugin-widget" && !ALLOWED_WIDGETS.has(value)) throw new TypeError("Forbidden plugin widget type"); + if (name === "data-plugin-widget-props") validateWidgetProps(value); if (name === "type" && element === "input" && !INPUT_TYPES.has(value.toLowerCase())) throw new TypeError("Forbidden input type"); if (name === "type" && element === "button" && !["button", "reset", "submit"].includes(value.toLowerCase())) throw new TypeError("Forbidden button type"); if (name === "src" && (!/^asset:[a-zA-Z0-9_-][a-zA-Z0-9_./-]{0,255}$/.test(value) || value.slice(6).split("/").some((part) => !part || part === "." || part === ".."))) throw new TypeError("Only package images are permitted"); @@ -38,7 +73,7 @@ function validatePluginRemoteTree(root) { validateId(node.id); if (ids.has(node.id)) throw new TypeError("Duplicate view node"); ids.add(node.id); if (node.type === 3 || node.type === 8) { if (Object.keys(node).some((key) => !["id", "type", "data"].includes(key)) || typeof node.data !== "string" || node.data.length > MAX_VALUE) throw new TypeError("Invalid view text"); - textSize += node.data.length; if (textSize > 128 * 1024) throw new TypeError("View text exceeds limits"); return; + textSize += node.data.length; if (textSize > MAX_TEXT_SIZE) throw new TypeError("View text exceeds limits"); return; } if (node.type !== 1 || typeof node.element !== "string" || !ELEMENTS.has(node.element) || !Array.isArray(node.children) || !record(node.attributes) @@ -50,7 +85,7 @@ function validatePluginRemoteTree(root) { for (const [name, value] of attributes) { validateAttribute(node.element, name, value); textSize += name.length + (value?.length ?? 0); - if (textSize > 128 * 1024) throw new TypeError("View data exceeds limits"); + if (textSize > MAX_TEXT_SIZE) throw new TypeError("View data exceeds limits"); } for (const child of node.children) visit(child, depth + 1); }; @@ -62,7 +97,7 @@ function validatePluginMutationBatch(batch) { if (!Array.isArray(batch) || batch.length > MAX_RECORDS) throw new TypeError("Invalid view mutations"); let size; try { size = new TextEncoder().encode(JSON.stringify(batch)).byteLength; } catch { throw new TypeError("Invalid view mutations"); } - if (size > 256 * 1024) throw new TypeError("View mutations exceed limits"); + if (size > MAX_BATCH_BYTES) throw new TypeError("View mutations exceed limits"); for (const item of batch) { if (!Array.isArray(item) || ![0, 1, 2, 3].includes(item[0])) throw new TypeError("Invalid view mutation"); validateId(item[1], true); @@ -79,4 +114,17 @@ function validatePluginMutationBatch(batch) { } return true; } -module.exports = { validatePluginRemoteTree, validatePluginMutationBatch, validateAttribute, ELEMENTS }; +module.exports = { + validatePluginRemoteTree, + validatePluginMutationBatch, + validateAttribute, + ELEMENTS, + ALLOWED_WIDGETS, + MAX_NODES, + MAX_DEPTH, + MAX_VALUE, + MAX_WIDGET_PROPS_VALUE, + MAX_TEXT_SIZE, + MAX_RECORDS, + MAX_BATCH_BYTES, +}; diff --git a/domain/pluginRemoteTreePolicy.test.cjs b/domain/pluginRemoteTreePolicy.test.cjs index 57bfd3f73..a4d26aa92 100644 --- a/domain/pluginRemoteTreePolicy.test.cjs +++ b/domain/pluginRemoteTreePolicy.test.cjs @@ -28,11 +28,24 @@ test("untrusted content cannot introduce executable elements, URLs or dangerous }); test("remote trees and mutation batches are bounded", () => { - assert.throws(() => validatePluginRemoteTree({ children: Array.from({ length: 1025 }, (_, i) => text(`${i}`, "x")) })); - let node = text("25", "x"); for (let i = 24; i >= 0; i--) node = element(`${i}`, "div", {}, [node]); + assert.throws(() => validatePluginRemoteTree({ children: Array.from({ length: 4097 }, (_, i) => text(`${i}`, "x")) })); + let node = text("33", "x"); for (let i = 32; i >= 0; i--) node = element(`${i}`, "div", {}, [node]); assert.throws(() => validatePluginRemoteTree({ children: [node] })); - assert.throws(() => validatePluginMutationBatch(Array.from({ length: 2049 }, () => [2, "1", "x"]))); - assert.throws(() => validatePluginMutationBatch([[2, "1", "x".repeat(8193)]])); + assert.throws(() => validatePluginMutationBatch(Array.from({ length: 4097 }, () => [2, "1", "x"]))); + assert.throws(() => validatePluginMutationBatch([[2, "1", "x".repeat(131073)]])); + assert.equal(validatePluginMutationBatch([[2, "1", "x".repeat(131072)]]), true); +}); + +test("declarative plugin widget markers and JSON props are strictly validated", () => { + const validWidget = element("w1", "div", { + "data-plugin-widget": "code-editor", + "data-plugin-widget-props": JSON.stringify({ value: "SELECT 1;", language: "sql" }), + }); + assert.equal(validatePluginRemoteTree({ children: [validWidget] }), true); + assert.throws(() => validatePluginRemoteTree({ children: [element("w2", "div", { "data-plugin-widget": "iframe-hack" })] }), /widget/); + assert.throws(() => validatePluginRemoteTree({ children: [element("w3", "div", { "data-plugin-widget": "data-grid", "data-plugin-widget-props": "{bad json" })] }), /JSON/); + assert.throws(() => validatePluginRemoteTree({ children: [element("w4", "div", { "data-plugin-widget": "data-grid", "data-plugin-widget-props": "[]" })] }), /JSON object/); + assert.throws(() => validatePluginRemoteTree({ children: [element("w5", "div", { "data-plugin-widget": "data-grid", "data-plugin-widget-props": "{\"__proto__\":{\"polluted\":true}}" })] }), /Forbidden key/); }); test("void children are rejected in snapshots and mutation insertions", () => { diff --git a/domain/pluginViewStylePolicy.cjs b/domain/pluginViewStylePolicy.cjs index 148f0d0fe..8328e287c 100644 --- a/domain/pluginViewStylePolicy.cjs +++ b/domain/pluginViewStylePolicy.cjs @@ -2,8 +2,8 @@ // Plugin styles are untrusted: they are never inserted before this check. const cssTree = require("css-tree"); -const MAX_CSS_LENGTH = 64 * 1024; -const MAX_AST_NODES = 20_000; +const MAX_CSS_LENGTH = 128 * 1024; +const MAX_AST_NODES = 40_000; const ALLOWED_AT_RULES = new Set(["media", "supports", "container", "keyframes", "-webkit-keyframes", "layer"]); const ALLOWED_FUNCTIONS = new Set([ "var", "calc", "min", "max", "clamp", "abs", "sign", "round", "mod", "rem", "hypot", "pow", "sqrt", "log", "exp", "sin", "cos", "tan", "asin", "acos", "atan", "atan2", @@ -14,7 +14,18 @@ const ALLOWED_FUNCTIONS = new Set([ "cubic-bezier", "steps", "linear", "minmax", "repeat", "fit-content", "env", "counter", "counters", "symbols", ]); const DENIED_PROPERTIES = new Set(["behavior", "-moz-binding", "-webkit-app-region", "app-region"]); -const HOST_TOKENS = new Set(["--background", "--foreground", "--muted", "--muted-foreground", "--border", "--primary", "--primary-foreground"]); +const HOST_TOKENS = new Set([ + "--background", "--foreground", + "--card", "--card-foreground", + "--popover", "--popover-foreground", + "--primary", "--primary-foreground", + "--secondary", "--secondary-foreground", + "--muted", "--muted-foreground", + "--accent", "--accent-foreground", + "--destructive", "--destructive-foreground", + "--border", "--input", "--ring", + "--radius", "--font-sans", "--font-mono", +]); const decode = (name) => cssTree.ident.decode(name).toLowerCase(); /** Returns canonical CSS only if every construct is safe for a clipped shadow root. */ diff --git a/domain/pluginViewStylePolicy.test.cjs b/domain/pluginViewStylePolicy.test.cjs index 1451b924a..ffbf1a49f 100644 --- a/domain/pluginViewStylePolicy.test.cjs +++ b/domain/pluginViewStylePolicy.test.cjs @@ -4,7 +4,11 @@ const assert = require("node:assert/strict"); const { validatePluginStylesheet } = require("./pluginViewStylePolicy.cjs"); test("plugin styling supports ordinary layouts, animation and scoped theme tokens", () => { - const css = `.layout { display: grid; grid-template-columns: 1fr 2fr; gap: 12px; --plugin-accent: #fa0; color: hsl(var(--foreground)); } + const css = `.layout { display: grid; grid-template-columns: 1fr 2fr; gap: 12px; --plugin-accent: #fa0; color: hsl(var(--foreground)); background: hsl(var(--card)); border-radius: var(--radius); font-family: var(--font-mono); } + .badge { background: hsl(var(--secondary)); color: hsl(var(--secondary-foreground)); border: 1px solid hsl(var(--input)); outline-color: hsl(var(--ring)); } + .danger { background: hsl(var(--destructive)); color: hsl(var(--destructive-foreground)); } + .menu { background: hsl(var(--popover)); color: hsl(var(--popover-foreground)); font-family: var(--font-sans); } + .active { background: hsl(var(--accent)); color: hsl(var(--accent-foreground)); } @media (max-width: 400px) { .layout { display:flex; flex-direction:column; } } @keyframes spin { from { transform:rotate(0deg) } to { transform:rotate(360deg) } } .action:hover { animation:spin 1s; color:var(--plugin-accent); }`; @@ -22,5 +26,5 @@ test("plugin CSS rejects network loads, escapes and access outside the surface", '.x{--foreground:red}', '.x{content:attr(data-secret)}', '.x{color:red;}\0', ]; for (const attack of attacks) assert.throws(() => validatePluginStylesheet(attack), undefined, attack); - assert.throws(() => validatePluginStylesheet('x'.repeat(65537))); + assert.throws(() => validatePluginStylesheet('x'.repeat(131073))); }); diff --git a/electron/plugins/byteStreamBroker.cjs b/electron/plugins/byteStreamBroker.cjs index 99e0a532a..1e5a71a6f 100644 --- a/electron/plugins/byteStreamBroker.cjs +++ b/electron/plugins/byteStreamBroker.cjs @@ -10,10 +10,25 @@ const { PluginRpcError, RPC_ERRORS, raceWithAbort } = require("./rpcRouter.cjs") const HOST_LIMITS = Object.freeze(require("./generated/plugin-contract.schema.json").$defs.HostByteStreamLimits.const); const LIMITS = Object.freeze(require("./generated/plugin-contract.schema.json").$defs.ByteStreamLimits.const); -const { canonicalizeStreamEndpoint, isLocalControlAddress } = require("./byteStreamEndpoint.cjs"); +const { + canonicalizeStreamEndpoint, + getNetcattyInternalControlPorts, + isLocalControlAddress, + isLoopbackAddress, + isUnconditionallyBlockedAddress, +} = require("./byteStreamEndpoint.cjs"); function failure(code, message) { return new PluginRpcError(RPC_ERRORS[code], message); } +function formatCertDistinguishedName(value) { + if (!value || typeof value !== "object") return ""; + return Object.entries(value) + .filter(([, v]) => typeof v === "string" || Array.isArray(v)) + .map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(",") : v}`) + .join(", ") + .slice(0, 512); +} + class PluginByteStreamBroker { constructor(options) { this.permissionEngine = options.permissionEngine; @@ -22,10 +37,17 @@ class PluginByteStreamBroker { this.lookup = options.lookup ?? dns.lookup; this.connectSocket = options.connectSocket ?? ((params) => net.createConnection(params)); this.connectTls = options.connectTls ?? ((params) => tls.connect(params)); - // Only a host test harness can opt a specific loopback endpoint in. The - // production default excludes all loopback/link-local control surfaces. + // Only a host test harness can opt a specific loopback endpoint in without + // interactive user confirmation. Production always blocks internal ports. this.testLocalEndpoints = new Set(options.testLocalEndpoints ?? []); this.isControlEndpoint = options.isControlEndpoint ?? (() => false); + this.isInternalControlPort = options.isInternalControlPort ?? ((address, port) => ( + (isLoopbackAddress(address) || this.isControlEndpoint(address, port)) + && getNetcattyInternalControlPorts().has(port) + )); + this.confirmTlsCert = options.confirmTlsCert ?? null; + this.isTrustedTlsCert = options.isTrustedTlsCert ?? (() => false); + this.rememberTlsCert = options.rememberTlsCert ?? (() => {}); this.connections = new Map(); this.closeListeners = new Set(); this.closed = false; @@ -91,7 +113,62 @@ class PluginByteStreamBroker { context.assertCommit?.(); } - async connect(endpoint, context, hostTransport) { + #attachSocketLifecycle(state, socket) { + const onError = () => this.finish(state, failure("unavailable", "Byte stream transport failed")); + const onClose = () => { + if (!state.eof) this.finish(state, failure("unavailable", "Byte stream transport closed")); + }; + const onEnd = () => { state.eof = true; }; + state.socketListeners = { socket, onError, onClose, onEnd }; + socket.on("error", onError); + socket.on("close", onClose); + socket.on("end", onEnd); + } + + #detachSocketLifecycle(state) { + const prev = state.socketListeners; + if (!prev) return; + prev.socket.off("error", prev.onError); + prev.socket.off("close", prev.onClose); + prev.socket.off("end", prev.onEnd); + state.socketListeners = null; + } + + async #verifyUntrustedTlsSocket(socket, state, context, servername) { + const cert = typeof socket.getPeerCertificate === "function" ? socket.getPeerCertificate(false) : null; + const fingerprint256 = typeof cert?.fingerprint256 === "string" ? cert.fingerprint256 : ""; + if (!fingerprint256) { + throw failure("permissionDenied", "TLS server did not present a verifiable certificate"); + } + if (this.isTrustedTlsCert(state.pluginId, state.endpoint, fingerprint256)) { + return; + } + if (typeof this.confirmTlsCert !== "function") { + throw failure("permissionDenied", "Untrusted TLS certificate requires explicit user confirmation"); + } + const certInfo = Object.freeze({ + endpoint: state.endpoint, + ...(servername ? { servername } : {}), + fingerprint256, + subject: formatCertDistinguishedName(cert.subject), + issuer: formatCertDistinguishedName(cert.issuer), + validTo: typeof cert.valid_to === "string" ? cert.valid_to.slice(0, 128) : "", + reason: String(socket.authorizationError || "UNTRUSTED_CERT").slice(0, 256), + }); + const decision = await raceWithAbort( + Promise.resolve(this.confirmTlsCert(certInfo, state, context)), + state.controller.signal, + ); + await this.active(state, context); + if (!decision?.approved) { + throw failure("permissionDenied", "TLS certificate was rejected by user"); + } + if (decision.remember === true) { + this.rememberTlsCert(state.pluginId, state.endpoint, fingerprint256); + } + } + + async connect(endpoint, context, hostTransport, connectOptions = {}) { let target; try { target = canonicalizeStreamEndpoint(endpoint); } catch { throw failure("invalidArgument", "Byte stream endpoint is invalid"); } @@ -99,17 +176,28 @@ class PluginByteStreamBroker { if (!context.runtimeId || !context.pluginId || typeof context.assertActive !== "function") { throw failure("unauthenticated", "Byte streams require a host runtime identity"); } + const activeLimits = hostTransport ? HOST_LIMITS : LIMITS; const count = [...this.connections.values()].filter((state) => state.runtimeId === context.runtimeId).length; - if (count >= LIMITS.connectionsPerRuntime || this.connections.size >= LIMITS.connectionsTotal) { + if (count >= activeLimits.connectionsPerRuntime || this.connections.size >= activeLimits.connectionsTotal) { throw failure("resourceExhausted", "Byte stream connection limit exceeded"); } + const { + localApproved = false, + skipPermissionAuthorize = false, + allowSelfSigned = false, + caPem, + servername, + } = connectOptions; const state = { ...target, permission: hostTransport ? "network.hostStream" : "network.stream", - limits: hostTransport ? HOST_LIMITS : LIMITS, + limits: activeLimits, id: randomUUID(), pluginId: context.pluginId, runtimeId: context.runtimeId, controller: new AbortController(), bytesRead: 0, bytesWritten: 0, sourceOwner: context.sourceOwner, sourceId: context.sourceId, closed: false, reading: false, writing: false, socket: null, + socketListeners: null, + isTls: target.transport === "tls", + upgrading: false, upgradeDone: null, suspendRead: null, }; this.connections.set(state.id, state); const onAbort = () => this.finish(state, failure("cancelled", "Byte stream connection cancelled")); @@ -117,16 +205,19 @@ class PluginByteStreamBroker { try { await this.active(state, context); this.assertCommit(state, context); - if (!hostTransport) await raceWithAbort(Promise.resolve(this.permissionEngine.authorize({ ...context, signal: state.controller.signal }, { - permission: "network.stream", resources: [target.endpoint], - reason: `Open byte stream to ${target.endpoint}`, - operationId: `network.stream:${target.endpoint}`, - validateBeforeGrant: () => this.assertCommit(state, context), - })), state.controller.signal); + if (!hostTransport && !skipPermissionAuthorize) { + await raceWithAbort(Promise.resolve(this.permissionEngine.authorize({ ...context, signal: state.controller.signal }, { + permission: "network.stream", resources: [target.endpoint], + reason: `Open byte stream to ${target.endpoint}`, + operationId: `network.stream:${target.endpoint}`, + validateBeforeGrant: () => this.assertCommit(state, context), + })), state.controller.signal); + } await this.active(state, context); state.connectTimer = setTimeout(() => this.finish(state, failure("deadlineExceeded", "Byte stream connect timeout")), state.limits.connectMs); let socket; + const effectiveServername = servername ?? (net.isIP(target.host) ? undefined : target.host); if (hostTransport) { socket = await raceWithAbort(hostTransport.open(state.controller.signal), state.controller.signal); } else { @@ -143,12 +234,18 @@ class PluginByteStreamBroker { if (![4, 6].includes(peer.family) || net.isIP(peer.address) !== peer.family) { throw failure("unavailable", "Byte stream resolver returned an invalid address"); } - const local = isLocalControlAddress(peer.address); - const allowedTestPeer = this.testLocalEndpoints.has(target.endpoint) - && !this.isControlEndpoint(peer.address, target.port); - if ((local && !allowedTestPeer) || (!local && this.isControlEndpoint(peer.address, target.port))) { + // Always block link-local/metadata/multicast and Netcatty's own internal ports. + if (isUnconditionallyBlockedAddress(peer.address) || this.isInternalControlPort(peer.address, target.port)) { throw failure("permissionDenied", "Byte streams cannot reach local or application control endpoints"); } + if (!localApproved) { + const local = isLocalControlAddress(peer.address); + const allowedTestPeer = this.testLocalEndpoints.has(target.endpoint) + && !this.isControlEndpoint(peer.address, target.port); + if ((local && !allowedTestPeer) || (!local && this.isControlEndpoint(peer.address, target.port))) { + throw failure("permissionDenied", "Byte streams cannot reach local or application control endpoints"); + } + } } const peer = addresses[0]; const params = { @@ -157,9 +254,10 @@ class PluginByteStreamBroker { }; if (target.transport === "tls") { Object.assign(params, { - rejectUnauthorized: true, minVersion: "TLSv1.2", - ...(net.isIP(target.host) ? {} : { servername: target.host }), - checkServerIdentity: (_name, certificate) => tls.checkServerIdentity(target.host, certificate), + rejectUnauthorized: !allowSelfSigned, minVersion: "TLSv1.2", + ...(effectiveServername ? { servername: effectiveServername } : {}), + ...(caPem ? { ca: caPem } : {}), + checkServerIdentity: (_name, certificate) => tls.checkServerIdentity(effectiveServername ?? target.host, certificate), }); } this.assertCommit(state, context); @@ -167,20 +265,17 @@ class PluginByteStreamBroker { } state.socket = socket; if (state.closed) { socket.destroy(); throw state.error ?? failure("cancelled", "Byte stream connection cancelled"); } - socket.on("error", () => this.finish(state, failure("unavailable", "Byte stream transport failed"))); - // Preserve one EOF observation for a delayed consumer. This reservation - // still counts toward quotas and expires on the existing idle/life timer. - socket.on("close", () => { - if (!state.eof) this.finish(state, failure("unavailable", "Byte stream transport closed")); - }); - socket.on("end", () => { state.eof = true; }); + this.#attachSocketLifecycle(state, socket); socket.pause(); if (!hostTransport) await raceWithAbort(new Promise((resolve) => socket.once( target.transport === "tls" ? "secureConnect" : "connect", resolve, )), state.controller.signal); await this.active(state, context); if (target.transport === "tls" && !socket.authorized) { - throw failure("permissionDenied", "Byte stream TLS validation failed"); + if (!allowSelfSigned) { + throw failure("permissionDenied", "Byte stream TLS validation failed"); + } + await this.#verifyUntrustedTlsSocket(socket, state, context, effectiveServername); } clearTimeout(state.connectTimer); state.lifetimeTimer = setTimeout(() => this.finish(state, @@ -198,6 +293,121 @@ class PluginByteStreamBroker { } } + async upgradeTls(id, options, context) { + const state = this.get(id, context); + if (state.isTls) throw failure("failedPrecondition", "Byte stream is already encrypted with TLS"); + if (state.upgrading) throw failure("failedPrecondition", "Byte stream TLS upgrade is already in progress"); + if (state.writing) throw failure("failedPrecondition", "Cannot upgrade TLS while a write is pending"); + const allowSelfSigned = options?.allowSelfSigned === true; + const caPem = options?.caPem; + const effectiveServername = options?.servername ?? (net.isIP(state.host) ? undefined : state.host); + state.upgrading = true; + let releaseUpgrade; + state.upgradeDone = new Promise((resolve) => { releaseUpgrade = resolve; }); + const onAbort = () => this.finish(state, failure("cancelled", "Byte stream TLS upgrade cancelled")); + context.signal?.addEventListener("abort", onAbort, { once: true }); + let upgradeTimer; + try { + await this.active(state, context); + // Pause any active read() waiting on the plaintext socket without closing it. + if (state.suspendRead) { + state.suspendRead(); + state.suspendRead = null; + } + const rawSocket = state.socket; + if (!rawSocket || rawSocket.destroyed) { + throw failure("unavailable", "Byte stream socket is closed"); + } + this.#detachSocketLifecycle(state); + const ignoreRawError = () => {}; + rawSocket.on("error", ignoreRawError); + rawSocket.pause(); + + const tlsParams = { + socket: rawSocket, + minVersion: "TLSv1.2", + rejectUnauthorized: !allowSelfSigned, + highWaterMark: LIMITS.bufferBytes, + ...(effectiveServername ? { servername: effectiveServername } : {}), + ...(caPem ? { ca: caPem } : {}), + ...(effectiveServername + ? { checkServerIdentity: (_name, certificate) => tls.checkServerIdentity(effectiveServername, certificate) } + : {}), + }; + this.assertCommit(state, context); + const tlsSocket = this.connectTls(tlsParams); + tlsSocket.pause(); + upgradeTimer = setTimeout(() => { + tlsSocket.destroy(); + this.finish(state, failure("deadlineExceeded", "Byte stream TLS upgrade timeout")); + }, state.limits.connectMs); + upgradeTimer.unref?.(); + + await raceWithAbort(new Promise((resolve, reject) => { + const cleanup = () => { + tlsSocket.off("secureConnect", onSecure); + tlsSocket.off("error", onError); + tlsSocket.off("close", onClose); + }; + const onSecure = () => { cleanup(); resolve(); }; + const onError = (err) => { cleanup(); reject(err); }; + const onClose = () => { cleanup(); reject(failure("unavailable", "Byte stream closed during TLS upgrade")); }; + tlsSocket.once("secureConnect", onSecure); + tlsSocket.once("error", onError); + tlsSocket.once("close", onClose); + }), state.controller.signal); + + clearTimeout(upgradeTimer); + upgradeTimer = null; + await this.active(state, context); + + if (!tlsSocket.authorized) { + if (!allowSelfSigned) { + tlsSocket.destroy(); + throw failure("permissionDenied", "Byte stream TLS validation failed"); + } + try { + await this.#verifyUntrustedTlsSocket(tlsSocket, state, context, effectiveServername); + } catch (err) { + tlsSocket.destroy(); + throw err; + } + } + + rawSocket.off("error", ignoreRawError); + state.socket = tlsSocket; + state.isTls = true; + this.#attachSocketLifecycle(state, tlsSocket); + this.touch(state); + this.assertCommit(state, context); + this.record(state, "upgradeTls"); + + const cert = typeof tlsSocket.getPeerCertificate === "function" ? tlsSocket.getPeerCertificate(false) : null; + const protocol = typeof tlsSocket.getProtocol === "function" ? tlsSocket.getProtocol() : undefined; + const fingerprint256 = typeof cert?.fingerprint256 === "string" ? cert.fingerprint256 : undefined; + const subject = cert?.subject ? formatCertDistinguishedName(cert.subject) : undefined; + return Object.freeze({ + upgraded: true, + authorized: Boolean(tlsSocket.authorized), + ...(protocol ? { protocol } : {}), + ...(fingerprint256 ? { fingerprint256 } : {}), + ...(subject ? { subject } : {}), + }); + } catch (error) { + clearTimeout(upgradeTimer); + const rpcError = error instanceof PluginRpcError + ? error + : failure("unavailable", "Byte stream TLS upgrade failed"); + this.finish(state, rpcError); + throw rpcError; + } finally { + context.signal?.removeEventListener("abort", onAbort); + state.upgrading = false; + state.upgradeDone = null; + releaseUpgrade(); + } + } + get(id, context) { const state = this.connections.get(id); if (!state || state.pluginId !== context.pluginId || state.runtimeId !== context.runtimeId @@ -226,24 +436,32 @@ class PluginByteStreamBroker { await this.active(state, context); while (true) { this.assertCommit(state, context); - const available = state.socket.readableLength; - const bytes = state.socket.read(Math.min(available || LIMITS.chunkBytes, LIMITS.chunkBytes)); + if (state.upgrading && state.upgradeDone) { + await raceWithAbort(state.upgradeDone, state.controller.signal); + await this.active(state, context); + continue; + } + const socket = state.socket; + const available = socket.readableLength; + const bytes = socket.read(Math.min(available || LIMITS.chunkBytes, LIMITS.chunkBytes)); if (bytes !== null) { this.charge(state, "bytesRead", bytes.byteLength); await this.active(state, context); this.assertCommit(state, context); return new Uint8Array(bytes); } - if (state.eof || state.socket.readableEnded) { this.finish(state); return null; } + if (state.eof || socket.readableEnded) { this.finish(state); return null; } await raceWithAbort(new Promise((resolve) => { const readable = () => { - state.socket.off("end", readable); - state.socket.off("readable", readable); + if (state.suspendRead === readable) state.suspendRead = null; + socket.off("end", readable); + socket.off("readable", readable); state.controller.signal.removeEventListener("abort", readable); resolve(); }; - state.socket.once("readable", readable); - state.socket.once("end", readable); + state.suspendRead = readable; + socket.once("readable", readable); + socket.once("end", readable); // Remove listeners even when cancellation wins the race. state.controller.signal.addEventListener("abort", readable, { once: true }); }), state.controller.signal); @@ -253,6 +471,7 @@ class PluginByteStreamBroker { this.finish(state, error); throw error; } finally { + state.suspendRead = null; context.signal?.removeEventListener("abort", onAbort); state.reading = false; } @@ -260,6 +479,7 @@ class PluginByteStreamBroker { async write(id, bytes, context) { const state = this.get(id, context); + if (state.upgrading) throw failure("failedPrecondition", "Cannot write while TLS upgrade is in progress"); if (!(bytes instanceof Uint8Array) || bytes.byteLength < 1 || bytes.byteLength > LIMITS.chunkBytes) { throw failure("invalidArgument", "Byte stream chunk size is invalid"); } @@ -302,4 +522,4 @@ class PluginByteStreamBroker { } } -module.exports = { LIMITS, PluginByteStreamBroker, canonicalizeStreamEndpoint, isLocalControlAddress }; +module.exports = { LIMITS, HOST_LIMITS, PluginByteStreamBroker, canonicalizeStreamEndpoint, isLocalControlAddress }; diff --git a/electron/plugins/byteStreamBroker.test.cjs b/electron/plugins/byteStreamBroker.test.cjs index 131d6fb96..6e8dd00fd 100644 --- a/electron/plugins/byteStreamBroker.test.cjs +++ b/electron/plugins/byteStreamBroker.test.cjs @@ -328,3 +328,129 @@ test("real TLS validates trust and the original hostname against a pinned IP", a const wrong = broker(t, wrongEndpoint, { lookup, connectTls: (options) => tls.connect({ ...options, ca: cert }) }).instance; await assert.rejects(wrong.connect(wrongEndpoint, context()), { code: RPC_ERRORS.unavailable }); }); + +test("dynamic local opt-in allows loopback when approved but unconditionally blocks Netcatty internal control ports and metadata IPs", async (t) => { + const peer = await server(t, (socket) => socket.on("data", (bytes) => socket.write(bytes))); + const port = peer.address().port; + const endpoint = `tcp://127.0.0.1:${port}`; + const { instance } = broker(t, null, { + isInternalControlPort: (_address, targetPort) => targetPort === port, + }); + // Even with localApproved: true, Netcatty's own internal control port is unconditionally blocked. + await assert.rejects( + instance.connect(endpoint, context(), undefined, { localApproved: true, skipPermissionAuthorize: true }), + { code: RPC_ERRORS.permissionDenied }, + ); + // Link-local cloud metadata IP is unconditionally blocked even with localApproved: true. + await assert.rejects( + instance.connect("tcp://169.254.169.254:80", context(), undefined, { localApproved: true, skipPermissionAuthorize: true }), + { code: RPC_ERRORS.permissionDenied }, + ); + // Approved loopback to a non-control DB port succeeds cleanly. + const allowed = broker(t, null, { + isInternalControlPort: () => false, + }).instance; + const ctx = context(); + const handle = await allowed.connect(endpoint, ctx, undefined, { localApproved: true, skipPermissionAuthorize: true }); + await allowed.write(handle.handleId, Uint8Array.from([1, 2, 3]), ctx); + assert.deepEqual(await allowed.read(handle.handleId, ctx), Uint8Array.from([1, 2, 3])); + allowed.close(handle.handleId, ctx); +}); + +test("in-band STARTTLS upgradeTls upgrades a plaintext TCP stream with CA validation, pending-read resume, and explicit self-signed cert approval", async (t) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-starttls-test-")); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + const keyPath = path.join(directory, "test.key"); + const certPath = path.join(directory, "test.crt"); + execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", keyPath, + "-out", certPath, "-days", "1", "-subj", "/CN=db.local.test", "-addext", "subjectAltName=DNS:db.local.test"], + { stdio: "ignore" }); + const key = fs.readFileSync(keyPath); + const cert = fs.readFileSync(certPath); + + // Simulate PostgreSQL SSLRequest -> 'S' -> STARTTLS upgrade -> encrypted echo. + const peer = await server(t, (rawSocket) => { + rawSocket.once("data", (chunk) => { + if (chunk.toString() === "SSLREQ") { + rawSocket.write("S"); + const tlsSocket = new tls.TLSSocket(rawSocket, { isServer: true, key, cert }); + tlsSocket.on("error", () => {}); + tlsSocket.on("data", (data) => tlsSocket.write(Buffer.concat([Buffer.from("TLS:"), data]))); + } + }); + }); + const endpoint = `tcp://127.0.0.1:${peer.address().port}`; + + // 1) Trusted CA upgrade with a pending read() already active on the plaintext socket. + { + const { instance } = broker(t, endpoint); + const ctx = context(); + const { handleId } = await instance.connect(endpoint, ctx); + await instance.write(handleId, Buffer.from("SSLREQ"), ctx); + assert.equal(Buffer.from(await instance.read(handleId, ctx)).toString(), "S"); + // Start a pending read (mirrors byteStreamService.pump()) BEFORE calling upgradeTls. + const pendingRead = instance.read(handleId, ctx); + await new Promise((resolve) => setImmediate(resolve)); + const upgraded = await instance.upgradeTls(handleId, { servername: "db.local.test", caPem: cert.toString("utf8") }, ctx); + assert.equal(upgraded.upgraded, true); + assert.equal(upgraded.authorized, true); + assert.ok(upgraded.fingerprint256); + await instance.write(handleId, Buffer.from("SELECT 1"), ctx); + assert.equal(Buffer.from(await pendingRead).toString(), "TLS:SELECT 1"); + instance.close(handleId, ctx); + } + + // 2) Self-signed cert fails closed without allowSelfSigned, prompts user with allowSelfSigned, and honors remembered fingerprint. + { + const trustedFingerprints = new Set(); + const prompts = []; + const { instance } = broker(t, endpoint, { + isTrustedTlsCert: (_pluginId, _ep, fp) => trustedFingerprints.has(fp), + rememberTlsCert: (_pluginId, _ep, fp) => trustedFingerprints.add(fp), + confirmTlsCert: async (info) => { + prompts.push(info); + return { approved: prompts.length > 1, remember: true }; + }, + }); + const ctx = context(); + // First attempt: user rejects self-signed cert -> fails closed. + const first = await instance.connect(endpoint, ctx); + await instance.write(first.handleId, Buffer.from("SSLREQ"), ctx); + assert.equal(Buffer.from(await instance.read(first.handleId, ctx)).toString(), "S"); + await assert.rejects( + instance.upgradeTls(first.handleId, { servername: "db.local.test", allowSelfSigned: true }, ctx), + { code: RPC_ERRORS.permissionDenied }, + ); + assert.equal(prompts.length, 1); + assert.ok(prompts[0].fingerprint256.length > 20); + assert.match(prompts[0].subject, /CN=db\.local\.test/); + + // Second attempt: user approves with remember: true. + const second = await instance.connect(endpoint, ctx); + await instance.write(second.handleId, Buffer.from("SSLREQ"), ctx); + assert.equal(Buffer.from(await instance.read(second.handleId, ctx)).toString(), "S"); + const res2 = await instance.upgradeTls(second.handleId, { servername: "db.local.test", allowSelfSigned: true }, ctx); + assert.equal(res2.upgraded, true); + assert.equal(res2.authorized, false); + assert.equal(prompts.length, 2); + await instance.write(second.handleId, Buffer.from("PING"), ctx); + assert.equal(Buffer.from(await instance.read(second.handleId, ctx)).toString(), "TLS:PING"); + instance.close(second.handleId, ctx); + + // Third attempt: remembered fingerprint skips prompt automatically. + const third = await instance.connect(endpoint, ctx); + await instance.write(third.handleId, Buffer.from("SSLREQ"), ctx); + assert.equal(Buffer.from(await instance.read(third.handleId, ctx)).toString(), "S"); + const res3 = await instance.upgradeTls(third.handleId, { servername: "db.local.test", allowSelfSigned: true }, ctx); + assert.equal(res3.upgraded, true); + assert.equal(prompts.length, 2); + instance.close(third.handleId, ctx); + } +}); + +test("DB-friendly stream budgets expose expanded concurrency, idle, lifetime, and byte caps", () => { + assert.equal(LIMITS.connectionsPerRuntime, 24); + assert.equal(LIMITS.idleMs, 1_800_000); + assert.equal(LIMITS.lifetimeMs, 28_800_000); + assert.equal(LIMITS.connectionBytes, 536_870_912); +}); diff --git a/electron/plugins/byteStreamEndpoint.cjs b/electron/plugins/byteStreamEndpoint.cjs index eca80402e..d6d3a5491 100644 --- a/electron/plugins/byteStreamEndpoint.cjs +++ b/electron/plugins/byteStreamEndpoint.cjs @@ -1,5 +1,6 @@ "use strict"; +const fs = require("node:fs"); const net = require("node:net"); function failure(_code, message) { return new TypeError(message); } @@ -42,18 +43,79 @@ function normalizeStreamAddress(address) { return [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join("."); } -function isLocalControlAddress(address) { - address = normalizeStreamAddress(address); - if (net.isIP(address) === 4) { - const [a, b] = address.split(".").map(Number); - return a === 0 || a === 127 || a >= 224 || (a === 169 && b === 254); +function isLoopbackAddress(address) { + const normalized = normalizeStreamAddress(address); + if (net.isIP(normalized) === 4) { + return normalized.startsWith("127."); } - if (net.isIP(address) !== 6) return true; - const canonical = address; - // Also exclude compatible/tunnel addresses that can obscure a local IPv4 peer. - return canonical.startsWith("::") || canonical.startsWith("ff") - || /^fe[89ab]/u.test(canonical) || canonical.startsWith("2002:") - || canonical.startsWith("2001:0:"); + return normalized === "::1"; } -module.exports = { canonicalizeStreamEndpoint, isLocalControlAddress, normalizeStreamAddress }; +function isUnconditionallyBlockedAddress(address) { + const normalized = normalizeStreamAddress(address); + if (net.isIP(normalized) === 4) { + const [a, b] = normalized.split(".").map(Number); + return a === 0 || a >= 224 || (a === 169 && b === 254); + } + if (net.isIP(normalized) !== 6) return true; + if (normalized === "::1") return false; + return normalized.startsWith("::") || normalized.startsWith("ff") + || /^fe[89ab]/u.test(normalized) || normalized.startsWith("2002:") + || normalized.startsWith("2001:0:"); +} + +function isLocalControlAddress(address) { + return isLoopbackAddress(address) || isUnconditionallyBlockedAddress(address); +} + +function getNetcattyInternalControlPorts() { + const ports = new Set(); + const discoveryFile = process.env.NETCATTY_TOOL_CLI_DISCOVERY_FILE; + if (typeof discoveryFile === "string" && discoveryFile.length > 0) { + try { + const parsed = JSON.parse(fs.readFileSync(discoveryFile, "utf8")); + if (Number.isInteger(parsed?.port) && parsed.port > 0 && parsed.port <= 65535) { + ports.add(parsed.port); + } + } catch { /* discovery file may not exist */ } + } + const viteUrl = process.env.VITE_DEV_SERVER_URL; + if (typeof viteUrl === "string" && viteUrl.length > 0) { + try { + const parsed = new URL(viteUrl); + const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80)); + if (Number.isInteger(port) && port > 0 && port <= 65535) ports.add(port); + } catch { /* ignore invalid dev server URL */ } + } + for (const arg of [...(process.argv ?? []), ...(process.execArgv ?? [])]) { + const match = /^--(?:remote-debugging-port|inspect|inspect-brk)=(?:[^:]*:)?(\d{1,5})$/u.exec(String(arg)); + if (match) { + const port = Number(match[1]); + if (port > 0 && port <= 65535) ports.add(port); + } + } + // In the live Electron main process, every active TCP net.Server belongs to + // Netcatty's own internal bridges (MCP/CLI RPC, external MCP HTTP, OAuth, etc.). + if (process.versions?.electron && typeof process._getActiveHandles === "function") { + try { + for (const handle of process._getActiveHandles()) { + if (handle instanceof net.Server && handle.listening) { + const addr = handle.address(); + if (addr && typeof addr === "object" && Number.isInteger(addr.port) && addr.port > 0) { + ports.add(addr.port); + } + } + } + } catch { /* ignore handle inspection errors */ } + } + return ports; +} + +module.exports = { + canonicalizeStreamEndpoint, + getNetcattyInternalControlPorts, + isLocalControlAddress, + isLoopbackAddress, + isUnconditionallyBlockedAddress, + normalizeStreamAddress, +}; diff --git a/electron/plugins/byteStreamService.cjs b/electron/plugins/byteStreamService.cjs index 4ce93ae4a..1f3824cf4 100644 --- a/electron/plugins/byteStreamService.cjs +++ b/electron/plugins/byteStreamService.cjs @@ -2,7 +2,11 @@ const { randomUUID } = require("node:crypto"); const os = require("node:os"); -const { normalizeStreamAddress } = require("./byteStreamEndpoint.cjs"); +const { + canonicalizeStreamEndpoint, + isLocalControlAddress, + normalizeStreamAddress, +} = require("./byteStreamEndpoint.cjs"); const { PluginByteStreamBroker, LIMITS } = require("./byteStreamBroker.cjs"); const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs"); const { createDefinitionValidator } = require("./contractValidator.cjs"); @@ -17,22 +21,63 @@ function validator(name) { }; } +function manifestStreamDeclaration(manifest, canonicalEndpoint) { + const declarations = [ + ...(manifest?.permissions?.required ?? []), + ...(manifest?.permissions?.optional ?? []), + ]; + let declared = false; + let staticMatch = false; + for (const item of declarations) { + if (item === "network.stream") { + declared = true; + } else if (item && typeof item === "object" && item.permission === "network.stream") { + declared = true; + if (Array.isArray(item.resources)) { + for (const resource of item.resources) { + try { + if (canonicalizeStreamEndpoint(resource).endpoint === canonicalEndpoint) { + staticMatch = true; + } + } catch { /* ignore invalid entry */ } + } + } + } + } + return { declared, staticMatch }; +} + +function isOwnMachineAddress(address) { + const normalized = normalizeStreamAddress(address); + return normalized !== null && Object.values(os.networkInterfaces()).flat() + .some((item) => item?.address && normalizeStreamAddress(item.address) === normalized); +} + class PluginByteStreamService { constructor(options) { this.database = options.database; + this.permissionEngine = options.permissionEngine; this.runtimeSupervisor = options.runtimeSupervisor; + this.interactionService = options.interactionService ?? null; this.records = new Map(); this.closedHandles = new Map(); + this.memoryEndpoints = new Map(); + this.memoryTrustedCerts = new Map(); this.closed = false; this.broker = new PluginByteStreamBroker({ permissionEngine: options.permissionEngine, quotaManager: options.quotaManager, // The public host service never forwards transport fixture overrides. - isControlEndpoint: (address) => { - const normalized = normalizeStreamAddress(address); - return normalized !== null && Object.values(os.networkInterfaces()).flat() - .some((item) => item?.address && normalizeStreamAddress(item.address) === normalized); - }, + isControlEndpoint: (address) => isOwnMachineAddress(address), + isTrustedTlsCert: (pluginId, endpoint, fingerprint256) => ( + this.isTrustedTlsCert(pluginId, endpoint, fingerprint256) + ), + rememberTlsCert: (pluginId, endpoint, fingerprint256) => ( + this.rememberTrustedTlsCert(pluginId, endpoint, fingerprint256) + ), + confirmTlsCert: async (certInfo, _state, context) => ( + this.#confirmTlsCert(certInfo, context) + ), audit: (pluginId, operation, fields, state) => { if (this.sourceMatches(state)) this.database.recordSecurityAudit(pluginId, operation, fields); }, @@ -40,6 +85,163 @@ class PluginByteStreamService { this.brokerClose = this.broker.onDidClose((state, reason) => { if (reason) this.closeRecord(this.records.get(state.id), reason); }); + this.revocation = this.permissionEngine?.onDidRevoke?.((event) => { + if (event.permission === undefined || event.permission === "network.stream") { + if (event.resource) { + this.revokeDynamicEndpoint(event.pluginId, event.resource); + } else { + this.clearRememberedEndpoints(event.pluginId); + } + } + }) ?? { dispose() {} }; + } + + #ownerKey(pluginId) { + return typeof this.database?.privateOwner === "function" + ? this.database.privateOwner(pluginId) + : pluginId; + } + + #readPref(key, fallback) { + if (this.database?.db) { + try { + const row = this.database.db.prepare("SELECT value_json FROM plugin_host_preferences WHERE key = ?").get(key); + if (row?.value_json) return JSON.parse(row.value_json); + } catch { /* fall through */ } + } + return fallback; + } + + #writePref(key, value) { + if (this.database?.db) { + try { + this.database.db.prepare( + "INSERT INTO plugin_host_preferences(key,value_json,updated_at) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET value_json=excluded.value_json,updated_at=excluded.updated_at", + ).run(key, JSON.stringify(value), Date.now()); + } catch { /* ignore when mock db */ } + } + } + + #deletePref(key) { + if (this.database?.db) { + try { + this.database.db.prepare("DELETE FROM plugin_host_preferences WHERE key = ?").run(key); + } catch { /* ignore when mock db */ } + } + } + + #endpointPrefKey(pluginId) { + return `permission:${this.#ownerKey(pluginId)}:stream-endpoints`; + } + + #tlsCertPrefKey(pluginId) { + return `permission:${this.#ownerKey(pluginId)}:stream-tls-certs`; + } + + listDynamicEndpoints(pluginId) { + const key = this.#endpointPrefKey(pluginId); + const list = this.#readPref(key, this.memoryEndpoints.get(key) ?? []); + return Array.isArray(list) ? list : []; + } + + isDynamicEndpointRemembered(pluginId, endpoint) { + return this.listDynamicEndpoints(pluginId).includes(endpoint); + } + + rememberDynamicEndpoint(pluginId, endpoint) { + const key = this.#endpointPrefKey(pluginId); + const current = new Set(this.listDynamicEndpoints(pluginId)); + current.add(endpoint); + const next = [...current].slice(-256); + this.memoryEndpoints.set(key, next); + this.#writePref(key, next); + } + + revokeDynamicEndpoint(pluginId, endpoint) { + const key = this.#endpointPrefKey(pluginId); + const next = this.listDynamicEndpoints(pluginId).filter((item) => item !== endpoint); + this.memoryEndpoints.set(key, next); + if (next.length === 0) this.#deletePref(key); + else this.#writePref(key, next); + // Also revoke remembered certs for that endpoint. + const certKey = this.#tlsCertPrefKey(pluginId); + const certs = { ...this.#readPref(certKey, this.memoryTrustedCerts.get(certKey) ?? {}) }; + if (endpoint in certs) { + delete certs[endpoint]; + this.memoryTrustedCerts.set(certKey, certs); + if (Object.keys(certs).length === 0) this.#deletePref(certKey); + else this.#writePref(certKey, certs); + } + } + + clearRememberedEndpoints(pluginId) { + const key = this.#endpointPrefKey(pluginId); + const certKey = this.#tlsCertPrefKey(pluginId); + this.memoryEndpoints.delete(key); + this.memoryTrustedCerts.delete(certKey); + this.#deletePref(key); + this.#deletePref(certKey); + } + + isTrustedTlsCert(pluginId, endpoint, fingerprint256) { + const certKey = this.#tlsCertPrefKey(pluginId); + const certs = this.#readPref(certKey, this.memoryTrustedCerts.get(certKey) ?? {}); + return Array.isArray(certs?.[endpoint]) && certs[endpoint].includes(fingerprint256); + } + + rememberTrustedTlsCert(pluginId, endpoint, fingerprint256) { + const certKey = this.#tlsCertPrefKey(pluginId); + const certs = { ...this.#readPref(certKey, this.memoryTrustedCerts.get(certKey) ?? {}) }; + const existing = new Set(Array.isArray(certs[endpoint]) ? certs[endpoint] : []); + existing.add(fingerprint256); + certs[endpoint] = [...existing].slice(-16); + this.memoryTrustedCerts.set(certKey, certs); + this.#writePref(certKey, certs); + } + + async #confirmDynamicEndpoint(target, context) { + const isLocal = target.host === "localhost" + || isLocalControlAddress(target.host) + || isOwnMachineAddress(target.host); + if (this.interactionService?.owner) { + const result = await this.interactionService.request({ + kind: "network.stream.confirm", + endpoint: target.endpoint, + host: target.host, + port: target.port, + transport: target.transport, + isLocal, + }, context); + if (result?.cancelled || !result?.approved) { + throw new PluginRpcError(RPC_ERRORS.cancelled, "Byte stream connection cancelled"); + } + if (result.remember === true) { + this.rememberDynamicEndpoint(context.pluginId, target.endpoint); + } + return; + } + // Non-interactive / headless test fallback: defer to permissionEngine hook. + await this.permissionEngine.authorize({ ...context, signal: context.signal }, { + permission: "network.stream", + resources: [target.endpoint], + reason: `Open byte stream to ${target.endpoint}`, + operationId: `network.stream:${target.endpoint}`, + validateBeforeGrant: () => context.assertCommit?.(), + }); + } + + async #confirmTlsCert(certInfo, context) { + if (this.interactionService?.owner) { + const result = await this.interactionService.request({ + kind: "network.stream.tlsConfirm", + ...certInfo, + }, context); + if (result?.cancelled || !result?.approved) { + return { approved: false }; + } + return { approved: true, remember: result.remember === true }; + } + return { approved: false }; } sourceMatches(identity) { @@ -73,13 +275,46 @@ class PluginByteStreamService { register(registry) { // These routes own authorization: connect authenticates before the broker - // obtains its exact endpoint grant; attach/close prove handle ownership. + // obtains its exact endpoint grant; attach/close/upgradeTls prove handle ownership. // The registry public flag skips only the generic permission middleware. // Runtime authentication and quota middleware still apply to every call. - registry.registerRequest("network.stream.connect", async ({ endpoint }, caller) => { + registry.registerRequest("network.stream.connect", async (params, caller) => { const context = await this.authenticate(caller); - return this.connect(endpoint, context); + let target; + try { target = canonicalizeStreamEndpoint(params.endpoint); } + catch { throw new PluginRpcError(RPC_ERRORS.invalidArgument, "Byte stream endpoint is invalid"); } + const { declared, staticMatch } = manifestStreamDeclaration(context.manifest, target.endpoint); + const isDynamic = !staticMatch || params.allowLocal === true; + const connectOptions = { + allowSelfSigned: params.allowSelfSigned === true, + ...(params.caPem === undefined ? {} : { caPem: params.caPem }), + ...(params.servername === undefined ? {} : { servername: params.servername }), + }; + if (isDynamic && declared) { + const mode = this.permissionEngine.getMode?.(context, "network.stream") ?? "allow"; + if (mode === "deny") { + throw new PluginRpcError(RPC_ERRORS.permissionDenied, "Plugin permission is disabled: network.stream"); + } + if (!this.isDynamicEndpointRemembered(context.pluginId, target.endpoint)) { + await this.#confirmDynamicEndpoint(target, context); + } + await context.assertActive(); + connectOptions.localApproved = true; + connectOptions.skipPermissionAuthorize = true; + } + return this.connect(target.endpoint, context, undefined, connectOptions); }, { validateParams: validator("ByteStreamConnectRequest"), metadata: { capability: "network.stream", mutating: true, public: true } }); + + registry.registerRequest("network.stream.upgradeTls", async ({ handleId, servername, allowSelfSigned, caPem }, caller) => { + const context = await this.authenticate(caller); + const record = this.get(handleId, context); + return this.broker.upgradeTls(handleId, { + ...(servername === undefined ? {} : { servername }), + allowSelfSigned: allowSelfSigned === true, + ...(caPem === undefined ? {} : { caPem }), + }, record.context); + }, { validateParams: validator("ByteStreamUpgradeTlsRequest"), metadata: { capability: "network.stream", mutating: true, public: true } }); + registry.registerRequest("network.stream.attach", async ({ handleId }, caller) => { const context = await this.authenticate(caller); const record = this.get(handleId, context); @@ -130,8 +365,8 @@ class PluginByteStreamService { }); } - async connect(endpoint, context, hostTransport) { - const handle = await this.broker.connect(endpoint, context, hostTransport); + async connect(endpoint, context, hostTransport, connectOptions) { + const handle = await this.broker.connect(endpoint, context, hostTransport, connectOptions); try { context.assertCommit(); this.broker.get(handle.handleId, context); @@ -208,6 +443,7 @@ class PluginByteStreamService { for (const record of this.records.values()) this.closeRecord(record); this.broker.shutdown(); this.brokerClose.dispose(); + this.revocation.dispose(); this.streamRegistration?.dispose(); this.closedHandles.clear(); } diff --git a/electron/plugins/constants.cjs b/electron/plugins/constants.cjs index 1c57d86c7..8216453d2 100644 --- a/electron/plugins/constants.cjs +++ b/electron/plugins/constants.cjs @@ -9,11 +9,11 @@ const PLUGIN_UTILITY_TERMINATION_GRACE_MS = 500; const PLUGIN_UTILITY_FORCE_EXIT_TIMEOUT_MS = 1_000; const PLUGIN_RPC_DEFAULT_TIMEOUT_MS = 30_000; const PLUGIN_RPC_MAX_PENDING = 256; -const PLUGIN_RPC_MAX_JSON_BYTES = 1024 * 1024; +const PLUGIN_RPC_MAX_JSON_BYTES = 8 * 1024 * 1024; // Broker payloads live inside the control-plane JSON envelope. Reserve enough // room for worst-case JSON string escaping (six wire bytes per raw byte), // headers, paths, correlation fields, and future compatible metadata. -const PLUGIN_RPC_MAX_RAW_BYTES = Math.floor(PLUGIN_RPC_MAX_JSON_BYTES / 8); +const PLUGIN_RPC_MAX_RAW_BYTES = 128 * 1024; const PLUGIN_STREAM_MAX_FRAME_JSON_BYTES = 24 * 1024 * 1024; const PLUGIN_CRASH_WINDOW_MS = 5 * 60_000; const PLUGIN_CRASH_QUARANTINE_THRESHOLD = 3; diff --git a/electron/plugins/contributionIconRasterizer.cjs b/electron/plugins/contributionIconRasterizer.cjs index 20ab54cda..6b75ecfd0 100644 --- a/electron/plugins/contributionIconRasterizer.cjs +++ b/electron/plugins/contributionIconRasterizer.cjs @@ -3,6 +3,9 @@ const { randomUUID } = require("node:crypto"); const DEFAULT_RASTER_TIMEOUT_MS = 5_000; +const DEFAULT_POOLED_RASTER_TIMEOUT_MS = 15_000; +const DEFAULT_POOLED_IDLE_MS = 15_000; +const RASTER_BLANK_HTML_URL = "data:text/html;charset=utf-8,%3Cmeta%20http-equiv%3D%22Content-Security-Policy%22%20content%3D%22default-src%20'none'%3B%20img-src%20data%3A%3B%22%3E"; function withTimeout(promise, timeoutMs, message) { let timer; @@ -82,7 +85,7 @@ function createIsolatedContributionIconRasterizer(options) { (_details, callback) => callback({ cancel: true }), ); await withTimeout( - Promise.resolve(win.loadURL("data:text/html;charset=utf-8,%3Cmeta%20http-equiv%3D%22Content-Security-Policy%22%20content%3D%22default-src%20'none'%3B%20img-src%20data%3A%3B%22%3E")), + Promise.resolve(win.loadURL(RASTER_BLANK_HTML_URL)), timeoutMs, "Plugin contribution icon rasterizer did not load in time", ); @@ -108,8 +111,147 @@ function createIsolatedContributionIconRasterizer(options) { }; } +/** + * Reuses a single sandboxed, network-denied BrowserWindow across burst decodes + * (e.g. plugin view icon grids) and destroys it automatically after idleMs, on + * any error/timeout, or on dispose(). Preserves the exact same sandbox, CSP, + * spellcheck:false, and network-deny guarantees as per-call windows while + * eliminating repeated OS window creation overhead. + */ +function createPooledContributionIconRasterizer(options) { + const BrowserWindow = options?.BrowserWindow; + const randomUUIDFn = options?.randomUUID ?? randomUUID; + const timeoutMs = options?.timeoutMs ?? DEFAULT_POOLED_RASTER_TIMEOUT_MS; + const idleMs = options?.idleMs ?? DEFAULT_POOLED_IDLE_MS; + + let activeWindow = null; + let windowReadyPromise = null; + let inFlight = 0; + let idleTimer = null; + let generation = 0; + + const clearIdleTimer = () => { + if (idleTimer !== null) { + clearTimeout(idleTimer); + idleTimer = null; + } + }; + + const destroyCurrent = (expectedGen) => { + if (expectedGen !== undefined && expectedGen !== generation) return; + clearIdleTimer(); + const win = activeWindow; + activeWindow = null; + windowReadyPromise = null; + generation += 1; + if (win) { + try { win.destroy(); } catch {} + } + }; + + const scheduleIdleDestroy = (expectedGen) => { + clearIdleTimer(); + if (inFlight > 0 || !activeWindow || idleMs <= 0) return; + idleTimer = setTimeout(() => { + idleTimer = null; + if (inFlight === 0 && generation === expectedGen) destroyCurrent(expectedGen); + }, idleMs); + idleTimer.unref?.(); + }; + + const acquireWindow = async () => { + if (typeof BrowserWindow !== "function") { + throw new Error("Isolated plugin contribution icon rasterizer is unavailable"); + } + clearIdleTimer(); + if (activeWindow && windowReadyPromise && !activeWindow.isDestroyed?.()) { + const currentGen = generation; + await windowReadyPromise; + if (activeWindow && generation === currentGen && !activeWindow.isDestroyed?.()) { + return { win: activeWindow, gen: currentGen }; + } + } + destroyCurrent(); + const currentGen = generation; + const partition = `plugin-icon-raster-${randomUUIDFn()}`; + const win = new BrowserWindow({ + show: false, + width: 64, + height: 64, + webPreferences: { + partition, + sandbox: true, + spellcheck: false, + contextIsolation: true, + nodeIntegration: false, + webSecurity: true, + allowRunningInsecureContent: false, + backgroundThrottling: false, + }, + }); + activeWindow = win; + const ready = (async () => { + win.removeMenu?.(); + win.webContents?.session?.webRequest?.onBeforeRequest?.( + { urls: ["http://*/*", "https://*/*", "file://*/*", "ftp://*/*"] }, + (_details, callback) => callback({ cancel: true }), + ); + await withTimeout( + Promise.resolve(win.loadURL(RASTER_BLANK_HTML_URL)), + timeoutMs, + "Plugin contribution icon rasterizer did not load in time", + ); + })(); + windowReadyPromise = ready; + try { + await ready; + return { win, gen: currentGen }; + } catch (error) { + destroyCurrent(currentGen); + throw error; + } + }; + + const rasterize = async ({ body, mimeType, width, height, maxEdge }) => { + inFlight += 1; + let gen; + try { + const acquired = await acquireWindow(); + gen = acquired.gen; + const result = await withTimeout( + Promise.resolve(acquired.win.webContents.executeJavaScript(browserRasterizeExpression({ + source: body.toString("base64"), + mimeType, + width, + height, + maxEdge, + }), true)), + timeoutMs, + "Plugin contribution icon rasterization timed out", + ); + const prefix = "data:image/png;base64,"; + if (typeof result !== "string" || !result.startsWith(prefix)) { + throw new Error("Plugin contribution icon rasterizer returned an invalid result"); + } + return Buffer.from(result.slice(prefix.length), "base64"); + } catch (error) { + destroyCurrent(gen); + throw error; + } finally { + inFlight = Math.max(0, inFlight - 1); + if (inFlight === 0 && activeWindow) scheduleIdleDestroy(generation); + } + }; + + rasterize.dispose = () => destroyCurrent(); + return rasterize; +} + module.exports = { DEFAULT_RASTER_TIMEOUT_MS, + DEFAULT_POOLED_RASTER_TIMEOUT_MS, + DEFAULT_POOLED_IDLE_MS, browserRasterizeExpression, createIsolatedContributionIconRasterizer, + createPooledContributionIconRasterizer, }; diff --git a/electron/plugins/contributionIconRasterizer.test.cjs b/electron/plugins/contributionIconRasterizer.test.cjs index 3a9968c24..c3710fb43 100644 --- a/electron/plugins/contributionIconRasterizer.test.cjs +++ b/electron/plugins/contributionIconRasterizer.test.cjs @@ -6,6 +6,7 @@ const test = require("node:test"); const { browserRasterizeExpression, createIsolatedContributionIconRasterizer, + createPooledContributionIconRasterizer, } = require("./contributionIconRasterizer.cjs"); test("viewBox-only SVG icons receive an explicit isolated raster viewport", () => { @@ -96,3 +97,52 @@ test("timed-out contribution icon rasterizers always destroy their isolated wind }), /timed out/); assert.equal(destroyed, true); }); + +test("pooled contribution icon rasterizer reuses one sandboxed window across bursts, destroys on error and dispose", async () => { + let created = 0; + let destroyed = 0; + let failNext = false; + class BrowserWindowStub { + constructor(options) { + created += 1; + assert.equal(options.webPreferences.sandbox, true); + assert.equal(options.webPreferences.spellcheck, false); + assert.equal(options.webPreferences.nodeIntegration, false); + this._destroyed = false; + this.webContents = { + session: { webRequest: { onBeforeRequest() {} } }, + async executeJavaScript() { + if (failNext) { + failNext = false; + throw new Error("transient decode failure"); + } + return `data:image/png;base64,${Buffer.from("pooled-png").toString("base64")}`; + }, + }; + } + async loadURL() {} + removeMenu() {} + isDestroyed() { return this._destroyed; } + destroy() { this._destroyed = true; destroyed += 1; } + } + const rasterize = createPooledContributionIconRasterizer({ + BrowserWindow: BrowserWindowStub, + idleMs: 10_000, + }); + const payload = { body: Buffer.from("img"), mimeType: "image/png", width: 16, height: 16, maxEdge: 64 }; + const [a, b, c] = await Promise.all([rasterize(payload), rasterize(payload), rasterize(payload)]); + assert.deepEqual(a, Buffer.from("pooled-png")); + assert.deepEqual(b, Buffer.from("pooled-png")); + assert.deepEqual(c, Buffer.from("pooled-png")); + assert.equal(created, 1); + assert.equal(destroyed, 0); + + failNext = true; + await assert.rejects(rasterize(payload), /transient decode failure/); + assert.equal(destroyed, 1); + + assert.deepEqual(await rasterize(payload), Buffer.from("pooled-png")); + assert.equal(created, 2); + rasterize.dispose(); + assert.equal(destroyed, 2); +}); diff --git a/electron/plugins/generated/plugin-contract.schema.json b/electron/plugins/generated/plugin-contract.schema.json index 87ccd1386..a3e838794 100644 --- a/electron/plugins/generated/plugin-contract.schema.json +++ b/electron/plugins/generated/plugin-contract.schema.json @@ -56,7 +56,7 @@ "RpcLimits": { "description": "Host-enforced byte limit for one JSON-RPC control message. Larger payloads must use a stream.", "const": { - "maxJsonBytes": 1048576 + "maxJsonBytes": 8388608 } }, "SafeUnsignedInteger": { @@ -576,9 +576,41 @@ }, "kind": { "const": "network.stream.connectViaHost" + }, + "durable": { + "type": "boolean" } }, "additionalProperties": false + }, + { + "type": "object", + "required": [ + "kind", + "hostBindingToken", + "endpoint" + ], + "properties": { + "kind": { + "const": "network.stream.connectViaHost" + }, + "hostBindingToken": { + "type": "string", + "minLength": 16, + "maxLength": 256, + "pattern": "^[A-Za-z0-9._-]+$" + }, + "endpoint": { + "$ref": "#/$defs/ByteStreamEndpoint" + } + }, + "additionalProperties": false + }, + { + "$ref": "#/$defs/HostByteStreamConfirmRequest" + }, + { + "$ref": "#/$defs/HostByteStreamTlsConfirmRequest" } ] }, @@ -820,12 +852,14 @@ "HostInteractionLimits": { "const": { "textBytes": 4096, - "requestBytes": 65536, + "clipboardBytes": 4194304, + "requestBytes": 4259840, "items": 100, "pendingPerRuntime": 1, "pendingTotal": 8, - "requestsPerMinute": 10, - "timeoutMs": 60000 + "requestsPerMinute": 60, + "timeoutMs": 60000, + "fileMaxBytes": 67108864 } }, "HostInteractionFeature": { @@ -957,7 +991,7 @@ }, "text": { "type": "string", - "maxLength": 4096, + "maxLength": 4194304, "pattern": "^[^\\u0000]*$" } }, @@ -1013,7 +1047,7 @@ "oneOf": [ { "type": "string", - "maxLength": 4096, + "maxLength": 4194304, "pattern": "^[^\\u0000]*$" }, { @@ -1035,6 +1069,25 @@ }, { "$ref": "#/$defs/ByteStreamConnectionDescriptor" + }, + { + "type": "object", + "required": [ + "cancelled", + "approved" + ], + "properties": { + "cancelled": { + "const": false + }, + "approved": { + "const": true + }, + "remember": { + "type": "boolean" + } + }, + "additionalProperties": false } ] }, @@ -1086,6 +1139,9 @@ }, "scriptsRun": { "type": "boolean" + }, + "remember": { + "type": "boolean" } }, "additionalProperties": false @@ -1202,6 +1258,14 @@ "$ref": "#/$defs/VaultHostEditFields" } ] + }, + "durableHostId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "autoCommit": { + "type": "boolean" } }, "additionalProperties": false @@ -1556,14 +1620,14 @@ }, "ByteStreamLimits": { "const": { - "connectionsPerRuntime": 4, - "connectionsTotal": 64, + "connectionsPerRuntime": 24, + "connectionsTotal": 128, "chunkBytes": 65536, "bufferBytes": 65536, - "connectionBytes": 8388608, + "connectionBytes": 536870912, "connectMs": 10000, - "idleMs": 30000, - "lifetimeMs": 120000 + "idleMs": 1800000, + "lifetimeMs": 28800000 } }, "ByteStreamEndpoint": { @@ -1581,6 +1645,23 @@ "properties": { "endpoint": { "$ref": "#/$defs/ByteStreamEndpoint" + }, + "allowLocal": { + "type": "boolean" + }, + "allowSelfSigned": { + "type": "boolean" + }, + "caPem": { + "type": "string", + "minLength": 1, + "maxLength": 65536 + }, + "servername": { + "type": "string", + "minLength": 1, + "maxLength": 253, + "pattern": "^[A-Za-z0-9.-]+$" } }, "additionalProperties": false @@ -1623,6 +1704,12 @@ }, "windowBytes": { "const": 65536 + }, + "hostBindingToken": { + "type": "string", + "minLength": 16, + "maxLength": 256, + "pattern": "^[A-Za-z0-9._-]+$" } }, "additionalProperties": false @@ -1964,10 +2051,7 @@ "PermissionDeclaration": { "oneOf": [ { - "$ref": "#/$defs/PluginPermission", - "not": { - "const": "network.stream" - } + "$ref": "#/$defs/PluginPermission" }, { "$ref": "#/$defs/PermissionResourceDeclaration" @@ -2591,14 +2675,14 @@ }, "mutations": { "type": "array", - "maxItems": 2048, + "maxItems": 4096, "items": { "$ref": "#/$defs/JsonValue" } }, "css": { "type": "string", - "maxLength": 65536 + "maxLength": 131072 } }, "additionalProperties": false @@ -2653,12 +2737,16 @@ "compositionend", "dismiss", "submit", - "reset" + "reset", + "dblclick", + "contextmenu", + "scroll", + "widget" ] }, "value": { "type": "string", - "maxLength": 8192 + "maxLength": 131072 }, "checked": { "type": "boolean" @@ -2695,6 +2783,47 @@ "type": "string", "maxLength": 8192 } + }, + "x": { + "type": "number" + }, + "y": { + "type": "number" + }, + "scrollTop": { + "type": "number", + "minimum": 0 + }, + "scrollLeft": { + "type": "number", + "minimum": 0 + }, + "clientHeight": { + "type": "number", + "minimum": 0 + }, + "clientWidth": { + "type": "number", + "minimum": 0 + }, + "selectionStart": { + "type": "integer", + "minimum": 0, + "maximum": 131072 + }, + "selectionEnd": { + "type": "integer", + "minimum": 0, + "maximum": 131072 + }, + "widgetEvent": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^[a-zA-Z][a-zA-Z0-9_-]{0,63}$" + }, + "detail": { + "$ref": "#/$defs/JsonValue" } }, "additionalProperties": false @@ -8664,35 +8793,387 @@ }, "HostByteStreamLimits": { "const": { - "connectionsPerRuntime": 4, - "connectionsTotal": 64, + "connectionsPerRuntime": 24, + "connectionsTotal": 128, "chunkBytes": 65536, "bufferBytes": 65536, - "connectionBytes": 67108864, + "connectionBytes": 536870912, "connectMs": 120000, - "idleMs": 300000, - "lifetimeMs": 1800000 + "idleMs": 1800000, + "lifetimeMs": 28800000 } }, "HostByteStreamConnectRequest": { + "oneOf": [ + { + "type": "object", + "required": [ + "target", + "expectedRevision", + "endpoint" + ], + "properties": { + "target": { + "$ref": "#/$defs/VaultHostRef" + }, + "expectedRevision": { + "type": "string", + "maxLength": 128, + "pattern": "^[^\\u0000-\\u001f\\u007f]*$", + "minLength": 1 + }, + "endpoint": { + "$ref": "#/$defs/ByteStreamEndpoint" + }, + "durable": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "hostBindingToken", + "endpoint" + ], + "properties": { + "hostBindingToken": { + "type": "string", + "minLength": 16, + "maxLength": 256, + "pattern": "^[A-Za-z0-9._-]+$" + }, + "endpoint": { + "$ref": "#/$defs/ByteStreamEndpoint" + } + }, + "additionalProperties": false + } + ] + }, + "ByteStreamUpgradeTlsRequest": { "type": "object", "required": [ - "target", - "expectedRevision", - "endpoint" + "handleId" ], "properties": { - "target": { - "$ref": "#/$defs/VaultHostRef" - }, - "expectedRevision": { + "handleId": { "type": "string", - "maxLength": 128, - "pattern": "^[^\\u0000-\\u001f\\u007f]*$", - "minLength": 1 + "format": "uuid" + }, + "servername": { + "type": "string", + "minLength": 1, + "maxLength": 253, + "pattern": "^[A-Za-z0-9.-]+$" + }, + "allowSelfSigned": { + "type": "boolean" + }, + "caPem": { + "type": "string", + "minLength": 1, + "maxLength": 65536 + } + }, + "additionalProperties": false + }, + "ByteStreamUpgradeTlsResult": { + "type": "object", + "required": [ + "upgraded", + "authorized" + ], + "properties": { + "upgraded": { + "const": true + }, + "authorized": { + "type": "boolean" + }, + "protocol": { + "type": "string", + "maxLength": 64 + }, + "fingerprint256": { + "type": "string", + "maxLength": 128 + }, + "subject": { + "type": "string", + "maxLength": 512 + } + }, + "additionalProperties": false + }, + "VaultHostBindingRevokeParams": { + "type": "object", + "required": [ + "hostBindingToken" + ], + "properties": { + "hostBindingToken": { + "type": "string", + "minLength": 16, + "maxLength": 256, + "pattern": "^[A-Za-z0-9._-]+$" + } + }, + "additionalProperties": false + }, + "HostByteStreamConfirmRequest": { + "type": "object", + "required": [ + "kind", + "endpoint", + "host", + "port", + "transport", + "isLocal" + ], + "properties": { + "kind": { + "const": "network.stream.confirm" }, "endpoint": { "$ref": "#/$defs/ByteStreamEndpoint" + }, + "host": { + "type": "string", + "minLength": 1, + "maxLength": 253 + }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "transport": { + "enum": [ + "tcp", + "tls" + ] + }, + "isLocal": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "HostByteStreamTlsConfirmRequest": { + "type": "object", + "required": [ + "kind", + "endpoint", + "fingerprint256", + "subject", + "issuer", + "validTo", + "reason" + ], + "properties": { + "kind": { + "const": "network.stream.tlsConfirm" + }, + "endpoint": { + "$ref": "#/$defs/ByteStreamEndpoint" + }, + "servername": { + "type": "string", + "minLength": 1, + "maxLength": 253 + }, + "fingerprint256": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "subject": { + "type": "string", + "maxLength": 512 + }, + "issuer": { + "type": "string", + "maxLength": 512 + }, + "validTo": { + "type": "string", + "maxLength": 128 + }, + "reason": { + "type": "string", + "maxLength": 256 + } + }, + "additionalProperties": false + }, + "HostFileDialogFilter": { + "type": "object", + "required": [ + "name", + "extensions" + ], + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^[^\\u0000-\\u001f\\u007f]*$" + }, + "extensions": { + "type": "array", + "minItems": 1, + "maxItems": 32, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 32, + "pattern": "^(\\*|[A-Za-z0-9][A-Za-z0-9._-]{0,31})$" + } + } + }, + "additionalProperties": false + }, + "HostOpenFileRequest": { + "type": "object", + "properties": { + "title": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[^\\u0000-\\u001f\\u007f]*$" + }, + "filters": { + "type": "array", + "maxItems": 32, + "items": { + "$ref": "#/$defs/HostFileDialogFilter" + } + }, + "readAs": { + "enum": [ + "bytes", + "utf8" + ] + }, + "maxBytes": { + "type": "integer", + "minimum": 1, + "maximum": 67108864 + } + }, + "additionalProperties": false + }, + "HostSaveFileRequest": { + "type": "object", + "properties": { + "title": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[^\\u0000-\\u001f\\u007f]*$" + }, + "defaultName": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[^\\u0000-\\u001f\\u007f/\\\\]+$" + }, + "filters": { + "type": "array", + "maxItems": 32, + "items": { + "$ref": "#/$defs/HostFileDialogFilter" + } + }, + "data": { + "type": "string", + "maxLength": 5592408 + }, + "encoding": { + "enum": [ + "base64", + "utf8" + ] + }, + "deferredWrite": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "HostFileHandleReadRequest": { + "type": "object", + "required": [ + "handleId" + ], + "properties": { + "handleId": { + "type": "string", + "format": "uuid" + }, + "offset": { + "type": "integer", + "minimum": 0, + "maximum": 67108864 + }, + "length": { + "type": "integer", + "minimum": 1, + "maximum": 4194304 + }, + "encoding": { + "enum": [ + "base64", + "utf8" + ] + } + }, + "additionalProperties": false + }, + "HostFileHandleWriteRequest": { + "type": "object", + "required": [ + "handleId", + "data" + ], + "properties": { + "handleId": { + "type": "string", + "format": "uuid" + }, + "data": { + "type": "string", + "maxLength": 5592408 + }, + "encoding": { + "enum": [ + "base64", + "utf8" + ] + }, + "mode": { + "enum": [ + "replace", + "append" + ] + }, + "commit": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "HostFileHandleCloseRequest": { + "type": "object", + "required": [ + "handleId" + ], + "properties": { + "handleId": { + "type": "string", + "format": "uuid" } }, "additionalProperties": false diff --git a/electron/plugins/hostBootstrap.cjs b/electron/plugins/hostBootstrap.cjs index 102515061..b110fcd31 100644 --- a/electron/plugins/hostBootstrap.cjs +++ b/electron/plugins/hostBootstrap.cjs @@ -1,11 +1,8 @@ "use strict"; -const { isPluginDevelopmentEnabled } = require("./constants.cjs"); - function startPluginHost(options) { - // The plugin platform is not shipping in this release. Keep its data - // untouched and allow existing developer workflows to opt in as before. - if (!isPluginDevelopmentEnabled(options.env)) return null; + // TODO(revert): temporarily enabled by default for database plugin development + if (options.env?.NETCATTY_PLUGIN_DEV === "0") return null; const reportFailure = (message, error) => { try { options.logger?.error?.(message, error); } catch {} diff --git a/electron/plugins/hostBootstrap.test.cjs b/electron/plugins/hostBootstrap.test.cjs index d9ca2f187..ad71a14cb 100644 --- a/electron/plugins/hostBootstrap.test.cjs +++ b/electron/plugins/hostBootstrap.test.cjs @@ -5,10 +5,10 @@ const test = require("node:test"); const { startPluginHost } = require("./hostBootstrap.cjs"); -test("default startup leaves the plugin host and stored plugin data untouched", () => { +test("explicitly disabling NETCATTY_PLUGIN_DEV leaves the plugin host and stored plugin data untouched", () => { const effects = []; assert.equal(startPluginHost({ - env: {}, + env: { NETCATTY_PLUGIN_DEV: "0" }, createService() { effects.push("create"); }, registerShutdown() { effects.push("register"); }, logger: { error() { effects.push("error"); } }, @@ -16,6 +16,24 @@ test("default startup leaves the plugin host and stored plugin data untouched", assert.deepEqual(effects, []); }); +test("default startup enables the plugin host during database plugin development", async () => { + let initialized = 0; + const service = { + manager: { + async initialize() { initialized += 1; }, + async shutdown() {}, + }, + }; + assert.equal(startPluginHost({ + env: {}, + createService: () => service, + registerShutdown() {}, + logger: { error() {} }, + }), service); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(initialized, 1); +}); + test("synchronous plugin host construction failure leaves Netcatty available", () => { const errors = []; let registered = 0; diff --git a/electron/plugins/hostByteStreamAuthorization.test.cjs b/electron/plugins/hostByteStreamAuthorization.test.cjs index 26845ff08..c312dfd28 100644 --- a/electron/plugins/hostByteStreamAuthorization.test.cjs +++ b/electron/plugins/hostByteStreamAuthorization.test.cjs @@ -102,3 +102,53 @@ test("window closure during opening aborts the operation and rejects a late conn assert.equal(f.opens[0].context.signal.aborted, true); assert.equal(f.vault.streams.size, 0); }); + +test("durable SSH tunnel binding survives selection expiry and blur, enforces exact endpoint, and can be revoked", async (t) => { + const f = await fixture(t); + const pending = f.call("network.stream.connectViaHost", { ...f.params, durable: true }); + await f.tick(); + await f.respond("submit", { remember: true }); + await f.respond("commit", {}, { hostId: "host-one" }); + const first = await pending; + assert.equal(typeof first.hostBindingToken, "string"); + assert.ok(first.hostBindingToken.startsWith("hb_")); + + // Expire ephemeral selection and clear selections (simulating blur/restart). + f.expire(); + f.vault.clearSelections(); + + // Mismatched endpoint with the same durable token must be rejected. + await assert.rejects( + f.call("network.stream.connectViaHost", { hostBindingToken: first.hostBindingToken, endpoint: "tcp://127.0.0.1:5432" }), + /binding/u, + ); + // Forged token must be rejected. + await assert.rejects( + f.call("network.stream.connectViaHost", { hostBindingToken: "hb_forged_token_000000000000000000", endpoint: f.params.endpoint }), + /binding/u, + ); + + // Reconnect with durable token skips request phase and emits autoCommit prompt bound to host-one. + const reconnect = f.call("network.stream.connectViaHost", { + hostBindingToken: first.hostBindingToken, + endpoint: f.params.endpoint, + }); + await f.tick(); + const prompt = f.prompts.at(-1); + assert.equal(prompt.phase, "commit"); + assert.equal(prompt.autoCommit, true); + assert.equal(prompt.durableHostId, "host-one"); + await f.respond("commit", {}, { hostId: "host-one" }); + const second = await reconnect; + assert.equal(second.endpoint, f.params.endpoint); + assert.equal(second.hostBindingToken, first.hostBindingToken); + assert.equal(f.opens.length, 2); + + // Revoke durable binding -> subsequent reconnect fails closed. + const revoked = await f.call("vault.revokeHostBinding", { hostBindingToken: first.hostBindingToken }); + assert.deepEqual(revoked, { revoked: true }); + await assert.rejects( + f.call("network.stream.connectViaHost", { hostBindingToken: first.hostBindingToken, endpoint: f.params.endpoint }), + /binding/u, + ); +}); diff --git a/electron/plugins/hostDrawnViewHost.cjs b/electron/plugins/hostDrawnViewHost.cjs index e996c4cd3..99a9b5f77 100644 --- a/electron/plugins/hostDrawnViewHost.cjs +++ b/electron/plugins/hostDrawnViewHost.cjs @@ -107,13 +107,16 @@ class HostDrawnViewHost { const { plugin } = this.contributions.assertViewActivationCurrent(instance.activation, { context: instance.context }); instance.resources ??= new Map(); if (instance.resources.has(resource)) return instance.resources.get(resource); - if (instance.resources.size >= 32) throw new Error("Plugin image limit exceeded"); + if (instance.resources.size >= 128) throw new Error("Plugin image limit exceeded"); const pending = this.resources.image(plugin, resource).then((result) => { if (this.isLocked() || this.instances.get(id) !== instance) throw new Error("Plugin view closed"); this.contributions.assertViewActivationCurrent(instance.activation, { context: instance.context }); instance.resourceBytes = (instance.resourceBytes ?? 0) + result.url.length; - if (instance.resourceBytes > 8 * 1024 * 1024) throw new Error("Plugin image budget exceeded"); + if (instance.resourceBytes > 24 * 1024 * 1024) throw new Error("Plugin image budget exceeded"); return result; + }).catch((error) => { + if (instance.resources?.get(resource) === pending) instance.resources.delete(resource); + throw error; }); instance.resources.set(resource, pending); return pending; @@ -121,6 +124,12 @@ class HostDrawnViewHost { async event(id, event, sender) { const instance = this.owned(id, sender); if (this.isLocked() || !validateEvent(event)) throw new TypeError("Invalid plugin view event"); + if (event.detail !== undefined) { + let detailBytes = 0; + try { detailBytes = Buffer.byteLength(JSON.stringify(event.detail), "utf8"); } + catch { throw new TypeError("Invalid plugin view event detail"); } + if (detailBytes > 256 * 1024) throw new TypeError("Plugin view event detail exceeds limits"); + } this.contributions.assertViewActivationCurrent(instance.activation, { context: instance.context }); await this.contributions.runtimeSupervisor.notify(instance.pluginId, "plugin.view.message", { viewId: instance.viewId, message: { kind: "host-ui.event", instanceId: id, event } }, { expectedIdentity: instance.identity }); @@ -144,6 +153,7 @@ class HostDrawnViewHost { this.closed = true; for (const opening of this.opening.values()) opening.cancelled = true; await Promise.all([...this.instances.keys()].map((id) => this.close(id, undefined, "shutdown"))); this.messageSubscription?.dispose(); this.changeSubscription?.dispose(); this.unsubscribeLock?.(); + this.resources?.dispose?.(); } } module.exports = { HostDrawnViewHost }; diff --git a/electron/plugins/hostDrawnViewHost.test.cjs b/electron/plugins/hostDrawnViewHost.test.cjs index a92382cb5..41c4a2582 100644 --- a/electron/plugins/hostDrawnViewHost.test.cjs +++ b/electron/plugins/hostDrawnViewHost.test.cjs @@ -61,6 +61,7 @@ test("package resources require the same window and survive no close or revocati await assert.rejects(pending, /closed/); await assert.rejects(duplicate, /closed/); await f.host.shutdown(); }); + test("disable and owner navigation invalidate every retained view", async () => { for (const reason of ['plugin-disabled', 'runtime-stopped', 'runtime-error', 'runtime-quarantined']) { const f = fixture(); await open(f); f.change({ reason, pluginId: 'com.test.plugin' }); @@ -69,10 +70,42 @@ test("disable and owner navigation invalidate every retained view", async () => const f = fixture(); await open(f); f.sender.emit('did-start-navigation', { isMainFrame: true, isSameDocument: false }); assert.equal(f.host.instances.size, 0); await f.host.shutdown(); }); + test("updates are rate limited and resource caches are bounded", async () => { const f = fixture({ image: async () => ({ url: 'data:image/png;base64,AAAA' }) }); await open(f); - for (let i = 0; i < 32; i++) await f.host.resource('instance-1', `image-${i}.png`, f.sender); + for (let i = 0; i < 128; i++) await f.host.resource('instance-1', `image-${i}.png`, f.sender); await assert.rejects(f.host.resource('instance-1', 'extra.png', f.sender), /limit/); for (let i = 1; i <= 121; i++) f.message({ ...update(i), mutations: [] }); assert.equal(f.host.instances.size, 0); await f.host.shutdown(); }); + +test("extended surface and widget events validate schema and bound detail payload size", async () => { + 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: "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"); + await assert.rejects( + f.host.event("instance-1", { nodeId: "1", type: "widget", widgetEvent: "change", detail: { value: "x".repeat(260 * 1024) } }, f.sender), + /exceeds limits/, + ); + await f.host.shutdown(); +}); + +test("transient resource decode failures are evicted so retries can succeed", async () => { + let calls = 0; + const f = fixture({ + image: async () => { + calls += 1; + if (calls === 1) throw new Error("temporary decode failure"); + return { url: "data:image/png;base64,AAAA" }; + }, + }); + await open(f); + await assert.rejects(f.host.resource("instance-1", "icon.png", f.sender), /temporary decode failure/); + const recovered = await f.host.resource("instance-1", "icon.png", f.sender); + assert.equal(recovered.url, "data:image/png;base64,AAAA"); + assert.equal(calls, 2); + await f.host.shutdown(); +}); diff --git a/electron/plugins/hostInteractionService.cjs b/electron/plugins/hostInteractionService.cjs index f4a1f0ddc..def7bb39b 100644 --- a/electron/plugins/hostInteractionService.cjs +++ b/electron/plugins/hostInteractionService.cjs @@ -1,6 +1,8 @@ "use strict"; const { createHmac, randomBytes, randomUUID, timingSafeEqual } = require("node:crypto"); +const fs = require("node:fs/promises"); +const path = require("node:path"); const { createDefinitionValidator } = require("./contractValidator.cjs"); const { TerminalSelectionAuthority } = require("./terminalSelectionAuthority.cjs"); const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs"); @@ -11,11 +13,28 @@ const validateRequest = createDefinitionValidator("HostInteractionRequest"); const validateResponse = createDefinitionValidator("HostInteractionResponse"); const validateResult = createDefinitionValidator("HostInteractionResult"); const validateSingleLineInput = createDefinitionValidator("HostSingleLineInputText"); +const validateOpenFile = createDefinitionValidator("HostOpenFileRequest"); +const validateSaveFile = createDefinitionValidator("HostSaveFileRequest"); +const validateReadFileHandle = createDefinitionValidator("HostFileHandleReadRequest"); +const validateWriteFileHandle = createDefinitionValidator("HostFileHandleWriteRequest"); +const validateCloseFileHandle = createDefinitionValidator("HostFileHandleCloseRequest"); const PROMPT_CHANNEL = "netcatty:plugins:host-interaction"; +const INLINE_FILE_BYTES = 2 * 1024 * 1024; +const MAX_FILE_HANDLES_PER_RUNTIME = 16; +const MAX_FILE_HANDLES_TOTAL = 64; + +function tryLoadElectronDialog() { + try { + return require("electron")?.dialog ?? null; + } catch { + return null; + } +} + function fail(code, message) { return new PluginRpcError(RPC_ERRORS[code], message); } -function assertTextBytes(text) { - if (typeof text !== "string" || Buffer.byteLength(text, "utf8") > LIMITS.textBytes || text.includes("\0")) { +function assertTextBytes(text, limit = LIMITS.textBytes) { + if (typeof text !== "string" || Buffer.byteLength(text, "utf8") > limit || text.includes("\0")) { throw fail("resourceExhausted", "Host interaction text exceeds its limit"); } return text; @@ -25,8 +44,8 @@ function assertInteractionRequest(params) { if (Buffer.byteLength(JSON.stringify(params)) > LIMITS.requestBytes) { throw fail("resourceExhausted", "Host interaction request exceeds its limit"); } - if (params.kind === "input") assertTextBytes(params.initialValue ?? ""); - if (params.kind === "clipboard.write") assertTextBytes(params.text); + if (params.kind === "input") assertTextBytes(params.initialValue ?? "", LIMITS.textBytes); + if (params.kind === "clipboard.write") assertTextBytes(params.text, LIMITS.clipboardBytes); if (params.kind === "terminal.input.propose" && Buffer.byteLength(params.text, "utf8") > LIMITS.textBytes) throw fail("resourceExhausted", "Terminal input draft exceeds its limit"); if (params.kind === "quickPick" && new Set(params.items.map((item) => item.id)).size !== params.items.length) { throw fail("invalidArgument", "Host interaction choice IDs must be unique"); @@ -39,6 +58,17 @@ function interactionAuthorization(params, terminalTarget) { return { permission: params.kind, resources: [terminalTarget.resource], reason: params.kind === "terminal.selection.read" ? "Preview and explicitly share the selected terminal text" : "Open an editable host draft without sending terminal input", operationId: params.kind, allowedScopes: ["once"], deferDecision: true }; } + if (params.kind === "network.stream.confirm" || params.kind === "network.stream.tlsConfirm") { + return { + permission: "network.stream", + resources: [params.endpoint], + reason: params.kind === "network.stream.tlsConfirm" + ? "Review an untrusted TLS certificate before continuing" + : `Confirm byte stream connection to ${params.endpoint}`, + operationId: `ui:${params.kind}`, + deferDecision: true, + }; + } const permission = params.kind === "clipboard.read" ? "clipboard.read" : params.kind === "clipboard.write" ? "clipboard.write" : "ui.interact"; return { @@ -57,12 +87,14 @@ class PluginHostInteractionService { this.permissionEngine = options.permissionEngine; this.quotaManager = options.quotaManager; this.clipboard = options.clipboard; + this.dialog = options.dialog ?? tryLoadElectronDialog(); this.getWindow = options.getWindow ?? (() => null); this.isLocked = options.isLocked ?? (() => true); this.clock = options.clock ?? Date.now; this.timeoutMs = Math.min(options.timeoutMs ?? LIMITS.timeoutMs, LIMITS.timeoutMs); this.key = randomBytes(32); this.pending = new Map(); + this.fileHandles = new Map(); this.terminalSelection = new TerminalSelectionAuthority({database: this.database, getWindow: this.getWindow, getManager: options.getTerminalWorkerManager, clock: this.clock}); this.terminalInvalidation = this.terminalSelection.onDidInvalidate(() => { for (const entry of [...this.pending.values()]) if (entry.terminalTarget && !this.#terminalCurrent(entry)) { @@ -91,6 +123,59 @@ class PluginHostInteractionService { } registerRpcCapabilities(registry) { + const fileAuth = (operation) => ({ + permission: "ui.interact", + resources: ["*"], + reason: operation === "open" + ? "Open a user-selected file via native file dialog" + : operation === "save" + ? "Save a file via native save dialog" + : "Access a user-selected file handle", + operationId: `ui:file:${operation}`, + deferDecision: true, + }); + registry.registerRequest("ui.openFile", (params, context) => this.openFile(params, context), { + metadata: { capability: "ui", mutating: false }, + validateParams: (params) => { + const normalized = params === undefined || params === null ? {} : params; + if (!validateOpenFile(normalized)) throw fail("invalidArgument", "Open file parameters are invalid"); + return Object.freeze(structuredClone(normalized)); + }, + authorization: () => fileAuth("open"), + }); + registry.registerRequest("ui.saveFile", (params, context) => this.saveFile(params, context), { + metadata: { capability: "ui", mutating: true }, + validateParams: (params) => { + const normalized = params === undefined || params === null ? {} : params; + if (!validateSaveFile(normalized)) throw fail("invalidArgument", "Save file parameters are invalid"); + return Object.freeze(structuredClone(normalized)); + }, + authorization: () => fileAuth("save"), + }); + registry.registerRequest("ui.readFileHandle", (params, context) => this.readFileHandle(params, context), { + metadata: { capability: "ui", mutating: false }, + validateParams: (params) => { + if (!validateReadFileHandle(params)) throw fail("invalidArgument", "File handle read parameters are invalid"); + return Object.freeze(structuredClone(params)); + }, + authorization: () => fileAuth("readHandle"), + }); + registry.registerRequest("ui.writeFileHandle", (params, context) => this.writeFileHandle(params, context), { + metadata: { capability: "ui", mutating: true }, + validateParams: (params) => { + if (!validateWriteFileHandle(params)) throw fail("invalidArgument", "File handle write parameters are invalid"); + return Object.freeze(structuredClone(params)); + }, + authorization: () => fileAuth("writeHandle"), + }); + registry.registerRequest("ui.closeFileHandle", (params, context) => this.closeFileHandle(params, context), { + metadata: { capability: "ui", mutating: true }, + validateParams: (params) => { + if (!validateCloseFileHandle(params)) throw fail("invalidArgument", "File handle close parameters are invalid"); + return Object.freeze(structuredClone(params)); + }, + authorization: () => fileAuth("closeHandle"), + }); registry.registerRequest("ui.interact", (params, context) => this.request(params, context), { metadata: { capability: "ui", mutating: true }, validateParams: assertInteractionRequest, @@ -101,6 +186,260 @@ class PluginHostInteractionService { }); } + #assertFileDialogPermission(context) { + const mode = this.permissionEngine.getMode?.(context, "ui.interact") ?? "allow"; + if (mode === "deny") throw fail("permissionDenied", "Plugin permission is disabled"); + } + + #allocateFileHandle(context, filePath) { + const runtimeCount = [...this.fileHandles.values()].filter((h) => h.runtimeId === context.runtimeId).length; + if (runtimeCount >= MAX_FILE_HANDLES_PER_RUNTIME || this.fileHandles.size >= MAX_FILE_HANDLES_TOTAL) { + throw fail("resourceExhausted", "Too many open file handles"); + } + const id = randomUUID(); + const handle = { + id, + pluginId: context.pluginId, + runtimeId: context.runtimeId, + sourceOwner: context.sourceOwner, + filePath, + name: path.basename(filePath), + stagingPath: null, + stagingBytes: 0, + createdAt: this.clock(), + }; + this.fileHandles.set(id, handle); + return handle; + } + + #getFileHandle(handleId, context) { + const handle = this.fileHandles.get(handleId); + if (!handle || handle.pluginId !== context.pluginId || handle.runtimeId !== context.runtimeId + || handle.sourceOwner !== context.sourceOwner) { + throw fail("permissionDenied", "File handle is invalid or closed"); + } + return handle; + } + + async #disposeFileHandle(handle) { + if (!handle) return; + this.fileHandles.delete(handle.id); + if (handle.stagingPath) { + const temp = handle.stagingPath; + handle.stagingPath = null; + handle.stagingBytes = 0; + await fs.unlink(temp).catch(() => {}); + } + } + + async openFile(params, context) { + await context.assertActive(); + this.#assertFileDialogPermission(context); + if (this.closed || this.isLocked()) { + throw fail("unavailable", "Host file dialogs require an unlocked window"); + } + if (typeof this.dialog?.showOpenDialog !== "function") { + throw fail("unavailable", "Native file dialog is unavailable"); + } + const window = this.getWindow(); + const dialogOptions = { + title: params.title ?? "Open File", + properties: ["openFile"], + ...(params.filters?.length ? { filters: params.filters } : {}), + }; + const picked = window && !window.isDestroyed?.() + ? await this.dialog.showOpenDialog(window, dialogOptions) + : await this.dialog.showOpenDialog(dialogOptions); + await context.assertActive(); + if (this.closed || this.isLocked()) { + throw fail("cancelled", "Host locked during file selection"); + } + if (!picked || picked.canceled || !Array.isArray(picked.filePaths) || picked.filePaths.length === 0) { + return { cancelled: true }; + } + const filePath = picked.filePaths[0]; + const stat = await fs.stat(filePath); + if (!stat.isFile()) { + throw fail("invalidArgument", "Selected path is not a regular file"); + } + const maxBytes = Math.min(params.maxBytes ?? LIMITS.fileMaxBytes, LIMITS.fileMaxBytes); + if (stat.size > maxBytes) { + throw fail("resourceExhausted", `Selected file exceeds the ${maxBytes} byte limit`); + } + const handle = this.#allocateFileHandle(context, filePath); + this.database?.recordSecurityAudit?.(context.pluginId, "ui.file.open", { size: stat.size }); + const encoding = params.readAs === "utf8" ? "utf8" : "base64"; + if (stat.size <= INLINE_FILE_BYTES) { + const raw = await fs.readFile(filePath); + await context.assertActive(); + this.quotaManager?.chargeBytes?.(context.runtimeId, "ui", raw.byteLength); + return { + cancelled: false, + name: handle.name, + size: raw.byteLength, + handleId: handle.id, + streamed: false, + encoding, + data: encoding === "utf8" ? raw.toString("utf8") : raw.toString("base64"), + }; + } + return { + cancelled: false, + name: handle.name, + size: stat.size, + handleId: handle.id, + streamed: true, + encoding, + }; + } + + async saveFile(params, context) { + await context.assertActive(); + this.#assertFileDialogPermission(context); + if (this.closed || this.isLocked()) { + throw fail("unavailable", "Host file dialogs require an unlocked window"); + } + if (typeof this.dialog?.showSaveDialog !== "function") { + throw fail("unavailable", "Native save dialog is unavailable"); + } + const window = this.getWindow(); + const dialogOptions = { + title: params.title ?? "Save File", + ...(params.defaultName ? { defaultPath: params.defaultName } : {}), + ...(params.filters?.length ? { filters: params.filters } : {}), + }; + const picked = window && !window.isDestroyed?.() + ? await this.dialog.showSaveDialog(window, dialogOptions) + : await this.dialog.showSaveDialog(dialogOptions); + await context.assertActive(); + if (this.closed || this.isLocked()) { + throw fail("cancelled", "Host locked during save dialog"); + } + if (!picked || picked.canceled || typeof picked.filePath !== "string" || picked.filePath.length === 0) { + return { cancelled: true }; + } + const handle = this.#allocateFileHandle(context, picked.filePath); + if (params.deferredWrite === true || params.data === undefined) { + this.database?.recordSecurityAudit?.(context.pluginId, "ui.file.save", { deferred: true }); + return { cancelled: false, name: handle.name, size: 0, handleId: handle.id }; + } + const buf = Buffer.from(params.data, params.encoding === "base64" ? "base64" : "utf8"); + if (buf.byteLength > LIMITS.fileMaxBytes) { + await this.#disposeFileHandle(handle); + throw fail("resourceExhausted", "File payload exceeds the maximum size limit"); + } + this.quotaManager?.chargeBytes?.(context.runtimeId, "ui", buf.byteLength); + const tempPath = `${handle.filePath}.netcatty-tmp-${randomUUID()}`; + try { + await fs.writeFile(tempPath, buf); + await context.assertActive(); + await fs.rename(tempPath, handle.filePath); + } catch (error) { + await fs.unlink(tempPath).catch(() => {}); + throw error; + } + this.database?.recordSecurityAudit?.(context.pluginId, "ui.file.save", { size: buf.byteLength }); + return { cancelled: false, name: handle.name, size: buf.byteLength, handleId: handle.id }; + } + + async readFileHandle(params, context) { + await context.assertActive(); + this.#assertFileDialogPermission(context); + if (this.closed || this.isLocked()) throw fail("unavailable", "Host is locked"); + const handle = this.#getFileHandle(params.handleId, context); + const stat = await fs.stat(handle.filePath); + if (!stat.isFile()) throw fail("unavailable", "File handle target is no longer a regular file"); + if (stat.size > LIMITS.fileMaxBytes) throw fail("resourceExhausted", "File exceeds the maximum size limit"); + const offset = params.offset ?? 0; + const length = Math.min(params.length ?? INLINE_FILE_BYTES, 4 * 1024 * 1024); + const remaining = Math.max(0, stat.size - offset); + const toRead = Math.min(length, remaining); + const encoding = params.encoding === "utf8" ? "utf8" : "base64"; + if (toRead === 0) { + return { data: "", encoding, bytesRead: 0, totalSize: stat.size, eof: true }; + } + const fd = await fs.open(handle.filePath, "r"); + try { + const buffer = Buffer.allocUnsafe(toRead); + const { bytesRead } = await fd.read(buffer, 0, toRead, offset); + await context.assertActive(); + const slice = buffer.subarray(0, bytesRead); + this.quotaManager?.chargeBytes?.(context.runtimeId, "ui", bytesRead); + return { + data: encoding === "utf8" ? slice.toString("utf8") : slice.toString("base64"), + encoding, + bytesRead, + totalSize: stat.size, + eof: offset + bytesRead >= stat.size, + }; + } finally { + await fd.close().catch(() => {}); + } + } + + async writeFileHandle(params, context) { + await context.assertActive(); + this.#assertFileDialogPermission(context); + if (this.closed || this.isLocked()) throw fail("unavailable", "Host is locked"); + const handle = this.#getFileHandle(params.handleId, context); + const buf = Buffer.from(params.data, params.encoding === "base64" ? "base64" : "utf8"); + const mode = params.mode ?? "replace"; + const commit = params.commit !== false; + if (mode === "replace") { + if (handle.stagingPath) { + await fs.unlink(handle.stagingPath).catch(() => {}); + handle.stagingPath = null; + handle.stagingBytes = 0; + } + if (buf.byteLength > LIMITS.fileMaxBytes) { + throw fail("resourceExhausted", "File write exceeds the maximum size limit"); + } + handle.stagingPath = `${handle.filePath}.netcatty-tmp-${randomUUID()}`; + handle.stagingBytes = buf.byteLength; + this.quotaManager?.chargeBytes?.(context.runtimeId, "ui", buf.byteLength); + await fs.writeFile(handle.stagingPath, buf); + } else { + if (!handle.stagingPath) { + throw fail("failedPrecondition", "Append write requires an open replace transaction"); + } + if (handle.stagingBytes + buf.byteLength > LIMITS.fileMaxBytes) { + const temp = handle.stagingPath; + handle.stagingPath = null; + handle.stagingBytes = 0; + await fs.unlink(temp).catch(() => {}); + throw fail("resourceExhausted", "File write exceeds the maximum size limit"); + } + this.quotaManager?.chargeBytes?.(context.runtimeId, "ui", buf.byteLength); + await fs.appendFile(handle.stagingPath, buf); + handle.stagingBytes += buf.byteLength; + } + const totalSize = handle.stagingBytes; + if (commit) { + await context.assertActive(); + const temp = handle.stagingPath; + handle.stagingPath = null; + handle.stagingBytes = 0; + try { + await fs.rename(temp, handle.filePath); + } catch (error) { + await fs.unlink(temp).catch(() => {}); + throw error; + } + this.database?.recordSecurityAudit?.(context.pluginId, "ui.file.writeHandle", { size: totalSize }); + } + return { bytesWritten: buf.byteLength, totalSize, committed: commit }; + } + + async closeFileHandle(params, context) { + await context.assertActive(); + const handle = this.fileHandles.get(params.handleId); + if (handle && handle.pluginId === context.pluginId && handle.runtimeId === context.runtimeId + && handle.sourceOwner === context.sourceOwner) { + await this.#disposeFileHandle(handle); + } + return null; + } + admitRequest(params, context) { const sender = this.#admit(params, context); let guard = this.admissionGuards.get(context.runtimeId); @@ -240,10 +579,6 @@ class PluginHostInteractionService { this.admissions.delete(params); let sender; if (admission?.runtimeId === context.runtimeId) { - // Electron may resolve showMessageBox before restoring parent focus. - // Never focus it ourselves or defer an originally background request. - // Owner replacement, lock, hide, revoke and runtime stop invalidate this - // host-owned admission, including changes during the permission prompt. const deadline = Date.now() + this.focusRestoreMs; for (;;) { context.signal?.throwIfAborted(); @@ -281,16 +616,19 @@ class PluginHostInteractionService { const entry = { context, params }; this.#audit(entry, "completed"); if (params.kind === "clipboard.write") { this.clipboard.writeText(params.text); return { cancelled: false, value: true }; } - const text = assertTextBytes(this.clipboard.readText()); + const text = assertTextBytes(this.clipboard.readText(), LIMITS.clipboardBytes); this.quotaManager.chargeBytes(context.runtimeId, "clipboard", Buffer.byteLength(text)); await context.assertActive(); return { cancelled: false, value: text }; } const now = this.clock(); + const initialPhase = this.vaultService?.isRequest(params) + ? (this.vaultService.initialPhase?.(params, context) ?? "request") + : "request"; return new Promise((resolve, reject) => { const entry = { id: randomUUID(), context, params, sender, resolve, reject, terminalTarget, permissionMode, controller: new AbortController(), - expiresAt: now + this.timeoutMs, phase: "request", actionToken: null, terminalWatch: null, + expiresAt: now + this.timeoutMs, phase: initialPhase, actionToken: null, terminalWatch: null, }; entry.onAbort = () => this.#finish(entry, null, fail("cancelled", "Host interaction was cancelled")); entry.timer = setTimeout(() => this.#finish(entry, null, fail("deadlineExceeded", "Host interaction expired")), this.timeoutMs); @@ -301,7 +639,7 @@ class PluginHostInteractionService { if (context.signal?.aborted) { entry.onAbort(); return; } try { if (params.kind === "clipboard.read") { - entry.previewText = assertTextBytes(this.clipboard.readText()); + entry.previewText = assertTextBytes(this.clipboard.readText(), LIMITS.clipboardBytes); this.quotaManager.chargeBytes(context.runtimeId, "clipboard", Buffer.byteLength(entry.previewText)); entry.phase = "preview"; } @@ -331,6 +669,15 @@ class PluginHostInteractionService { this.#audit(entry, "cancelled"); return this.#finish(entry, { cancelled: true }); } + if (entry.params.kind === "network.stream.confirm" || entry.params.kind === "network.stream.tlsConfirm") { + if (response.action !== "submit") throw fail("invalidArgument", "Stream confirmation requires a submit action"); + this.#audit(entry, entry.params.kind === "network.stream.tlsConfirm" ? "tls-cert-confirmed" : "stream-confirmed"); + return this.#finish(entry, { + cancelled: false, + approved: true, + remember: response.remember === true, + }); + } if (this.vaultService?.isRequest(entry.params)) { const outcome = await this.vaultService.respond(entry, response, nativeOptions); await entry.context.assertActive(); @@ -352,7 +699,7 @@ class PluginHostInteractionService { } if (entry.params.kind === "terminal.selection.read" && entry.phase === "request") { if (response.action !== "preview") throw fail("invalidArgument", "Terminal sharing requires a preview action"); - const text = assertTextBytes(response.value); + const text = assertTextBytes(response.value, LIMITS.textBytes); if (!text.length) throw fail("failedPrecondition", "Select terminal text before requesting a share"); this.#audit(entry, "preview-confirmed"); this.quotaManager.chargeBytes(entry.context.runtimeId, "terminal", Buffer.byteLength(text)); @@ -369,7 +716,7 @@ class PluginHostInteractionService { let rawText; try { rawText = this.clipboard.readText(); } catch { throw fail("unavailable", "Host clipboard text is unavailable"); } - const text = assertTextBytes(rawText); + const text = assertTextBytes(rawText, LIMITS.clipboardBytes); this.quotaManager.chargeBytes(entry.context.runtimeId, "clipboard", Buffer.byteLength(text)); entry.previewText = text; entry.phase = "preview"; @@ -381,7 +728,7 @@ class PluginHostInteractionService { let value; if (entry.params.kind === "input") { if (!validateSingleLineInput(response.value)) throw fail("invalidArgument", "Host input must be a single line"); - value = assertTextBytes(response.value); + value = assertTextBytes(response.value, LIMITS.textBytes); } else if (entry.params.kind === "quickPick") { if (!entry.params.items.some((item) => item.id === response.value)) throw fail("invalidArgument", "Host interaction choice is invalid"); @@ -423,6 +770,9 @@ class PluginHostInteractionService { this.terminalSelection.releasePlugin(pluginId); this.admissionRevision++; this.vaultService?.releasePlugin(pluginId); + for (const handle of [...this.fileHandles.values()]) { + if (handle.pluginId === pluginId) void this.#disposeFileHandle(handle); + } for (const entry of [...this.pending.values()]) { if (entry.context.pluginId === pluginId) this.#finish(entry, null, fail("cancelled", "Plugin access was revoked")); } @@ -432,6 +782,9 @@ class PluginHostInteractionService { this.cancelRuntimeRequests(runtimeId, "Plugin runtime stopped"); this.rates.delete(runtimeId); this.vaultService?.releaseRuntime(runtimeId); + for (const handle of [...this.fileHandles.values()]) { + if (handle.runtimeId === runtimeId) void this.#disposeFileHandle(handle); + } } cancelRuntimeRequests(runtimeId, reason = "Host command finished") { const guard = this.admissionGuards.get(runtimeId); @@ -454,6 +807,8 @@ class PluginHostInteractionService { this.closed = true; if (this.owner) this.releaseWindow(this.owner); this.cancelAll(); this.rates.clear(); this.admissionGuards.clear(); + for (const handle of [...this.fileHandles.values()]) void this.#disposeFileHandle(handle); + this.fileHandles.clear(); this.revocation.dispose(); this.unsubscribeLock?.(); this.terminalInvalidation.dispose(); this.terminalSelection.shutdown(); this.key.fill(0); diff --git a/electron/plugins/hostInteractionService.test.cjs b/electron/plugins/hostInteractionService.test.cjs index 69b2ee79e..21735424f 100644 --- a/electron/plugins/hostInteractionService.test.cjs +++ b/electron/plugins/hostInteractionService.test.cjs @@ -2,7 +2,7 @@ const assert = require("node:assert/strict"); const { EventEmitter } = require("node:events"); const test = require("node:test"); -const { PluginHostInteractionService, assertInteractionRequest, interactionAuthorization, PROMPT_CHANNEL } = require("./hostInteractionService.cjs"); +const { PluginHostInteractionService, LIMITS, assertInteractionRequest, interactionAuthorization, PROMPT_CHANNEL } = require("./hostInteractionService.cjs"); function fixture(t, options = {}) { const messages = [], audit = [], writes = [], charges = []; @@ -210,7 +210,8 @@ test("quota, deadline, locked host, unknown fields, duplicate choices and text b await assert.rejects(f.service.request(assertInteractionRequest({ kind: "input", title: "Locked" }), f.context), /focused unlocked/); assert.throws(() => assertInteractionRequest({ kind: "clipboard.read", title: "Forged", userGesture: true }), /invalid/); assert.throws(() => assertInteractionRequest({ kind: "quickPick", title: "Duplicate", items: [{ id: "same", label: "A" }, { id: "same", label: "B" }] }), /unique/); - assert.throws(() => assertInteractionRequest({ kind: "clipboard.write", title: "Too long", text: "文".repeat(1500) }), /limit/); + assert.throws(() => assertInteractionRequest({ kind: "input", title: "Too long", initialValue: "文".repeat(1500) }), /limit/); + assert.throws(() => assertInteractionRequest({ kind: "clipboard.write", title: "Too long", text: "a".repeat(LIMITS.clipboardBytes + 1) }), /invalid|limit/); assert.equal(interactionAuthorization({ kind: "clipboard.read" }).permission, "clipboard.read"); assert.equal(interactionAuthorization({ kind: "clipboard.write" }).permission, "clipboard.write"); assert.equal(interactionAuthorization({ kind: "input" }).permission, "ui.interact"); @@ -234,7 +235,7 @@ test("manifest permission checks and interaction quota run before any host promp await assert.rejects(denied({ kind: "input", title: "Undeclared" }, { signal: f.context.signal }), /declare/); assert.equal(decisions, 0); assert.equal(f.messages.length, 0); const route = registry.createRoutes({ ...base, manifest: { ...base.manifest, permissions: { optional: ["ui.interact"] } } }).requestHandlers["ui.interact"]; - for (let count = 1; count < 10; count++) { + for (let count = 1; count < LIMITS.requestsPerMinute; count++) { await assert.rejects(route({ kind: "input", title: "Denied" }, { signal: f.context.signal }), /disabled/); } const before = decisions; @@ -408,3 +409,104 @@ test("terminalSelection timer stays idle without terminal dialogs/handles and st service.terminalSelection.clearHandles(); assert.equal(service.terminalSelection.timer, null, "timer disarms once handle is cleared"); }); + +test("clipboard write supports up to 4 MiB and native file dialogs support open, save, chunked handles, and isolation", async (t) => { + const fsPromises = require("node:fs/promises"); + const os = require("node:os"); + const path = require("node:path"); + const dir = await fsPromises.mkdtemp(path.join(os.tmpdir(), "netcatty-file-dialog-test-")); + t.after(() => fsPromises.rm(dir, { recursive: true, force: true })); + const samplePath = path.join(dir, "demo.sqlite"); + const savePath = path.join(dir, "export.bin"); + const initialBytes = Buffer.from("SQLite format 3\0demo-payload"); + await fsPromises.writeFile(samplePath, initialBytes); + + let nextOpen = { canceled: false, filePaths: [samplePath] }; + let nextSave = { canceled: false, filePath: savePath }; + const f = fixture(t, { + dialog: { + showOpenDialog: async () => nextOpen, + showSaveDialog: async () => nextSave, + }, + }); + + // 1) Large clipboard write (1 MiB) succeeds within the 4 MiB limit. + const largeText = "SELECT 1;\n".repeat(100_000); + const clipReq = await f.begin({ kind: "clipboard.write", title: "Copy SQL", text: largeText }); + await f.respond(clipReq.prompt, "submit"); + assert.deepEqual(await clipReq.promise, { cancelled: false, value: true }); + assert.equal(f.writes.at(-1).length, largeText.length); + + // 2) ui.openFile returns basename, data, and opaque handleId without exposing full path. + const opened = await f.service.openFile({ title: "Open DB", readAs: "bytes" }, f.context); + assert.equal(opened.cancelled, false); + assert.equal(opened.name, "demo.sqlite"); + assert.equal(opened.streamed, false); + assert.equal(JSON.stringify(opened).includes(dir), false); + assert.deepEqual(Buffer.from(opened.data, "base64"), initialBytes); + + // 3) Re-save back to the exact picked handle without re-prompting (chunked atomic write). + const part1 = Buffer.from("SQLite format 3\0updated-part-1-"); + const part2 = Buffer.from("updated-part-2"); + await f.service.writeFileHandle({ handleId: opened.handleId, data: part1.toString("base64"), encoding: "base64", mode: "replace", commit: false }, f.context); + // Before commit, the original file is untouched! + assert.deepEqual(await fsPromises.readFile(samplePath), initialBytes); + const commitRes = await f.service.writeFileHandle({ handleId: opened.handleId, data: part2.toString("base64"), encoding: "base64", mode: "append", commit: true }, f.context); + assert.equal(commitRes.committed, true); + assert.deepEqual(await fsPromises.readFile(samplePath), Buffer.concat([part1, part2])); + + // 4) Another runtime cannot access this handle. + await assert.rejects( + f.service.readFileHandle({ handleId: opened.handleId }, { ...f.context, runtimeId: "other-runtime" }), + /invalid or closed/, + ); + + // 5) ui.saveFile writes atomically and returns handleId. + const saved = await f.service.saveFile({ + title: "Save Export", + defaultName: "export.bin", + data: Buffer.from("exported-csv").toString("base64"), + encoding: "base64", + }, f.context); + assert.equal(saved.cancelled, false); + assert.equal(saved.name, "export.bin"); + assert.equal(await fsPromises.readFile(savePath, "utf8"), "exported-csv"); + + // 6) Closing handle prevents further reads/writes. + await f.service.closeFileHandle({ handleId: opened.handleId }, f.context); + await assert.rejects(f.service.readFileHandle({ handleId: opened.handleId }, f.context), /invalid or closed/); + + // 7) Cancelled file dialog returns { cancelled: true }. + nextOpen = { canceled: true, filePaths: [] }; + assert.deepEqual(await f.service.openFile({}, f.context), { cancelled: true }); +}); + +test("stream endpoint and TLS certificate confirmation prompts return approval and remember choice", async (t) => { + const f = fixture(t); + const streamPromise = f.service.request({ + kind: "network.stream.confirm", + endpoint: "tcp://127.0.0.1:5432", + host: "127.0.0.1", + port: 5432, + transport: "tcp", + isLocal: true, + }, f.context); + await new Promise((resolve) => setImmediate(resolve)); + const streamPrompt = f.messages.filter((m) => !m.closed).at(-1); + await f.service.respond(f.sender, { requestId: streamPrompt.requestId, actionToken: streamPrompt.actionToken, action: "submit", remember: true }); + assert.deepEqual(await streamPromise, { cancelled: false, approved: true, remember: true }); + + const tlsPromise = f.service.request({ + kind: "network.stream.tlsConfirm", + endpoint: "tcp://127.0.0.1:5432", + fingerprint256: "AA:BB:CC", + subject: "CN=postgres", + issuer: "CN=postgres", + validTo: "2030-01-01", + reason: "DEPTH_ZERO_SELF_SIGNED_CERT", + }, f.context); + await new Promise((resolve) => setImmediate(resolve)); + const tlsPrompt = f.messages.filter((m) => !m.closed).at(-1); + await f.service.respond(f.sender, { requestId: tlsPrompt.requestId, actionToken: tlsPrompt.actionToken, action: "submit", remember: false }); + assert.deepEqual(await tlsPromise, { cancelled: false, approved: true, remember: false }); +}); diff --git a/electron/plugins/hostRpcRegistry.cjs b/electron/plugins/hostRpcRegistry.cjs index d8e967301..ea7b41221 100644 --- a/electron/plugins/hostRpcRegistry.cjs +++ b/electron/plugins/hostRpcRegistry.cjs @@ -336,15 +336,31 @@ function createDefaultPluginHostRpcRegistry(options) { validateParams: (params) => options.assertStorageParams(params), }); registry.registerRequest("storage.keys", async (params, context) => { - return { keys: options.database.listKeys(context.pluginId) }; + const keys = options.database.listKeys(context.pluginId); + const prefix = params?.prefix; + return { + keys: typeof prefix === "string" && prefix.length > 0 + ? keys.filter((key) => key.startsWith(prefix)) + : keys, + }; }, { metadata: { capability: "storage", mutating: false, permission: "storage" }, authorization: { permission: "storage", resources: ["*"], reason: "List plugin storage keys" }, validateParams: (params) => { - if (params && (typeof params !== "object" || Array.isArray(params) || Object.keys(params).length > 0)) { - throw new TypeError("storage.keys does not accept parameters"); + if (params === undefined || params === null) return {}; + if (typeof params !== "object" || Array.isArray(params)) { + throw new TypeError("storage.keys parameters must be an object"); } - return params; + const keys = Object.keys(params); + if (keys.some((key) => key !== "prefix")) { + throw new TypeError("storage.keys only accepts an optional prefix parameter"); + } + if (params.prefix !== undefined) { + if (typeof params.prefix !== "string" || params.prefix.length > 256 || params.prefix.includes("\0")) { + throw new TypeError("storage.keys prefix is invalid"); + } + } + return params.prefix === undefined ? {} : { prefix: params.prefix }; }, }); registry.registerNotification("log.write", async (params, context) => { diff --git a/electron/plugins/hostRpcRegistry.test.cjs b/electron/plugins/hostRpcRegistry.test.cjs index 4e1b47f7f..185d64ca3 100644 --- a/electron/plugins/hostRpcRegistry.test.cjs +++ b/electron/plugins/hostRpcRegistry.test.cjs @@ -308,3 +308,30 @@ test("reserved lifecycle and transport methods cannot be claimed as host capabil } assert.equal(assertHostMethod("commands.execute"), "commands.execute"); }); + +test("storage.keys supports optional prefix filtering and rejects unknown parameters", async () => { + const { createDefaultPluginHostRpcRegistry } = require("./hostRpcRegistry.cjs"); + const registry = createDefaultPluginHostRpcRegistry({ + assertStorageParams: (params) => params, + database: { + listKeys: () => ["conn:1", "conn:2", "history:1", "draft:tab1"], + getValue: () => undefined, + setValue() {}, + deleteValue() {}, + }, + }); + const routes = registry.createRoutes(identity()); + const transport = { signal: AbortSignal.timeout(100) }; + assert.deepEqual( + await routes.requestHandlers["storage.keys"]({}, transport), + { keys: ["conn:1", "conn:2", "history:1", "draft:tab1"] }, + ); + assert.deepEqual( + await routes.requestHandlers["storage.keys"]({ prefix: "conn:" }, transport), + { keys: ["conn:1", "conn:2"] }, + ); + await assert.rejects( + routes.requestHandlers["storage.keys"]({ unknown: true }, transport), + /only accepts an optional prefix/, + ); +}); diff --git a/electron/plugins/hostService.cjs b/electron/plugins/hostService.cjs index 0a904e81a..96a7d29f7 100644 --- a/electron/plugins/hostService.cjs +++ b/electron/plugins/hostService.cjs @@ -222,6 +222,7 @@ function createPluginHostService(options) { interactionService = new PluginHostInteractionService({ database, permissionEngine, quotaManager, clipboard: options.electron.clipboard, + dialog: options.electron.dialog, getWindow: options.getInteractionWindow, isLocked: options.isAppLocked, subscribeLock: options.subscribeAppLock, @@ -327,7 +328,7 @@ function createPluginHostService(options) { }, utilityModuleMappings: options.utilityModuleMappings ?? createUtilityModuleMappings(moduleResources), }); - byteStreamService = new PluginByteStreamService({ database, permissionEngine, quotaManager, runtimeSupervisor }); + byteStreamService = new PluginByteStreamService({ database, permissionEngine, quotaManager, runtimeSupervisor, interactionService }); byteStreamService.register(rpcRegistry); aiHostAdapter = options.pluginAIHostAdapter ?? new PluginAITrustedHostAdapter({ getWindow: options.getInteractionWindow ?? (() => null), diff --git a/electron/plugins/hostVaultService.cjs b/electron/plugins/hostVaultService.cjs index 15cb3f4d8..2c3ad3a26 100644 --- a/electron/plugins/hostVaultService.cjs +++ b/electron/plugins/hostVaultService.cjs @@ -1,6 +1,6 @@ "use strict"; -const { createHmac, randomBytes } = require("node:crypto"); +const { createHash, createHmac, randomBytes, timingSafeEqual } = require("node:crypto"); const { canonicalizeStreamEndpoint } = require("./byteStreamEndpoint.cjs"); const { createDefinitionValidator } = require("./contractValidator.cjs"); const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs"); @@ -8,25 +8,43 @@ const fail = (code, message) => new PluginRpcError(RPC_ERRORS[code], message); const METHODS = ["vault.selectHosts", "vault.requestHostDraft", "vault.requestConnect", "network.stream.connectViaHost"]; const MAX_SELECTED = 50; const MAX_REFERENCES = 500; +const MAX_DURABLE_BINDINGS_PER_PLUGIN = 128; const TARGET_LIFETIME_MS = 5 * 60_000; +function hashToken(token) { + return createHash("sha256").update(token).digest("hex"); +} + +function timingSafeHexEqual(a, b) { + if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false; + return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8")); +} + /** Typed host selection only. Selection references identify a reviewed target; * the interaction service owns separate operation-specific commit authority. */ class PluginHostVaultService { - constructor({ sourceBinding, interactionService, openStream, clock = Date.now }) { + constructor({ sourceBinding, interactionService, openStream, database, clock = Date.now }) { this.sourceBinding = sourceBinding; this.openStream = openStream; this.interactionService = interactionService; + this.database = database ?? interactionService?.database ?? null; this.clock = clock; this.key = randomBytes(32); this.targets = new Map(); + this.memoryDurableBindings = new Map(); this.streams = new Set(); this.admissions = new WeakMap(); this.validators = Object.fromEntries([ "VaultSelectHostsParams", "VaultHostDraftParams", "VaultHostConnectParams", - "HostByteStreamConnectRequest", "VaultHostSelectedResources", "VaultHostCreateFields", "VaultHostEditFields", + "HostByteStreamConnectRequest", "VaultHostBindingRevokeParams", + "VaultHostSelectedResources", "VaultHostCreateFields", "VaultHostEditFields", ].map((name) => [name, createDefinitionValidator(name)])); interactionService.vaultService = this; + this.revocation = interactionService.permissionEngine?.onDidRevoke?.((event) => { + if (event.permission === undefined || event.permission === "network.hostStream") { + this.clearDurableBindings(event.pluginId); + } + }) ?? { dispose() {} }; } isRequest(params) { return METHODS.includes(params?.kind); } @@ -37,6 +55,90 @@ class PluginHostVaultService { return structuredClone(value); } + #ownerKey(pluginId) { + return typeof this.database?.privateOwner === "function" + ? this.database.privateOwner(pluginId) + : pluginId; + } + + #bindingsPrefKey(pluginId) { + return `permission:${this.#ownerKey(pluginId)}:vault-host-bindings`; + } + + #readBindings(pluginId) { + const key = this.#bindingsPrefKey(pluginId); + if (this.database?.db) { + try { + const row = this.database.db.prepare("SELECT value_json FROM plugin_host_preferences WHERE key = ?").get(key); + if (row?.value_json) { + const parsed = JSON.parse(row.value_json); + if (Array.isArray(parsed)) return parsed; + } + } catch { /* fall through */ } + } + return this.memoryDurableBindings.get(key) ?? []; + } + + #writeBindings(pluginId, bindings) { + const key = this.#bindingsPrefKey(pluginId); + const trimmed = bindings.slice(-MAX_DURABLE_BINDINGS_PER_PLUGIN); + this.memoryDurableBindings.set(key, trimmed); + if (this.database?.db) { + try { + if (trimmed.length === 0) { + this.database.db.prepare("DELETE FROM plugin_host_preferences WHERE key = ?").run(key); + } else { + this.database.db.prepare( + "INSERT INTO plugin_host_preferences(key,value_json,updated_at) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET value_json=excluded.value_json,updated_at=excluded.updated_at", + ).run(key, JSON.stringify(trimmed), this.clock()); + } + } catch { /* ignore when mock db */ } + } + } + + #issueDurableBinding(pluginId, hostId, endpoint) { + const token = `hb_${randomBytes(24).toString("base64url")}`; + const tokenHash = hashToken(token); + const current = this.#readBindings(pluginId); + // Replace any existing binding for the same (hostId, endpoint) so list stays tidy. + const next = current.filter((item) => !(item.hostId === hostId && item.endpoint === endpoint)); + next.push({ tokenHash, hostId, endpoint, createdAt: this.clock() }); + this.#writeBindings(pluginId, next); + return token; + } + + #resolveDurableBinding(pluginId, token, endpoint) { + if (typeof token !== "string" || token.length < 16) { + throw fail("permissionDenied", "SSH tunnel binding token is invalid"); + } + const candidateHash = hashToken(token); + const bindings = this.#readBindings(pluginId); + const match = bindings.find((item) => timingSafeHexEqual(item.tokenHash, candidateHash)); + if (!match || match.endpoint !== endpoint) { + throw fail("permissionDenied", "SSH tunnel binding is invalid, expired, or was revoked"); + } + return match; + } + + revokeDurableBinding(pluginId, token) { + const candidateHash = hashToken(token); + const current = this.#readBindings(pluginId); + const next = current.filter((item) => !timingSafeHexEqual(item.tokenHash, candidateHash)); + if (next.length === current.length) return false; + this.#writeBindings(pluginId, next); + return true; + } + + clearDurableBindings(pluginId) { + const key = this.#bindingsPrefKey(pluginId); + this.memoryDurableBindings.delete(key); + if (this.database?.db) { + try { + this.database.db.prepare("DELETE FROM plugin_host_preferences WHERE key = ?").run(key); + } catch { /* ignore */ } + } + } + registerRpcCapabilities(registry) { const definitions = ["VaultSelectHostsParams", "VaultHostDraftParams", "VaultHostConnectParams", "HostByteStreamConnectRequest"]; for (const [index, method] of METHODS.entries()) { @@ -56,6 +158,7 @@ class PluginHostVaultService { } const binding = await this.sourceBinding.resolve(context); if (params.target) this.#resolveTarget(params.target, params.expectedRevision, binding); + if (params.hostBindingToken) this.#resolveDurableBinding(context.pluginId, params.hostBindingToken, params.endpoint); this.interactionService.admitRequest(params, context); this.admissions.set(params, binding); return { @@ -67,6 +170,29 @@ class PluginHostVaultService { }, }); } + registry.registerRequest("vault.revokeHostBinding", async (params, context) => { + await context.assertActive(); + await this.sourceBinding.resolve(context); + const revoked = this.revokeDurableBinding(context.pluginId, params.hostBindingToken); + return { revoked }; + }, { + metadata: { capability: "vault", mutating: true }, + validateParams: (params) => this.#validate("VaultHostBindingRevokeParams", params), + authorization: { + permission: "network.hostStream", + resources: ["*"], + reason: "Revoke a saved SSH tunnel binding", + operationId: "vault.revokeHostBinding", + deferDecision: true, + }, + }); + } + + initialPhase(params) { + if (params.kind === "network.stream.connectViaHost" && params.hostBindingToken) { + return "commit"; + } + return "request"; } async request(params, originalContext) { @@ -81,6 +207,7 @@ class PluginHostVaultService { await originalContext.assertActive(); if (await this.sourceBinding.resolve(originalContext) !== binding) throw fail("permissionDenied", "Host action source changed"); if (params.target) this.#resolveTarget(params.target, params.expectedRevision, binding); + if (params.hostBindingToken) this.#resolveDurableBinding(originalContext.pluginId, params.hostBindingToken, params.endpoint); }; await assertActive(); return this.interactionService.request(params, Object.freeze({ ...originalContext, assertActive, assertStreamActive, vaultBinding: binding })); @@ -114,6 +241,14 @@ class PluginHostVaultService { } describePrompt(entry) { + if (entry.params.kind === "network.stream.connectViaHost" && entry.params.hostBindingToken) { + const saved = this.#resolveDurableBinding(entry.context.pluginId, entry.params.hostBindingToken, entry.params.endpoint); + return { + vaultTarget: { resourceId: saved.hostId, revision: "durable" }, + durableHostId: saved.hostId, + autoCommit: true, + }; + } if (!entry.params.target) return {}; const target = this.#resolveTarget(entry.params.target, entry.params.expectedRevision, entry.context.vaultBinding); return { vaultTarget: { resourceId: target.resourceId, revision: target.revision } }; @@ -143,18 +278,32 @@ class PluginHostVaultService { const draft = this.#validate(entry.params.target ? "VaultHostEditFields" : "VaultHostCreateFields", response.draft); return { phase: "commit", reviewedDraft: draft }; } - if (entry.params.kind === "network.stream.connectViaHost") return { phase: "commit" }; + if (entry.params.kind === "network.stream.connectViaHost") { + entry.rememberBinding = response.remember === true; + return { phase: "commit" }; + } if (typeof response.scriptsRun !== "boolean") throw fail("invalidArgument", "Connection script disclosure is required"); return { phase: "commit" }; } if (entry.params.kind === "network.stream.connectViaHost" && entry.phase === "commit" && response.action === "commit") { - const target = this.#resolveTarget(entry.params.target, entry.params.expectedRevision, entry.context.vaultBinding); - if (!this.openStream || !nativeOptions || nativeOptions.hostId !== target.resourceId) throw fail("permissionDenied", "Reviewed server connection is unavailable"); + const isDurableReconnect = Boolean(entry.params.hostBindingToken); + const expectedHostId = isDurableReconnect + ? this.#resolveDurableBinding(entry.context.pluginId, entry.params.hostBindingToken, entry.params.endpoint).hostId + : this.#resolveTarget(entry.params.target, entry.params.expectedRevision, entry.context.vaultBinding).resourceId; + if (!this.openStream || !nativeOptions || nativeOptions.hostId !== expectedHostId) { + throw fail("permissionDenied", "Reviewed server connection is unavailable"); + } const assertActive = async () => { entry.controller.signal.throwIfAborted(); if (entry.streamDelivered) await entry.context.assertStreamActive(); else await entry.context.assertActive(); - if (!entry.streamDelivered) this.#resolveTarget(entry.params.target, entry.params.expectedRevision, entry.context.vaultBinding); + if (!entry.streamDelivered) { + if (isDurableReconnect) { + this.#resolveDurableBinding(entry.context.pluginId, entry.params.hostBindingToken, entry.params.endpoint); + } else { + this.#resolveTarget(entry.params.target, entry.params.expectedRevision, entry.context.vaultBinding); + } + } }; const lease = { controller: entry.controller, runtimeId: entry.context.runtimeId, pluginId: entry.context.pluginId }; this.streams.add(lease); @@ -162,7 +311,15 @@ class PluginHostVaultService { const handle = await this.openStream(entry.params.endpoint, { ...entry.context, signal: entry.controller.signal, assertActive }, entry.sender, nativeOptions); handle.onClose?.(() => { this.streams.delete(lease); }); entry.disposeResult = () => { this.streams.delete(lease); handle.close(); }; - return { result: handle.descriptor }; + let hostBindingToken = isDurableReconnect ? entry.params.hostBindingToken : undefined; + if (!isDurableReconnect && entry.rememberBinding === true) { + hostBindingToken = this.#issueDurableBinding(entry.context.pluginId, expectedHostId, entry.params.endpoint); + } + return { + result: hostBindingToken + ? { ...handle.descriptor, hostBindingToken } + : handle.descriptor, + }; } if (entry.phase === "commit" && response.action === "commit") return { phase: "executing" }; if (entry.phase === "executing" && response.action === "complete") { @@ -185,7 +342,7 @@ class PluginHostVaultService { // revoked old runtime must never rebind itself to a replacement source. } clearSelections() { this.targets.clear(); for (const lease of this.streams) lease.controller.abort(); } - shutdown() { this.clearSelections(); this.sourceBinding.shutdown(); this.key.fill(0); } + shutdown() { this.clearSelections(); this.revocation.dispose(); this.sourceBinding.shutdown(); this.key.fill(0); } } module.exports = { PluginHostVaultService, METHODS, MAX_SELECTED, TARGET_LIFETIME_MS }; diff --git a/electron/plugins/permissionResources.cjs b/electron/plugins/permissionResources.cjs index 5faa49b8a..26129a3e7 100644 --- a/electron/plugins/permissionResources.cjs +++ b/electron/plugins/permissionResources.cjs @@ -115,7 +115,7 @@ function normalizePermissionDeclarations(manifest) { : [...new Set((value.resources ?? []).map((resource) => ( canonicalizePermissionResource(permission, resource) )))].sort(); - if ((required && RESOURCE_SCOPED_PERMISSIONS.has(permission)) || permission === "network.stream") { + if (required && RESOURCE_SCOPED_PERMISSIONS.has(permission)) { if (resources.length === 0) { throw new TypeError(`Required permission ${permission} must declare resources`); } diff --git a/electron/plugins/quotaManager.cjs b/electron/plugins/quotaManager.cjs index 113f71d92..46c9d174d 100644 --- a/electron/plugins/quotaManager.cjs +++ b/electron/plugins/quotaManager.cjs @@ -3,13 +3,14 @@ const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs"); const DEFAULT_QUOTAS = Object.freeze({ - messageBurst: 512, - messagesPerSecond: 256, - concurrentCapabilities: 32, - capabilityBurst: 120, - capabilitiesPerMinute: 600, + messageBurst: 1024, + messagesPerSecond: 512, + concurrentCapabilities: 64, + capabilityBurst: 240, + capabilitiesPerMinute: 2400, logWritesPerMinute: 240, - bytesPerMinute: 32 * 1024 * 1024, + bytesPerMinute: 128 * 1024 * 1024, + streamBytesPerMinute: 512 * 1024 * 1024, memoryBytes: 256 * 1024 * 1024, cpuPercent: 80, sustainedCpuSamples: 3, @@ -44,7 +45,12 @@ class TokenBucket { class PluginQuotaManager { constructor(options = {}) { this.clock = options.clock ?? (() => Date.now()); - this.quotas = Object.freeze({ ...DEFAULT_QUOTAS, ...(options.quotas ?? {}) }); + this.quotas = Object.freeze({ + ...DEFAULT_QUOTAS, + ...(options.quotas ?? {}), + streamBytesPerMinute: options.quotas?.streamBytesPerMinute + ?? (options.quotas?.bytesPerMinute ?? DEFAULT_QUOTAS.streamBytesPerMinute), + }); this.getProcessMetrics = options.getProcessMetrics ?? null; this.onViolation = options.onViolation ?? (() => {}); this.setInterval = options.setInterval ?? setInterval; @@ -124,7 +130,10 @@ class PluginQuotaManager { this.byteWindows.set(key, window); } window.bytes += byteLength; - if (window.bytes > this.quotas.bytesPerMinute) { + const limit = category === "network.stream" + ? this.quotas.streamBytesPerMinute + : this.quotas.bytesPerMinute; + if (window.bytes > limit) { throw quotaError(`Plugin ${category} byte quota exceeded`); } } diff --git a/electron/plugins/runtime/byteStreamClient.mjs b/electron/plugins/runtime/byteStreamClient.mjs index 66ed908a5..1e0ea3774 100644 --- a/electron/plugins/runtime/byteStreamClient.mjs +++ b/electron/plugins/runtime/byteStreamClient.mjs @@ -27,6 +27,12 @@ export async function connectByteStream({ client, streams, subscriptions, enable await close().catch(() => {}); throw new PluginError("cancelled", "Byte stream connection cancelled"); }; + const upgradeTls = (options = {}) => client.request("network.stream.upgradeTls", { + handleId: descriptor.handleId, + ...(options?.servername === undefined ? {} : { servername: options.servername }), + ...(options?.allowSelfSigned === undefined ? {} : { allowSelfSigned: options.allowSelfSigned }), + ...(options?.caPem === undefined ? {} : { caPem: options.caPem }), + }, { cancellationToken, deadlineMs: 60_000 }); try { await checkCancelled(); readablePromise = streams.acceptReadable(descriptor.outputStreamId); @@ -37,6 +43,7 @@ export async function connectByteStream({ client, streams, subscriptions, enable await checkCancelled(); connection = Object.freeze({ endpoint: descriptor.endpoint, + ...(descriptor.hostBindingToken ? { hostBindingToken: descriptor.hostBindingToken } : {}), readable: Object.freeze({ id: readable.id, read: () => readable.read(), cancel, dispose: cancel, }), @@ -44,6 +51,7 @@ export async function connectByteStream({ client, streams, subscriptions, enable id: writable.id, write: (bytes) => writable.write(bytes), end: () => writable.end(), fail: cancel, cancel, dispose: cancel, }), + upgradeTls, close, dispose: cancel, }); cancellation = cancellationToken?.onCancellationRequested(cancel); diff --git a/electron/plugins/runtime/runtimePeer.mjs b/electron/plugins/runtime/runtimePeer.mjs index 36a113f09..938e558e3 100644 --- a/electron/plugins/runtime/runtimePeer.mjs +++ b/electron/plugins/runtime/runtimePeer.mjs @@ -347,6 +347,50 @@ function createEmitter() { }; } +const FILE_CHUNK_BYTES = 2 * 1024 * 1024; +const FILE_DIALOG_DEADLINE_MS = 300_000; + +function bytesToBase64(bytes) { + if (typeof Buffer === "function") return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64"); + let binary = ""; + const step = 0x8000; + for (let offset = 0; offset < bytes.byteLength; offset += step) { + binary += String.fromCharCode(...bytes.subarray(offset, offset + step)); + } + return btoa(binary); +} + +function base64ToBytes(encoded) { + if (typeof Buffer === "function") { + const buf = Buffer.from(encoded, "base64"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + const binary = atob(encoded); + const out = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i); + return out; +} + +function concatUint8Arrays(chunks, totalBytes) { + const out = new Uint8Array(totalBytes); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.byteLength; + } + return out; +} + +function toBytes(data, encoding) { + if (data instanceof Uint8Array) return data; + if (data instanceof ArrayBuffer) return new Uint8Array(data); + if (typeof data === "string") { + if (encoding === "base64") return base64ToBytes(data); + return new TextEncoder().encode(data); + } + throw new PluginError("invalid_argument", "File data must be a Uint8Array, ArrayBuffer, or string"); +} + function createPluginContext(config, client, runtimeApi) { const subscriptions = new DisposableStore(); const storage = { @@ -356,11 +400,18 @@ function createPluginContext(config, client, runtimeApi) { .then(() => undefined), delete: (key) => client.request("storage.delete", { key: assertStorageKey(key) }) .then(() => undefined), - keys: () => client.request("storage.keys", {}).then((result) => result?.keys ?? []), + keys: (options) => client.request( + "storage.keys", + options?.prefix !== undefined ? { prefix: options.prefix } : {}, + ).then((result) => result?.keys ?? []), }; + const readOwnSecret = (key) => client.request("secrets.getPlaintext", { key: assertStorageKey(key) }) + .then((result) => result?.found ? result.value : undefined); const secrets = { get: (key) => client.request("secrets.get", { key: assertStorageKey(key) }) .then((result) => result?.found ? result.secret : undefined), + getPlaintext: readOwnSecret, + readOwn: readOwnSecret, set: (key, value) => client.request("secrets.set", { key: assertStorageKey(key), value, @@ -378,13 +429,113 @@ function createPluginContext(config, client, runtimeApi) { }; const interact = (params) => client.request("ui.interact", params, { deadlineMs: PLUGIN_HOST_INTERACTION_LIMITS.timeoutMs }) .then((result) => result.cancelled ? undefined : result.value); + const readFileHandleAll = async (handleId, options = {}) => { + const chunks = []; + let offset = 0; + let total = 0; + while (true) { + const page = await client.request("ui.readFileHandle", { + handleId, + offset, + length: FILE_CHUNK_BYTES, + encoding: "base64", + }, { deadlineMs: 60_000 }); + const bytes = page.bytesRead > 0 ? base64ToBytes(page.data) : new Uint8Array(0); + if (bytes.byteLength > 0) { + chunks.push(bytes); + offset += bytes.byteLength; + total += bytes.byteLength; + } + if (page.eof || page.bytesRead === 0) break; + } + const merged = concatUint8Arrays(chunks, total); + return options?.readAs === "utf8" ? new TextDecoder().decode(merged) : merged; + }; + const writeFileHandleAll = async (handleId, data, options = {}) => { + const bytes = toBytes(data, options?.encoding); + if (bytes.byteLength === 0) { + return client.request("ui.writeFileHandle", { + handleId, data: "", encoding: "base64", mode: "replace", commit: true, + }, { deadlineMs: 60_000 }); + } + let lastResult; + for (let offset = 0; offset < bytes.byteLength; offset += FILE_CHUNK_BYTES) { + const end = Math.min(offset + FILE_CHUNK_BYTES, bytes.byteLength); + const slice = bytes.subarray(offset, end); + lastResult = await client.request("ui.writeFileHandle", { + handleId, + data: bytesToBase64(slice), + encoding: "base64", + mode: offset === 0 ? "replace" : "append", + commit: end >= bytes.byteLength, + }, { deadlineMs: 60_000 }); + } + return { bytesWritten: bytes.byteLength, totalSize: lastResult?.totalSize ?? bytes.byteLength }; + }; const ui = { quickPick: (title, items) => interact({ kind: "quickPick", title, items }), input: (title, initialValue) => interact({ kind: "input", title, ...(initialValue === undefined ? {} : { initialValue }) }), + openFile: async (options = {}) => { + const result = await client.request("ui.openFile", { + ...(options?.title === undefined ? {} : { title: options.title }), + ...(options?.filters === undefined ? {} : { filters: options.filters }), + ...(options?.readAs === undefined ? {} : { readAs: options.readAs }), + ...(options?.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }), + }, { deadlineMs: FILE_DIALOG_DEADLINE_MS }); + if (result?.cancelled) return { cancelled: true }; + let data; + if (result.streamed) { + data = await readFileHandleAll(result.handleId, { readAs: options?.readAs }); + } else if (options?.readAs === "utf8") { + data = result.encoding === "utf8" ? result.data : new TextDecoder().decode(base64ToBytes(result.data ?? "")); + } else { + data = result.encoding === "base64" ? base64ToBytes(result.data ?? "") : new TextEncoder().encode(result.data ?? ""); + } + return { + cancelled: false, + name: result.name, + size: result.size, + handleId: result.handleId, + data, + }; + }, + saveFile: async (options = {}) => { + const bytes = options?.data === undefined ? new Uint8Array(0) : toBytes(options.data, options.encoding); + const baseReq = { + ...(options?.title === undefined ? {} : { title: options.title }), + ...(options?.defaultName === undefined ? {} : { defaultName: options.defaultName }), + ...(options?.filters === undefined ? {} : { filters: options.filters }), + }; + if (bytes.byteLength <= FILE_CHUNK_BYTES) { + return client.request("ui.saveFile", { + ...baseReq, + data: bytesToBase64(bytes), + encoding: "base64", + }, { deadlineMs: FILE_DIALOG_DEADLINE_MS }); + } + const opened = await client.request("ui.saveFile", { + ...baseReq, + deferredWrite: true, + }, { deadlineMs: FILE_DIALOG_DEADLINE_MS }); + if (opened?.cancelled) return { cancelled: true }; + const written = await writeFileHandleAll(opened.handleId, bytes); + return { + cancelled: false, + name: opened.name, + size: written.totalSize, + handleId: opened.handleId, + }; + }, + readFileHandle: readFileHandleAll, + writeFileHandle: writeFileHandleAll, + closeFileHandle: (handleId) => client.request("ui.closeFileHandle", { handleId }).then(() => undefined), + }; + const vault = { + ...Object.fromEntries(["selectHosts", "requestHostDraft", "requestConnect"].map((method) => [ + method, (params) => client.request(`vault.${method}`, params, { deadlineMs: PLUGIN_HOST_INTERACTION_LIMITS.timeoutMs }), + ])), + revokeHostBinding: (hostBindingToken) => client.request("vault.revokeHostBinding", { hostBindingToken }), }; - const vault = Object.fromEntries(["selectHosts", "requestHostDraft", "requestConnect"].map((method) => [ - method, (params) => client.request(`vault.${method}`, params, { deadlineMs: PLUGIN_HOST_INTERACTION_LIMITS.timeoutMs }), - ])); const clipboard = { readText: (title) => interact({ kind: "clipboard.read", title }), writeText: (text, title) => interact({ kind: "clipboard.write", title, text }).then((value) => value === true), diff --git a/electron/plugins/secretStore.cjs b/electron/plugins/secretStore.cjs index eb1b61d4f..2042ef13a 100644 --- a/electron/plugins/secretStore.cjs +++ b/electron/plugins/secretStore.cjs @@ -343,6 +343,22 @@ class PluginSecretStore { throw new PluginRpcError(RPC_ERRORS.dataLoss, "Plugin secret could not be decrypted"); } } + + /** + * Decrypts a secret stored by this plugin itself in its own safeStorage-encrypted + * namespace. Never accesses Netcatty Vault credentials or another plugin's secrets. + */ + getPlaintext(pluginId, key) { + this.#assertAvailable(); + assertSecretKey(key); + const record = this.database.getSecretByKey(pluginId, key); + if (!record) return undefined; + try { + return this.safeStorage.decryptString(record.ciphertext); + } catch { + throw new PluginRpcError(RPC_ERRORS.dataLoss, "Plugin secret could not be decrypted"); + } + } } module.exports = { diff --git a/electron/plugins/secretStore.test.cjs b/electron/plugins/secretStore.test.cjs index 5c2622db4..3b39d7cd1 100644 --- a/electron/plugins/secretStore.test.cjs +++ b/electron/plugins/secretStore.test.cjs @@ -571,3 +571,18 @@ test("live provider backfill does not resurrect explicit unbind tombstones", (co assert.equal(store.resolveSyncProviderPlugin("com.example.sync"), undefined); database.close(); }); + +test("getPlaintext reads only the calling plugin's own encrypted secrets and never leaks across plugins", (context) => { + const database = createDatabase(context); + const store = new PluginSecretStore({ + database, + safeStorage: fakeSafeStorage(), + }); + store.set("com.example.db", "conn:pg:password", "pg-secret-123"); + assert.equal(store.getPlaintext("com.example.db", "conn:pg:password"), "pg-secret-123"); + assert.equal(store.getPlaintext("com.example.db", "conn:missing"), undefined); + assert.equal(store.getPlaintext("com.example.other", "conn:pg:password"), undefined); + store.delete("com.example.db", "conn:pg:password"); + assert.equal(store.getPlaintext("com.example.db", "conn:pg:password"), undefined); + database.close(); +}); diff --git a/electron/plugins/secureCapabilities.cjs b/electron/plugins/secureCapabilities.cjs index 8a621d665..a8a6cd78e 100644 --- a/electron/plugins/secureCapabilities.cjs +++ b/electron/plugins/secureCapabilities.cjs @@ -39,6 +39,15 @@ function registerSecurePluginCapabilities(registry, options) { validateParams: (params) => assertSecretParams(params), authorization: (params) => secretAuthorization(params, "Read"), }); + registry.registerRequest("secrets.getPlaintext", async ({ key }, context) => { + await context.assertActive(); + const value = options.secretStore.getPlaintext(context.pluginId, key); + return value === undefined ? { found: false } : { found: true, value }; + }, { + metadata: { capability: "secrets", mutating: false, permission: "secrets" }, + validateParams: (params) => assertSecretParams(params), + authorization: (params) => secretAuthorization(params, "Read"), + }); registry.registerRequest("secrets.set", async ({ key, value }, context) => { await context.assertActive(); return { secret: options.secretStore.set(context.pluginId, key, value) }; diff --git a/electron/plugins/secureCapabilities.test.cjs b/electron/plugins/secureCapabilities.test.cjs index 5a02d44df..14acd4def 100644 --- a/electron/plugins/secureCapabilities.test.cjs +++ b/electron/plugins/secureCapabilities.test.cjs @@ -334,3 +334,29 @@ test("networkBroker.validate preserves credentialLease for registry dispatch", ( assert.equal(validated.authorization.scheme, "Basic"); assert.equal(validated.authorization.username, "alice"); }); + +test("secrets.getPlaintext reads only the calling plugin's own encrypted secrets and checks runtime liveness", async () => { + const store = new Map([["com.example.db\0conn:pg", "s3cr3t-pg-pass"]]); + const requests = createRegistrations({ + getPlaintext(pluginId, key) { + return store.get(`${pluginId}\0${key}`); + }, + getReference() { return null; }, + set() { return { kind: "secret", id: "0".repeat(32), key: "k" }; }, + delete() {}, + }); + const ownCtx = { pluginId: "com.example.db", async assertActive() {} }; + const otherCtx = { pluginId: "com.example.other", async assertActive() {} }; + assert.deepEqual( + await requests.get("secrets.getPlaintext")({ key: "conn:pg" }, ownCtx), + { found: true, value: "s3cr3t-pg-pass" }, + ); + assert.deepEqual( + await requests.get("secrets.getPlaintext")({ key: "conn:pg" }, otherCtx), + { found: false }, + ); + await assert.rejects( + requests.get("secrets.getPlaintext")({ key: "conn:pg" }, { pluginId: "com.example.db", async assertActive() { throw new Error("inactive"); } }), + /inactive/, + ); +}); diff --git a/electron/plugins/viewResourceService.cjs b/electron/plugins/viewResourceService.cjs index 0ab758a8b..ed5066b14 100644 --- a/electron/plugins/viewResourceService.cjs +++ b/electron/plugins/viewResourceService.cjs @@ -2,23 +2,87 @@ const path = require("node:path"); const { readContainedFile } = require("./pluginProtocol.cjs"); const { inspectContributionIconSource, createBoundedIconRasterizer } = require("./contributionIconService.cjs"); -const { createIsolatedContributionIconRasterizer } = require("./contributionIconRasterizer.cjs"); +const { createPooledContributionIconRasterizer } = require("./contributionIconRasterizer.cjs"); + +const MAX_VIEW_RESOURCE_CACHE_ENTRIES = 256; +const MAX_VIEW_RESOURCE_CACHE_BYTES = 24 * 1024 * 1024; + +function buildCacheKey(plugin, resource) { + if (!plugin || typeof plugin.id !== "string" || typeof plugin.activeVersion !== "string") return null; + return JSON.stringify([plugin.id, plugin.activeVersion, plugin.archiveSha256 ?? "", resource]); +} + class PluginViewResources { constructor({ electron, packageStore }) { this.packageStore = packageStore; - this.rasterize = createBoundedIconRasterizer(createIsolatedContributionIconRasterizer(electron), { maxConcurrent: 2, maxQueued: 16 }); + this.pooledRasterizer = createPooledContributionIconRasterizer(electron); + this.rasterize = createBoundedIconRasterizer(this.pooledRasterizer, { maxConcurrent: 8, maxQueued: 256 }); + this.cache = new Map(); + this.cacheBytes = 0; + this.pending = new Map(); } + + #getCached(key) { + if (!key || !this.cache.has(key)) return undefined; + const value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return value; + } + + #setCached(key, value) { + if (!key) return; + const size = value.url.length; + if (size > MAX_VIEW_RESOURCE_CACHE_BYTES) return; + if (this.cache.has(key)) { + this.cacheBytes -= this.cache.get(key).url.length; + this.cache.delete(key); + } + while (this.cache.size >= MAX_VIEW_RESOURCE_CACHE_ENTRIES || this.cacheBytes + size > MAX_VIEW_RESOURCE_CACHE_BYTES) { + const oldestKey = this.cache.keys().next().value; + if (oldestKey === undefined) break; + this.cacheBytes -= this.cache.get(oldestKey).url.length; + this.cache.delete(oldestKey); + } + this.cache.set(key, value); + this.cacheBytes += size; + } + async image(plugin, resource) { if (typeof resource !== 'string' || resource.length > 256 || !/^[a-zA-Z0-9_-][a-zA-Z0-9_./-]*$/.test(resource) || resource.split('/').some((part) => !part || part === '.' || part === '..')) throw new TypeError('Invalid plugin image path'); - const root = await this.packageStore.preparePackageRoot(plugin); - const file = await readContainedFile(root, resource.split('/'), 512 * 1024); - if (path.extname(resource).toLowerCase() === '.svg' && / 4 * 1024 * 1024) throw new Error('Plugin image exceeds size limit'); - inspectContributionIconSource(png, '.png', 2048); - return { url: `data:image/png;base64,${png.toString('base64')}` }; + const cacheKey = buildCacheKey(plugin, resource); + const cached = this.#getCached(cacheKey); + if (cached) return cached; + if (cacheKey && this.pending.has(cacheKey)) return this.pending.get(cacheKey); + + const task = (async () => { + const root = await this.packageStore.preparePackageRoot(plugin); + const file = await readContainedFile(root, resource.split('/'), 512 * 1024); + if (path.extname(resource).toLowerCase() === '.svg' && / 4 * 1024 * 1024) throw new Error('Plugin image exceeds size limit'); + inspectContributionIconSource(png, '.png', 2048); + const result = { url: `data:image/png;base64,${png.toString('base64')}` }; + this.#setCached(cacheKey, result); + return result; + })(); + + if (cacheKey) { + this.pending.set(cacheKey, task); + task.finally(() => { + if (this.pending.get(cacheKey) === task) this.pending.delete(cacheKey); + }).catch(() => {}); + } + return task; + } + + dispose() { + this.pooledRasterizer?.dispose?.(); + this.cache.clear(); + this.cacheBytes = 0; + this.pending.clear(); } } module.exports = { PluginViewResources }; diff --git a/electron/plugins/viewResourceService.test.cjs b/electron/plugins/viewResourceService.test.cjs index ecdcb7152..e00c13251 100644 --- a/electron/plugins/viewResourceService.test.cjs +++ b/electron/plugins/viewResourceService.test.cjs @@ -21,3 +21,31 @@ test('view images reject traversal, symlink escapes, external SVGs and oversize } assert.equal(decoded, 0); }); + +test('view images cache decoded results by plugin version/hash and never cache transient failures', async (t) => { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'netcatty-view-image-cache-')); + t.after(() => fs.rm(directory, { recursive: true, force: true })); + const root = path.join(directory, 'package'); await fs.mkdir(root); + // Minimal valid 1x1 PNG header/bytes + const pngHeader = Buffer.from([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, + 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, + 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, + ]); + await fs.writeFile(path.join(root, 'icon.png'), pngHeader); + const resources = new PluginViewResources({ electron: {}, packageStore: { preparePackageRoot: async () => root } }); + let attempts = 0; + resources.rasterize = async () => { + attempts += 1; + if (attempts === 1) throw new Error('transient timeout'); + return pngHeader; + }; + const plugin = { id: 'com.test.db', activeVersion: '0.2.0', archiveSha256: 'abc123' }; + await assert.rejects(resources.image(plugin, 'icon.png'), /transient timeout/); + const first = await resources.image(plugin, 'icon.png'); + const second = await resources.image(plugin, 'icon.png'); + assert.equal(first.url, second.url); + assert.equal(attempts, 2); + resources.dispose(); +}); diff --git a/packages/plugin-cli/src/byteStreams.test.ts b/packages/plugin-cli/src/byteStreams.test.ts index 4edc83b6a..4af1e4cbc 100644 --- a/packages/plugin-cli/src/byteStreams.test.ts +++ b/packages/plugin-cli/src/byteStreams.test.ts @@ -12,7 +12,8 @@ test("byte stream packages require negotiated features and exact resources in op for (const resources of [["*"], ["tcp://*:3306"], ["tcp://host:3306/"], ["udp://host:3306"], ["https://host"]]) { assert.equal(validateManifestValue({ ...manifest, permissions: { required: ["commands", "views"], optional: [{ permission: "network.stream", resources }] } }).valid, false); } - assert.equal(validateManifestValue({ ...manifest, permissions: { required: ["commands", "views"], optional: ["network.stream"] } }).valid, false); + assert.equal(validateManifestValue({ ...manifest, permissions: { required: ["commands", "views"], optional: ["network.stream"] } }).valid, true); + assert.equal(validateManifestValue({ ...manifest, permissions: { required: ["commands", "views", "network.stream"] } }).valid, false); assert.equal(checkPluginCompatibility(manifest, { netcattyVersion: "1.0.0", features: [] }).compatible, false); assert.equal(checkPluginCompatibility(manifest, { netcattyVersion: "1.0.0", features: ["network.byte-streams"] }).compatible, true); }); diff --git a/packages/plugin-contract/schema/plugin-contract.schema.json b/packages/plugin-contract/schema/plugin-contract.schema.json index 87ccd1386..a3e838794 100644 --- a/packages/plugin-contract/schema/plugin-contract.schema.json +++ b/packages/plugin-contract/schema/plugin-contract.schema.json @@ -56,7 +56,7 @@ "RpcLimits": { "description": "Host-enforced byte limit for one JSON-RPC control message. Larger payloads must use a stream.", "const": { - "maxJsonBytes": 1048576 + "maxJsonBytes": 8388608 } }, "SafeUnsignedInteger": { @@ -576,9 +576,41 @@ }, "kind": { "const": "network.stream.connectViaHost" + }, + "durable": { + "type": "boolean" } }, "additionalProperties": false + }, + { + "type": "object", + "required": [ + "kind", + "hostBindingToken", + "endpoint" + ], + "properties": { + "kind": { + "const": "network.stream.connectViaHost" + }, + "hostBindingToken": { + "type": "string", + "minLength": 16, + "maxLength": 256, + "pattern": "^[A-Za-z0-9._-]+$" + }, + "endpoint": { + "$ref": "#/$defs/ByteStreamEndpoint" + } + }, + "additionalProperties": false + }, + { + "$ref": "#/$defs/HostByteStreamConfirmRequest" + }, + { + "$ref": "#/$defs/HostByteStreamTlsConfirmRequest" } ] }, @@ -820,12 +852,14 @@ "HostInteractionLimits": { "const": { "textBytes": 4096, - "requestBytes": 65536, + "clipboardBytes": 4194304, + "requestBytes": 4259840, "items": 100, "pendingPerRuntime": 1, "pendingTotal": 8, - "requestsPerMinute": 10, - "timeoutMs": 60000 + "requestsPerMinute": 60, + "timeoutMs": 60000, + "fileMaxBytes": 67108864 } }, "HostInteractionFeature": { @@ -957,7 +991,7 @@ }, "text": { "type": "string", - "maxLength": 4096, + "maxLength": 4194304, "pattern": "^[^\\u0000]*$" } }, @@ -1013,7 +1047,7 @@ "oneOf": [ { "type": "string", - "maxLength": 4096, + "maxLength": 4194304, "pattern": "^[^\\u0000]*$" }, { @@ -1035,6 +1069,25 @@ }, { "$ref": "#/$defs/ByteStreamConnectionDescriptor" + }, + { + "type": "object", + "required": [ + "cancelled", + "approved" + ], + "properties": { + "cancelled": { + "const": false + }, + "approved": { + "const": true + }, + "remember": { + "type": "boolean" + } + }, + "additionalProperties": false } ] }, @@ -1086,6 +1139,9 @@ }, "scriptsRun": { "type": "boolean" + }, + "remember": { + "type": "boolean" } }, "additionalProperties": false @@ -1202,6 +1258,14 @@ "$ref": "#/$defs/VaultHostEditFields" } ] + }, + "durableHostId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "autoCommit": { + "type": "boolean" } }, "additionalProperties": false @@ -1556,14 +1620,14 @@ }, "ByteStreamLimits": { "const": { - "connectionsPerRuntime": 4, - "connectionsTotal": 64, + "connectionsPerRuntime": 24, + "connectionsTotal": 128, "chunkBytes": 65536, "bufferBytes": 65536, - "connectionBytes": 8388608, + "connectionBytes": 536870912, "connectMs": 10000, - "idleMs": 30000, - "lifetimeMs": 120000 + "idleMs": 1800000, + "lifetimeMs": 28800000 } }, "ByteStreamEndpoint": { @@ -1581,6 +1645,23 @@ "properties": { "endpoint": { "$ref": "#/$defs/ByteStreamEndpoint" + }, + "allowLocal": { + "type": "boolean" + }, + "allowSelfSigned": { + "type": "boolean" + }, + "caPem": { + "type": "string", + "minLength": 1, + "maxLength": 65536 + }, + "servername": { + "type": "string", + "minLength": 1, + "maxLength": 253, + "pattern": "^[A-Za-z0-9.-]+$" } }, "additionalProperties": false @@ -1623,6 +1704,12 @@ }, "windowBytes": { "const": 65536 + }, + "hostBindingToken": { + "type": "string", + "minLength": 16, + "maxLength": 256, + "pattern": "^[A-Za-z0-9._-]+$" } }, "additionalProperties": false @@ -1964,10 +2051,7 @@ "PermissionDeclaration": { "oneOf": [ { - "$ref": "#/$defs/PluginPermission", - "not": { - "const": "network.stream" - } + "$ref": "#/$defs/PluginPermission" }, { "$ref": "#/$defs/PermissionResourceDeclaration" @@ -2591,14 +2675,14 @@ }, "mutations": { "type": "array", - "maxItems": 2048, + "maxItems": 4096, "items": { "$ref": "#/$defs/JsonValue" } }, "css": { "type": "string", - "maxLength": 65536 + "maxLength": 131072 } }, "additionalProperties": false @@ -2653,12 +2737,16 @@ "compositionend", "dismiss", "submit", - "reset" + "reset", + "dblclick", + "contextmenu", + "scroll", + "widget" ] }, "value": { "type": "string", - "maxLength": 8192 + "maxLength": 131072 }, "checked": { "type": "boolean" @@ -2695,6 +2783,47 @@ "type": "string", "maxLength": 8192 } + }, + "x": { + "type": "number" + }, + "y": { + "type": "number" + }, + "scrollTop": { + "type": "number", + "minimum": 0 + }, + "scrollLeft": { + "type": "number", + "minimum": 0 + }, + "clientHeight": { + "type": "number", + "minimum": 0 + }, + "clientWidth": { + "type": "number", + "minimum": 0 + }, + "selectionStart": { + "type": "integer", + "minimum": 0, + "maximum": 131072 + }, + "selectionEnd": { + "type": "integer", + "minimum": 0, + "maximum": 131072 + }, + "widgetEvent": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^[a-zA-Z][a-zA-Z0-9_-]{0,63}$" + }, + "detail": { + "$ref": "#/$defs/JsonValue" } }, "additionalProperties": false @@ -8664,35 +8793,387 @@ }, "HostByteStreamLimits": { "const": { - "connectionsPerRuntime": 4, - "connectionsTotal": 64, + "connectionsPerRuntime": 24, + "connectionsTotal": 128, "chunkBytes": 65536, "bufferBytes": 65536, - "connectionBytes": 67108864, + "connectionBytes": 536870912, "connectMs": 120000, - "idleMs": 300000, - "lifetimeMs": 1800000 + "idleMs": 1800000, + "lifetimeMs": 28800000 } }, "HostByteStreamConnectRequest": { + "oneOf": [ + { + "type": "object", + "required": [ + "target", + "expectedRevision", + "endpoint" + ], + "properties": { + "target": { + "$ref": "#/$defs/VaultHostRef" + }, + "expectedRevision": { + "type": "string", + "maxLength": 128, + "pattern": "^[^\\u0000-\\u001f\\u007f]*$", + "minLength": 1 + }, + "endpoint": { + "$ref": "#/$defs/ByteStreamEndpoint" + }, + "durable": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "hostBindingToken", + "endpoint" + ], + "properties": { + "hostBindingToken": { + "type": "string", + "minLength": 16, + "maxLength": 256, + "pattern": "^[A-Za-z0-9._-]+$" + }, + "endpoint": { + "$ref": "#/$defs/ByteStreamEndpoint" + } + }, + "additionalProperties": false + } + ] + }, + "ByteStreamUpgradeTlsRequest": { "type": "object", "required": [ - "target", - "expectedRevision", - "endpoint" + "handleId" ], "properties": { - "target": { - "$ref": "#/$defs/VaultHostRef" - }, - "expectedRevision": { + "handleId": { "type": "string", - "maxLength": 128, - "pattern": "^[^\\u0000-\\u001f\\u007f]*$", - "minLength": 1 + "format": "uuid" + }, + "servername": { + "type": "string", + "minLength": 1, + "maxLength": 253, + "pattern": "^[A-Za-z0-9.-]+$" + }, + "allowSelfSigned": { + "type": "boolean" + }, + "caPem": { + "type": "string", + "minLength": 1, + "maxLength": 65536 + } + }, + "additionalProperties": false + }, + "ByteStreamUpgradeTlsResult": { + "type": "object", + "required": [ + "upgraded", + "authorized" + ], + "properties": { + "upgraded": { + "const": true + }, + "authorized": { + "type": "boolean" + }, + "protocol": { + "type": "string", + "maxLength": 64 + }, + "fingerprint256": { + "type": "string", + "maxLength": 128 + }, + "subject": { + "type": "string", + "maxLength": 512 + } + }, + "additionalProperties": false + }, + "VaultHostBindingRevokeParams": { + "type": "object", + "required": [ + "hostBindingToken" + ], + "properties": { + "hostBindingToken": { + "type": "string", + "minLength": 16, + "maxLength": 256, + "pattern": "^[A-Za-z0-9._-]+$" + } + }, + "additionalProperties": false + }, + "HostByteStreamConfirmRequest": { + "type": "object", + "required": [ + "kind", + "endpoint", + "host", + "port", + "transport", + "isLocal" + ], + "properties": { + "kind": { + "const": "network.stream.confirm" }, "endpoint": { "$ref": "#/$defs/ByteStreamEndpoint" + }, + "host": { + "type": "string", + "minLength": 1, + "maxLength": 253 + }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "transport": { + "enum": [ + "tcp", + "tls" + ] + }, + "isLocal": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "HostByteStreamTlsConfirmRequest": { + "type": "object", + "required": [ + "kind", + "endpoint", + "fingerprint256", + "subject", + "issuer", + "validTo", + "reason" + ], + "properties": { + "kind": { + "const": "network.stream.tlsConfirm" + }, + "endpoint": { + "$ref": "#/$defs/ByteStreamEndpoint" + }, + "servername": { + "type": "string", + "minLength": 1, + "maxLength": 253 + }, + "fingerprint256": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "subject": { + "type": "string", + "maxLength": 512 + }, + "issuer": { + "type": "string", + "maxLength": 512 + }, + "validTo": { + "type": "string", + "maxLength": 128 + }, + "reason": { + "type": "string", + "maxLength": 256 + } + }, + "additionalProperties": false + }, + "HostFileDialogFilter": { + "type": "object", + "required": [ + "name", + "extensions" + ], + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^[^\\u0000-\\u001f\\u007f]*$" + }, + "extensions": { + "type": "array", + "minItems": 1, + "maxItems": 32, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 32, + "pattern": "^(\\*|[A-Za-z0-9][A-Za-z0-9._-]{0,31})$" + } + } + }, + "additionalProperties": false + }, + "HostOpenFileRequest": { + "type": "object", + "properties": { + "title": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[^\\u0000-\\u001f\\u007f]*$" + }, + "filters": { + "type": "array", + "maxItems": 32, + "items": { + "$ref": "#/$defs/HostFileDialogFilter" + } + }, + "readAs": { + "enum": [ + "bytes", + "utf8" + ] + }, + "maxBytes": { + "type": "integer", + "minimum": 1, + "maximum": 67108864 + } + }, + "additionalProperties": false + }, + "HostSaveFileRequest": { + "type": "object", + "properties": { + "title": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[^\\u0000-\\u001f\\u007f]*$" + }, + "defaultName": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[^\\u0000-\\u001f\\u007f/\\\\]+$" + }, + "filters": { + "type": "array", + "maxItems": 32, + "items": { + "$ref": "#/$defs/HostFileDialogFilter" + } + }, + "data": { + "type": "string", + "maxLength": 5592408 + }, + "encoding": { + "enum": [ + "base64", + "utf8" + ] + }, + "deferredWrite": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "HostFileHandleReadRequest": { + "type": "object", + "required": [ + "handleId" + ], + "properties": { + "handleId": { + "type": "string", + "format": "uuid" + }, + "offset": { + "type": "integer", + "minimum": 0, + "maximum": 67108864 + }, + "length": { + "type": "integer", + "minimum": 1, + "maximum": 4194304 + }, + "encoding": { + "enum": [ + "base64", + "utf8" + ] + } + }, + "additionalProperties": false + }, + "HostFileHandleWriteRequest": { + "type": "object", + "required": [ + "handleId", + "data" + ], + "properties": { + "handleId": { + "type": "string", + "format": "uuid" + }, + "data": { + "type": "string", + "maxLength": 5592408 + }, + "encoding": { + "enum": [ + "base64", + "utf8" + ] + }, + "mode": { + "enum": [ + "replace", + "append" + ] + }, + "commit": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "HostFileHandleCloseRequest": { + "type": "object", + "required": [ + "handleId" + ], + "properties": { + "handleId": { + "type": "string", + "format": "uuid" } }, "additionalProperties": false diff --git a/packages/plugin-contract/src/contract.test.ts b/packages/plugin-contract/src/contract.test.ts index 54274765d..ba6fb14a7 100644 --- a/packages/plugin-contract/src/contract.test.ts +++ b/packages/plugin-contract/src/contract.test.ts @@ -366,7 +366,7 @@ test("required resource-scoped permissions declare activation-time bounds", () = assert.equal(validate({ ...validManifest, permissions: { optional: [permission] }, - }), permission !== "network.stream", `${permission}: ${JSON.stringify(validate.errors)}`); + }), true, `${permission}: ${JSON.stringify(validate.errors)}`); assert.equal(validate({ ...validManifest, permissions: { optional: [{ permission, resources: [resource] }] }, diff --git a/packages/plugin-contract/src/generated/plugin-contract-limits.ts b/packages/plugin-contract/src/generated/plugin-contract-limits.ts index 8df8a1fc6..6125c9739 100644 --- a/packages/plugin-contract/src/generated/plugin-contract-limits.ts +++ b/packages/plugin-contract/src/generated/plugin-contract-limits.ts @@ -5,9 +5,9 @@ export const PLUGIN_JSON_MAX_DEPTH = 128 as const; export const PLUGIN_JSON_MAX_NODES = 100000 as const; export const PLUGIN_WIRE_MAX_SAFE_INTEGER = 9007199254740991 as const; -export const PLUGIN_RPC_MAX_JSON_BYTES = 1048576 as const; -export const PLUGIN_HOST_INTERACTION_LIMITS = {"textBytes":4096,"requestBytes":65536,"items":100,"pendingPerRuntime":1,"pendingTotal":8,"requestsPerMinute":10,"timeoutMs":60000} as const; -export const PLUGIN_BYTE_STREAM_LIMITS = {"connectionsPerRuntime":4,"connectionsTotal":64,"chunkBytes":65536,"bufferBytes":65536,"connectionBytes":8388608,"connectMs":10000,"idleMs":30000,"lifetimeMs":120000} as const; +export const PLUGIN_RPC_MAX_JSON_BYTES = 8388608 as const; +export const PLUGIN_HOST_INTERACTION_LIMITS = {"textBytes":4096,"clipboardBytes":4194304,"requestBytes":4259840,"items":100,"pendingPerRuntime":1,"pendingTotal":8,"requestsPerMinute":60,"timeoutMs":60000,"fileMaxBytes":67108864} as const; +export const PLUGIN_BYTE_STREAM_LIMITS = {"connectionsPerRuntime":24,"connectionsTotal":128,"chunkBytes":65536,"bufferBytes":65536,"connectionBytes":536870912,"connectMs":10000,"idleMs":1800000,"lifetimeMs":28800000} as const; export const PLUGIN_RPC_ERROR_CODES = [-32700,-32600,-32601,-32602,-32603,-32001,-32002,-32003,-32004,-32005,-32006,-32007,-32008,-32009,-32010,-32011,-32012,-32013,-32014,-32015,-32016] as const; export const PLUGIN_STREAM_MAX_ID_LENGTH = 128 as const; export const PLUGIN_STREAM_MAX_CHUNK_BYTES = 16777216 as const; diff --git a/packages/plugin-contract/src/generated/plugin-contract.ts b/packages/plugin-contract/src/generated/plugin-contract.ts index 5b1697f3c..ceee4b6fc 100644 --- a/packages/plugin-contract/src/generated/plugin-contract.ts +++ b/packages/plugin-contract/src/generated/plugin-contract.ts @@ -83,10 +83,15 @@ export type ByteStreamConnectionDescriptor = { inputStreamId: StreamId; outputStreamId: StreamId; windowBytes: 65536; + hostBindingToken?: string; }; export type ByteStreamConnectRequest = { endpoint: ByteStreamEndpoint; + allowLocal?: boolean; + allowSelfSigned?: boolean; + caPem?: string; + servername?: string; }; export type ByteStreamEndpoint = string; @@ -97,7 +102,22 @@ export type ByteStreamHandleRequest = { handleId: string; }; -export type ByteStreamLimits = {"connectionsPerRuntime":4,"connectionsTotal":64,"chunkBytes":65536,"bufferBytes":65536,"connectionBytes":8388608,"connectMs":10000,"idleMs":30000,"lifetimeMs":120000}; +export type ByteStreamLimits = {"connectionsPerRuntime":24,"connectionsTotal":128,"chunkBytes":65536,"bufferBytes":65536,"connectionBytes":536870912,"connectMs":10000,"idleMs":1800000,"lifetimeMs":28800000}; + +export type ByteStreamUpgradeTlsRequest = { + handleId: string; + servername?: string; + allowSelfSigned?: boolean; + caPem?: string; +}; + +export type ByteStreamUpgradeTlsResult = { + upgraded: true; + authorized: boolean; + protocol?: string; + fingerprint256?: string; + subject?: string; +}; export type CommandContribution = { id: ContributionId; @@ -196,15 +216,39 @@ export type FeatureId = string; export type FilesystemDirectoryEnumerationFeature = "filesystem.directory-enumeration"; -export type HostByteStreamConnectRequest = { +export type HostByteStreamConfirmRequest = { + kind: "network.stream.confirm"; + endpoint: ByteStreamEndpoint; + host: string; + port: number; + transport: "tcp" | "tls"; + isLocal: boolean; +}; + +export type HostByteStreamConnectRequest = ({ target: VaultHostRef; expectedRevision: string; endpoint: ByteStreamEndpoint; -}; + durable?: boolean; +}) | ({ + hostBindingToken: string; + endpoint: ByteStreamEndpoint; +}); export type HostByteStreamFeature = "network.host-byte-streams"; -export type HostByteStreamLimits = {"connectionsPerRuntime":4,"connectionsTotal":64,"chunkBytes":65536,"bufferBytes":65536,"connectionBytes":67108864,"connectMs":120000,"idleMs":300000,"lifetimeMs":1800000}; +export type HostByteStreamLimits = {"connectionsPerRuntime":24,"connectionsTotal":128,"chunkBytes":65536,"bufferBytes":65536,"connectionBytes":536870912,"connectMs":120000,"idleMs":1800000,"lifetimeMs":28800000}; + +export type HostByteStreamTlsConfirmRequest = { + kind: "network.stream.tlsConfirm"; + endpoint: ByteStreamEndpoint; + servername?: string; + fingerprint256: string; + subject: string; + issuer: string; + validTo: string; + reason: string; +}; export type HostClipboardReadRequest = { kind: "clipboard.read"; @@ -219,7 +263,7 @@ export type HostClipboardWriteRequest = { export type HostDrawnViewEvent = { nodeId: string; - type: "click" | "input" | "change" | "keydown" | "keyup" | "focusin" | "focusout" | "compositionstart" | "compositionupdate" | "compositionend" | "dismiss" | "submit" | "reset"; + type: "click" | "input" | "change" | "keydown" | "keyup" | "focusin" | "focusout" | "compositionstart" | "compositionupdate" | "compositionend" | "dismiss" | "submit" | "reset" | "dblclick" | "contextmenu" | "scroll" | "widget"; value?: string; checked?: boolean; eventId?: number; @@ -230,6 +274,16 @@ export type HostDrawnViewEvent = { altKey?: boolean; shiftKey?: boolean; values?: Array; + x?: number; + y?: number; + scrollTop?: number; + scrollLeft?: number; + clientHeight?: number; + clientWidth?: number; + selectionStart?: number; + selectionEnd?: number; + widgetEvent?: string; + detail?: JsonValue; }; export type HostDrawnViewMessage = ({ @@ -261,6 +315,30 @@ export type HostDrawnViewOpenRequest = { export type HostDrawnViewsFeature = "views.host-drawn"; +export type HostFileDialogFilter = { + name: string; + extensions: Array; +}; + +export type HostFileHandleCloseRequest = { + handleId: string; +}; + +export type HostFileHandleReadRequest = { + handleId: string; + offset?: number; + length?: number; + encoding?: "base64" | "utf8"; +}; + +export type HostFileHandleWriteRequest = { + handleId: string; + data: string; + encoding?: "base64" | "utf8"; + mode?: "replace" | "append"; + commit?: boolean; +}; + export type HostInputRequest = { kind: "input"; title: string; @@ -276,7 +354,7 @@ export type HostInteractionEvent = (HostInteractionPrompt) | (HostInteractionClo export type HostInteractionFeature = "host.interactions"; -export type HostInteractionLimits = {"textBytes":4096,"requestBytes":65536,"items":100,"pendingPerRuntime":1,"pendingTotal":8,"requestsPerMinute":10,"timeoutMs":60000}; +export type HostInteractionLimits = {"textBytes":4096,"clipboardBytes":4194304,"requestBytes":4259840,"items":100,"pendingPerRuntime":1,"pendingTotal":8,"requestsPerMinute":60,"timeoutMs":60000,"fileMaxBytes":67108864}; export type HostInteractionPrompt = { permissionMode?: "allow" | "ask" | "deny"; @@ -293,6 +371,8 @@ export type HostInteractionPrompt = { terminalLabel?: string; vaultTarget?: VaultHostLocalTarget; reviewedDraft?: (VaultHostCreateFields) | (VaultHostEditFields); + durableHostId?: string; + autoCommit?: boolean; }; export type HostInteractionReceipt = (boolean) | ({ @@ -309,6 +389,7 @@ export type HostInteractionResponse = { resources?: VaultHostSelectedResources; draft?: (VaultHostCreateFields) | (VaultHostEditFields); scriptsRun?: boolean; + remember?: boolean; }; export type HostInteractionResult = ({ @@ -316,7 +397,18 @@ export type HostInteractionResult = ({ }) | ({ cancelled: false; value: (string) | (true) | (SharedTerminalSelection); -}) | (VaultHostSelectedResult) | (VaultHostActionAccepted) | (ByteStreamConnectionDescriptor); +}) | (VaultHostSelectedResult) | (VaultHostActionAccepted) | (ByteStreamConnectionDescriptor) | ({ + cancelled: false; + approved: true; + remember?: boolean; +}); + +export type HostOpenFileRequest = { + title?: string; + filters?: Array; + readAs?: "bytes" | "utf8"; + maxBytes?: number; +}; export type HostQuickPickItem = { id: string; @@ -330,6 +422,15 @@ export type HostQuickPickRequest = { items: Array; }; +export type HostSaveFileRequest = { + title?: string; + defaultName?: string; + filters?: Array; + data?: string; + encoding?: "base64" | "utf8"; + deferredWrite?: boolean; +}; + export type HostSingleLineInputText = string; export type HostTerminalInputProposalRequest = { @@ -562,7 +663,7 @@ export type PermissionDecision = ({ decision: "deny" | "cancel"; }); -export type PermissionDeclaration = Exclude | PermissionResourceDeclaration; +export type PermissionDeclaration = PluginPermission | PermissionResourceDeclaration; export type PermissionGrantScope = "once" | "session" | "application" | "always"; @@ -1288,7 +1389,7 @@ export type RpcFailure = { export type RpcId = (string) | (SafeUnsignedInteger); -export type RpcLimits = {"maxJsonBytes":1048576}; +export type RpcLimits = {"maxJsonBytes":8388608}; export type RpcMessage = (RpcRequest) | (RpcNotification) | (RpcSuccess) | (RpcFailure) | (RpcCancel) | (RpcProgressNotification) | (RuntimeInitializeRequest) | (TerminalInterceptorAttachmentRequest); @@ -1760,12 +1861,21 @@ export type VaultHostActionRequest = ({ expectedRevision: string; endpoint: ByteStreamEndpoint; kind: "network.stream.connectViaHost"; -}); + durable?: boolean; +}) | ({ + kind: "network.stream.connectViaHost"; + hostBindingToken: string; + endpoint: ByteStreamEndpoint; +}) | (HostByteStreamConfirmRequest) | (HostByteStreamTlsConfirmRequest); export type VaultHostActionResult = ({ cancelled: true; }) | (VaultHostActionAccepted); +export type VaultHostBindingRevokeParams = { + hostBindingToken: string; +}; + export type VaultHostConnectParams = { target: VaultHostRef; expectedRevision: string; diff --git a/packages/plugin-sdk/src/hostDom.ts b/packages/plugin-sdk/src/hostDom.ts index b29f9e712..a79f8131e 100644 --- a/packages/plugin-sdk/src/hostDom.ts +++ b/packages/plugin-sdk/src/hostDom.ts @@ -104,9 +104,12 @@ function subscribeControlPropertyMutations(container: HTMLElement, onMutation: ( }; } +const MAX_PLUGIN_CSS_LENGTH = 131072; +const MAX_PLUGIN_EVENT_VALUE_LENGTH = 131072; + /** Build ordinary DOM in the isolated runtime; only validated data reaches the visible host. */ export function registerHostDomView(views: PluginViews, viewId: string, mount: (container: HTMLElement, stateScope: string) => (() => void) | void, css = ''): Disposable { - if (css.length > 65536) throw new TypeError('Plugin CSS exceeds the view limit'); + if (css.length > MAX_PLUGIN_CSS_LENGTH) throw new TypeError('Plugin CSS exceeds the view limit'); type View = { container: HTMLDivElement; unmount: () => void; @@ -142,8 +145,51 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: ( view.syncElementIndex(); const element = view.elementsById.get(event.nodeId); if (!element || !(element instanceof HTMLElement)) return; - if (event.type === 'dismiss') { element.dispatchEvent(new Event('netcatty-dismiss')); return; } - if (event.type === 'click') { + const eventType = event.type; + if (eventType === 'dismiss') { element.dispatchEvent(new Event('netcatty-dismiss')); return; } + if (eventType === 'widget') { + element.dispatchEvent(new CustomEvent('netcatty-widget-event', { + bubbles: false, + detail: { widgetEvent: event.widgetEvent, detail: event.detail }, + })); + return; + } + if (eventType === 'dblclick') { + element.dispatchEvent(new MouseEvent('dblclick', { + bubbles: true, + cancelable: true, + clientX: event.x ?? 0, + clientY: event.y ?? 0, + })); + return; + } + if (eventType === 'contextmenu') { + element.dispatchEvent(new MouseEvent('contextmenu', { + bubbles: true, + cancelable: true, + button: 2, + clientX: event.x ?? 0, + clientY: event.y ?? 0, + })); + return; + } + if (eventType === 'scroll') { + try { + if (typeof event.scrollTop === 'number') element.scrollTop = event.scrollTop; + if (typeof event.scrollLeft === 'number') element.scrollLeft = event.scrollLeft; + } catch {} + element.dispatchEvent(new CustomEvent('scroll', { + bubbles: false, + detail: { + scrollTop: event.scrollTop ?? 0, + scrollLeft: event.scrollLeft ?? 0, + clientHeight: event.clientHeight ?? 0, + clientWidth: event.clientWidth ?? 0, + }, + })); + return; + } + if (eventType === 'click') { // The host already performed native checkbox/label behavior. Reproduce it // once for React's click-based change handler, without a second toggle. if (element instanceof HTMLInputElement && ['checkbox', 'radio'].includes(element.type) && event.checked !== undefined) { @@ -160,26 +206,34 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: ( } return; } - if (event.type === 'reset' && element instanceof HTMLFormElement) { element.reset(); return; } - if (event.type === 'submit') { const action = new Event(event.type, { bubbles: true, cancelable: true }); action.preventDefault(); element.dispatchEvent(action); return; } - if (event.type === 'keydown' || event.type === 'keyup') { - element.dispatchEvent(new KeyboardEvent(event.type, { key: event.key ?? '', ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey, bubbles: true, cancelable: true })); return; + if (eventType === 'reset' && element instanceof HTMLFormElement) { element.reset(); return; } + if (eventType === 'submit') { const action = new Event(eventType, { bubbles: true, cancelable: true }); action.preventDefault(); element.dispatchEvent(action); return; } + if (eventType === 'keydown' || eventType === 'keyup') { + if ((element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) + && typeof event.selectionStart === 'number' && typeof event.selectionEnd === 'number') { + try { element.setSelectionRange(event.selectionStart, event.selectionEnd); } catch {} + } + element.dispatchEvent(new KeyboardEvent(eventType, { key: event.key ?? '', ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey, bubbles: true, cancelable: true })); return; } - if (event.type.startsWith('composition')) { element.dispatchEvent(new CompositionEvent(event.type, { data: event.data ?? '', bubbles: true })); return; } - if (event.type === 'focusin' || event.type === 'focusout') { element.dispatchEvent(new FocusEvent(event.type, { bubbles: true })); return; } + if (eventType.startsWith('composition')) { element.dispatchEvent(new CompositionEvent(eventType, { data: event.data ?? '', bubbles: true })); return; } + if (eventType === 'focusin' || eventType === 'focusout') { element.dispatchEvent(new FocusEvent(eventType, { bubbles: true })); return; } if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) { if (element instanceof HTMLSelectElement && element.multiple && event.values) { for (const option of element.options) option.selected = event.values.includes(option.value); } - if (!(element instanceof HTMLSelectElement && element.multiple) && event.value !== undefined && event.value.length <= 8192) { + if (!(element instanceof HTMLSelectElement && element.multiple) && event.value !== undefined && event.value.length <= MAX_PLUGIN_EVENT_VALUE_LENGTH) { const prototype = element instanceof HTMLInputElement ? HTMLInputElement.prototype : element instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLSelectElement.prototype; Object.getOwnPropertyDescriptor(prototype, 'value')?.set?.call(element, event.value); } + if ((element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) + && typeof event.selectionStart === 'number' && typeof event.selectionEnd === 'number') { + try { element.setSelectionRange(event.selectionStart, event.selectionEnd); } catch {} + } if (element instanceof HTMLInputElement && typeof event.checked === 'boolean') { Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'checked')?.set?.call(element, event.checked); } - element.dispatchEvent(new Event(event.type, { bubbles: true, cancelable: true })); + element.dispatchEvent(new Event(eventType, { bubbles: true, cancelable: true })); } }; const subscription = views.onDidReceiveMessage(viewId, (message) => { diff --git a/packages/plugin-sdk/src/hostReact.test.tsx b/packages/plugin-sdk/src/hostReact.test.tsx index f63a71be1..8797171e6 100644 --- a/packages/plugin-sdk/src/hostReact.test.tsx +++ b/packages/plugin-sdk/src/hostReact.test.tsx @@ -422,3 +422,107 @@ test('hostDom syncs valueAsNumber, valueAsDate, stepUp, stepDown, and setRangeTe dom.window.close(); } }); + +test('hostReact widgets and extended surface events round-trip cleanly through hostDom', async () => { + const dom = new JSDOM('', { url: 'http://localhost', pretendToBeVisual: true }); + const saved = new Map(); + for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLOptionElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'CustomEvent', 'MouseEvent']) { + saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] }); + } + Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true }); + + const { default: React, act } = await import('react'); + const { remoteId } = await import('@remote-dom/core/elements'); + const { + registerHostReactView, + PluginPopover, + PluginCodeEditor, + PluginDataGrid, + PluginSplitPane, + PluginErCanvas, + } = await import('./hostReact.js'); + + let receive: (value: JsonValue) => void = () => {}; + const messages: Array> = []; + 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); }, + getState: async () => undefined, + setState: async () => {}, + }; + + const received: Record = {}; + function IdeView() { + return ( +
+ + { received.dismissed = true; }}> + Action + + { received.resizeEnd = d; }}> + { received.execute = d; }} /> + { received.cellEdit = d; }} + /> + + { received.tableClick = d; }} + /> +
+ ); + } + + const registration = registerHostReactView(views, 'com.example.ide', () => ); + try { + await act(async () => { + receive({ kind: 'host-ui.open', instanceId: 'ide-1' }); + await new Promise((resolve) => setTimeout(resolve, 20)); + }); + + const btn = document.getElementById('row-btn')!; + const editorEl = document.querySelector('[data-plugin-widget="code-editor"]')!; + const gridEl = document.querySelector('[data-plugin-widget="data-grid"]')!; + const splitEl = document.querySelector('[data-plugin-widget="split-pane"]')!; + const erEl = document.querySelector('[data-plugin-widget="er-canvas"]')!; + const popoverEl = document.querySelector('[data-plugin-popover="true"]')!; + + assert.equal(popoverEl.getAttribute('data-plugin-anchor-x'), '40'); + assert.equal(popoverEl.getAttribute('data-plugin-anchor-y'), '60'); + assert.equal(popoverEl.getAttribute('data-plugin-popover-width'), '240'); + assert.equal(popoverEl.getAttribute('data-plugin-popover-max-height'), '300'); + + await act(async () => { + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'dblclick', nodeId: remoteId(btn), x: 12, y: 34 } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'contextmenu', nodeId: remoteId(btn), x: 56, y: 78 } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(editorEl), widgetEvent: 'execute', detail: { value: 'SELECT 1;', selectedText: '', currentStatement: 'SELECT 1' } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'id', value: '2', isNull: false } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(splitEl), widgetEvent: 'resizeEnd', detail: { size: 320, collapsed: false } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(erEl), widgetEvent: 'tableClick', detail: { table: 'users' } } }); + }); + + assert.deepEqual(received.dblclick, { x: 12, y: 34 }); + assert.deepEqual(received.contextmenu, { x: 56, y: 78 }); + assert.deepEqual(received.execute, { value: 'SELECT 1;', selectedText: '', currentStatement: 'SELECT 1' }); + assert.deepEqual(received.cellEdit, { rowIndex: 0, colName: 'id', value: '2', isNull: false }); + assert.deepEqual(received.resizeEnd, { size: 320, collapsed: false }); + assert.deepEqual(received.tableClick, { table: 'users' }); + await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'ide-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(); + } +}); diff --git a/packages/plugin-sdk/src/hostReact.ts b/packages/plugin-sdk/src/hostReact.ts index 023bf3509..8760bbe1a 100644 --- a/packages/plugin-sdk/src/hostReact.ts +++ b/packages/plugin-sdk/src/hostReact.ts @@ -1,5 +1,5 @@ import { createRoot } from 'react-dom/client'; -import { createElement, useEffect, useRef, type ReactNode } from 'react'; +import { createElement, useEffect, useMemo, useRef, type CSSProperties, type ReactNode } from 'react'; import type { Disposable, PluginViews } from './index.js'; import { registerHostDomView } from './hostDom.js'; @@ -10,13 +10,370 @@ export function registerHostReactView(views: PluginViews, viewId: string, render }, css); } +export interface PluginPopoverProps { + anchor?: string; + anchorX?: number; + anchorY?: number; + width?: number; + maxHeight?: number; + open: boolean; + onClose(): void; + children: ReactNode; +} + /** A host-positioned popup with freely authored content. */ -export function PluginPopover({ anchor, open, onClose, children }: { anchor: string; open: boolean; onClose(): void; children: ReactNode }) { +export function PluginPopover({ + anchor, + anchorX, + anchorY, + width, + maxHeight, + open, + onClose, + children, +}: PluginPopoverProps) { const ref = useRef(null); useEffect(() => { const node = ref.current; if (!node) return; node.addEventListener('netcatty-dismiss', onClose); return () => node.removeEventListener('netcatty-dismiss', onClose); }, [onClose]); - return createElement('div', { ref, 'data-plugin-popover': 'true', 'data-plugin-anchor': anchor, ...(open ? { open: true } : {}) }, children); + return createElement( + 'div', + { + ref, + 'data-plugin-popover': 'true', + ...(anchor ? { 'data-plugin-anchor': anchor } : {}), + ...(anchorX !== undefined ? { 'data-plugin-anchor-x': String(anchorX) } : {}), + ...(anchorY !== undefined ? { 'data-plugin-anchor-y': String(anchorY) } : {}), + ...(width !== undefined ? { 'data-plugin-popover-width': String(width) } : {}), + ...(maxHeight !== undefined ? { 'data-plugin-popover-max-height': String(maxHeight) } : {}), + ...(open ? { open: true } : {}), + }, + children, + ); +} + +type WidgetEventDetail = { widgetEvent?: string; detail?: Record }; + +function useWidgetEventBridge( + ref: React.RefObject, + handler: (widgetEvent: string, detail: Record) => void, +) { + const handlerRef = useRef(handler); + handlerRef.current = handler; + useEffect(() => { + const node = ref.current; + if (!node) return; + const listener = (event: Event) => { + const payload = (event as CustomEvent).detail; + if (!payload || typeof payload.widgetEvent !== 'string') return; + handlerRef.current(payload.widgetEvent, payload.detail ?? {}); + }; + node.addEventListener('netcatty-widget-event', listener); + return () => node.removeEventListener('netcatty-widget-event', listener); + }, [ref]); +} + +export interface PluginCodeEditorCompletionColumn { + name: string; + type?: string; +} + +export interface PluginCodeEditorCompletionTable { + name: string; + schema?: string; + columns?: PluginCodeEditorCompletionColumn[]; +} + +export interface PluginCodeEditorCompletionFunction { + name: string; + detail?: string; + insertText?: string; +} + +export interface PluginCodeEditorCompletionSchema { + tables?: PluginCodeEditorCompletionTable[]; + functions?: PluginCodeEditorCompletionFunction[]; + keywords?: string[]; +} + +export interface PluginCodeEditorDiagnostic { + line: number; + column: number; + endLine?: number; + endColumn?: number; + message: string; + severity?: 'error' | 'warning' | 'info' | 'hint'; +} + +export interface PluginCodeEditorProps { + value: string; + language?: 'sql' | 'pgsql' | 'mysql' | 'json' | 'plaintext'; + readOnly?: boolean; + placeholder?: string; + lineNumbers?: 'on' | 'off' | 'relative'; + minimap?: boolean; + wordWrap?: 'on' | 'off' | 'wordWrapColumn' | 'bounded'; + completionSchema?: PluginCodeEditorCompletionSchema; + diagnostics?: PluginCodeEditorDiagnostic[]; + height?: number | string; + className?: string; + style?: CSSProperties; + onChange?: (detail: { value: string }) => void; + onSelection?: (detail: { selectionStart: number; selectionEnd: number; selectedText: string }) => void; + onExecute?: (detail: { value: string; selectedText: string; currentStatement: string }) => void; + onFormat?: (detail: { value: string }) => void; +} + +/** Host-rendered Monaco code editor with local zero-IPC schema completion. */ +export function PluginCodeEditor({ + value, + language, + readOnly, + placeholder, + lineNumbers, + minimap, + wordWrap, + completionSchema, + diagnostics, + height, + className, + style, + onChange, + onSelection, + onExecute, + onFormat, +}: PluginCodeEditorProps) { + const ref = useRef(null); + useWidgetEventBridge(ref, (eventName, detail) => { + if (eventName === 'change') onChange?.(detail as { value: string }); + else if (eventName === 'selection') onSelection?.(detail as { selectionStart: number; selectionEnd: number; selectedText: string }); + else if (eventName === 'execute') onExecute?.(detail as { value: string; selectedText: string; currentStatement: string }); + else if (eventName === 'format') onFormat?.(detail as { value: string }); + }); + const serialized = useMemo( + () => JSON.stringify({ + value, + ...(language !== undefined ? { language } : {}), + ...(readOnly !== undefined ? { readOnly } : {}), + ...(placeholder !== undefined ? { placeholder } : {}), + ...(lineNumbers !== undefined ? { lineNumbers } : {}), + ...(minimap !== undefined ? { minimap } : {}), + ...(wordWrap !== undefined ? { wordWrap } : {}), + ...(completionSchema !== undefined ? { completionSchema } : {}), + ...(diagnostics !== undefined ? { diagnostics } : {}), + ...(height !== undefined ? { height } : {}), + }), + [value, language, readOnly, placeholder, lineNumbers, minimap, wordWrap, completionSchema, diagnostics, height], + ); + return createElement('div', { + ref, + className, + style, + 'data-plugin-widget': 'code-editor', + 'data-plugin-widget-props': serialized, + }); +} + +export interface PluginDataGridColumn { + name: string; + type?: string; + primaryKey?: boolean; + nullable?: boolean; + width?: number; + sortable?: boolean; +} + +export interface PluginDataGridSort { + column: string; + direction: 'asc' | 'desc'; +} + +export type PluginDataGridRow = Record | unknown[]; + +export interface PluginDataGridProps { + columns: PluginDataGridColumn[]; + rows: PluginDataGridRow[]; + rowKeyField?: string; + dirtyCells?: Record; + deletedRowIndices?: number[]; + insertedRows?: PluginDataGridRow[]; + selectedRowIndices?: number[]; + sort?: PluginDataGridSort | null; + editable?: boolean; + loading?: boolean; + emptyMessage?: string; + className?: string; + style?: CSSProperties; + onCellSelect?: (detail: { rowIndex: number; colName: string; value: unknown }) => void; + onCellEdit?: (detail: { rowIndex: number; colName: string; value: unknown; isNull: boolean }) => void; + onCellContextMenu?: (detail: { rowIndex: number; colName: string; x: number; y: number }) => void; + onSortChange?: (detail: { column: string; direction: 'asc' | 'desc' }) => void; + onRowSelect?: (detail: { selectedRowIndices: number[] }) => void; +} + +/** Host-rendered virtualized editable data grid powered by @tanstack/react-virtual. */ +export function PluginDataGrid({ + columns, + rows, + rowKeyField, + dirtyCells, + deletedRowIndices, + insertedRows, + selectedRowIndices, + sort, + editable, + loading, + emptyMessage, + className, + style, + onCellSelect, + onCellEdit, + onCellContextMenu, + onSortChange, + onRowSelect, +}: PluginDataGridProps) { + const ref = useRef(null); + useWidgetEventBridge(ref, (eventName, detail) => { + if (eventName === 'cellSelect') onCellSelect?.(detail as { rowIndex: number; colName: string; value: unknown }); + else if (eventName === 'cellEdit') onCellEdit?.(detail as { rowIndex: number; colName: string; value: unknown; isNull: boolean }); + else if (eventName === 'cellContextMenu') onCellContextMenu?.(detail as { rowIndex: number; colName: string; x: number; y: number }); + else if (eventName === 'sortChange') onSortChange?.(detail as { column: string; direction: 'asc' | 'desc' }); + else if (eventName === 'rowSelect') onRowSelect?.(detail as { selectedRowIndices: number[] }); + }); + const serialized = useMemo( + () => JSON.stringify({ + columns, + rows, + ...(rowKeyField !== undefined ? { rowKeyField } : {}), + ...(dirtyCells !== undefined ? { dirtyCells } : {}), + ...(deletedRowIndices !== undefined ? { deletedRowIndices } : {}), + ...(insertedRows !== undefined ? { insertedRows } : {}), + ...(selectedRowIndices !== undefined ? { selectedRowIndices } : {}), + ...(sort !== undefined ? { sort } : {}), + ...(editable !== undefined ? { editable } : {}), + ...(loading !== undefined ? { loading } : {}), + ...(emptyMessage !== undefined ? { emptyMessage } : {}), + }), + [columns, rows, rowKeyField, dirtyCells, deletedRowIndices, insertedRows, selectedRowIndices, sort, editable, loading, emptyMessage], + ); + return createElement('div', { + ref, + className, + style, + 'data-plugin-widget': 'data-grid', + 'data-plugin-widget-props': serialized, + }); +} + +export interface PluginSplitPaneProps { + direction?: 'horizontal' | 'vertical'; + initialSize?: number; + minSize?: number; + maxSize?: number; + collapsible?: boolean; + collapsed?: boolean; + className?: string; + style?: CSSProperties; + onResizeEnd?: (detail: { size: number; collapsed?: boolean }) => void; + children: ReactNode; +} + +/** Host-rendered 60fps resizable 2-child split pane container. */ +export function PluginSplitPane({ + direction = 'horizontal', + initialSize, + minSize, + maxSize, + collapsible, + collapsed, + className, + style, + onResizeEnd, + children, +}: PluginSplitPaneProps) { + const ref = useRef(null); + useWidgetEventBridge(ref, (eventName, detail) => { + if (eventName === 'resizeEnd') onResizeEnd?.(detail as { size: number; collapsed?: boolean }); + }); + const serialized = useMemo( + () => JSON.stringify({ + direction, + ...(initialSize !== undefined ? { initialSize } : {}), + ...(minSize !== undefined ? { minSize } : {}), + ...(maxSize !== undefined ? { maxSize } : {}), + ...(collapsible !== undefined ? { collapsible } : {}), + ...(collapsed !== undefined ? { collapsed } : {}), + }), + [direction, initialSize, minSize, maxSize, collapsible, collapsed], + ); + return createElement( + 'div', + { + ref, + className, + style, + 'data-plugin-widget': 'split-pane', + 'data-plugin-widget-props': serialized, + }, + children, + ); +} + +export interface PluginErColumn { + name: string; + type: string; + isPk?: boolean; + isFk?: boolean; + nullable?: boolean; +} + +export interface PluginErTable { + name: string; + schema?: string; + columns: PluginErColumn[]; + x?: number; + y?: number; +} + +export interface PluginErRelation { + fromTable: string; + fromColumn: string; + toTable: string; + toColumn: string; + name?: string; +} + +export interface PluginErCanvasProps { + tables: PluginErTable[]; + relations: PluginErRelation[]; + className?: string; + style?: CSSProperties; + onTableClick?: (detail: { table: string; schema?: string }) => void; +} + +/** Host-rendered interactive pan/zoom SVG ER diagram canvas. */ +export function PluginErCanvas({ + tables, + relations, + className, + style, + onTableClick, +}: PluginErCanvasProps) { + const ref = useRef(null); + useWidgetEventBridge(ref, (eventName, detail) => { + if (eventName === 'tableClick') onTableClick?.(detail as { table: string; schema?: string }); + }); + const serialized = useMemo( + () => JSON.stringify({ tables, relations }), + [tables, relations], + ); + return createElement('div', { + ref, + className, + style, + 'data-plugin-widget': 'er-canvas', + 'data-plugin-widget-props': serialized, + }); } diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.ts index 8e80fd11c..9f93f1f3c 100644 --- a/packages/plugin-sdk/src/index.test.ts +++ b/packages/plugin-sdk/src/index.test.ts @@ -55,6 +55,12 @@ const testSecretStore: PluginSecretStore = { async get() { return testSecretRef; }, + async getPlaintext() { + return "own-secret-value"; + }, + async readOwn() { + return "own-secret-value"; + }, async set() { return testSecretRef; }, diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts index 7ac3ff675..8e34f6d8b 100644 --- a/packages/plugin-sdk/src/index.ts +++ b/packages/plugin-sdk/src/index.ts @@ -72,11 +72,15 @@ export interface PluginKeyValueStore { get(key: string): Promise; set(key: string, value: JsonValue): Promise; delete(key: string): Promise; - keys(): Promise; + keys(options?: Readonly<{ prefix?: string }>): Promise; } export interface PluginSecretStore { get(key: string): Promise; + /** Reads plaintext of a secret previously stored by this plugin in its own encrypted namespace. */ + getPlaintext(key: string): Promise; + /** Alias for getPlaintext(key); strictly scoped to this plugin's own secrets, never Netcatty Vault credentials. */ + readOwn(key: string): Promise; set(key: string, value: string): Promise; delete(key: string): Promise; } @@ -110,10 +114,68 @@ export interface PluginCommands { executeCommand(commandId: string, args?: JsonValue): Promise; } +export interface PluginFileDialogFilter { + readonly name: string; + readonly extensions: readonly string[]; +} + +export interface PluginOpenFileOptions { + readonly title?: string; + readonly filters?: readonly PluginFileDialogFilter[]; + readonly readAs?: "bytes" | "utf8"; + readonly maxBytes?: number; +} + +export type PluginOpenFileResult = + | Readonly<{ cancelled: true }> + | Readonly<{ + cancelled: false; + name: string; + size: number; + handleId: string; + data: TData; + }>; + +export interface PluginSaveFileOptions { + readonly title?: string; + readonly defaultName?: string; + readonly filters?: readonly PluginFileDialogFilter[]; + readonly data: Uint8Array | ArrayBuffer | string; + readonly encoding?: "base64" | "utf8"; +} + +export type PluginSaveFileResult = + | Readonly<{ cancelled: true }> + | Readonly<{ + cancelled: false; + name: string; + size: number; + handleId: string; + }>; + +export interface PluginFileHandleWriteResult { + readonly bytesWritten: number; + readonly totalSize: number; +} + export interface PluginHostUI { quickPick(title: string, items: readonly import("@netcatty/plugin-contract").HostQuickPickItem[]): Promise; /** Single-line text. The host rejects CR/LF in initial values and submitted responses. */ input(title: string, initialValue?: string): Promise; + /** Opens a native OS file picker and returns contents + a revocable per-runtime file handle. */ + openFile(options?: PluginOpenFileOptions & Readonly<{ readAs: "utf8" }>): Promise>; + openFile(options?: PluginOpenFileOptions & Readonly<{ readAs?: "bytes" }>): Promise>; + openFile(options?: PluginOpenFileOptions): Promise; + /** Opens a native OS save dialog and writes atomically, returning a revocable per-runtime file handle. */ + saveFile(options: PluginSaveFileOptions): Promise; + /** Reads from a previously user-picked file handle without re-prompting. */ + readFileHandle(handleId: string, options: Readonly<{ readAs: "utf8" }>): Promise; + readFileHandle(handleId: string, options?: Readonly<{ readAs?: "bytes" }>): Promise; + readFileHandle(handleId: string, options?: Readonly<{ readAs?: "bytes" | "utf8" }>): Promise; + /** Atomically writes back to a previously user-picked file handle without re-prompting. */ + writeFileHandle(handleId: string, data: Uint8Array | ArrayBuffer | string, options?: Readonly<{ encoding?: "base64" | "utf8" }>): Promise; + /** Releases a user-picked file handle. */ + closeFileHandle(handleId: string): Promise; } /** Saved-host selection does not grant editing, connecting or session access. @@ -124,6 +186,8 @@ export interface PluginVault { /** Managed SSH-config drafts require the full Vault host editor. */ requestHostDraft(params: import("@netcatty/plugin-contract").VaultHostDraftParams): Promise; requestConnect(params: import("@netcatty/plugin-contract").VaultHostConnectParams): Promise; + /** Revokes a previously remembered durable SSH tunnel binding token. */ + revokeHostBinding(hostBindingToken: string): Promise>; } export interface PluginClipboard { @@ -701,10 +765,20 @@ export interface PluginAgentClient { closeChat(params: import("@netcatty/plugin-contract").PluginAgentChatRef): Promise; } +export interface PluginByteStreamUpgradeTlsOptions { + readonly servername?: string; + readonly allowSelfSigned?: boolean; + readonly caPem?: string; +} + export interface PluginByteConnection extends Disposable { readonly endpoint: string; + /** Present when connectViaHost created or reused a durable SSH tunnel binding. */ + readonly hostBindingToken?: string; readonly readable: PluginReadableByteStream; readonly writable: PluginWritableByteStream; + /** Performs an in-band STARTTLS upgrade on an open plaintext byte stream. */ + upgradeTls(options?: PluginByteStreamUpgradeTlsOptions): Promise; /** Closes both directions. Repeated calls on this handle are harmless. */ close(): Promise; } @@ -985,7 +1059,7 @@ export function throwIfCancellationRequested(token: CancellationToken): void { } export { PLUGIN_NETWORK_CREDENTIAL_LEASE_FEATURE } from "@netcatty/plugin-contract"; -export { PLUGIN_BYTE_STREAM_FEATURE, PLUGIN_BYTE_STREAM_LIMITS } from "@netcatty/plugin-contract"; +export { PLUGIN_BYTE_STREAM_FEATURE, PLUGIN_HOST_BYTE_STREAM_FEATURE, PLUGIN_BYTE_STREAM_LIMITS } from "@netcatty/plugin-contract"; export { PLUGIN_AI_MODEL_INVOCATION_FEATURE, PLUGIN_SELECTED_CONTEXT_FEATURE } from "@netcatty/plugin-contract"; export { PLUGIN_HOST_INTERACTION_FEATURE } from "@netcatty/plugin-contract"; diff --git a/scripts/generate-plugin-contract.mjs b/scripts/generate-plugin-contract.mjs index 2f8922ce5..cb7c78f06 100644 --- a/scripts/generate-plugin-contract.mjs +++ b/scripts/generate-plugin-contract.mjs @@ -22,7 +22,7 @@ const electronBundlePath = path.join( ); const checkOnly = process.argv.includes("--check"); const typescriptTypeOverrides = new Map([ - ["PermissionDeclaration", 'Exclude | PermissionResourceDeclaration'], + ["PermissionDeclaration", "PluginPermission | PermissionResourceDeclaration"], [ "ActivationEvent", '"onStartupFinished" | `onCommand:${ContributionId}` | `onView:${ContributionId}` | `onProvider:${ContributionId}`', From 1595d2ed62a7cf53ee412ef015fe0115ac52d130 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:03:26 +0800 Subject: [PATCH 06/24] style(plugins): apply immersive overlay scrollbars to plugin surfaces and data grid (#4438) --- components/plugins/PluginRemoteSurface.tsx | 12 ++++++++++-- components/plugins/primitives/PluginDataGrid.tsx | 5 ++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/components/plugins/PluginRemoteSurface.tsx b/components/plugins/PluginRemoteSurface.tsx index 44cd3804b..5f137524c 100644 --- a/components/plugins/PluginRemoteSurface.tsx +++ b/components/plugins/PluginRemoteSurface.tsx @@ -343,6 +343,14 @@ export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadIm ); } +const SHADOW_BASE_SCROLLBAR_CSS = [ + '*::-webkit-scrollbar{width:6px;height:6px}', + '*::-webkit-scrollbar-track,*::-webkit-scrollbar-corner{background:transparent}', + '*::-webkit-scrollbar-thumb{min-height:28px;border:1px solid transparent;border-radius:999px;background-color:transparent;background-clip:content-box}', + '*:hover::-webkit-scrollbar-thumb{background-color:hsl(var(--muted-foreground) / 0.24)}', + '*::-webkit-scrollbar-thumb:hover{background-color:hsl(var(--muted-foreground) / 0.45)}', +].join(''); + function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: { settled: boolean; depth: number; tree: { children: RemoteNode[] }; css: string; onEvent(event: PluginSurfaceEvent): void }) { const surfaceRef = useRef(null); const hostRef = useRef(null); @@ -467,8 +475,8 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: { return (
-
- {shadow && createPortal(<>{tree.children.map((node) => renderRemoteNode(node, settled))}, shadow)} +
+ {shadow && createPortal(<>{tree.children.map((node) => renderRemoteNode(node, settled))}, shadow)}
); diff --git a/components/plugins/primitives/PluginDataGrid.tsx b/components/plugins/primitives/PluginDataGrid.tsx index d885c4917..fd8ff5b1b 100644 --- a/components/plugins/primitives/PluginDataGrid.tsx +++ b/components/plugins/primitives/PluginDataGrid.tsx @@ -272,7 +272,10 @@ export function PluginDataGrid({
)} -
+
{columns.length === 0 ? (
{emptyMessage} From a0f7a376db0f3075870bff722e7e5707322ce6c0 Mon Sep 17 00:00:00 2001 From: Imzl-zl <69853158+Imzl-zl@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:52:09 +0800 Subject: [PATCH 07/24] fix(tabs): respect configured SSH names and dynamic title modes (#4409) Fixes #4432 Fixes #4436 --- ...mptHostnameSessionSignalController.test.ts | 44 +++- .../promptHostnameSessionSignalController.ts | 21 +- components/TopTabs.test.ts | 28 +- components/top-tabs/TopTabItems.tsx | 21 +- domain/sessionTabTitle.test.ts | 246 +++++++++++++++++- domain/sessionTabTitle.ts | 124 +++++---- scripts/fixtures/ssh-tab-title-policy.tsx | 242 +++++++++++++++++ scripts/ssh-tab-title-policy.live.test.cjs | 125 +++++++++ 8 files changed, 756 insertions(+), 95 deletions(-) create mode 100644 scripts/fixtures/ssh-tab-title-policy.tsx create mode 100644 scripts/ssh-tab-title-policy.live.test.cjs diff --git a/application/state/promptHostnameSessionSignalController.test.ts b/application/state/promptHostnameSessionSignalController.test.ts index f76a25e7a..6a236bd58 100644 --- a/application/state/promptHostnameSessionSignalController.test.ts +++ b/application/state/promptHostnameSessionSignalController.test.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { createPromptHostnameSessionSignalController } from './promptHostnameSessionSignalController.ts'; +import { extractTerminalPromptHostname } from '../../domain/terminalPromptSecurity'; type Change = readonly [sessionId: string, hostname: string | null]; @@ -20,10 +21,34 @@ function createHarness() { return { changes, controller }; } -test('prompt host controller ignores the initial jumpserver prompt', () => { +test('prompt observations are independent of IP, alias, and matching connection addresses', () => { + const prompt = '[root@vm-prod ~]# '; + const observedHost = extractTerminalPromptHostname(prompt)!; + for (const hostname of ['203.0.113.10', 'alias.example.test', observedHost]) { + const changes: Change[] = []; + const controller = createPromptHostnameSessionSignalController({ + getSession: () => ({ protocol: 'ssh', hostname }), + onChange: (sessionId, host) => changes.push([sessionId, host]), + }); + controller.handleTerminalOutput('ssh-1', prompt); + assert.deepEqual(changes, [['ssh-1', observedHost]], hostname); + } +}); + +test('forgetting a session permits the first matching-host prompt to publish again', () => { + const { changes, controller } = createHarness(); + const prompt = '[root@jump.example.com ~]# '; + const observedHost = extractTerminalPromptHostname(prompt)!; + controller.handleTerminalOutput('ssh-1', prompt); + controller.forgetSession('ssh-1'); + controller.handleTerminalOutput('ssh-1', prompt); + assert.deepEqual(changes, [['ssh-1', observedHost], ['ssh-1', observedHost]]); +}); + +test('prompt host controller observes the initial jumpserver prompt', () => { const { changes, controller } = createHarness(); controller.handleTerminalOutput('ssh-1', 'Last login\r\n[root@jump.example.com ~]# '); - assert.deepEqual(changes, []); + assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname]]); }); test('prompt host controller publishes a nested target and de-duplicates it', () => { @@ -31,17 +56,18 @@ test('prompt host controller publishes a nested target and de-duplicates it', () controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# '); controller.handleTerminalOutput('ssh-1', 'ssh root@10.1.64.1\r\n[root@10.1.64.1 ~]# '); controller.handleTerminalOutput('ssh-1', '\r\n[root@10.1.64.1 ~]# '); - assert.deepEqual(changes, [['ssh-1', '10.1.64.1']]); + assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname], ['ssh-1', '10.1.64.1']]); }); -test('prompt host controller clears the override when returning to the jumpserver', () => { +test('prompt host controller observes the original host when returning from a target', () => { const { changes, controller } = createHarness(); controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# '); controller.handleTerminalOutput('ssh-1', '\r\n[root@10.1.64.1 ~]# '); controller.handleTerminalOutput('ssh-1', 'exit\r\n[root@jump.example.com ~]# '); assert.deepEqual(changes, [ + ['ssh-1', getSession('ssh-1').hostname], ['ssh-1', '10.1.64.1'], - ['ssh-1', null], + ['ssh-1', getSession('ssh-1').hostname], ]); }); @@ -50,26 +76,28 @@ test('prompt host controller detects an identity split across output chunks', () controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# '); controller.handleTerminalOutput('ssh-1', 'ssh target\r\n[root@10.1.'); controller.handleTerminalOutput('ssh-1', '64.1 ~]# '); - assert.deepEqual(changes, [['ssh-1', '10.1.64.1']]); + assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname], ['ssh-1', '10.1.64.1']]); }); test('prompt host controller ignores ambiguous, sensitive, and local output', () => { const { changes, controller } = createHarness(); controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# '); + const initialChanges = changes.slice(); controller.handleTerminalOutput('ssh-1', 'Password:\n# '); controller.handleTerminalOutput('ssh-1', 'copied output\n# '); controller.handleTerminalOutput('local-1', '[root@10.1.64.1 ~]# '); - assert.deepEqual(changes, []); + assert.deepEqual(changes, initialChanges); }); test('prompt host controller ignores host-like text embedded in copied output', () => { const { changes, controller } = createHarness(); controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# '); + const initialChanges = changes.slice(); controller.handleTerminalOutput('ssh-1', 'see [root@prod] logs\n# '); controller.handleTerminalOutput('ssh-1', '[root@prod] copied output\n# '); controller.handleTerminalOutput('ssh-1', 'root@prod output\n# '); controller.handleTerminalOutput('ssh-1', '[root@prod] version = 1.2\n# '); - assert.deepEqual(changes, []); + assert.deepEqual(changes, initialChanges); }); test('prompt host controller publishes common zsh, Alpine, and macOS root prompt hosts', () => { diff --git a/application/state/promptHostnameSessionSignalController.ts b/application/state/promptHostnameSessionSignalController.ts index 105e6868e..1b76bc1ac 100644 --- a/application/state/promptHostnameSessionSignalController.ts +++ b/application/state/promptHostnameSessionSignalController.ts @@ -5,7 +5,7 @@ import { } from '../../domain/terminalPromptSecurity'; type PromptHostnameSessionSignalOptions = { - getSession: (sessionId: string) => Pick | undefined; + getSession: (sessionId: string) => Pick | undefined; onChange: (sessionId: string, hostname: string | null) => void; maxTailChars?: number; }; @@ -22,20 +22,18 @@ export function createPromptHostnameSessionSignalController({ maxTailChars = DEFAULT_MAX_TAIL_CHARS, }: PromptHostnameSessionSignalOptions) { const tails = new Map(); - const baselines = new Map(); const published = new Map(); const tailLimit = Math.max(256, maxTailChars); const forgetSession = (sessionId: string): void => { tails.delete(sessionId); - baselines.delete(sessionId); published.delete(sessionId); }; return { forgetSession, pruneSessions(validSessionIds: ReadonlySet): void { - for (const sessionId of [...tails.keys(), ...baselines.keys(), ...published.keys()]) { + for (const sessionId of [...tails.keys(), ...published.keys()]) { if (!validSessionIds.has(sessionId)) { forgetSession(sessionId); } @@ -65,19 +63,8 @@ export function createPromptHostnameSessionSignalController({ const detectedKey = normalizedHostname(detected); if (!detectedKey) return; - let baseline = baselines.get(sessionId); - if (baseline === undefined) { - baseline = normalizedHostname(session.hostname) || detectedKey; - baselines.set(sessionId, baseline); - } - - if (detectedKey === baseline) { - if (!published.has(sessionId)) return; - published.delete(sessionId); - onChange(sessionId, null); - return; - } - + // Observe the prompt, not whether its hostname matches an IP or DNS alias. + // The domain title policy decides if this presentation is shown. if (published.get(sessionId) === detectedKey) return; published.set(sessionId, detectedKey); onChange(sessionId, detected); diff --git a/components/TopTabs.test.ts b/components/TopTabs.test.ts index 7a9e68205..7e9755cfb 100644 --- a/components/TopTabs.test.ts +++ b/components/TopTabs.test.ts @@ -80,7 +80,7 @@ test("host tree tab gutter style animates only when host tree transitions and yi }); }); -test("workspace tabs resolve generated labels from live prompt hosts", () => { +test("workspace tabs resolve generated labels from live prompt hosts in all mode", () => { const sessions = [ topTabSession("s1", "h1", { customName: "", promptHostname: "" }), topTabSession("s2", "h2", { customName: "", promptHostname: "" }), @@ -95,7 +95,7 @@ test("workspace tabs resolve generated labels from live prompt hosts", () => { publishSessionPromptHost("s1", "target-a"); publishSessionPromptHost("s2", "target-b"); assert.equal( - resolveWorkspaceTopTabLabel(workspace, sessions), + resolveWorkspaceTopTabLabel(workspace, sessions, "all"), "target-a/target-b", ); @@ -103,6 +103,30 @@ test("workspace tabs resolve generated labels from live prompt hosts", () => { sessionPresentationStore.clearSession("s2"); }); +test("generated workspace tabs keep saved names in disabled and agent-only modes", (t) => { + const sessions = [ + topTabSession("mode-s1", "h1", { hostLabel: "Production" }), + topTabSession("mode-s2", "h2", { hostLabel: "Database" }), + ]; + t.after(() => sessions.forEach((session) => sessionPresentationStore.clearSession(session.id))); + const savedTitle = sessions.map((session) => session.hostLabel).join("/"); + const workspace = { title: savedTitle, autoTitle: false, generatedTitle: true, focusedSessionId: "mode-s1" }; + publishSessionPromptHost("mode-s1", "vm-prod"); + publishSessionPromptHost("mode-s2", "db-prod"); + for (const mode of [undefined, "off", "agent"] as const) { + assert.equal(resolveWorkspaceTopTabLabel(workspace, sessions, mode), savedTitle, String(mode)); + } +}); + +test("auto workspace tabs apply presentation with the current mode", (t) => { + const session = topTabSession("auto-mode", "h1", { hostLabel: "Production" }); + t.after(() => sessionPresentationStore.clearSession(session.id)); + const workspace = { title: "Workspace", autoTitle: true, focusedSessionId: session.id }; + publishSessionPromptHost(session.id, "vm-prod"); + assert.equal(resolveWorkspaceTopTabLabel(workspace, [session], "off"), session.hostLabel); + assert.equal(resolveWorkspaceTopTabLabel(workspace, [session], "all"), "vm-prod"); +}); + test("workspace tabs keep explicit names ahead of live prompt hosts", () => { const sessions = [ topTabSession("s1", "h1", { customName: "", promptHostname: "" }), diff --git a/components/top-tabs/TopTabItems.tsx b/components/top-tabs/TopTabItems.tsx index 9f4072097..61ad699ba 100644 --- a/components/top-tabs/TopTabItems.tsx +++ b/components/top-tabs/TopTabItems.tsx @@ -26,8 +26,6 @@ import { resolveSessionCodingCliProvider } from '../../domain/codingCliProviderM import type { CodingCliProvider } from '../../domain/codingCliProviders'; import { resolveCodingCliActivityPhase, type CodingCliActivityPhase } from '../../domain/codingCliTitleParse'; import { - buildMergedWorkspaceTitleFromSessions, - DEFAULT_WORKSPACE_TITLE, resolveSessionTabTitle, resolveWorkspaceTabLabel, } from '../../domain/sessionTabTitle'; @@ -261,24 +259,15 @@ export const formatSessionTopTabLabel = ( type WorkspaceTopTabLabelWorkspace = Pick< Workspace, - 'title' | 'focusedSessionId' | 'autoTitle' -> & { - generatedTitle?: boolean; -}; + 'title' | 'focusedSessionId' | 'autoTitle' | 'generatedTitle' +>; export const resolveWorkspaceTopTabLabel = ( workspace: WorkspaceTopTabLabelWorkspace, sessions: readonly TerminalSession[], + dynamicTabTitleMode?: DynamicTabTitleMode, ): string => { - const presentedSessions = sessions.map(applySessionPresentation); - const resolvedWorkspace = workspace.generatedTitle - ? { - ...workspace, - title: buildMergedWorkspaceTitleFromSessions(presentedSessions) ?? DEFAULT_WORKSPACE_TITLE, - autoTitle: false, - } - : workspace; - return resolveWorkspaceTabLabel(resolvedWorkspace, presentedSessions); + return resolveWorkspaceTabLabel(workspace, sessions.map(applySessionPresentation), dynamicTabTitleMode); }; export const createTopTabCopyDoubleClickHandler = ( @@ -1106,7 +1095,7 @@ export const WorkspaceTopTab: React.FC = memo(({ [onCopyWorkspace, workspace.id, tabDoubleClickBehavior], ); const detachSessions = workspaceSessions ?? []; - const tabLabel = resolveWorkspaceTopTabLabel(workspace, detachSessions); + const tabLabel = resolveWorkspaceTopTabLabel(workspace, detachSessions, dynamicTabTitleMode); return ( diff --git a/domain/sessionTabTitle.test.ts b/domain/sessionTabTitle.test.ts index 3d807640c..e50958a77 100644 --- a/domain/sessionTabTitle.test.ts +++ b/domain/sessionTabTitle.test.ts @@ -22,6 +22,68 @@ test('getSessionConnectionLabel prefers customName over hostLabel', () => { ); }); +test('connection identity ignores live prompt hostnames', () => { + const session = { hostLabel: 'Production', promptHostname: 'vm-prod' }; + assert.equal(getSessionConnectionLabel(session), session.hostLabel); +}); + +test('ordinary SSH prompt hostnames do not replace configured names by default', () => { + const session = { hostLabel: 'Production', promptHostname: 'vm-prod' }; + for (const mode of [undefined, 'off', 'agent'] as const) { + assert.equal(resolveSessionTabTitle(session, mode), session.hostLabel, String(mode)); + } +}); + +test('agent mode does not use a prompt hostname when the agent has no title', () => { + const session = { + hostLabel: 'Production', promptHostname: 'vm-prod', codingCliProviderId: 'claude' as const, + }; + assert.equal(resolveSessionTabTitle(session, 'agent'), session.hostLabel); +}); + +test('persisted merged workspace identities ignore live hostnames', () => { + const sessions = [ + { id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod' }, + { id: 'b', hostId: 'h2', hostLabel: 'Database', promptHostname: 'db-prod' }, + ]; + assert.equal( + buildMergedWorkspaceTitleFromSessions(sessions), + buildMergedWorkspaceTitle(sessions[0].hostLabel, sessions[1].hostLabel), + ); +}); + +test('auto workspace labels honor disabled and agent-only modes', () => { + const session = { id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod' }; + const workspace = { title: DEFAULT_WORKSPACE_TITLE, autoTitle: true, focusedSessionId: session.id }; + for (const mode of [undefined, 'off', 'agent'] as const) { + assert.equal(resolveWorkspaceTabLabel(workspace, [session], mode), session.hostLabel, String(mode)); + } +}); + +test('auto workspace labels use the same agent title policy as session tabs', () => { + const session = { + id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod', + dynamicTitle: 'claude: deploy', codingCliProviderId: 'claude' as const, + }; + const workspace = { title: DEFAULT_WORKSPACE_TITLE, autoTitle: true, focusedSessionId: session.id }; + assert.equal(resolveWorkspaceTabLabel(workspace, [session], 'agent'), session.dynamicTitle); +}); + +test('generated workspace display titles honor mode without changing their saved identity', () => { + const sessions = [ + { id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod' }, + { id: 'b', hostId: 'h2', hostLabel: 'Database', promptHostname: 'db-prod' }, + ]; + const savedTitle = buildMergedWorkspaceTitle(sessions[0].hostLabel, sessions[1].hostLabel)!; + const workspace = { title: savedTitle, autoTitle: false, generatedTitle: true, focusedSessionId: 'a' }; + assert.equal(resolveWorkspaceTabLabel(workspace, sessions, 'off'), savedTitle); + assert.equal( + resolveWorkspaceTabLabel(workspace, sessions, 'all'), + buildMergedWorkspaceTitle(sessions[0].promptHostname, sessions[1].promptHostname), + ); + assert.equal(workspace.title, savedTitle); +}); + test('resolveSessionTabTitle ignores dynamic title for non-agent sessions', () => { assert.equal( resolveSessionTabTitle( @@ -85,12 +147,12 @@ test('resolveSessionTabTitle strips agent spinner prefixes from dynamic titles', ); }); -test('resolveSessionTabTitle uses a detected prompt host ahead of hostLabel', () => { +test('resolveSessionTabTitle uses a detected prompt host in all mode', () => { assert.equal( resolveSessionTabTitle({ hostLabel: 'jumpserver', promptHostname: '10.1.64.1', - }), + }, 'all'), '10.1.64.1', ); }); @@ -300,3 +362,183 @@ test('buildMergedWorkspaceTitleFromSessions recomputes from live membership', () '01/02', ); }); + +// External review examples: the expected field is part of the contract, not +// computed by resolveSessionTabTitle or another display-title helper. +const reviewedAllTitleCases = [ + { + name: 'same-host shell title retains username and cwd', + session: { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle: 'ubuntu@web01: ~/app' }, + expectedField: 'dynamicTitle', + }, + { + name: 'old shell host gives way to the current prompt host', + session: { hostLabel: 'Database entry', promptHostname: 'db02', dynamicTitle: 'ubuntu@web01: ~/app' }, + expectedField: 'promptHostname', + }, + { + name: 'JumpServer transport title gives way to the target prompt host', + session: { hostLabel: 'Jump fleet', promptHostname: 'target-01', dynamicTitle: 'user@jumpssh:2222' }, + expectedField: 'promptHostname', + }, + { + name: 'program title retains its document context', + session: { hostLabel: 'Editor server', promptHostname: 'web01', dynamicTitle: 'vim README.md' }, + expectedField: 'dynamicTitle', + }, +] as const; + +for (const { name, session, expectedField } of reviewedAllTitleCases) { + test(`all title policy review: ${name}`, () => { + assert.equal(resolveSessionTabTitle(session, 'all'), session[expectedField]); + }); +} + +test('all title policy compares shell hostnames case-insensitively without rewriting the title', () => { + const session = { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle: 'ubuntu@WEB01: ~/app' }; + assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle); +}); + +test('all title policy ignores one FQDN trailing dot only when comparing host identity', () => { + for (const session of [ + { hostLabel: 'Production', promptHostname: 'WEB01.EXAMPLE.TEST', dynamicTitle: 'ubuntu@web01.example.test.: ~/app' }, + { hostLabel: 'Production', promptHostname: 'web01.example.test.', dynamicTitle: 'ubuntu@WEB01.EXAMPLE.TEST: /srv' }, + ]) { + assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle); + } +}); + +test('all title policy equates bracketed IPv6 title hosts with the same literal prompt address', () => { + const session = { + hostLabel: 'IPv6 production', promptHostname: '2001:DB8::A', dynamicTitle: 'root@[2001:db8::a]: ~/app', + }; + assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle); +}); + +test('all title policy rejects a clearly different bracketed IPv6 title host', () => { + const session = { + hostLabel: 'IPv6 production', promptHostname: '2001:db8::b', dynamicTitle: 'root@[2001:db8::a]: /srv', + }; + assert.equal(resolveSessionTabTitle(session, 'all'), session.promptHostname); +}); + +test('all title policy does not treat embedded email or URI text as a shell host report', () => { + for (const dynamicTitle of [ + 'vim maintainer@old.example.test:notes.txt', + 'Issue for maintainer@old.example.test', + 'https://maintainer@old.example.test/docs', + 'mailto:maintainer@old.example.test', + ]) { + const session = { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle }; + assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle); + } +}); + +test('reviewed shell and program titles remain disabled in default off and agent modes', () => { + for (const { session } of reviewedAllTitleCases) { + for (const mode of [undefined, 'off', 'agent'] as const) { + assert.equal(resolveSessionTabTitle(session, mode), session.hostLabel); + } + } +}); + +test('manual names stay authoritative for every reviewed title and mode', () => { + for (const example of reviewedAllTitleCases) { + const session = { ...example.session, customName: 'Operator production tab' }; + for (const mode of [undefined, 'off', 'agent', 'all'] as const) { + assert.equal(resolveSessionTabTitle(session, mode), session.customName); + } + } +}); + +test('active Agent titles retain priority over reviewed prompt identities only in enabled modes', () => { + for (const example of reviewedAllTitleCases) { + const session = { ...example.session, codingCliProviderId: 'claude' as const, dynamicTitle: 'claude: deploy' }; + for (const mode of [undefined, 'agent', 'all'] as const) { + assert.equal(resolveSessionTabTitle(session, mode), session.dynamicTitle); + } + assert.equal(resolveSessionTabTitle(session, 'off'), session.hostLabel); + } +}); + +const reviewedWorkspaceSessions = reviewedAllTitleCases.map(({ session }, index) => ({ + ...session, id: `review-pane-${index}`, hostId: `review-host-${index}`, +})); +const reviewedWorkspaceLabels = reviewedAllTitleCases.map(({ session, expectedField }) => session[expectedField]); + +test('auto workspace titles apply the reviewed all policy to the focused pane', () => { + for (let index = 0; index < reviewedWorkspaceSessions.length; index += 1) { + const session = reviewedWorkspaceSessions[index]; + const workspace = { title: DEFAULT_WORKSPACE_TITLE, autoTitle: true, focusedSessionId: session.id }; + assert.equal( + resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, 'all'), + `${reviewedWorkspaceLabels[index]} +${reviewedWorkspaceSessions.length - 1}`, + ); + for (const mode of [undefined, 'off', 'agent'] as const) { + assert.equal( + resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, mode), + `${session.hostLabel} +${reviewedWorkspaceSessions.length - 1}`, + ); + } + } +}); + +test('generated workspace display titles apply the reviewed policy without changing stored names', () => { + const workspace = { + title: reviewedWorkspaceSessions.map(session => session.hostLabel).join('/'), + autoTitle: false, generatedTitle: true, focusedSessionId: reviewedWorkspaceSessions[0].id, + }; + const storedTitle = workspace.title; + assert.equal( + resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, 'all'), + reviewedWorkspaceLabels.join('/'), + ); + for (const mode of [undefined, 'off', 'agent'] as const) { + assert.equal(resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, mode), storedTitle); + } + assert.equal(workspace.title, storedTitle); +}); + +test('all title policy preserves bare emails and suffixes without shell or port evidence', () => { + for (const dynamicTitle of [ + 'maintainer@old.example.test', + 'ubuntu@old.example.test: notes.txt', + 'ubuntu@old.example.test:0', + 'ubuntu@old.example.test:65536', + 'ubuntu@old.example.test:999999', + 'ubuntu@old.example.test:22garbage', + ]) { + const session = { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle }; + assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle); + } +}); + +test('all title policy recognizes legal endpoint port boundaries', () => { + for (const port of [1, 65_535]) { + const session = { hostLabel: 'Jump fleet', promptHostname: 'target', dynamicTitle: `ubuntu@jump:${port}` }; + assert.equal(resolveSessionTabTitle(session, 'all'), session.promptHostname); + } +}); + +test('all title policy does not infer short names or matching first labels as aliases', () => { + for (const reportedHost of ['web', 'web.dev.example']) { + const session = { + hostLabel: 'Production', promptHostname: 'web.prod.example', dynamicTitle: `root@${reportedHost}: /srv`, + }; + assert.equal(resolveSessionTabTitle(session, 'all'), session.promptHostname); + } +}); + +test('all title policy preserves titles with invalid bracketed host addresses', () => { + for (const reportedHost of ['not-ip', '2001:db8:::1']) { + const session = { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle: `root@[${reportedHost}]: ~/app` }; + assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle); + } +}); + +test('explicit workspace names ignore all reviewed live title shapes', () => { + const workspace = { title: 'Operator layout', autoTitle: false, generatedTitle: false }; + for (const mode of [undefined, 'off', 'agent', 'all'] as const) { + assert.equal(resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, mode), workspace.title); + } +}); diff --git a/domain/sessionTabTitle.ts b/domain/sessionTabTitle.ts index 2aa7faa28..20b5c887f 100644 --- a/domain/sessionTabTitle.ts +++ b/domain/sessionTabTitle.ts @@ -3,11 +3,21 @@ import type { CodingCliProviderId } from './codingCliProviders'; import { normalizeCodingCliTitle } from './codingCliTitleParse'; import type { DynamicTabTitleMode } from './models/terminal'; -/** Connection label: user rename, live prompt host, then configured host label. */ +/** Configured connection label, independent of live terminal presentation. */ export const getSessionConnectionLabel = ( - session: Pick, + session: Pick, ): string => { - return session.customName || session.promptHostname || session.hostLabel || ''; + return session.customName || session.hostLabel || ''; +}; + +type SessionTabLabelSession = Pick< + TerminalSession, + 'customName' | 'hostLabel' | 'promptHostname' | 'dynamicTitle' | 'codingCliProviderId' +>; + +const joinWorkspaceLabels = (labels: readonly string[]): string | null => { + const uniqueLabels = [...new Set(labels.map((label) => label.trim()).filter(Boolean))]; + return uniqueLabels.length > 0 ? uniqueLabels.join('/') : null; }; /** @@ -31,18 +41,10 @@ export const buildMergedWorkspaceTitle = ( baseLabel: string, joiningLabel: string, ): string | null => { - const base = baseLabel.trim(); - const joining = joiningLabel.trim(); - if (!base && !joining) return null; - if (!base) return joining; - if (!joining || joining === base) return base; - return `${base}/${joining}`; + return joinWorkspaceLabels([baseLabel, joiningLabel]); }; -type WorkspaceTabLabelSession = Pick< - TerminalSession, - 'id' | 'customName' | 'hostLabel' | 'hostId' | 'promptHostname' ->; +type WorkspaceTabLabelSession = Pick & SessionTabLabelSession; /** * Recompute a merged workspace's composed title from its *current* member @@ -57,14 +59,7 @@ type WorkspaceTabLabelSession = Pick< export const buildMergedWorkspaceTitleFromSessions = ( sessions: readonly WorkspaceTabLabelSession[], ): string | null => { - const labels: string[] = []; - for (const session of sessions) { - const label = getSessionConnectionLabel(session).trim(); - if (!label || labels.includes(label)) continue; - labels.push(label); - } - if (labels.length === 0) return null; - return labels.join('/'); + return joinWorkspaceLabels(sessions.map(getSessionConnectionLabel)); }; /** @@ -75,17 +70,26 @@ export const buildMergedWorkspaceTitleFromSessions = ( * workspace holds sessions for more than one distinct host, the focused host is * shown with a "+N" suffix for the others. * - * Uses the stable connection label (rename / host label) rather than the - * dynamic shell/agent title: those live titles are published only to the - * session presentation store (not the plain session records passed here), and - * they can differ per-pane on a single host — counting them would both go stale - * and produce a bogus "+N". The host identity is what this tab is about. + * Presented sessions use the same title policy as individual tabs. Generated + * merge titles are display-only compositions; their persisted identity is built + * separately by buildMergedWorkspaceTitleFromSessions. Host counts always use + * hostId, never a dynamic title or per-pane rename. */ export const resolveWorkspaceTabLabel = ( - workspace: { title?: string; focusedSessionId?: string | null; autoTitle?: boolean }, + workspace: { + title?: string; + focusedSessionId?: string | null; + autoTitle?: boolean; + generatedTitle?: boolean; + }, sessions: readonly WorkspaceTabLabelSession[], + dynamicTabTitleMode: DynamicTabTitleMode = 'agent', ): string => { const title = workspace.title?.trim(); + if (workspace.generatedTitle) { + return joinWorkspaceLabels(sessions.map((session) => resolveSessionTabTitle(session, dynamicTabTitleMode))) + ?? DEFAULT_WORKSPACE_TITLE; + } // Derive a host label only for an auto-titled workspace. The `autoTitle` flag // is authoritative when present (so a workspace a user explicitly named // "Workspace" is kept, not overwritten); legacy workspaces without the flag @@ -98,7 +102,7 @@ export const resolveWorkspaceTabLabel = ( return title || DEFAULT_WORKSPACE_TITLE; } const focused = sessions.find((s) => s.id === workspace.focusedSessionId) ?? sessions[0]; - const primary = getSessionConnectionLabel(focused); + const primary = resolveSessionTabTitle(focused, dynamicTabTitleMode); // Count distinct HOSTS by hostId, the only stable host identity: a rename // rewrites both customName and hostLabel (useSessionState.submitSessionRename), // so neither is safe to count by — a renamed pane on the same host would add a @@ -130,38 +134,58 @@ export const resolveCodingCliProviderIconUpdate = ({ return nextProviderId; }; +const shellTitleHostname = (title: string): string | undefined => { + // A title is not a prompt: require an anchored identity plus cwd/port evidence, + // so program titles, email addresses, and URIs do not become host reports. + const match = /^[a-z0-9_.+-]+@(\[[^\]\s]+\]|[a-z0-9][a-z0-9_.-]*):\s*(.*)$/iu.exec(title); + if (!match) return undefined; + const [, hostname, suffix] = match; + const isPath = /^(?:~(?:\/|$)|\/)/u.test(suffix); + const isPort = /^\d{1,5}$/u.test(suffix) && Number(suffix) > 0 && Number(suffix) <= 65_535; + if (!isPath && !isPort) return undefined; + if (hostname.startsWith('[')) { + try { + // Validate IPv6 brackets only; do not use URL canonicalization to infer + // aliases or compressed/expanded address equivalence. + new URL(`http://${hostname}/`); + } catch { + return undefined; + } + } + return hostname; +}; + +const titleHostnameKey = (hostname: string): string => + hostname.replace(/^\[(.*)\]$/u, '$1').replace(/\.$/u, '').toLowerCase(); + /** * Resolve the label shown on session tabs and pane headers. - * Uses the shell-reported title according to the global dynamic title mode. + * Live prompt and Shell titles require all mode; agent mode permits Agent titles only. */ export const resolveSessionTabTitle = ( - session: Pick< - TerminalSession, - 'customName' | 'hostLabel' | 'promptHostname' | 'dynamicTitle' | 'codingCliProviderId' - >, + session: SessionTabLabelSession, dynamicTabTitleMode: DynamicTabTitleMode = 'agent', ): string => { const connectionLabel = getSessionConnectionLabel(session); - if (session.customName) { - return session.customName; + if (session.customName || dynamicTabTitleMode === 'off') { + return connectionLabel; } - if (dynamicTabTitleMode !== 'off' && session.codingCliProviderId) { - const agentTitle = session.dynamicTitle?.trim(); - if (agentTitle) return normalizeCodingCliTitle(agentTitle) || agentTitle; + + const rawTitle = session.dynamicTitle?.trim(); + const dynamicTitle = rawTitle ? normalizeCodingCliTitle(rawTitle) || rawTitle : undefined; + if (session.codingCliProviderId && dynamicTitle) { + return dynamicTitle; + } + if (dynamicTabTitleMode !== 'all') { + return connectionLabel; } const promptHostname = session.promptHostname?.trim(); + if (!dynamicTitle) return promptHostname || connectionLabel; if (promptHostname) { - return promptHostname; + const reportedHost = shellTitleHostname(dynamicTitle); + if (reportedHost && titleHostnameKey(reportedHost) !== titleHostnameKey(promptHostname)) { + return promptHostname; + } } - if (dynamicTabTitleMode === 'off') { - return connectionLabel; - } - if (dynamicTabTitleMode === 'agent' && !session.codingCliProviderId) { - return connectionLabel; - } - const dynamicTitle = session.dynamicTitle?.trim(); - if (!dynamicTitle) { - return connectionLabel; - } - return normalizeCodingCliTitle(dynamicTitle) || dynamicTitle; + return dynamicTitle; }; diff --git a/scripts/fixtures/ssh-tab-title-policy.tsx b/scripts/fixtures/ssh-tab-title-policy.tsx new file mode 100644 index 000000000..93c0eac43 --- /dev/null +++ b/scripts/fixtures/ssh-tab-title-policy.tsx @@ -0,0 +1,242 @@ +import React, { useState } from "react"; +import { createRoot } from "react-dom/client"; +import { flushSync } from "react-dom"; +import { useSessionState } from "../../application/state/useSessionState"; +import { createPromptHostnameSessionSignalController } from "../../application/state/promptHostnameSessionSignalController"; +import { sessionPresentationStore } from "../../application/state/sessionPresentationStore"; +import { extractTerminalPromptHostname } from "../../domain/terminalPromptSecurity"; +import type { DynamicTabTitleMode, Host, TerminalSession, Workspace } from "../../domain/models"; +import { SessionTopTab, WorkspaceTopTab } from "../../components/top-tabs/TopTabItems"; +import { TooltipProvider } from "../../components/ui/tooltip"; + +const hosts: Host[] = [ + { id: "production", label: "\u751f\u4ea7", hostname: "203.0.113.10", username: "fixture", port: 22, protocol: "ssh", os: "linux", tags: [] }, + { id: "database", label: "Database", hostname: "198.51.100.20", username: "fixture", port: 22, protocol: "ssh", os: "linux", tags: [] }, + { id: "jump", label: "Jump fleet", hostname: "jump.example.test", username: "fixture", port: 22, protocol: "ssh", os: "linux", tags: [] }, +]; +const noop = () => {}; +type SessionState = ReturnType; +let state: SessionState; +let setMode: React.Dispatch>; +let setRevision: React.Dispatch>; +let revision = 0; +let fixtureRenderCount = 0; + +function workspace(id: string, sessions: TerminalSession[], title: string, autoTitle: boolean, generatedTitle = false): Workspace { + return { + id, title, autoTitle, generatedTitle, focusedSessionId: sessions[0].id, + root: { id: `${id}-root`, type: "split", direction: "vertical", children: sessions.map(session => ({ id: `${id}-${session.id}`, type: "pane", sessionId: session.id })) }, + }; +} + +function Fixture() { + fixtureRenderCount += 1; + state = useSessionState({ persistSessionRestore: false }); + const [mode, updateMode] = useState(); + const [commit, updateRevision] = useState(0); + setMode = updateMode; + setRevision = updateRevision; + const members = state.sessions.slice(0, 2); + const shared = { + isBeingDragged: false, isDraggingForReorder: false, shiftStyle: {}, + showDropIndicatorBefore: false, showDropIndicatorAfter: false, + onTabDragStart: noop, onTabDragEnd: noop, onTabDragOver: noop, onTabDragLeave: noop, onTabDrop: noop, + tabDoubleClickBehavior: "disabled" as const, dynamicTabTitleMode: mode, + renderBulkCloseItems: () => null, t: (key: string) => key, + }; + const workspaces = members.length === 2 ? [ + workspace("auto", members, "Workspace", true), + workspace("generated", members, members.map(session => session.hostLabel).join("/"), false, true), + workspace("explicit", members, "My Cluster", false), + ] : []; + return +
+

Production SSH tab title policy

+
+ {state.sessions.map(session => host.id === session.hostId)} + onCloseSession={noop} onRenameSession={state.startSessionRename} + onCopySession={noop} onCopySessionToNewWindow={noop} />)} +
+
+ {workspaces.map(item => session.id)} + paneCount={members.length} isHostDropTarget={false} + onRenameWorkspace={noop} onCopyWorkspace={noop} onCloseWorkspace={noop} />)} +
+
+
; +} + +function waitForCommit(expected: number): Promise { + const ready = () => document.querySelector(`[data-fixture-commit="${expected}"]`) !== null; + if (ready()) return Promise.resolve(); + return new Promise((resolve, reject) => { + const observer = new MutationObserver(() => { + if (!ready()) return; + observer.disconnect(); + clearTimeout(timeout); + resolve(); + }); + const timeout = setTimeout(() => { + observer.disconnect(); + reject(new Error(`React commit ${expected} was not observed within 60 seconds`)); + }, 60_000); + observer.observe(document.body, { attributes: true, childList: true, subtree: true }); + }); +} + +async function change(action: () => void): Promise { + revision += 1; + flushSync(() => { action(); setRevision(revision); }); + await waitForCommit(revision); +} + +export type TitleMeasurement = { scenario: string; tabId: string; actual: string; expected: string }; + +function titleSpan(tabId: string): Element { + const span = document.querySelector(`[data-tab-id="${tabId}"] span.truncate.leading-5`); + if (!span) throw new Error(`Missing production title span for ${tabId}`); + return span; +} + +function title(tabId: string): string { + return titleSpan(tabId).textContent ?? ""; +} + +function waitForTitleMutation(tabId: string, action: () => void): Promise { + const span = titleSpan(tabId); + const before = span.textContent; + return new Promise((resolve, reject) => { + const observer = new MutationObserver(() => { + if (span.textContent === before) return; + observer.disconnect(); + clearTimeout(timeout); + resolve(); + }); + const timeout = setTimeout(() => { + observer.disconnect(); + reject(new Error(`Production title ${tabId} did not mutate after a store-only update within 60 seconds`)); + }, 60_000); + observer.observe(span, { characterData: true, childList: true, subtree: true }); + try { action(); } catch (error) { + observer.disconnect(); + clearTimeout(timeout); + reject(error); + } + }); +} + +function promptHost(prompt: string): string { + const hostname = extractTerminalPromptHostname(prompt); + if (!hostname) throw new Error(`Fixture prompt was not parsed: ${JSON.stringify(prompt)}`); + return hostname; +} + +export async function runSshTabTitlePolicy(): Promise<{ rows: TitleMeasurement[]; promptOnlyParentRenders: number }> { + const node = document.getElementById("root"); + if (!node) throw new Error("Missing fixture root"); + const root = createRoot(node); + const rows: TitleMeasurement[] = []; + const record = (scenario: string, tabId: string, expected: string) => { + rows.push({ scenario, tabId, actual: title(tabId), expected }); + }; + const controller = createPromptHostnameSessionSignalController({ + getSession: id => state.sessions.find(session => session.id === id), + onChange: (id, hostname) => state.updateSessionPromptHost(id, hostname), + }); + let first = ""; + let second = ""; + let jump = ""; + try { + flushSync(() => root.render()); + await waitForCommit(0); + await change(() => { + first = state.connectToHost(hosts[0]); + second = state.connectToHost(hosts[1]); + }); + await change(() => { + state.updateSessionStatus(first, "connected"); + state.updateSessionStatus(second, "connected"); + }); + record("initial saved host name", first, hosts[0].label); + const firstPrompt = "[fixture@VM-0-8-centos ~]# "; + const secondPrompt = "[fixture@db-target ~]# "; + const firstObserved = promptHost(firstPrompt); + const secondObserved = promptHost(secondPrompt); + await change(() => { + controller.handleTerminalOutput(first, firstPrompt); + controller.handleTerminalOutput(second, secondPrompt); + }); + // Do not call the title resolver for expectations: names come from the + // saved host entities; dynamic hostnames come from the prompt parser. + const recordGroup = (scenario: string, firstName: string, secondName: string) => { + record(scenario, first, firstName); + record(scenario, second, secondName); + record(scenario, "auto", `${firstName} +1`); + record(scenario, "generated", `${firstName}/${secondName}`); + record(scenario, "explicit", "My Cluster"); + }; + for (const mode of [undefined, "off", "agent", "all"] as const) { + await change(() => setMode(mode)); + recordGroup(`ordinary SSH mode=${mode ?? "default"}`, + mode === "all" ? firstObserved : hosts[0].label, + mode === "all" ? secondObserved : hosts[1].label); + } + const updatedPrompt = "[fixture@production-next ~]# "; + const parentRendersBefore = fixtureRenderCount; + // This action deliberately bypasses change(), setRevision and flushSync: + // only the production store subscriptions may update these mounted tabs. + await waitForTitleMutation(first, () => controller.handleTerminalOutput(first, `\r\n${updatedPrompt}`)); + const promptOnlyParentRenders = fixtureRenderCount - parentRendersBefore; + recordGroup("all-mode prompt-only store subscription", promptHost(updatedPrompt), secondObserved); + const agentTitle = "claude: deploy"; + await change(() => { + state.updateSessionCodingCliProvider(first, "claude"); + state.updateSessionDynamicTitle(first, agentTitle); + }); + for (const mode of ["off", "agent", "all"] as const) { + await change(() => setMode(mode)); + recordGroup(`Agent title mode=${mode}`, mode === "off" ? hosts[0].label : agentTitle, + mode === "all" ? secondObserved : hosts[1].label); + } + const manualName = "Manual production"; + await change(() => state.submitSessionRename(first, manualName)); + for (const mode of ["off", "agent", "all"] as const) { + await change(() => setMode(mode)); + const renamed = state.sessions.find(session => session.id === first); + if (!renamed?.customName) throw new Error("Production rename hook did not set customName"); + recordGroup(`manual title mode=${mode}`, renamed.customName, + mode === "all" ? secondObserved : hosts[1].label); + } + await change(() => { jump = state.connectToHost(hosts[2]); setMode("all"); }); + await change(() => state.updateSessionStatus(jump, "connected")); + const targetPrompt = "[fixture@app-target ~]# "; + const targetObserved = promptHost(targetPrompt); + await change(() => controller.handleTerminalOutput(jump, targetPrompt)); + record("JumpServer first output is target", jump, targetObserved); + for (const mode of ["off", "agent", "all"] as const) { + await change(() => setMode(mode)); + record(`JumpServer direct target mode=${mode}`, jump, mode === "all" ? targetObserved : hosts[2].label); + } + for (const menu of ["Opt> ", "[Host]> ", "\x1b[32mOpt> \x1b[0m"]) { + await change(() => controller.handleTerminalOutput(jump, `\r\nlogout\r\n${menu}`)); + record(`JumpServer return to menu ${JSON.stringify(menu)}`, jump, hosts[2].label); + await change(() => controller.handleTerminalOutput(jump, `\r\n${targetPrompt}`)); + record("JumpServer re-enter target", jump, targetObserved); + } + await change(() => controller.handleTerminalOutput(jump, "\r\nOpt> ")); + await change(() => state.updateSessionStatus(jump, "disconnected")); + await change(() => { state.updateSessionStatus(jump, "connecting"); setMode("off"); }); + record("same-session reconnect preserves saved name in off", jump, hosts[2].label); + await change(() => { state.updateSessionStatus(jump, "connected"); setMode("all"); }); + await change(() => controller.handleTerminalOutput(jump, `\r\n${targetPrompt}`)); + record("first target after reconnect is observed again", jump, targetObserved); + return { rows, promptOnlyParentRenders }; + } finally { + flushSync(() => root.unmount()); + for (const id of [first, second, jump]) { + if (id) { controller.forgetSession(id); sessionPresentationStore.clearSession(id); } + } + } +} diff --git a/scripts/ssh-tab-title-policy.live.test.cjs b/scripts/ssh-tab-title-policy.live.test.cjs new file mode 100644 index 000000000..481458b65 --- /dev/null +++ b/scripts/ssh-tab-title-policy.live.test.cjs @@ -0,0 +1,125 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const esbuild = require("esbuild"); +const root = path.resolve(__dirname, ".."); + +function launchFromNode() { + const { spawnSync } = require("node:child_process"); + const { applyElectronLaunchEnv } = require("../electron/launchEnv.cjs"); + const temp = require("../electron/bridges/tempDirBridge.cjs"); + const prefix = `${temp.getTempFilePath("ssh-tab-title-policy")}-`; + const userData = fs.mkdtempSync(prefix); + let code = 1; + try { + const result = spawnSync(require("electron"), [__filename], { + cwd: root, stdio: "inherit", timeout: 65_000, + env: { ...applyElectronLaunchEnv(process.env), NETCATTY_SSH_TITLE_USER_DATA: userData }, + }); + if (result.error) throw result.error; + code = result.status ?? 1; + } finally { + // Chromium owns profile files until the child exits, especially on Windows. + const target = path.resolve(userData); + console.log("SSH_TAB_TITLE_CLEANUP", target); + assert.equal(path.dirname(target), path.dirname(path.resolve(prefix))); + assert.ok(path.basename(target).startsWith(path.basename(prefix))); + const stat = fs.lstatSync(target); + assert.ok(stat.isDirectory() && !stat.isSymbolicLink()); + fs.rmSync(target, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); + } + process.exit(code); +} + +function fixtureResponse(request) { + const url = new URL(request.url); + if (url.hostname !== "fixture") return new Response("Not found", { status: 404 }); + if (url.pathname === "/index.html") return new Response("
", { + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + let pathname; + try { pathname = decodeURIComponent(url.pathname); } catch { + return new Response("Invalid resource path", { status: 400 }); + } + const publicRoot = path.join(root, "public"); + const file = path.resolve(publicRoot, `.${pathname}`); + const relative = path.relative(publicRoot, file); + if (relative.startsWith("..") || path.isAbsolute(relative)) return new Response("Not found", { status: 404 }); + if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return new Response("Not found", { status: 404 }); + const mime = { + ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", + ".css": "text/css", ".js": "text/javascript", ".woff2": "font/woff2", + }[path.extname(file)] ?? "application/octet-stream"; + return new Response(fs.readFileSync(file), { headers: { "Content-Type": mime } }); +} + +function runInElectron() { + const { app, BrowserWindow, protocol } = require("electron"); + assert.ok(process.env.NETCATTY_SSH_TITLE_USER_DATA, + "Launch with node scripts/ssh-tab-title-policy.live.test.cjs so profile cleanup runs after Electron exits."); + protocol.registerSchemesAsPrivileged([{ + scheme: "ssh-title-test", privileges: { standard: true, secure: true, supportFetchAPI: true }, + }]); + app.setPath("userData", process.env.NETCATTY_SSH_TITLE_USER_DATA); + app.on("window-all-closed", () => {}); + let win; + let finished = false; + const finish = code => { + if (finished) return; + finished = true; + clearTimeout(watchdog); + win?.destroy(); + app.exit(code); + }; + const watchdog = setTimeout(() => { + console.error("SSH_TAB_TITLE_FAILED: real component verification exceeded 60 seconds"); + finish(1); + }, 60_000); + + void app.whenReady().then(async () => { + const bundle = esbuild.buildSync({ + entryPoints: [path.join(__dirname, "fixtures/ssh-tab-title-policy.tsx")], + bundle: true, format: "cjs", platform: "browser", write: false, + alias: { + "node:diagnostics_channel": path.join(root, "infrastructure/shims/nodeDiagnosticsChannel.ts"), + "diagnostics_channel": path.join(root, "infrastructure/shims/nodeDiagnosticsChannel.ts"), + }, + define: { + "import.meta.env.DEV": "false", "import.meta.env.PROD": "true", "import.meta": "{}", + "process.env.NODE_ENV": '"production"', + }, + }).outputFiles[0].text; + win = new BrowserWindow({ + show: process.env.NETCATTY_SSH_TITLE_SHOW_WINDOW === "1", width: 1280, height: 800, + webPreferences: { contextIsolation: true, nodeIntegration: false, backgroundThrottling: false }, + }); + const consoleErrors = []; + win.webContents.on("console-message", details => { + if (details.level === "error") consoleErrors.push(details.message); + }); + protocol.handle("ssh-title-test", fixtureResponse); + await win.loadURL("ssh-title-test://fixture/index.html"); + const { rows, promptOnlyParentRenders } = await win.webContents.executeJavaScript(`(async () => { + const loaded = { exports: {} }; + ((module, exports) => { ${bundle} })(loaded, loaded.exports); + return loaded.exports.runSshTabTitlePolicy(); + })()`); + assert.ok(rows.length > 0, "The real component fixture must produce assertions"); + for (const row of rows) { + assert.equal(row.actual, row.expected, `${row.scenario}; production tab=${row.tabId}`); + } + console.log("SSH_TAB_TITLE_BROWSER_CONSOLE_ERRORS", JSON.stringify(consoleErrors)); + assert.equal(consoleErrors.length, 0, "The real production components must not log browser errors"); + assert.equal(promptOnlyParentRenders, 0, "Prompt-only store updates must not force the fixture parent to render"); + console.log("SSH_TAB_TITLE_POLICY_OK", JSON.stringify({ assertions: rows.length, consoleErrors: consoleErrors.length, promptOnlyParentRenders })); + finish(0); + }).catch(error => { + console.error("SSH_TAB_TITLE_POLICY_FAILED", error); + finish(1); + }); +} + +if (process.versions.electron) runInElectron(); +else launchFromNode(); From 93c74cb068512f9d32ddaaab480a70d59113280f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:21:11 +0800 Subject: [PATCH 08/24] feat(plugins): add workbench shortcut forwarding, DataGrid FK jump & keyboard parity, and ER canvas polish (#4451) --- application/app/AppHandlers.ts | 20 ++ .../plugins/PluginRemoteSurface.test.tsx | 177 ++++++++++++++ components/plugins/PluginRemoteSurface.tsx | 54 ++++- .../primitives/PluginCodeEditorInner.tsx | 51 ++++ .../plugins/primitives/PluginDataGrid.tsx | 220 ++++++++++++++---- .../plugins/primitives/PluginErCanvas.tsx | 205 +++++++++++----- .../plugins/primitives/erFormat.test.ts | 55 +++++ components/plugins/primitives/erFormat.ts | 155 ++++++++++++ components/plugins/primitives/shortcuts.ts | 36 +++ components/plugins/primitives/types.ts | 19 ++ packages/plugin-sdk/src/hostDom.ts | 43 +++- packages/plugin-sdk/src/hostReact.test.tsx | 32 ++- packages/plugin-sdk/src/hostReact.ts | 72 +++++- 13 files changed, 1024 insertions(+), 115 deletions(-) create mode 100644 components/plugins/primitives/erFormat.test.ts create mode 100644 components/plugins/primitives/erFormat.ts create mode 100644 components/plugins/primitives/shortcuts.ts diff --git a/application/app/AppHandlers.ts b/application/app/AppHandlers.ts index 4443e77df..160225948 100644 --- a/application/app/AppHandlers.ts +++ b/application/app/AppHandlers.ts @@ -331,6 +331,26 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo if (binding.category === 'sftp') { continue; } + if (binding.action === 'commandPalette') { + const hasOpenHostModal = Array.from( + document.querySelectorAll('[role="dialog"][aria-modal="true"]:not([data-plugin-dialog])'), + ).some((el) => { + const r = el.getBoundingClientRect(); + return r.width > 0 && r.height > 0; + }); + if (!hasOpenHostModal) { + const inPluginSurface = Boolean(target?.closest?.('[data-plugin-remote-surface]')); + const activeFullBleedSurface = inPluginSurface || Array.from( + document.querySelectorAll('[data-plugin-chrome="full-bleed"] [data-plugin-remote-surface]'), + ).some((el) => { + const r = el.getBoundingClientRect(); + return r.width > 0 && r.height > 0; + }); + if (activeFullBleedSurface) { + return; + } + } + } if (TERMINAL_PASSTHROUGH_ACTIONS.has(binding.action)) { if (isTerminalElement) { return; diff --git a/components/plugins/PluginRemoteSurface.test.tsx b/components/plugins/PluginRemoteSurface.test.tsx index 8dfd6be2c..1ee059b1a 100644 --- a/components/plugins/PluginRemoteSurface.test.tsx +++ b/components/plugins/PluginRemoteSurface.test.tsx @@ -470,3 +470,180 @@ test('PluginRemoteSurface forwards dblclick, contextmenu, throttled scroll, curs Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); } }); + +test('PluginDataGrid FK jump, hiddenColumns, keyboard shortcuts, and PluginErCanvas double-click + SVG export', async () => { + const dom = new JSDOM('
', { url: 'http://localhost', pretendToBeVisual: true }); + const saved = new Map(); + for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', '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: 0, y: 0, width: 800, height: 600, top: 0, left: 0, right: 800, bottom: 600, 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 { act } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { PluginRemoteSurface } = await import('./PluginRemoteSurface'); + + const events: Array> = []; + const gridProps = { + columns: [ + { name: 'id', type: 'int4', primaryKey: true }, + { name: 'customer_id', type: 'int4', foreignKey: { table: 'customers', column: 'id', schema: 'public' } }, + { name: 'secret_col', type: 'text' }, + ], + hiddenColumns: ['secret_col'], + rows: [[10, 42, 'hidden-val']], + editable: true, + }; + const roGridProps = { + columns: [{ name: 'id', type: 'int4' }], + rows: [{ id: 99 }], + editable: false, + }; + const erProps = { + tables: [ + { name: 'customers', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'created_at', type: 'timestamp with time zone' }] }, + { name: 'orders', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'customer_id', type: 'integer', isFk: true }] }, + ], + relations: [{ fromTable: 'public.orders', fromColumn: 'customer_id', toTable: 'public.customers', toColumn: 'id', onDelete: 'CASCADE' }], + }; + const tree = { + children: [ + { id: 'surface-btn', type: 1, element: 'button', attributes: { type: 'button' }, children: [{ id: 'sbt', type: 3, data: 'Btn' }] }, + { id: 'grid', type: 1, element: 'div', attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(gridProps) }, children: [] }, + { id: 'ro-grid', type: 1, element: 'div', attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(roGridProps) }, children: [] }, + { id: 'er', type: 1, element: 'div', attributes: { 'data-plugin-widget': 'er-canvas', 'data-plugin-widget-props': JSON.stringify(erProps) }, children: [] }, + ], + }; + + const root = createRoot(document.getElementById('root')!); + try { + await act(async () => { + root.render( events.push(e as unknown as Record)} />); + }); + + // Shadow surface prevents default on Cmd+K / Cmd+S + const btn = shadows[0].querySelector('button')!; + const modK = new dom.window.KeyboardEvent('keydown', { key: 'k', metaKey: true, bubbles: true, cancelable: true }); + await act(async () => { btn.dispatchEvent(modK); }); + assert.equal(modK.defaultPrevented, true, 'Cmd+K inside shadow surface must preventDefault'); + + // DataGrid: hiddenColumns excludes secret_col while preserving values + const gridHost = document.querySelector('[data-plugin-widget-node="grid"]') as HTMLElement; + assert.equal(gridHost.querySelector('[data-col-name="secret_col"]'), null, 'hidden column must not render'); + const fkCell = gridHost.querySelector('[role="gridcell"][data-row-index="0"][data-col-name="customer_id"]') as HTMLElement; + assert.ok(fkCell, 'customer_id FK cell rendered'); + const jumpBtn = fkCell.querySelector('[data-fk-jump]') as HTMLButtonElement; + assert.ok(jumpBtn, 'FK jump button rendered'); + await act(async () => { jumpBtn.click(); }); + assert.deepEqual( + events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'fkJump'), + { nodeId: 'grid', type: 'widget', widgetEvent: 'fkJump', detail: { rowIndex: 0, colName: 'customer_id', value: 42, targetTable: 'customers', targetColumn: 'id', targetSchema: 'public' } }, + ); + + // Select FK cell then press Cmd+C -> cellCopy, Delete -> cellEdit NULL, Cmd+Z -> shortcut mod+z + await act(async () => { fkCell.click(); }); + const gridRoot = gridHost.querySelector('[data-plugin-data-grid]') as HTMLElement; + await act(async () => { + gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'c', metaKey: true, bubbles: true, cancelable: true })); + gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Delete', bubbles: true, cancelable: true })); + gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'z', metaKey: true, bubbles: true, cancelable: true })); + }); + assert.deepEqual( + events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'cellCopy'), + { nodeId: 'grid', type: 'widget', widgetEvent: 'cellCopy', detail: { text: '42', rowIndex: 0, colName: 'customer_id', rowIndices: [0] } }, + ); + assert.deepEqual( + events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'cellEdit'), + { nodeId: 'grid', type: 'widget', widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'customer_id', value: null, isNull: true } }, + ); + assert.deepEqual( + events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'shortcut'), + { nodeId: 'grid', type: 'widget', widgetEvent: 'shortcut', detail: { shortcut: 'mod+z' } }, + ); + + // Non-editable grid double-click emits cellDoubleClick + const roHost = document.querySelector('[data-plugin-widget-node="ro-grid"]') as HTMLElement; + const roCell = roHost.querySelector('[role="gridcell"][data-row-index="0"][data-col-name="id"]') as HTMLElement; + await act(async () => { roCell.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true })); }); + assert.deepEqual( + events.find((e) => e.nodeId === 'ro-grid' && e.widgetEvent === 'cellDoubleClick'), + { nodeId: 'ro-grid', type: 'widget', widgetEvent: 'cellDoubleClick', detail: { rowIndex: 0, colName: 'id', value: 99 } }, + ); + + // ER Canvas: abbreviated type, tableDoubleClick, Export SVG + const erHost = document.querySelector('[data-plugin-widget-node="er"]') as HTMLElement; + assert.ok(erHost.textContent?.includes('timestamptz'), 'verbose PG timestamp abbreviated to timestamptz'); + const ordersCard = erHost.querySelector('[data-er-table="orders"]') as Element; + await act(async () => { ordersCard.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true })); }); + assert.deepEqual( + events.find((e) => e.nodeId === 'er' && e.widgetEvent === 'tableDoubleClick'), + { nodeId: 'er', type: 'widget', widgetEvent: 'tableDoubleClick', detail: { table: 'orders', schema: 'public' } }, + ); + const exportBtn = erHost.querySelector('[data-er-export-svg]') as HTMLButtonElement; + await act(async () => { exportBtn.click(); }); + const exportEvt = events.find((e) => e.nodeId === 'er' && e.widgetEvent === 'exportSvg'); + assert.ok(exportEvt, 'exportSvg event emitted'); + assert.match(String((exportEvt!.detail as { svg: string }).svg), /^ handleGlobalHotkeyKeyDownImpl(() => ({ + HOTKEY_DEBUG: false, + closeTabKeyStr: '⌘ + W', + hotkeyScheme: 'mac', + keyBindings: DEFAULT_KEY_BINDINGS, + matchesKeyBinding, + executeHotkeyAction: (action: string) => hostActions.push(action), + }), event); + dom.window.addEventListener('keydown', onGlobalKey as unknown as EventListener, true); + try { + await act(async () => { + gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'k', code: 'KeyK', metaKey: true, bubbles: true, cancelable: true })); + }); + assert.deepEqual(hostActions, [], 'host commandPalette must not hijack Cmd+K inside plugin surface'); + assert.ok( + events.some((e) => e.nodeId === 'grid' && e.widgetEvent === 'shortcut' && (e.detail as { shortcut?: string })?.shortcut === 'mod+k'), + 'Cmd+K reaches plugin DataGrid as mod+k shortcut', + ); + await act(async () => { + gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'j', code: 'KeyJ', metaKey: true, bubbles: true, cancelable: true })); + }); + assert.deepEqual(hostActions, ['quickSwitch'], 'Cmd+J still opens Netcatty Quick Switcher'); + } finally { + dom.window.removeEventListener('keydown', onGlobalKey as unknown as EventListener, true); + } + } 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'); + } +}); diff --git a/components/plugins/PluginRemoteSurface.tsx b/components/plugins/PluginRemoteSurface.tsx index 5f137524c..133747525 100644 --- a/components/plugins/PluginRemoteSurface.tsx +++ b/components/plugins/PluginRemoteSurface.tsx @@ -3,6 +3,7 @@ import { LazyLoadBoundary } from '../ui/lazy-load-boundary'; import { PluginViewPopover } from './PluginViewPopover'; import { PluginSplitPane } from './primitives/PluginSplitPane'; import { parseWidgetPropsJson, PluginSlottedWidget, type SlottedWidgetKind } from './primitives/PluginWidgetRenderer'; +import { matchWorkbenchShortcut } from './primitives/shortcuts'; import type { PluginSplitPaneWidgetProps } from './primitives/types'; import { createPortal } from 'react-dom'; import { validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs'; @@ -407,8 +408,15 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: { if (event.type === 'submit') event.preventDefault(); if (event.type === 'contextmenu') event.preventDefault(); + if (event.type === 'keydown' && event instanceof view.KeyboardEvent) { + const sc = matchWorkbenchShortcut(event, { includeUndoRedo: false }); + if (sc === 'mod+k' || sc === 'mod+s') { + event.preventDefault(); + } + } - const nodeId = target.dataset.netcattyRemoteNode; + const nodeId = target.dataset.netcattyRemoteNode + ?? (event.type === 'keydown' ? (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode : undefined); if (!nodeId) return; if (event.type === 'scroll') { @@ -464,13 +472,55 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: { }; for (const event of SURFACE_EVENTS) shadow.addEventListener(event, listener, true); + + // 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; + if (!surfaceEl || !surfaceEl.closest('[data-plugin-chrome="full-bleed"]')) return; + const rect = surfaceEl.getBoundingClientRect(); + if (rect.width <= 0 || rect.height <= 0) return; + const doc = surfaceEl.ownerDocument; + const hasHostModal = [...doc.querySelectorAll('[role=dialog][aria-modal=true]:not([data-plugin-dialog])')].some((dialog) => { + const r = dialog.getBoundingClientRect(); + return r.width > 0 && r.height > 0; + }); + if (hasHostModal) return; + const active = doc.activeElement; + const focusInsideHostChrome = active + && active !== doc.body + && active !== doc.documentElement + && !surfaceEl.contains(active) + && !active.closest?.('[data-plugin-view-slot]'); + if (focusInsideHostChrome) return; + const sc = matchWorkbenchShortcut(event, { includeUndoRedo: false }); + if (sc !== 'mod+k' && sc !== 'mod+s') return; + const rootNodeId = (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode; + if (!rootNodeId) return; + event.preventDefault(); + onEventRef.current({ + nodeId: rootNodeId, + type: 'keydown', + key: event.key, + ctrlKey: event.ctrlKey, + metaKey: event.metaKey, + altKey: event.altKey, + shiftKey: event.shiftKey, + }); + }; + view?.addEventListener('keydown', onWindowKeyDown, false); + return () => { + view?.removeEventListener('keydown', onWindowKeyDown, false); for (const timer of scrollTimers.values()) clearTimeout(timer); scrollTimers.clear(); pendingScroll.clear(); for (const event of SURFACE_EVENTS) shadow.removeEventListener(event, listener, true); }; - }, [shadow]); + }, [shadow, depth]); return ( diff --git a/components/plugins/primitives/PluginCodeEditorInner.tsx b/components/plugins/primitives/PluginCodeEditorInner.tsx index e796be33d..ade816442 100644 --- a/components/plugins/primitives/PluginCodeEditorInner.tsx +++ b/components/plugins/primitives/PluginCodeEditorInner.tsx @@ -8,6 +8,7 @@ import { readClipboardTextWithFallbacks, } from '@/infrastructure/monaco/monacoClipboardPaste'; import { useNetcattyMonacoTheme } from '@/infrastructure/monaco/useNetcattyMonacoTheme'; +import { matchWorkbenchShortcut } from './shortcuts'; import { extractCurrentSqlStatement, extractSqlTableAliases } from './sqlStatement'; import type { PluginCodeEditorCompletionSchema, @@ -62,8 +63,10 @@ export default function PluginCodeEditorInner({ const editorId = useId(); const modelPath = `inmemory://netcatty-plugin-editor/${editorId.replace(/[^a-zA-Z0-9_-]/g, '_')}.${language}`; + const wrapperRef = useRef(null); const editorRef = useRef[0] | null>(null); const monacoRef = useRef(null); + const handledKeyEventsRef = useRef>(new WeakSet()); const disposablesRef = useRef>([]); const onWidgetEventRef = useRef(onWidgetEvent); onWidgetEventRef.current = onWidgetEvent; @@ -316,6 +319,26 @@ export default function PluginCodeEditorInner({ ], run: emitFormat, }), + editor.onKeyDown((monacoKeyEvent) => { + const nativeEvent = monacoKeyEvent.browserEvent; + if (handledKeyEventsRef.current.has(nativeEvent)) return; + const shortcut = matchWorkbenchShortcut(nativeEvent, { includeUndoRedo: false }); + if (!shortcut) return; + if (shortcut === 'escape') { + const target = nativeEvent.target as Element | null; + if (target?.closest?.('.suggest-widget, .find-widget, .parameter-hints-widget')) return; + handledKeyEventsRef.current.add(nativeEvent); + onWidgetEventRef.current('shortcut', { shortcut }); + return; + } + handledKeyEventsRef.current.add(nativeEvent); + monacoKeyEvent.preventDefault(); + monacoKeyEvent.stopPropagation(); + nativeEvent.preventDefault(); + nativeEvent.stopImmediatePropagation?.(); + nativeEvent.stopPropagation(); + onWidgetEventRef.current('shortcut', { shortcut }); + }), editor.addAction({ id: 'netcatty.pluginCodeEditor.paste', label: 'Paste', @@ -354,10 +377,38 @@ export default function PluginCodeEditorInner({ }, 80); }, []); + // Native capture listener runs BEFORE Monaco's textarea / chord-prefix handler + // so Cmd/Ctrl+K never enters Monaco's chord state and always reaches the plugin once. + useEffect(() => { + const el = wrapperRef.current; + if (!el) return; + const onNativeKeyDownCapture = (event: KeyboardEvent) => { + if (handledKeyEventsRef.current.has(event)) return; + // Keep Monaco's native Cmd/Ctrl+Z undo/redo intact while forwarding global workbench shortcuts. + const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: false }); + if (!shortcut) return; + if (shortcut === 'escape') { + const target = event.target as Element | null; + if (target?.closest?.('.suggest-widget, .find-widget, .parameter-hints-widget')) return; + handledKeyEventsRef.current.add(event); + onWidgetEventRef.current('shortcut', { shortcut }); + return; + } + handledKeyEventsRef.current.add(event); + event.preventDefault(); + event.stopImmediatePropagation(); + event.stopPropagation(); + onWidgetEventRef.current('shortcut', { shortcut }); + }; + el.addEventListener('keydown', onNativeKeyDownCapture, true); + return () => el.removeEventListener('keydown', onNativeKeyDownCapture, true); + }, []); + const resolvedHeight = typeof height === 'number' ? `${height}px` : height; return (
new Set(deletedRowIndices ?? []), [deletedRowIndices]); const selectedSet = useMemo(() => new Set(selectedRowIndices ?? []), [selectedRowIndices]); + const hiddenSet = useMemo(() => new Set(hiddenColumns ?? []), [hiddenColumns]); + const visibleCols = useMemo( + () => columns.map((col, origIndex) => ({ col, origIndex })).filter(({ col }) => !hiddenSet.has(col.name)), + [columns, hiddenSet], + ); const totalRows = rows.length + insertedRows.length; const getColWidth = useCallback((col: PluginDataGridColumn): number => { @@ -91,16 +98,16 @@ export function PluginDataGrid({ const colVirtualizer = useVirtualizer({ horizontal: true, - count: columns.length, + count: visibleCols.length, getScrollElement: () => scrollRef.current, - estimateSize: (index) => (columns[index] ? getColWidth(columns[index]) : DEFAULT_COL_WIDTH), + estimateSize: (index) => (visibleCols[index] ? getColWidth(visibleCols[index].col) : DEFAULT_COL_WIDTH), overscan: 4, initialRect: { width: 960, height: 420 }, }); useEffect(() => { colVirtualizer.measure(); - }, [colWidths, columns, colVirtualizer]); + }, [colWidths, visibleCols, colVirtualizer]); useEffect(() => { if (editingCell) { @@ -125,11 +132,11 @@ export function PluginDataGrid({ return null; }, [rows, insertedRows]); - const getEffectiveValue = useCallback((rowIndex: number, col: PluginDataGridColumn, colIndex: number) => { + const getEffectiveValue = useCallback((rowIndex: number, col: PluginDataGridColumn, origColIndex: number) => { const dirtyKey = `${rowIndex}:${col.name}`; const isDirty = Boolean(dirtyCells && Object.prototype.hasOwnProperty.call(dirtyCells, dirtyKey)); const entry = getRowAt(rowIndex); - const rawValue = entry ? readCellValue(entry.row, col, colIndex) : undefined; + const rawValue = entry ? readCellValue(entry.row, col, origColIndex) : undefined; return { value: isDirty ? dirtyCells![dirtyKey] : rawValue, isDirty, @@ -147,19 +154,19 @@ export function PluginDataGrid({ }); }, [onWidgetEvent]); - const beginEdit = useCallback((rowIndex: number, colIndex: number) => { + const beginEdit = useCallback((rowIndex: number, visibleColIndex: number) => { if (!editable || deletedSet.has(rowIndex)) return; - const col = columns[colIndex]; - if (!col) return; - const { value } = getEffectiveValue(rowIndex, col, colIndex); - setActiveCell({ rowIndex, colIndex }); + const entry = visibleCols[visibleColIndex]; + if (!entry) return; + const { value } = getEffectiveValue(rowIndex, entry.col, entry.origIndex); + setActiveCell({ rowIndex, colIndex: visibleColIndex }); setEditingCell({ rowIndex, - colIndex, - colName: col.name, + colIndex: visibleColIndex, + colName: entry.col.name, draft: value === null || value === undefined ? '' : formatCellDisplay(value), }); - }, [editable, deletedSet, columns, getEffectiveValue]); + }, [editable, deletedSet, visibleCols, getEffectiveValue]); const toggleRowSelection = useCallback((rowIndex: number, shiftKey: boolean) => { const next = new Set(selectedSet); @@ -225,9 +232,78 @@ export function PluginDataGrid({ onWidgetEvent('cellContextMenu', { rowIndex, colName, x, y }); }, [onWidgetEvent]); + const copySelectionOrActiveCell = useCallback(() => { + const selectedIndices = [...selectedSet].sort((a, b) => a - b); + if (selectedIndices.length > 0 && visibleCols.length > 0) { + const text = selectedIndices + .map((rowIdx) => visibleCols.map(({ col, origIndex }) => { + const { value } = getEffectiveValue(rowIdx, col, origIndex); + return value === null || value === undefined ? 'NULL' : formatCellDisplay(value); + }).join('\t')) + .join('\n'); + try { void navigator.clipboard?.writeText?.(text)?.catch?.(() => {}); } catch {} + onWidgetEvent('cellCopy', { + text, + rowIndex: activeCell?.rowIndex ?? selectedIndices[0], + colName: activeCell ? visibleCols[activeCell.colIndex]?.col.name ?? null : null, + rowIndices: selectedIndices, + }); + return true; + } + if (activeCell) { + const entry = visibleCols[activeCell.colIndex]; + if (!entry) return false; + const { value } = getEffectiveValue(activeCell.rowIndex, entry.col, entry.origIndex); + const text = value === null || value === undefined ? 'NULL' : formatCellDisplay(value); + try { void navigator.clipboard?.writeText?.(text)?.catch?.(() => {}); } catch {} + onWidgetEvent('cellCopy', { + text, + rowIndex: activeCell.rowIndex, + colName: entry.col.name, + rowIndices: [activeCell.rowIndex], + }); + return true; + } + return false; + }, [selectedSet, visibleCols, activeCell, getEffectiveValue, onWidgetEvent]); + const handleGridKeyDown = useCallback((event: React.KeyboardEvent) => { - if (editingCell || !activeCell || columns.length === 0 || totalRows === 0) return; + const mod = event.metaKey || event.ctrlKey; + + // While editing an inline cell input, only forward Cmd/Ctrl+K and Cmd/Ctrl+S. + if (editingCell) { + const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: false }); + if (shortcut === 'mod+k' || shortcut === 'mod+s') { + event.preventDefault(); + event.stopPropagation(); + onWidgetEvent('shortcut', { shortcut }); + } + return; + } + + // Global workbench shortcuts + grid Undo/Redo + const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: true }); + if (shortcut) { + if (shortcut !== 'escape') { + event.preventDefault(); + } + event.stopPropagation(); + onWidgetEvent('shortcut', { shortcut }); + return; + } + + // Cmd/Ctrl+C copies active cell or selected rows + if (mod && !event.altKey && !event.shiftKey && event.key.toLowerCase() === 'c') { + if (copySelectionOrActiveCell()) { + event.preventDefault(); + event.stopPropagation(); + } + return; + } + + if (!activeCell || visibleCols.length === 0 || totalRows === 0) return; const { rowIndex, colIndex } = activeCell; + if (event.key === 'ArrowDown' && rowIndex + 1 < totalRows) { event.preventDefault(); setActiveCell({ rowIndex: rowIndex + 1, colIndex }); @@ -236,7 +312,7 @@ export function PluginDataGrid({ event.preventDefault(); setActiveCell({ rowIndex: rowIndex - 1, colIndex }); rowVirtualizer.scrollToIndex(rowIndex - 1); - } else if (event.key === 'ArrowRight' && colIndex + 1 < columns.length) { + } else if (event.key === 'ArrowRight' && colIndex + 1 < visibleCols.length) { event.preventDefault(); setActiveCell({ rowIndex, colIndex: colIndex + 1 }); colVirtualizer.scrollToIndex(colIndex + 1); @@ -244,11 +320,34 @@ export function PluginDataGrid({ event.preventDefault(); setActiveCell({ rowIndex, colIndex: colIndex - 1 }); colVirtualizer.scrollToIndex(colIndex - 1); - } else if (event.key === 'Enter' && editable) { + } else if ((event.key === 'Enter' || event.key === 'F2') && editable) { event.preventDefault(); beginEdit(rowIndex, colIndex); + } else if ((event.key === 'Delete' || event.key === 'Backspace') && editable && !deletedSet.has(rowIndex)) { + const entry = visibleCols[colIndex]; + if (entry && entry.col.nullable !== false) { + event.preventDefault(); + onWidgetEvent('cellEdit', { + rowIndex, + colName: entry.col.name, + value: null, + isNull: true, + }); + } } - }, [editingCell, activeCell, columns.length, totalRows, rowVirtualizer, colVirtualizer, editable, beginEdit]); + }, [ + editingCell, + activeCell, + visibleCols, + totalRows, + rowVirtualizer, + colVirtualizer, + editable, + deletedSet, + beginEdit, + copySelectionOrActiveCell, + onWidgetEvent, + ]); const virtualRows = rowVirtualizer.getVirtualItems(); const virtualCols = colVirtualizer.getVirtualItems(); @@ -272,11 +371,8 @@ export function PluginDataGrid({
)} -
- {columns.length === 0 ? ( +
+ {visibleCols.length === 0 ? (
{emptyMessage}
@@ -304,8 +400,9 @@ export function PluginDataGrid({
{virtualCols.map((vCol) => { - const col = columns[vCol.index]; - if (!col) return null; + const colEntry = visibleCols[vCol.index]; + if (!colEntry) return null; + const { col } = colEntry; const isSorted = sort?.column === col.name; const sortable = col.sortable !== false; return ( @@ -324,11 +421,16 @@ export function PluginDataGrid({ disabled={!sortable} onClick={() => handleSortClick(col)} className={`flex min-w-0 flex-1 items-center gap-1.5 text-left ${sortable ? 'cursor-pointer hover:text-primary' : 'cursor-default'}`} - title={col.type ? `${col.name} (${col.type})` : col.name} + title={col.foreignKey + ? `${col.name}${col.type ? ` (${col.type})` : ''} -> ${col.foreignKey.schema ? `${col.foreignKey.schema}.` : ''}${col.foreignKey.table}.${col.foreignKey.column}` + : col.type ? `${col.name} (${col.type})` : col.name} > {col.primaryKey && ( )} + {col.foreignKey && ( + + )} {col.name} {col.type && ( @@ -399,7 +501,7 @@ export function PluginDataGrid({
handleCellContextMenu(e, rowIndex, columns[0]?.name ?? '')} + onContextMenu={(e) => handleCellContextMenu(e, rowIndex, visibleCols[0]?.col.name ?? '')} > {virtualCols.map((vCol) => { - const colIndex = vCol.index; - const col = columns[colIndex]; - if (!col) return null; - const { value, isDirty } = getEffectiveValue(rowIndex, col, colIndex); - const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === colIndex; - const isActive = activeCell?.rowIndex === rowIndex && activeCell?.colIndex === colIndex; + const visibleColIndex = vCol.index; + const colEntry = visibleCols[visibleColIndex]; + if (!colEntry) return null; + const { col, origIndex } = colEntry; + const { value, isDirty } = getEffectiveValue(rowIndex, col, origIndex); + const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === visibleColIndex; + const isActive = activeCell?.rowIndex === rowIndex && activeCell?.colIndex === visibleColIndex; const isNull = value === null || value === undefined; const numeric = !isNull && isNumericColumn(col, value); + const fk = col.foreignKey; return (
{ - setActiveCell({ rowIndex, colIndex }); + setActiveCell({ rowIndex, colIndex: visibleColIndex }); onWidgetEvent('cellSelect', { rowIndex, colName: col.name, value: value === undefined ? null : value, }); }} - onDoubleClick={() => beginEdit(rowIndex, colIndex)} + onDoubleClick={() => { + if (editable && !isDeleted) { + beginEdit(rowIndex, visibleColIndex); + } else { + onWidgetEvent('cellDoubleClick', { + rowIndex, + colName: col.name, + value: value === undefined ? null : value, + }); + } + }} onContextMenu={(e) => handleCellContextMenu(e, rowIndex, col.name)} > {isEditing ? ( @@ -465,6 +579,13 @@ export function PluginDataGrid({ value={editingCell.draft} onChange={(e) => setEditingCell({ ...editingCell, draft: e.target.value })} onKeyDown={(e) => { + const sc = matchWorkbenchShortcut(e, { includeUndoRedo: false }); + if (sc === 'mod+k' || sc === 'mod+s') { + e.preventDefault(); + e.stopPropagation(); + onWidgetEvent('shortcut', { shortcut: sc }); + return; + } e.stopPropagation(); if (e.key === 'Enter') { e.preventDefault(); @@ -475,14 +596,13 @@ export function PluginDataGrid({ } else if (e.key === 'Tab') { e.preventDefault(); commitEdit(editingCell, false); - const nextCol = e.shiftKey ? colIndex - 1 : colIndex + 1; - if (nextCol >= 0 && nextCol < columns.length) { + const nextCol = e.shiftKey ? visibleColIndex - 1 : visibleColIndex + 1; + if (nextCol >= 0 && nextCol < visibleCols.length) { beginEdit(rowIndex, nextCol); } } }} onBlur={() => { - // Delay slightly so clicking the inline NULL button wins over blur. const snapshot = editingCell; setTimeout(() => { setEditingCell((curr) => { @@ -534,6 +654,28 @@ export function PluginDataGrid({ {formatCellDisplay(value)} )} + {!isEditing && !isNull && fk && ( + + )}
); })} diff --git a/components/plugins/primitives/PluginErCanvas.tsx b/components/plugins/primitives/PluginErCanvas.tsx index e281153c9..fafd66ded 100644 --- a/components/plugins/primitives/PluginErCanvas.tsx +++ b/components/plugins/primitives/PluginErCanvas.tsx @@ -1,16 +1,22 @@ -import { Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react'; +import { Download, Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { + abbreviateSqlType, + buildStandaloneErSvg, + ER_CARD_HEADER_HEIGHT, + ER_CARD_ROW_HEIGHT, + ER_CARD_WIDTH, + erCardHeight, + erTableKey, +} from './erFormat'; +import { matchWorkbenchShortcut } from './shortcuts'; import type { PluginErCanvasWidgetProps, PluginErTable, PluginWidgetEventCallback, } from './types'; -const CARD_WIDTH = 236; -const CARD_HEADER_HEIGHT = 34; -const CARD_ROW_HEIGHT = 24; -const CARD_FOOTER_PADDING = 8; -const GRID_GAP_X = 76; +const GRID_GAP_X = 80; const GRID_GAP_Y = 56; const MIN_ZOOM = 0.25; const MAX_ZOOM = 2.5; @@ -19,35 +25,45 @@ export interface PluginErCanvasProps extends PluginErCanvasWidgetProps { onWidgetEvent: PluginWidgetEventCallback; } -function tableKey(table: Pick): string { - return table.schema ? `${table.schema}.${table.name}` : table.name; -} - -function cardHeight(table: PluginErTable): number { - return CARD_HEADER_HEIGHT + Math.max(1, table.columns.length) * CARD_ROW_HEIGHT + CARD_FOOTER_PADDING; -} - function computeInitialPositions(tables: PluginErTable[]): Record { const result: Record = {}; const colsPerRow = Math.max(1, Math.min(4, Math.ceil(Math.sqrt(tables.length || 1)))); const colY = Array.from({ length: colsPerRow }, () => 40); tables.forEach((table, index) => { - const key = tableKey(table); + const key = erTableKey(table); if (typeof table.x === 'number' && Number.isFinite(table.x) && typeof table.y === 'number' && Number.isFinite(table.y)) { result[key] = { x: table.x, y: table.y }; return; } const colIdx = index % colsPerRow; - const x = 40 + colIdx * (CARD_WIDTH + GRID_GAP_X); + const x = 40 + colIdx * (ER_CARD_WIDTH + GRID_GAP_X); const y = colY[colIdx]; result[key] = { x, y }; - colY[colIdx] = y + cardHeight(table) + GRID_GAP_Y; + colY[colIdx] = y + erCardHeight(table) + GRID_GAP_Y; }); return result; } +function resolveCanvasPalette(el: HTMLElement | null) { + const isDark = typeof document !== 'undefined' && document.documentElement.classList.contains('dark'); + const readVar = (name: string, fallback: string) => { + if (!el || typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') return fallback; + const val = window.getComputedStyle(el).getPropertyValue(name).trim(); + return val ? `hsl(${val})` : fallback; + }; + return { + background: readVar('--background', isDark ? '#0f1117' : '#ffffff'), + card: readVar('--card', isDark ? '#161922' : '#ffffff'), + cardForeground: readVar('--card-foreground', isDark ? '#f1f5f9' : '#0f172a'), + muted: readVar('--muted', isDark ? '#1e2230' : '#f1f5f9'), + mutedForeground: readVar('--muted-foreground', isDark ? '#94a3b8' : '#64748b'), + border: readVar('--border', isDark ? '#2a3040' : '#e2e8f0'), + primary: readVar('--primary', isDark ? '#38bdf8' : '#2563eb'), + }; +} + export function PluginErCanvas({ tables = [], relations = [], @@ -61,7 +77,7 @@ export function PluginErCanvas({ const [panning, setPanning] = useState(false); const tableSignature = useMemo( - () => tables.map((t) => `${tableKey(t)}:${t.x ?? ''}:${t.y ?? ''}`).join('|'), + () => tables.map((t) => `${erTableKey(t)}:${t.x ?? ''}:${t.y ?? ''}`).join('|'), [tables], ); @@ -70,7 +86,7 @@ export function PluginErCanvas({ const defaults = computeInitialPositions(tables); const next: Record = {}; for (const tbl of tables) { - const key = tableKey(tbl); + const key = erTableKey(tbl); next[key] = prev[key] ?? defaults[key]; } return next; @@ -81,7 +97,7 @@ export function PluginErCanvas({ const byKey = new Map(); const byName = new Map(); for (const tbl of tables) { - byKey.set(tableKey(tbl), tbl); + byKey.set(erTableKey(tbl), tbl); if (!byName.has(tbl.name)) byName.set(tbl.name, tbl); } return { byKey, byName }; @@ -104,11 +120,11 @@ export function PluginErCanvas({ let maxX = -Infinity; let maxY = -Infinity; for (const tbl of tables) { - const pos = positions[tableKey(tbl)] ?? { x: 0, y: 0 }; + const pos = positions[erTableKey(tbl)] ?? { x: 0, y: 0 }; minX = Math.min(minX, pos.x); minY = Math.min(minY, pos.y); - maxX = Math.max(maxX, pos.x + CARD_WIDTH); - maxY = Math.max(maxY, pos.y + cardHeight(tbl)); + maxX = Math.max(maxX, pos.x + ER_CARD_WIDTH); + maxY = Math.max(maxY, pos.y + erCardHeight(tbl)); } const contentW = Math.max(1, maxX - minX); const contentH = Math.max(1, maxY - minY); @@ -154,6 +170,7 @@ export function PluginErCanvas({ if (event.button !== 0) return; if ((event.target as Element).closest?.('[data-er-table]')) return; event.preventDefault(); + containerRef.current?.focus(); const startX = event.clientX; const startY = event.clientY; const initialX = viewport.x; @@ -180,7 +197,8 @@ export function PluginErCanvas({ const startCardDrag = useCallback((event: React.PointerEvent, table: PluginErTable) => { if (event.button !== 0) return; event.stopPropagation(); - const key = tableKey(table); + containerRef.current?.focus(); + const key = erTableKey(table); const startX = event.clientX; const startY = event.clientY; const origin = positions[key] ?? { x: 0, y: 0 }; @@ -216,6 +234,14 @@ export function PluginErCanvas({ window.addEventListener('pointercancel', onUp); }, [positions, viewport.zoom, onWidgetEvent]); + const handleCardDoubleClick = useCallback((event: React.MouseEvent, table: PluginErTable) => { + event.stopPropagation(); + onWidgetEvent('tableDoubleClick', { + table: table.name, + ...(table.schema ? { schema: table.schema } : {}), + }); + }, [onWidgetEvent]); + const zoomBy = useCallback((factor: number) => { const el = containerRef.current; const rect = el?.getBoundingClientRect(); @@ -234,15 +260,35 @@ export function PluginErCanvas({ const resetLayout = useCallback(() => { setPositions(computeInitialPositions(tables)); - requestAnimationFrame(fitToView); + if (typeof requestAnimationFrame === 'function') { + requestAnimationFrame(fitToView); + } else { + fitToView(); + } }, [tables, fitToView]); + const handleExportSvg = useCallback(() => { + const palette = resolveCanvasPalette(containerRef.current); + const svg = buildStandaloneErSvg(tables, relations, positions, palette); + onWidgetEvent('exportSvg', { svg }); + }, [tables, relations, positions, onWidgetEvent]); + + const handleKeyDown = useCallback((event: React.KeyboardEvent) => { + const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: true }); + if (!shortcut) return; + if (shortcut !== 'escape') event.preventDefault(); + event.stopPropagation(); + onWidgetEvent('shortcut', { shortcut }); + }, [onWidgetEvent]); + return (
{/* Floating Canvas Controls */}
@@ -251,7 +297,7 @@ export function PluginErCanvas({ onClick={() => zoomBy(1.2)} aria-label="Zoom in" title="Zoom in" - className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-accent text-muted-foreground hover:text-foreground" + className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground" > @@ -263,7 +309,7 @@ export function PluginErCanvas({ onClick={() => zoomBy(1 / 1.2)} aria-label="Zoom out" title="Zoom out" - className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-accent text-muted-foreground hover:text-foreground" + className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground" > @@ -273,7 +319,7 @@ export function PluginErCanvas({ onClick={fitToView} aria-label="Fit to view" title="Fit to view" - className="inline-flex h-6 items-center gap-1 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground" + className="inline-flex h-6 items-center gap-1 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground" > Fit @@ -283,10 +329,22 @@ export function PluginErCanvas({ onClick={resetLayout} aria-label="Reset layout" title="Reset layout" - className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-accent text-muted-foreground hover:text-foreground" + className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground" > +
+
{tables.length === 0 ? ( @@ -314,28 +372,34 @@ export function PluginErCanvas({ const fromTable = resolveTable(rel.fromTable); const toTable = resolveTable(rel.toTable); if (!fromTable || !toTable) return null; - const fromKey = tableKey(fromTable); - const toKey = tableKey(toTable); + const fromKey = erTableKey(fromTable); + const toKey = erTableKey(toTable); const fromPos = positions[fromKey] ?? { x: 0, y: 0 }; const toPos = positions[toKey] ?? { x: 0, y: 0 }; const fromColIdx = Math.max(0, fromTable.columns.findIndex((c) => c.name === rel.fromColumn)); const toColIdx = Math.max(0, toTable.columns.findIndex((c) => c.name === rel.toColumn)); - const y1 = fromPos.y + CARD_HEADER_HEIGHT + fromColIdx * CARD_ROW_HEIGHT + CARD_ROW_HEIGHT / 2; - const y2 = toPos.y + CARD_HEADER_HEIGHT + toColIdx * CARD_ROW_HEIGHT + CARD_ROW_HEIGHT / 2; - const fromCenter = fromPos.x + CARD_WIDTH / 2; - const toCenter = toPos.x + CARD_WIDTH / 2; + const y1 = fromPos.y + ER_CARD_HEADER_HEIGHT + fromColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2; + const y2 = toPos.y + ER_CARD_HEADER_HEIGHT + toColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2; + const fromCenter = fromPos.x + ER_CARD_WIDTH / 2; + const toCenter = toPos.x + ER_CARD_WIDTH / 2; const goRight = toCenter >= fromCenter; - const x1 = goRight ? fromPos.x + CARD_WIDTH : fromPos.x; - const x2 = goRight ? toPos.x : toPos.x + CARD_WIDTH; + const x1 = goRight ? fromPos.x + ER_CARD_WIDTH : fromPos.x; + const x2 = goRight ? toPos.x : toPos.x + ER_CARD_WIDTH; const dx = Math.max(48, Math.abs(x2 - x1) * 0.45); const c1x = goRight ? x1 + dx : x1 - dx; const c2x = goRight ? x2 - dx : x2 + dx; - const highlighted = hoveredRelation === idx || selectedTable === fromKey || selectedTable === toKey; + const isHovered = hoveredRelation === idx; + const highlighted = isHovered || selectedTable === fromKey || selectedTable === toKey; const stroke = highlighted ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))'; + const midX = (x1 + x2) / 2; + const midY = (y1 + y2) / 2; + const edgeLabel = `${rel.fromColumn} -> ${rel.toColumn}${rel.onDelete ? ` (ON DELETE ${rel.onDelete})` : ''}`; + const labelWidth = Math.min(260, Math.max(72, edgeLabel.length * 6.2 + 14)); return ( ${toKey}.${rel.toColumn}:${idx}`} + data-er-relation={`${rel.fromTable}.${rel.fromColumn}->${rel.toTable}.${rel.toColumn}`} onPointerEnter={() => setHoveredRelation(idx)} onPointerLeave={() => setHoveredRelation(null)} > @@ -343,7 +407,7 @@ export function PluginErCanvas({ d={`M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}`} fill="none" stroke="transparent" - strokeWidth={12} + strokeWidth={14} /> - {rel.name && highlighted && ( - - {rel.name} - + {isHovered && ( + + + + {edgeLabel} + + )} ); @@ -372,9 +446,9 @@ export function PluginErCanvas({ {/* Table Cards */} {tables.map((table) => { - const key = tableKey(table); + const key = erTableKey(table); const pos = positions[key] ?? { x: 0, y: 0 }; - const height = cardHeight(table); + const height = erCardHeight(table); const isSelected = selectedTable === key; return ( @@ -383,11 +457,12 @@ export function PluginErCanvas({ data-er-table={table.name} transform={`translate(${pos.x}, ${pos.y})`} onPointerDown={(e) => startCardDrag(e, table)} + onDoubleClick={(e) => handleCardDoubleClick(e, table)} className="cursor-pointer" filter="url(#nc-er-shadow)" > {/* Header band */} @@ -420,15 +495,19 @@ export function PluginErCanvas({ {/* Columns */} {table.columns.map((col, colIdx) => { - const rowY = CARD_HEADER_HEIGHT + colIdx * CARD_ROW_HEIGHT; + const rowY = ER_CARD_HEADER_HEIGHT + colIdx * ER_CARD_ROW_HEIGHT; const badgeOffset = (col.isPk ? 26 : 0) + (col.isFk ? 26 : 0); + const maxNameChars = badgeOffset >= 52 ? 12 : badgeOffset >= 26 ? 15 : 19; + const displayName = col.name.length > maxNameChars ? `${col.name.slice(0, maxNameChars - 1)}…` : col.name; + const displayType = `${abbreviateSqlType(col.type)}${col.nullable ? '?' : ''}`; return ( + {`${col.name}: ${col.type}${col.nullable ? ' NULL' : ' NOT NULL'}`} {colIdx > 0 && ( - {col.name.length > 18 ? `${col.name.slice(0, 17)}…` : col.name} + {displayName} - {`${col.type}${col.nullable ? '?' : ''}`.slice(0, 14)} + {displayType} ); diff --git a/components/plugins/primitives/erFormat.test.ts b/components/plugins/primitives/erFormat.test.ts new file mode 100644 index 000000000..1c615622f --- /dev/null +++ b/components/plugins/primitives/erFormat.test.ts @@ -0,0 +1,55 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { abbreviateSqlType, buildStandaloneErSvg } from './erFormat'; +import { matchWorkbenchShortcut } from './shortcuts'; + +test('abbreviateSqlType shortens verbose SQL catalog types cleanly without mid-word clipping', () => { + assert.equal(abbreviateSqlType('character varying(180)'), 'varchar(180)'); + assert.equal(abbreviateSqlType('timestamp with time zone'), 'timestamptz'); + assert.equal(abbreviateSqlType('timestamp without time zone'), 'timestamp'); + assert.equal(abbreviateSqlType('double precision'), 'float8'); + assert.equal(abbreviateSqlType('integer'), 'int4'); + assert.equal(abbreviateSqlType('boolean'), 'bool'); + assert.equal(abbreviateSqlType('numeric(10,2)'), 'numeric(10,2)'); +}); + +test('buildStandaloneErSvg generates valid self-contained SVG markup with tables, PK/FK pills, and Bezier relations', () => { + const svg = buildStandaloneErSvg( + [ + { name: 'customers', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'email', type: 'character varying(180)', nullable: false }] }, + { name: 'orders', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'customer_id', type: 'integer', isFk: true }] }, + ], + [{ fromTable: 'public.orders', fromColumn: 'customer_id', toTable: 'public.customers', toColumn: 'id', onDelete: 'CASCADE' }], + { 'public.customers': { x: 40, y: 40 }, 'public.orders': { x: 380, y: 40 } }, + { + background: '#0f1117', + card: '#161922', + cardForeground: '#f1f5f9', + muted: '#1e2230', + mutedForeground: '#94a3b8', + border: '#2a3040', + primary: '#38bdf8', + }, + ); + assert.match(svg, /^$/); + assert.match(svg, /public\.customers/); + assert.match(svg, /varchar\(180\)/); + assert.match(svg, />PKFK { + assert.equal(matchWorkbenchShortcut({ key: 'k', metaKey: true }), 'mod+k'); + assert.equal(matchWorkbenchShortcut({ key: 'K', ctrlKey: true }), 'mod+k'); + assert.equal(matchWorkbenchShortcut({ key: 's', metaKey: true }), 'mod+s'); + assert.equal(matchWorkbenchShortcut({ key: 't', ctrlKey: true }), 'mod+t'); + assert.equal(matchWorkbenchShortcut({ key: 'w', metaKey: true }), 'mod+w'); + assert.equal(matchWorkbenchShortcut({ key: 'z', metaKey: true }), 'mod+z'); + assert.equal(matchWorkbenchShortcut({ key: 'Z', metaKey: true, shiftKey: true }), 'mod+shift+z'); + assert.equal(matchWorkbenchShortcut({ key: 'y', ctrlKey: true }), 'mod+shift+z'); + assert.equal(matchWorkbenchShortcut({ key: 'Escape' }), 'escape'); + assert.equal(matchWorkbenchShortcut({ key: 'z', metaKey: true }, { includeUndoRedo: false }), null); + assert.equal(matchWorkbenchShortcut({ key: 'c', metaKey: true }), null); +}); diff --git a/components/plugins/primitives/erFormat.ts b/components/plugins/primitives/erFormat.ts new file mode 100644 index 000000000..243a87b1c --- /dev/null +++ b/components/plugins/primitives/erFormat.ts @@ -0,0 +1,155 @@ +import type { PluginErRelation, PluginErTable } from './types'; + +export const ER_CARD_WIDTH = 252; +export const ER_CARD_HEADER_HEIGHT = 34; +export const ER_CARD_ROW_HEIGHT = 24; +export const ER_CARD_FOOTER_PADDING = 8; + +/** Abbreviate verbose SQL types (especially PostgreSQL catalog names) so ER cards never clip mid-word. */ +export function abbreviateSqlType(rawType: string): string { + const trimmed = rawType.trim(); + if (!trimmed) return ''; + let out = trimmed + .replace(/\bcharacter\s+varying\b/gi, 'varchar') + .replace(/\bcharacter\b(?=\s*\()/gi, 'char') + .replace(/\btimestamp\s*(?:\(\d+\)\s*)?with\s+time\s+zone\b/gi, 'timestamptz') + .replace(/\btimestamp\s*(?:\(\d+\)\s*)?without\s+time\s+zone\b/gi, 'timestamp') + .replace(/\btime\s*(?:\(\d+\)\s*)?with\s+time\s+zone\b/gi, 'timetz') + .replace(/\btime\s*(?:\(\d+\)\s*)?without\s+time\s+zone\b/gi, 'time') + .replace(/\bdouble\s+precision\b/gi, 'float8') + .replace(/\bboolean\b/gi, 'bool') + .replace(/\binteger\b/gi, 'int4') + .replace(/\bsmallint\b/gi, 'int2') + .replace(/\bbigint\b/gi, 'int8') + .replace(/\s+/g, ' '); + if (out.length > 18) { + out = `${out.slice(0, 17)}…`; + } + return out; +} + +export function erTableKey(table: Pick): string { + return table.schema ? `${table.schema}.${table.name}` : table.name; +} + +export function erCardHeight(table: PluginErTable): number { + return ER_CARD_HEADER_HEIGHT + Math.max(1, table.columns.length) * ER_CARD_ROW_HEIGHT + ER_CARD_FOOTER_PADDING; +} + +function escapeXml(value: string): string { + return value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +export interface ErSvgPalette { + background: string; + card: string; + cardForeground: string; + muted: string; + mutedForeground: string; + border: string; + primary: string; +} + +export function buildStandaloneErSvg( + tables: PluginErTable[], + relations: PluginErRelation[], + positions: Record, + palette: ErSvgPalette, +): string { + const byKey = new Map(); + const byName = new Map(); + for (const tbl of tables) { + byKey.set(erTableKey(tbl), tbl); + if (!byName.has(tbl.name)) byName.set(tbl.name, tbl); + } + const resolveTable = (ref: string) => byKey.get(ref) ?? byName.get(ref); + + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const tbl of tables) { + const pos = positions[erTableKey(tbl)] ?? { x: 40, y: 40 }; + minX = Math.min(minX, pos.x); + minY = Math.min(minY, pos.y); + maxX = Math.max(maxX, pos.x + ER_CARD_WIDTH); + maxY = Math.max(maxY, pos.y + erCardHeight(tbl)); + } + if (!Number.isFinite(minX)) { + minX = 0; minY = 0; maxX = 400; maxY = 240; + } + const pad = 40; + const vbX = Math.floor(minX - pad); + const vbY = Math.floor(minY - pad); + const vbW = Math.max(200, Math.ceil(maxX - minX + pad * 2)); + const vbH = Math.max(160, Math.ceil(maxY - minY + pad * 2)); + + const lines: string[] = [ + ``, + ``, + ]; + + for (const rel of relations) { + const fromTable = resolveTable(rel.fromTable); + const toTable = resolveTable(rel.toTable); + if (!fromTable || !toTable) continue; + const fromPos = positions[erTableKey(fromTable)] ?? { x: 0, y: 0 }; + const toPos = positions[erTableKey(toTable)] ?? { x: 0, y: 0 }; + const fromColIdx = Math.max(0, fromTable.columns.findIndex((c) => c.name === rel.fromColumn)); + const toColIdx = Math.max(0, toTable.columns.findIndex((c) => c.name === rel.toColumn)); + const y1 = fromPos.y + ER_CARD_HEADER_HEIGHT + fromColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2; + const y2 = toPos.y + ER_CARD_HEADER_HEIGHT + toColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2; + const goRight = (toPos.x + ER_CARD_WIDTH / 2) >= (fromPos.x + ER_CARD_WIDTH / 2); + const x1 = goRight ? fromPos.x + ER_CARD_WIDTH : fromPos.x; + const x2 = goRight ? toPos.x : toPos.x + ER_CARD_WIDTH; + const dx = Math.max(48, Math.abs(x2 - x1) * 0.45); + const c1x = goRight ? x1 + dx : x1 - dx; + const c2x = goRight ? x2 - dx : x2 + dx; + lines.push( + ``, + ``, + ``, + ); + } + + for (const tbl of tables) { + const pos = positions[erTableKey(tbl)] ?? { x: 0, y: 0 }; + const h = erCardHeight(tbl); + const title = tbl.schema ? `${tbl.schema}.${tbl.name}` : tbl.name; + lines.push(``); + lines.push(``); + lines.push(``); + lines.push(``); + lines.push(`${escapeXml(title)}`); + + tbl.columns.forEach((col, colIdx) => { + const rowY = ER_CARD_HEADER_HEIGHT + colIdx * ER_CARD_ROW_HEIGHT; + const badgeOffset = (col.isPk ? 26 : 0) + (col.isFk ? 26 : 0); + const shortType = `${abbreviateSqlType(col.type)}${col.nullable ? '?' : ''}`; + const colLabel = col.name.length > 18 ? `${col.name.slice(0, 17)}…` : col.name; + lines.push(``); + if (colIdx > 0) { + lines.push(``); + } + if (col.isPk) { + lines.push(`PK`); + } + if (col.isFk) { + const fkX = col.isPk ? 34 : 8; + lines.push(`FK`); + } + lines.push(`${escapeXml(colLabel)}`); + lines.push(`${escapeXml(shortType)}`); + lines.push(''); + }); + lines.push(''); + } + + lines.push(''); + return lines.join('\n'); +} diff --git a/components/plugins/primitives/shortcuts.ts b/components/plugins/primitives/shortcuts.ts new file mode 100644 index 000000000..3f32acc45 --- /dev/null +++ b/components/plugins/primitives/shortcuts.ts @@ -0,0 +1,36 @@ +import type { PluginWorkbenchShortcut } from './types'; + +export interface KeyboardShortcutLike { + key: string; + metaKey?: boolean; + ctrlKey?: boolean; + altKey?: boolean; + shiftKey?: boolean; +} + +/** + * Normalize global workbench shortcuts pressed inside plugin views/widgets. + * Returns null for unrecognized key combinations. + */ +export function matchWorkbenchShortcut( + event: KeyboardShortcutLike, + options?: { includeUndoRedo?: boolean }, +): PluginWorkbenchShortcut | null { + const includeUndoRedo = options?.includeUndoRedo ?? true; + if (event.key === 'Escape' && !event.metaKey && !event.ctrlKey && !event.altKey) { + return 'escape'; + } + const mod = Boolean(event.metaKey || event.ctrlKey); + if (!mod || event.altKey) return null; + const key = event.key.toLowerCase(); + if (key === 'k' && !event.shiftKey) return 'mod+k'; + if (key === 's' && !event.shiftKey) return 'mod+s'; + if (key === 't' && !event.shiftKey) return 'mod+t'; + if (key === 'w' && !event.shiftKey) return 'mod+w'; + if (includeUndoRedo) { + if (key === 'z' && event.shiftKey) return 'mod+shift+z'; + if (key === 'z' && !event.shiftKey) return 'mod+z'; + if (key === 'y' && event.ctrlKey && !event.metaKey && !event.shiftKey) return 'mod+shift+z'; + } + return null; +} diff --git a/components/plugins/primitives/types.ts b/components/plugins/primitives/types.ts index d7e6beecc..8b48ef92a 100644 --- a/components/plugins/primitives/types.ts +++ b/components/plugins/primitives/types.ts @@ -3,6 +3,15 @@ export type PluginWidgetEventCallback = ( detail?: Record, ) => void; +export type PluginWorkbenchShortcut = + | 'mod+k' + | 'mod+s' + | 'mod+t' + | 'mod+w' + | 'mod+z' + | 'mod+shift+z' + | 'escape'; + export interface PluginCodeEditorCompletionColumn { name: string; type?: string; @@ -48,6 +57,12 @@ export interface PluginCodeEditorWidgetProps { height?: number | string; } +export interface PluginDataGridForeignKey { + table: string; + column: string; + schema?: string; +} + export interface PluginDataGridColumn { name: string; type?: string; @@ -55,6 +70,7 @@ export interface PluginDataGridColumn { nullable?: boolean; width?: number; sortable?: boolean; + foreignKey?: PluginDataGridForeignKey; } export interface PluginDataGridSort { @@ -67,6 +83,7 @@ export type PluginDataGridRow = Record | unknown[]; export interface PluginDataGridWidgetProps { columns?: PluginDataGridColumn[]; rows?: PluginDataGridRow[]; + hiddenColumns?: string[]; rowKeyField?: string; dirtyCells?: Record; deletedRowIndices?: number[]; @@ -109,6 +126,8 @@ export interface PluginErRelation { toTable: string; toColumn: string; name?: string; + onDelete?: string; + onUpdate?: string; } export interface PluginErCanvasWidgetProps { diff --git a/packages/plugin-sdk/src/hostDom.ts b/packages/plugin-sdk/src/hostDom.ts index a79f8131e..3fe576872 100644 --- a/packages/plugin-sdk/src/hostDom.ts +++ b/packages/plugin-sdk/src/hostDom.ts @@ -107,6 +107,24 @@ function subscribeControlPropertyMutations(container: HTMLElement, onMutation: ( const MAX_PLUGIN_CSS_LENGTH = 131072; const MAX_PLUGIN_EVENT_VALUE_LENGTH = 131072; +function matchShortcutFromKeyEvent(event: HostDrawnViewEvent, isTextControl: boolean): string | null { + const key = event.key ?? ''; + if (key === 'Escape' && !event.metaKey && !event.ctrlKey && !event.altKey) return 'escape'; + const mod = Boolean(event.metaKey || event.ctrlKey); + if (!mod || event.altKey) return null; + const lower = key.toLowerCase(); + if (lower === 'k' && !event.shiftKey) return 'mod+k'; + if (lower === 's' && !event.shiftKey) return 'mod+s'; + if (lower === 't' && !event.shiftKey) return 'mod+t'; + if (lower === 'w' && !event.shiftKey) return 'mod+w'; + if (!isTextControl) { + if (lower === 'z' && event.shiftKey) return 'mod+shift+z'; + if (lower === 'z' && !event.shiftKey) return 'mod+z'; + if (lower === 'y' && event.ctrlKey && !event.metaKey && !event.shiftKey) return 'mod+shift+z'; + } + return null; +} + /** Build ordinary DOM in the isolated runtime; only validated data reaches the visible host. */ export function registerHostDomView(views: PluginViews, viewId: string, mount: (container: HTMLElement, stateScope: string) => (() => void) | void, css = ''): Disposable { if (css.length > MAX_PLUGIN_CSS_LENGTH) throw new TypeError('Plugin CSS exceeds the view limit'); @@ -148,10 +166,18 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: ( const eventType = event.type; if (eventType === 'dismiss') { element.dispatchEvent(new Event('netcatty-dismiss')); return; } if (eventType === 'widget') { - element.dispatchEvent(new CustomEvent('netcatty-widget-event', { + const widgetEvent = new CustomEvent('netcatty-widget-event', { bubbles: false, + cancelable: true, detail: { widgetEvent: event.widgetEvent, detail: event.detail }, - })); + }); + element.dispatchEvent(widgetEvent); + if (!widgetEvent.defaultPrevented && event.widgetEvent === 'shortcut' && event.detail && typeof event.detail === 'object' && !Array.isArray(event.detail)) { + const shortcut = (event.detail as Record).shortcut; + if (typeof shortcut === 'string') { + element.dispatchEvent(new CustomEvent('netcatty-shortcut', { bubbles: true, detail: { shortcut } })); + } + } return; } if (eventType === 'dblclick') { @@ -209,11 +235,18 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: ( if (eventType === 'reset' && element instanceof HTMLFormElement) { element.reset(); return; } if (eventType === 'submit') { const action = new Event(eventType, { bubbles: true, cancelable: true }); action.preventDefault(); element.dispatchEvent(action); return; } if (eventType === 'keydown' || eventType === 'keyup') { - if ((element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) - && typeof event.selectionStart === 'number' && typeof event.selectionEnd === 'number') { + const isTextControl = element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement; + if (isTextControl && typeof event.selectionStart === 'number' && typeof event.selectionEnd === 'number') { try { element.setSelectionRange(event.selectionStart, event.selectionEnd); } catch {} } - element.dispatchEvent(new KeyboardEvent(eventType, { key: event.key ?? '', ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey, bubbles: true, cancelable: true })); return; + element.dispatchEvent(new KeyboardEvent(eventType, { key: event.key ?? '', ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey, bubbles: true, cancelable: true })); + if (eventType === 'keydown') { + const shortcut = matchShortcutFromKeyEvent(event, isTextControl); + if (shortcut) { + element.dispatchEvent(new CustomEvent('netcatty-shortcut', { bubbles: true, detail: { shortcut } })); + } + } + return; } if (eventType.startsWith('composition')) { element.dispatchEvent(new CompositionEvent(eventType, { data: event.data ?? '', bubbles: true })); return; } if (eventType === 'focusin' || eventType === 'focusout') { element.dispatchEvent(new FocusEvent(eventType, { bubbles: true })); return; } diff --git a/packages/plugin-sdk/src/hostReact.test.tsx b/packages/plugin-sdk/src/hostReact.test.tsx index 8797171e6..5f0c4f2ee 100644 --- a/packages/plugin-sdk/src/hostReact.test.tsx +++ b/packages/plugin-sdk/src/hostReact.test.tsx @@ -426,7 +426,7 @@ test('hostDom syncs valueAsNumber, valueAsDate, stepUp, stepDown, and setRangeTe test('hostReact widgets and extended surface events round-trip cleanly through hostDom', async () => { const dom = new JSDOM('', { url: 'http://localhost', pretendToBeVisual: true }); const saved = new Map(); - for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLOptionElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'CustomEvent', 'MouseEvent']) { + for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLOptionElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'CustomEvent', 'MouseEvent', 'KeyboardEvent']) { 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] }); } @@ -436,6 +436,7 @@ test('hostReact widgets and extended surface events round-trip cleanly through h const { remoteId } = await import('@remote-dom/core/elements'); const { registerHostReactView, + usePluginShortcuts, PluginPopover, PluginCodeEditor, PluginDataGrid, @@ -453,7 +454,9 @@ test('hostReact widgets and extended surface events round-trip cleanly through h }; const received: Record = {}; + const globalShortcuts: string[] = []; function IdeView() { + usePluginShortcuts((sc) => { globalShortcuts.push(sc); }); return (
); @@ -506,18 +515,35 @@ test('hostReact widgets and extended surface events round-trip cleanly through h await act(async () => { receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'dblclick', nodeId: remoteId(btn), x: 12, y: 34 } }); receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'contextmenu', nodeId: remoteId(btn), x: 56, y: 78 } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'keydown', nodeId: remoteId(btn), key: 'k', metaKey: true } }); receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(editorEl), widgetEvent: 'execute', detail: { value: 'SELECT 1;', selectedText: '', currentStatement: 'SELECT 1' } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(editorEl), widgetEvent: 'shortcut', detail: { shortcut: 'mod+s' } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'shortcut', detail: { shortcut: 'mod+z' } } }); receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'id', value: '2', isNull: false } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'fkJump', detail: { rowIndex: 0, colName: 'id', value: 1, targetTable: 'users', targetColumn: 'id' } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'cellCopy', detail: { text: '1', rowIndex: 0, colName: 'id', rowIndices: [0] } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'cellDoubleClick', detail: { rowIndex: 0, colName: 'id', value: 1 } } }); receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(splitEl), widgetEvent: 'resizeEnd', detail: { size: 320, collapsed: false } } }); receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(erEl), widgetEvent: 'tableClick', detail: { table: 'users' } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(erEl), widgetEvent: 'tableDoubleClick', detail: { table: 'users' } } }); + receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(erEl), widgetEvent: 'exportSvg', detail: { svg: '' } } }); }); assert.deepEqual(received.dblclick, { x: 12, y: 34 }); assert.deepEqual(received.contextmenu, { x: 56, y: 78 }); assert.deepEqual(received.execute, { value: 'SELECT 1;', selectedText: '', currentStatement: 'SELECT 1' }); + assert.deepEqual(received.editorShortcut, { shortcut: 'mod+s' }); + // editorEl consumed mod+s via onShortcut (must NOT double-fire usePluginShortcuts); + // btn (Shadow DOM) and gridEl (no onShortcut) bubble to usePluginShortcuts once each. + assert.deepEqual(globalShortcuts, ['mod+k', 'mod+z']); assert.deepEqual(received.cellEdit, { rowIndex: 0, colName: 'id', value: '2', isNull: false }); + assert.deepEqual(received.fkJump, { rowIndex: 0, colName: 'id', value: 1, targetTable: 'users', targetColumn: 'id' }); + assert.deepEqual(received.cellCopy, { text: '1', rowIndex: 0, colName: 'id', rowIndices: [0] }); + assert.deepEqual(received.cellDoubleClick, { rowIndex: 0, colName: 'id', value: 1 }); assert.deepEqual(received.resizeEnd, { size: 320, collapsed: false }); assert.deepEqual(received.tableClick, { table: 'users' }); + assert.deepEqual(received.tableDoubleClick, { table: 'users' }); + assert.deepEqual(received.exportSvg, { svg: '' }); await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'ide-1' }); }); } finally { await act(async () => { registration.dispose(); }); diff --git a/packages/plugin-sdk/src/hostReact.ts b/packages/plugin-sdk/src/hostReact.ts index 8760bbe1a..68f0a4389 100644 --- a/packages/plugin-sdk/src/hostReact.ts +++ b/packages/plugin-sdk/src/hostReact.ts @@ -10,6 +10,34 @@ export function registerHostReactView(views: PluginViews, viewId: string, render }, css); } +export type PluginWorkbenchShortcut = + | 'mod+k' + | 'mod+s' + | 'mod+t' + | 'mod+w' + | 'mod+z' + | 'mod+shift+z' + | 'escape'; + +/** + * Subscribe to normalized global workbench shortcuts forwarded from both the + * Shadow DOM surface and slotted host-rendered widgets (CodeEditor, DataGrid, ErCanvas). + */ +export function usePluginShortcuts(handler: (shortcut: PluginWorkbenchShortcut) => void): void { + const handlerRef = useRef(handler); + handlerRef.current = handler; + useEffect(() => { + const listener = (event: Event) => { + const shortcut = (event as CustomEvent<{ shortcut?: PluginWorkbenchShortcut }>).detail?.shortcut; + if (typeof shortcut === 'string') { + handlerRef.current(shortcut); + } + }; + document.addEventListener('netcatty-shortcut', listener); + return () => document.removeEventListener('netcatty-shortcut', listener); + }, []); +} + export interface PluginPopoverProps { anchor?: string; anchorX?: number; @@ -58,7 +86,7 @@ type WidgetEventDetail = { widgetEvent?: string; detail?: Record, - handler: (widgetEvent: string, detail: Record) => void, + handler: (widgetEvent: string, detail: Record) => boolean | void, ) { const handlerRef = useRef(handler); handlerRef.current = handler; @@ -68,7 +96,9 @@ function useWidgetEventBridge( const listener = (event: Event) => { const payload = (event as CustomEvent).detail; if (!payload || typeof payload.widgetEvent !== 'string') return; - handlerRef.current(payload.widgetEvent, payload.detail ?? {}); + if (handlerRef.current(payload.widgetEvent, payload.detail ?? {}) === true) { + event.preventDefault(); + } }; node.addEventListener('netcatty-widget-event', listener); return () => node.removeEventListener('netcatty-widget-event', listener); @@ -124,6 +154,7 @@ export interface PluginCodeEditorProps { onSelection?: (detail: { selectionStart: number; selectionEnd: number; selectedText: string }) => void; onExecute?: (detail: { value: string; selectedText: string; currentStatement: string }) => void; onFormat?: (detail: { value: string }) => void; + onShortcut?: (detail: { shortcut: PluginWorkbenchShortcut }) => void; } /** Host-rendered Monaco code editor with local zero-IPC schema completion. */ @@ -144,6 +175,7 @@ export function PluginCodeEditor({ onSelection, onExecute, onFormat, + onShortcut, }: PluginCodeEditorProps) { const ref = useRef(null); useWidgetEventBridge(ref, (eventName, detail) => { @@ -151,6 +183,7 @@ export function PluginCodeEditor({ else if (eventName === 'selection') onSelection?.(detail as { selectionStart: number; selectionEnd: number; selectedText: string }); else if (eventName === 'execute') onExecute?.(detail as { value: string; selectedText: string; currentStatement: string }); else if (eventName === 'format') onFormat?.(detail as { value: string }); + else if (eventName === 'shortcut' && onShortcut) { onShortcut(detail as { shortcut: PluginWorkbenchShortcut }); return true; } }); const serialized = useMemo( () => JSON.stringify({ @@ -176,6 +209,12 @@ export function PluginCodeEditor({ }); } +export interface PluginDataGridForeignKey { + table: string; + column: string; + schema?: string; +} + export interface PluginDataGridColumn { name: string; type?: string; @@ -183,6 +222,7 @@ export interface PluginDataGridColumn { nullable?: boolean; width?: number; sortable?: boolean; + foreignKey?: PluginDataGridForeignKey; } export interface PluginDataGridSort { @@ -195,6 +235,7 @@ export type PluginDataGridRow = Record | unknown[]; export interface PluginDataGridProps { columns: PluginDataGridColumn[]; rows: PluginDataGridRow[]; + hiddenColumns?: string[]; rowKeyField?: string; dirtyCells?: Record; deletedRowIndices?: number[]; @@ -207,16 +248,21 @@ export interface PluginDataGridProps { className?: string; style?: CSSProperties; onCellSelect?: (detail: { rowIndex: number; colName: string; value: unknown }) => void; + onCellDoubleClick?: (detail: { rowIndex: number; colName: string; value: unknown }) => void; onCellEdit?: (detail: { rowIndex: number; colName: string; value: unknown; isNull: boolean }) => void; onCellContextMenu?: (detail: { rowIndex: number; colName: string; x: number; y: number }) => void; + onCellCopy?: (detail: { text: string; rowIndex: number | null; colName: string | null; rowIndices: number[] }) => void; + onFkJump?: (detail: { rowIndex: number; colName: string; value: unknown; targetTable: string; targetColumn: string; targetSchema?: string }) => void; onSortChange?: (detail: { column: string; direction: 'asc' | 'desc' }) => void; onRowSelect?: (detail: { selectedRowIndices: number[] }) => void; + onShortcut?: (detail: { shortcut: PluginWorkbenchShortcut }) => void; } /** Host-rendered virtualized editable data grid powered by @tanstack/react-virtual. */ export function PluginDataGrid({ columns, rows, + hiddenColumns, rowKeyField, dirtyCells, deletedRowIndices, @@ -229,23 +275,32 @@ export function PluginDataGrid({ className, style, onCellSelect, + onCellDoubleClick, onCellEdit, onCellContextMenu, + onCellCopy, + onFkJump, onSortChange, onRowSelect, + onShortcut, }: PluginDataGridProps) { const ref = useRef(null); useWidgetEventBridge(ref, (eventName, detail) => { if (eventName === 'cellSelect') onCellSelect?.(detail as { rowIndex: number; colName: string; value: unknown }); + else if (eventName === 'cellDoubleClick') onCellDoubleClick?.(detail as { rowIndex: number; colName: string; value: unknown }); else if (eventName === 'cellEdit') onCellEdit?.(detail as { rowIndex: number; colName: string; value: unknown; isNull: boolean }); else if (eventName === 'cellContextMenu') onCellContextMenu?.(detail as { rowIndex: number; colName: string; x: number; y: number }); + else if (eventName === 'cellCopy') onCellCopy?.(detail as { text: string; rowIndex: number | null; colName: string | null; rowIndices: number[] }); + else if (eventName === 'fkJump') onFkJump?.(detail as { rowIndex: number; colName: string; value: unknown; targetTable: string; targetColumn: string; targetSchema?: string }); else if (eventName === 'sortChange') onSortChange?.(detail as { column: string; direction: 'asc' | 'desc' }); else if (eventName === 'rowSelect') onRowSelect?.(detail as { selectedRowIndices: number[] }); + else if (eventName === 'shortcut' && onShortcut) { onShortcut(detail as { shortcut: PluginWorkbenchShortcut }); return true; } }); const serialized = useMemo( () => JSON.stringify({ columns, rows, + ...(hiddenColumns !== undefined ? { hiddenColumns } : {}), ...(rowKeyField !== undefined ? { rowKeyField } : {}), ...(dirtyCells !== undefined ? { dirtyCells } : {}), ...(deletedRowIndices !== undefined ? { deletedRowIndices } : {}), @@ -256,7 +311,7 @@ export function PluginDataGrid({ ...(loading !== undefined ? { loading } : {}), ...(emptyMessage !== undefined ? { emptyMessage } : {}), }), - [columns, rows, rowKeyField, dirtyCells, deletedRowIndices, insertedRows, selectedRowIndices, sort, editable, loading, emptyMessage], + [columns, rows, hiddenColumns, rowKeyField, dirtyCells, deletedRowIndices, insertedRows, selectedRowIndices, sort, editable, loading, emptyMessage], ); return createElement('div', { ref, @@ -343,6 +398,8 @@ export interface PluginErRelation { toTable: string; toColumn: string; name?: string; + onDelete?: string; + onUpdate?: string; } export interface PluginErCanvasProps { @@ -351,6 +408,9 @@ export interface PluginErCanvasProps { className?: string; style?: CSSProperties; onTableClick?: (detail: { table: string; schema?: string }) => void; + onTableDoubleClick?: (detail: { table: string; schema?: string }) => void; + onExportSvg?: (detail: { svg: string }) => void; + onShortcut?: (detail: { shortcut: PluginWorkbenchShortcut }) => void; } /** Host-rendered interactive pan/zoom SVG ER diagram canvas. */ @@ -360,10 +420,16 @@ export function PluginErCanvas({ className, style, onTableClick, + onTableDoubleClick, + onExportSvg, + onShortcut, }: PluginErCanvasProps) { const ref = useRef(null); useWidgetEventBridge(ref, (eventName, detail) => { if (eventName === 'tableClick') onTableClick?.(detail as { table: string; schema?: string }); + else if (eventName === 'tableDoubleClick') onTableDoubleClick?.(detail as { table: string; schema?: string }); + else if (eventName === 'exportSvg') onExportSvg?.(detail as { svg: string }); + else if (eventName === 'shortcut' && onShortcut) { onShortcut(detail as { shortcut: PluginWorkbenchShortcut }); return true; } }); const serialized = useMemo( () => JSON.stringify({ tables, relations }), From db433c4c192202b0888f1a13d342be785c2c91b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:47:31 +0800 Subject: [PATCH 09/24] fix(terminal): keep magnified pane chrome through the shrink animation (#4335) (#4450) Co-authored-by: Codex --- .../terminalLayer/TerminalLayerSupport.tsx | 6 +-- .../TerminalLayerWorkspaceSection.test.ts | 37 ++++++++++++++++--- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/components/terminalLayer/TerminalLayerSupport.tsx b/components/terminalLayer/TerminalLayerSupport.tsx index 0b93baf55..bed750fb8 100644 --- a/components/terminalLayer/TerminalLayerSupport.tsx +++ b/components/terminalLayer/TerminalLayerSupport.tsx @@ -1643,12 +1643,12 @@ const TerminalPane: React.FC = memo(({ "absolute bg-background", inActiveWorkspace && "workspace-pane", isVisible && "z-10", - isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl", + magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl", )} style={{ ...style, - borderColor: isMagnified && magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined, - borderWidth: isMagnified && magnifiedSurfaceBounds + borderColor: magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined, + borderWidth: magnifiedSurfaceBounds ? resolveMagnifiedChromeBorderWidth(magnifiedDevicePixelRatio) : undefined, }} diff --git a/components/terminalLayer/TerminalLayerWorkspaceSection.test.ts b/components/terminalLayer/TerminalLayerWorkspaceSection.test.ts index 9acf815a5..52a37890d 100644 --- a/components/terminalLayer/TerminalLayerWorkspaceSection.test.ts +++ b/components/terminalLayer/TerminalLayerWorkspaceSection.test.ts @@ -5,18 +5,45 @@ import React from "react"; import { act, create } from "react-test-renderer"; import { sidePanelLiveStore, SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT } from "../../application/state/sidePanelLiveStore.ts"; import { createEmptyWorkspaceRoot } from "../../domain/workspace.ts"; +import { resolveMagnifiedChromeBorderWidth } from "../../domain/paneMagnification.ts"; import { renderToStaticMarkup } from "react-dom/server"; import { TerminalLayerWorkspaceSection } from "./TerminalLayerWorkspaceSection.tsx"; -test("magnified terminal panes use the resolved terminal accent for border chrome", () => { +test("terminal pane chrome follows retained surface bounds through restore", () => { const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8"); const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf(" { + const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8"); + const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf(" { From 6236f5bb95949eedb101586ae92e156a56e60012 Mon Sep 17 00:00:00 2001 From: Radwan Selo <133098464+RadwanSelo@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:23:51 +0900 Subject: [PATCH 10/24] fix(mcp): keep host and group proxy updates consistent with Host Details (#4443) * fix(mcp): keep vault_hosts_update proxy changes consistent with Host Details - Selecting a proxy profile now removes an explicit direct choice, so the host actually connects through the selected proxy instead of staying direct. - Clearing with an empty proxyProfileId now removes every host proxy setting (as the Host Details remove button does) instead of storing "". The stored "" made Host Details show no proxy and skipped a group's one-off proxy. - Correct the proxyProfileId description: an empty value inherits the group or global default proxy rather than clearing it. * fix(mcp): clearing a group proxy lets the parent group proxy apply vault_groups_update stored proxyProfileId "" on the group. resolveGroupDefaults treats that as a group value, so it dropped the parent group's proxy and hosts in the child group fell back to the global default or no proxy. Group Details removes the keys instead; do the same. --- domain/vaultGroupAgentOps.test.ts | 22 +++++++++ domain/vaultGroupAgentOps.ts | 4 +- domain/vaultHostCreate.test.ts | 45 ++++++++++++++++++- domain/vaultHostCreate.ts | 6 ++- electron/capabilities/schemas/toolInputs.cjs | 2 +- .../ai/harness/generated/cattyToolSpecs.json | 2 +- .../generated/globalAgentToolSpecs.json | 2 +- 7 files changed, 77 insertions(+), 6 deletions(-) diff --git a/domain/vaultGroupAgentOps.test.ts b/domain/vaultGroupAgentOps.test.ts index bf0d7f18c..a9ce0a2d1 100644 --- a/domain/vaultGroupAgentOps.test.ts +++ b/domain/vaultGroupAgentOps.test.ts @@ -1,6 +1,7 @@ import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import type { Host, ManagedSource, ProxyProfile } from './models'; +import { applyGroupDefaults, resolveGroupDefaults } from './groupConfig'; import { deleteGroup, upsertGroup } from './vaultGroupAgentOps'; const hosts: Host[] = [ @@ -25,6 +26,27 @@ describe('vaultGroupAgentOps', () => { assert.equal(result.config?.username, 'deploy'); }); + it('clearing a child group proxy lets the parent group proxy apply, like Group Details', () => { + const result = upsertGroup({ + groups: ['prod', 'prod/web'], + configs: [ + { path: 'prod', proxyConfig: { type: 'http', host: 'parent-gw.test', port: 3128 } }, + { path: 'prod/web', proxyProfileId: 'proxy-1' }, + ], + hosts, + managedSources: [], + }, 'prod/web', '{"proxyProfileId":""}', [], proxyProfiles); + assert.equal(result.ok, true); + if (!result.ok) return; + assert.equal(result.config?.proxyProfileId, undefined); + assert.equal(result.config?.proxyConfig, undefined); + const proxyOptions = { validProxyProfileIds: new Set(['proxy-1']), globalProxyProfileId: '' }; + const effective = applyGroupDefaults( + hosts[0], resolveGroupDefaults('prod/web', result.state.configs, proxyOptions), proxyOptions, + ); + assert.equal(effective.proxyConfig?.host, 'parent-gw.test'); + }); + 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); diff --git a/domain/vaultGroupAgentOps.ts b/domain/vaultGroupAgentOps.ts index 2c43651bd..b27ba1354 100644 --- a/domain/vaultGroupAgentOps.ts +++ b/domain/vaultGroupAgentOps.ts @@ -149,7 +149,9 @@ export function patchGroupConfig( if (proxyProfileId && !proxyProfiles.some((profile) => profile.id === proxyProfileId)) { return { ok: false, error: `Proxy profile "${proxyProfileId}" was not found.` }; } - next.proxyProfileId = proxyProfileId; + // Like Group Details: an empty value removes the group proxy so a parent + // group proxy (or the global default) applies, instead of blocking it. + next.proxyProfileId = proxyProfileId || undefined; next.proxyConfig = undefined; } if (Object.hasOwn(defaults, 'jumpHostIds')) { diff --git a/domain/vaultHostCreate.test.ts b/domain/vaultHostCreate.test.ts index b1efa6014..88395cb61 100644 --- a/domain/vaultHostCreate.test.ts +++ b/domain/vaultHostCreate.test.ts @@ -643,7 +643,7 @@ test('applyVaultHostUpdate applies and clears advanced connection settings', () assert.equal(cleared.ok, true); if (!cleared.ok) return; assert.deepEqual(cleared.updatedHost.hostChain, { hostIds: [] }); - assert.equal(cleared.updatedHost.proxyProfileId, ''); + assert.equal(cleared.updatedHost.proxyProfileId, undefined); assert.equal(cleared.updatedHost.startupCommand, ''); assert.equal(cleared.updatedHost.startupCommandRunMode, undefined); assert.deepEqual(cleared.updatedHost.environmentVariables, []); @@ -652,6 +652,49 @@ test('applyVaultHostUpdate applies and clears advanced connection settings', () assert.equal(cleared.updatedHost.etEnabled, false); }); +const proxyUpdateProfile: ProxyProfile = { + id: 'proxy-1', label: 'proxy', config: { type: 'socks5', host: '127.0.0.1', port: 1080 }, createdAt: 1, +}; +const proxyUpdateHost = (overrides: Partial = {}): Host => ({ + id: 'host-1', label: 'host', hostname: 'host.example.com', username: 'root', tags: [], os: 'linux', + ...overrides, +}); +const updateProxy = (host: Host, patch: VaultHostUpdatePatch) => applyVaultHostUpdate( + [host], [], host.id, patch, { proxyProfiles: [proxyUpdateProfile] }, +); +const proxyOptions = { validProxyProfileIds: new Set([proxyUpdateProfile.id]), globalProxyProfileId: '' }; + +test('applyVaultHostUpdate selecting a proxy profile replaces an explicit direct choice', () => { + const result = updateProxy( + proxyUpdateHost({ directProxy: true }), + { proxyProfileId: proxyUpdateProfile.id }, + ); + assert.equal(result.ok, true); + if (!result.ok) return; + assert.equal(result.updatedHost.proxyProfileId, proxyUpdateProfile.id); + assert.equal(result.updatedHost.directProxy, undefined); + assert.equal(result.updatedHost.proxyConfig, undefined); + assert.equal(applyGroupDefaults(result.updatedHost, {}, proxyOptions).proxyProfileId, proxyUpdateProfile.id); +}); + +test('applyVaultHostUpdate clearing the proxy removes every host proxy setting so group proxies apply', () => { + const groupProxyConfig = { type: 'http' as const, host: 'group-proxy.example.com', port: 3128 }; + for (const current of [ + proxyUpdateHost({ proxyProfileId: proxyUpdateProfile.id }), + proxyUpdateHost({ proxyConfig: { type: 'http', host: 'host-proxy.example.com', port: 8080 } }), + proxyUpdateHost({ directProxy: true }), + ]) { + const result = updateProxy(current, { proxyProfileId: '' }); + assert.equal(result.ok, true, JSON.stringify(current)); + if (!result.ok) continue; + assert.equal(result.updatedHost.proxyProfileId, undefined); + assert.equal(result.updatedHost.proxyConfig, undefined); + assert.equal(result.updatedHost.directProxy, undefined); + const effective = applyGroupDefaults(result.updatedHost, { proxyConfig: groupProxyConfig }, proxyOptions); + assert.deepEqual(effective.proxyConfig, groupProxyConfig); + } +}); + test('applyVaultHostUpdate rejects malformed advanced connection settings', () => { const host: Host = { id: 'host-1', label: 'host', hostname: 'host.example.com', username: 'root', tags: [], os: 'linux', diff --git a/domain/vaultHostCreate.ts b/domain/vaultHostCreate.ts index d64e0bea4..39d0e8bc7 100644 --- a/domain/vaultHostCreate.ts +++ b/domain/vaultHostCreate.ts @@ -514,8 +514,12 @@ export function applyVaultHostUpdate( if (nextProxyProfileId && !options.proxyProfiles?.some((profile) => profile.id === nextProxyProfileId)) { return { ok: false, error: `Proxy profile "${nextProxyProfileId}" was not found.` }; } - updated.proxyProfileId = nextProxyProfileId; + // Mirror the Host Details proxy panel: a selected profile replaces any + // one-off proxy and the explicit direct choice; an empty value removes + // every host proxy setting so the group and global default apply again. + updated.proxyProfileId = nextProxyProfileId || undefined; updated.proxyConfig = undefined; + updated.directProxy = undefined; } if (startupCommand.provided) { if (typeof startupCommand.value !== 'string') return { ok: false, error: 'startupCommand must be a string.' }; diff --git a/electron/capabilities/schemas/toolInputs.cjs b/electron/capabilities/schemas/toolInputs.cjs index efde6d2ba..3dbea23a5 100644 --- a/electron/capabilities/schemas/toolInputs.cjs +++ b/electron/capabilities/schemas/toolInputs.cjs @@ -145,7 +145,7 @@ const TOOL_INPUT_FIELDS = Object.freeze({ os: { type: "string", optional: true, description: "Operating system override: auto (default), linux, windows, macos, freebsd, or unknown. Use auto to use detected system information; network device mode is separate." }, identityId: { type: "string", optional: true, description: "Reusable identity ID from vault_identities_list. Empty string detaches the identity." }, jumpHostIds: { type: "string", optional: true, description: "JSON array of vault host IDs in jump order. Empty array clears the chain." }, - proxyProfileId: { type: "string", optional: true, description: "Reusable proxy ID from vault_proxy_profiles_list. Empty string clears it." }, + proxyProfileId: { type: "string", optional: true, description: "Reusable proxy ID from vault_proxy_profiles_list. Empty string removes it so the group or global default applies." }, startupCommand: { type: "string", optional: true, description: "Command to run after connecting. Empty string clears it." }, startupCommandRunMode: { type: "string", optional: true, description: "paste or lineDelay." }, environmentVariables: { type: "string", optional: true, description: "JSON object or array of {name,value} entries. Empty object clears them." }, diff --git a/infrastructure/ai/harness/generated/cattyToolSpecs.json b/infrastructure/ai/harness/generated/cattyToolSpecs.json index b2620ac1b..a49fe7bd1 100644 --- a/infrastructure/ai/harness/generated/cattyToolSpecs.json +++ b/infrastructure/ai/harness/generated/cattyToolSpecs.json @@ -759,7 +759,7 @@ "proxyProfileId": { "type": "string", "optional": true, - "description": "Reusable proxy ID from vault_proxy_profiles_list. Empty string clears it." + "description": "Reusable proxy ID from vault_proxy_profiles_list. Empty string removes it so the group or global default applies." }, "startupCommand": { "type": "string", diff --git a/infrastructure/ai/harness/generated/globalAgentToolSpecs.json b/infrastructure/ai/harness/generated/globalAgentToolSpecs.json index f6a27a98e..fd28b832d 100644 --- a/infrastructure/ai/harness/generated/globalAgentToolSpecs.json +++ b/infrastructure/ai/harness/generated/globalAgentToolSpecs.json @@ -817,7 +817,7 @@ "proxyProfileId": { "type": "string", "optional": true, - "description": "Reusable proxy ID from vault_proxy_profiles_list. Empty string clears it." + "description": "Reusable proxy ID from vault_proxy_profiles_list. Empty string removes it so the group or global default applies." }, "startupCommand": { "type": "string", From 1009f131fe5c4d09d49fbafab38fcf42dee07c03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:25:32 +0800 Subject: [PATCH 11/24] fix(ui): use a 1px continuous stroke for magnified pane chrome (#4168) (#4452) Co-authored-by: Codex --- .../TerminalLayerSidePanelSection.test.ts | 12 ++++++++ .../TerminalLayerSidePanelSection.tsx | 10 +++---- .../terminalLayer/TerminalLayerSupport.tsx | 9 +++--- .../TerminalLayerWorkspaceSection.test.ts | 30 +++++++++---------- domain/paneMagnification.test.ts | 10 ------- domain/paneMagnification.ts | 4 --- 6 files changed, 35 insertions(+), 40 deletions(-) diff --git a/components/terminalLayer/TerminalLayerSidePanelSection.test.ts b/components/terminalLayer/TerminalLayerSidePanelSection.test.ts index 912d261fc..c7e082f85 100644 --- a/components/terminalLayer/TerminalLayerSidePanelSection.test.ts +++ b/components/terminalLayer/TerminalLayerSidePanelSection.test.ts @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; import test from 'node:test'; import { JSDOM } from 'jsdom'; @@ -19,6 +20,17 @@ import { resolveSidePanelPortalTarget, } from './terminalLayerSidePanelSlots.tsx'; +test('magnified side panels use a continuous 1px inset outline in the side panel accent', () => { + const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); + const chromeStart = source.indexOf('className="absolute inset-3'); + const chromeSource = source.slice(chromeStart, source.indexOf('\n >', chromeStart)); + + assert.match(chromeSource, /overflow-hidden rounded-md bg-background shadow-2xl/); + assert.match(chromeSource, /outline: `1px solid \$\{sidePanelTheme\.accent\}`/); + assert.match(chromeSource, /outlineOffset: -1/); + assert.doesNotMatch(chromeSource, /\bborder(?:Color|Width|Style)?\b/); +}); + test('AI side panel shell can be force-hidden for layout isolation', () => { assert.equal(getTerminalSidePanelShellWidth({ activeSidePanelTab: 'ai', diff --git a/components/terminalLayer/TerminalLayerSidePanelSection.tsx b/components/terminalLayer/TerminalLayerSidePanelSection.tsx index b6f344fac..609cfc9db 100644 --- a/components/terminalLayer/TerminalLayerSidePanelSection.tsx +++ b/components/terminalLayer/TerminalLayerSidePanelSection.tsx @@ -64,7 +64,7 @@ import { PersistentSidePanelPortal, SidePanelMountedContent } from './terminalLa import { usePluginTerminalSidebar } from '../../application/state/usePluginTerminalSidebar'; import { PluginTerminalSidebarPageHost } from '../plugins/PluginTerminalSidebar'; import { PluginContributionIcon } from '../plugins/PluginContributionIcon'; -import { getPaneMagnificationShortcutLabel, resolveMagnifiedChromeBorderWidth } from '../../domain/paneMagnification'; +import { getPaneMagnificationShortcutLabel } from '../../domain/paneMagnification'; const MemoizedSidePanelMountedContent = memo( SidePanelMountedContent, @@ -1567,12 +1567,10 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon data-section="pane-magnification-backdrop" />
= memo(({ "absolute bg-background", inActiveWorkspace && "workspace-pane", isVisible && "z-10", - magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl", + magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl", )} style={{ ...style, - borderColor: magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined, - borderWidth: magnifiedSurfaceBounds - ? resolveMagnifiedChromeBorderWidth(magnifiedDevicePixelRatio) + outline: magnifiedSurfaceBounds + ? `1px solid ${sessionAppearanceTheme.colors.cursor}` : undefined, + outlineOffset: magnifiedSurfaceBounds ? -1 : undefined, }} tabIndex={-1} onClick={handlePaneClick} diff --git a/components/terminalLayer/TerminalLayerWorkspaceSection.test.ts b/components/terminalLayer/TerminalLayerWorkspaceSection.test.ts index 52a37890d..b35da8a5d 100644 --- a/components/terminalLayer/TerminalLayerWorkspaceSection.test.ts +++ b/components/terminalLayer/TerminalLayerWorkspaceSection.test.ts @@ -5,43 +5,43 @@ import React from "react"; import { act, create } from "react-test-renderer"; import { sidePanelLiveStore, SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT } from "../../application/state/sidePanelLiveStore.ts"; import { createEmptyWorkspaceRoot } from "../../domain/workspace.ts"; -import { resolveMagnifiedChromeBorderWidth } from "../../domain/paneMagnification.ts"; import { renderToStaticMarkup } from "react-dom/server"; import { TerminalLayerWorkspaceSection } from "./TerminalLayerWorkspaceSection.tsx"; -test("terminal pane chrome follows retained surface bounds through restore", () => { +test("terminal pane chrome follows retained surface bounds through restore with a continuous 1px inset outline", () => { const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8"); const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf(" { +test("restoring terminal chrome keeps its 1px inset outline until surface bounds clear at any DPR", () => { const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8"); const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf(" { - assert.equal(resolveMagnifiedChromeBorderWidth(1), 2); - assert.equal(resolveMagnifiedChromeBorderWidth(1.2), 2); - assert.equal(resolveMagnifiedChromeBorderWidth(1.49), 2); - assert.equal(resolveMagnifiedChromeBorderWidth(1.5), 1); - assert.equal(resolveMagnifiedChromeBorderWidth(2), 1); - assert.equal(resolveMagnifiedChromeBorderWidth(0), 1); -}); - test('magnified surface bounds snap to the device-pixel grid after the 12px inset', () => { const original = { left: '0px', top: '0px', width: '100px', height: '100px' }; // Integer CSS pixels at 1x stay unchanged (existing contract). diff --git a/domain/paneMagnification.ts b/domain/paneMagnification.ts index 7400ebc49..55b8850fb 100644 --- a/domain/paneMagnification.ts +++ b/domain/paneMagnification.ts @@ -92,10 +92,6 @@ export function getPaneMagnificationShortcutLabel( return (hotkeyScheme === 'mac' ? binding?.mac : binding?.pc)?.replace(/ \+ /g, '+') ?? ''; } -export function resolveMagnifiedChromeBorderWidth(devicePixelRatio = 1): number { - return devicePixelRatio > 0 && devicePixelRatio < 1.5 ? 2 : 1; -} - export function snapCssRectToDevicePixels( left: number, top: number, From bbbea4a157f423e89d622c218e9faa6bf7689af6 Mon Sep 17 00:00:00 2001 From: GOUKI9999 Date: Thu, 26 Nov 2026 22:32:23 +0800 Subject: [PATCH 12/24] fix(ai): allow dismissing the model catalog warning banner (#4431) * fix(ai): allow dismissing the model catalog warning banner * fix(ai): address Codex review on catalog warning dismissal * fix(ai): persist catalog warning dismissals across empty-panel remounts --------- Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com> --- .../useModelCatalogWarningDismissal.test.tsx | 125 ++++++++++++++++++ .../state/useModelCatalogWarningDismissal.ts | 70 ++++++++++ components/AIChatPanelContent.tsx | 21 ++- components/AIChatSidePanel.tsx | 37 +++++- components/AIChatSidePanelHelpers.test.tsx | 21 +++ components/AIChatSidePanelHelpers.ts | 19 +++ 6 files changed, 290 insertions(+), 3 deletions(-) create mode 100644 application/state/useModelCatalogWarningDismissal.test.tsx create mode 100644 application/state/useModelCatalogWarningDismissal.ts diff --git a/application/state/useModelCatalogWarningDismissal.test.tsx b/application/state/useModelCatalogWarningDismissal.test.tsx new file mode 100644 index 000000000..a2ff59fc0 --- /dev/null +++ b/application/state/useModelCatalogWarningDismissal.test.tsx @@ -0,0 +1,125 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import React from 'react'; +import { createRoot } from 'react-dom/client'; +import { JSDOM } from 'jsdom'; + +import { + resetModelCatalogWarningDismissals, + useModelCatalogWarningDismissal, + type ModelCatalogWarningDismissalState, +} from './useModelCatalogWarningDismissal.ts'; +import { isModelCatalogWarningVisible } from '../../components/AIChatSidePanelHelpers.ts'; + +test('useModelCatalogWarningDismissal dismisses per cacheKey, survives remounts, and rearms on clean catalog', async () => { + const dom = new JSDOM('
'); + const prevWindow = globalThis.window; + const prevDocument = globalThis.document; + const prevActEnv = (globalThis as Record).IS_REACT_ACT_ENVIRONMENT; + + (globalThis as Record).window = dom.window; + (globalThis as Record).document = dom.window.document; + (globalThis as Record).IS_REACT_ACT_ENVIRONMENT = true; + resetModelCatalogWarningDismissals(); + + let latest!: ModelCatalogWarningDismissalState; + const Probe: React.FC = () => { + latest = useModelCatalogWarningDismissal(); + return null; + }; + + const container = dom.window.document.getElementById('root')!; + let root = createRoot(container); + try { + await React.act(async () => { + root.render(React.createElement(Probe)); + }); + + assert.equal(latest.dismissedKeys.size, 0); + const warningK1 = { cacheKey: 'k1', message: 'Catalog unavailable' }; + const warningK2 = { cacheKey: 'k2', message: 'Other catalog unavailable' }; + assert.equal( + isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys), + 'Catalog unavailable', + ); + + // Dismissing k1 hides only k1, leaving k2 visible. + await React.act(async () => { + latest.dismissWarning('k1'); + }); + assert.equal(latest.dismissedKeys.has('k1'), true); + assert.equal(isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys), undefined); + assert.equal( + isModelCatalogWarningVisible(warningK2, 'k2', latest.dismissedKeys), + 'Other catalog unavailable', + ); + + // Unmounting and remounting (e.g., empty panel hidden on tab/tool switch) + // must keep the dismissed cacheKey hidden until a clean catalog arrives. + await React.act(async () => { + root.unmount(); + }); + root = createRoot(container); + await React.act(async () => { + root.render(React.createElement(Probe)); + }); + assert.equal(latest.dismissedKeys.has('k1'), true); + assert.equal(isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys), undefined); + + // Undefined and duplicate dismissals are no-ops that keep state identity. + const setBeforeNoop = latest.dismissedKeys; + await React.act(async () => { + latest.dismissWarning(undefined); + latest.dismissWarning('k1'); + }); + assert.equal(latest.dismissedKeys, setBeforeNoop); + + // A clean catalog for k1 re-arms k1 so future failures surface again. + await React.act(async () => { + latest.rearmWarning('k1'); + }); + assert.equal(latest.dismissedKeys.has('k1'), false); + assert.equal( + isModelCatalogWarningVisible(warningK1, 'k1', latest.dismissedKeys), + 'Catalog unavailable', + ); + + // Rearming a non-dismissed or undefined key is a no-op. + const setAfterRearm = latest.dismissedKeys; + await React.act(async () => { + latest.rearmWarning('k1'); + latest.rearmWarning(undefined); + }); + assert.equal(latest.dismissedKeys, setAfterRearm); + } finally { + await React.act(async () => { + root.unmount(); + }); + resetModelCatalogWarningDismissals(); + (globalThis as Record).window = prevWindow; + (globalThis as Record).document = prevDocument; + (globalThis as Record).IS_REACT_ACT_ENVIRONMENT = prevActEnv; + } +}); + +test('AIChatPanelContent keeps raw modelCatalogWarning for ChatInput when banner is dismissed', () => { + const panelSource = readFileSync(new URL('../../components/AIChatPanelContent.tsx', import.meta.url), 'utf8'); + const sidePanelSource = readFileSync(new URL('../../components/AIChatSidePanel.tsx', import.meta.url), 'utf8'); + + assert.match( + panelSource, + /modelCatalogWarning && !modelCatalogWarningDismissed \?/, + 'banner visibility must check modelCatalogWarningDismissed separately from raw modelCatalogWarning', + ); + assert.match( + panelSource, + /; + dismissWarning: (cacheKey: string | undefined) => void; + rearmWarning: (cacheKey: string | undefined) => void; +} + +type Listener = () => void; + +let dismissedKeysSnapshot: ReadonlySet = new Set(); +const listeners = new Set(); + +function emitChange(): void { + for (const listener of listeners) { + listener(); + } +} + +function subscribe(listener: Listener): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +function getSnapshot(): ReadonlySet { + return dismissedKeysSnapshot; +} + +export function dismissModelCatalogWarningKey(cacheKey: string | undefined): void { + if (!cacheKey || dismissedKeysSnapshot.has(cacheKey)) return; + const next = new Set(dismissedKeysSnapshot); + next.add(cacheKey); + dismissedKeysSnapshot = next; + emitChange(); +} + +export function rearmModelCatalogWarningKey(cacheKey: string | undefined): void { + if (!cacheKey || !dismissedKeysSnapshot.has(cacheKey)) return; + const next = new Set(dismissedKeysSnapshot); + next.delete(cacheKey); + dismissedKeysSnapshot = next; + emitChange(); +} + +export function resetModelCatalogWarningDismissals(): void { + if (dismissedKeysSnapshot.size === 0) return; + dismissedKeysSnapshot = new Set(); + emitChange(); +} + +/** + * Tracks SDK model catalog cache keys whose composer warning banner was + * dismissed by the user. + * + * Stored at module scope so dismissals survive empty-panel unmounts during + * normal tab/tool navigation and stay consistent with the shared + * `sdkRuntimeModelCache`. Dismissals remain scoped by cacheKey so switching + * agents or config re-arms the banner, and a clean catalog load clears that + * key so a later failure warns again. + */ +export function useModelCatalogWarningDismissal(): ModelCatalogWarningDismissalState { + const dismissedKeys = useSyncExternalStore(subscribe, getSnapshot, getSnapshot); + return { + dismissedKeys, + dismissWarning: dismissModelCatalogWarningKey, + rearmWarning: rearmModelCatalogWarningKey, + }; +} diff --git a/components/AIChatPanelContent.tsx b/components/AIChatPanelContent.tsx index ed0ece3d7..1b5a0fa6f 100644 --- a/components/AIChatPanelContent.tsx +++ b/components/AIChatPanelContent.tsx @@ -1,5 +1,5 @@ import React, { type Dispatch, type SetStateAction } from 'react'; -import { History, Plus, Undo2 } from 'lucide-react'; +import { History, Plus, Undo2, X } from 'lucide-react'; import type { AIPermissionMode, AISession, ChatMessage, DiscoveredAgent, ExternalAgentConfig, AgentModelPreset, ProviderConfig, UploadedFile } from '../infrastructure/ai/types'; import type { Host, VaultNote } from '../types'; import type { UserSkillOption } from './ai/userSkillsState'; @@ -87,6 +87,8 @@ interface AIChatPanelContentProps { providerDisplayName?: string; modelDisplayName?: string; modelCatalogWarning?: string; + /** Whether the composer warning banner itself was dismissed (picker still sees raw warning). */ + modelCatalogWarningDismissed?: boolean; /** Live SDK model catalog is loading (no built-in presets to show yet). */ modelCatalogLoading?: boolean; /** Provenance of the active model list, rendered as the picker status chip. */ @@ -95,6 +97,8 @@ interface AIChatPanelContentProps { modelCatalogFetchedAt?: string; /** Retry a failed SDK model catalog load from the warning banner. */ handleModelCatalogRetry?: () => void; + /** Dismiss the warning banner for this agent config until a clean catalog re-arms it. */ + handleModelCatalogDismiss?: () => void; handleModelPickerOpen?: () => void; agentModelPresets: AgentModelPreset[]; /** Suppress the composer picker's "use custom model" action (locked model). */ @@ -174,6 +178,7 @@ export const AIChatPanelContent: React.FC = ({ handleSteer, handleStop, handleModelCatalogRetry, + handleModelCatalogDismiss, handleModelPickerOpen, canSteer, isSteering, @@ -183,6 +188,7 @@ export const AIChatPanelContent: React.FC = ({ providerDisplayName, modelDisplayName, modelCatalogWarning, + modelCatalogWarningDismissed = false, modelCatalogLoading = false, modelCatalogSource, modelCatalogFetchedAt, @@ -421,7 +427,7 @@ export const AIChatPanelContent: React.FC = ({
{steerWarning}
- ) : modelCatalogWarning ? ( + ) : modelCatalogWarning && !modelCatalogWarningDismissed ? (
{modelCatalogWarning} {handleModelCatalogRetry && ( @@ -432,6 +438,17 @@ export const AIChatPanelContent: React.FC = ({ {t('ai.chat.modelCatalogRetry')} )} + {handleModelCatalogDismiss && ( + + )}
) : modelCatalogLoading ? (
diff --git a/components/AIChatSidePanel.tsx b/components/AIChatSidePanel.tsx index 236257fda..af397e0e6 100644 --- a/components/AIChatSidePanel.tsx +++ b/components/AIChatSidePanel.tsx @@ -85,12 +85,14 @@ import { getAgentRuntime } from '../infrastructure/ai/harness/globalAgentRuntime import { useAIPermissionGrantsState } from '../application/state/useAIPermissionGrantsState'; import { useConversationExport } from './ai/hooks/useConversationExport'; import { useAgentContextUsage } from '../application/state/useAgentCompactionUi'; +import { useModelCatalogWarningDismissal } from '../application/state/useModelCatalogWarningDismissal'; import type { AIChatSidePanelProps } from './AIChatSidePanel.types'; import { buildCursorListModelsAgentEnv, buildSdkRuntimeModelCacheKey, sdkRuntimeModelCache, reconcileRuntimeModelWarning, + isModelCatalogWarningVisible, retainStoredModelPresetForCatalog, toSdkRuntimeModelCatalog, generateId, @@ -361,6 +363,11 @@ const AIChatSidePanelActive: React.FC = ({ const [isUndoingLastTurn, setIsUndoingLastTurn] = useState(false); const [runtimeAgentModelPresets, setRuntimeAgentModelPresets] = useState>({}); const [runtimeModelWarnings, setRuntimeModelWarnings] = useState>({}); + const { + dismissedKeys: dismissedModelCatalogKeys, + dismissWarning: dismissModelCatalogWarning, + rearmWarning: rearmModelCatalogWarning, + } = useModelCatalogWarningDismissal(); // Tracks SDK runtime model catalogs currently loading (per agent scope); // the composer shows the loading row alongside the build-time presets and // the live catalog replaces them when it arrives. @@ -1352,6 +1359,11 @@ const AIChatSidePanelActive: React.FC = ({ t('ai.chat.modelCatalogWarning'), ); }); + // A clean catalog re-arms a banner the user previously dismissed, so a + // later failure for the same config is visible again. + if (catalog && !catalog.warning) { + rearmModelCatalogWarning(target.cacheKey); + } return catalog; }).catch((err) => { setRuntimeModelWarnings((current) => { @@ -1367,7 +1379,7 @@ const AIChatSidePanelActive: React.FC = ({ } return null; }); - }, [t, buildExternalAgentRuntimeModelTarget]); + }, [t, buildExternalAgentRuntimeModelTarget, rearmModelCatalogWarning]); useEffect(() => { if (!isVisible) return; @@ -1390,6 +1402,9 @@ const AIChatSidePanelActive: React.FC = ({ Boolean(cached.warning), t('ai.chat.modelCatalogWarning'), )); + if (!cached.warning) { + rearmModelCatalogWarning(target.cacheKey); + } } // Respect renderer TTL / in-flight coalescing for all SDK agents including @@ -1470,6 +1485,7 @@ const AIChatSidePanelActive: React.FC = ({ buildExternalAgentRuntimeModelTarget, loadSdkRuntimeModelCatalog, applySdkRuntimeModelCatalog, + rearmModelCatalogWarning, t, ]); @@ -1625,6 +1641,14 @@ const AIChatSidePanelActive: React.FC = ({ applySdkRuntimeModelCatalog, ]); + // Hide the composer warning banner for this config until a clean catalog + // re-arms it. The underlying warning stays active so the model picker keeps + // its manual refresh action. + const handleDismissModelCatalogWarning = useCallback(() => { + const target = buildExternalAgentRuntimeModelTarget(currentAgentConfig); + dismissModelCatalogWarning(target?.cacheKey); + }, [currentAgentConfig, buildExternalAgentRuntimeModelTarget, dismissModelCatalogWarning]); + const selectedCattyThinking = agentThinkingMap.catty; const handleCattyThinkingSelect = useCallback((level: string) => { setAgentThinking('catty', level); @@ -2516,6 +2540,17 @@ const AIChatSidePanelActive: React.FC = ({ && runtimeModelWarnings[currentAgentId].cacheKey === buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey ? runtimeModelWarnings[currentAgentId].message : undefined} + modelCatalogWarningDismissed={!hasCodexCustomConfig + && Boolean( + runtimeModelWarnings[currentAgentId] + && runtimeModelWarnings[currentAgentId].cacheKey === buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey + && !isModelCatalogWarningVisible( + runtimeModelWarnings[currentAgentId], + buildExternalAgentRuntimeModelTarget(currentAgentConfig)?.cacheKey, + dismissedModelCatalogKeys, + ), + )} + handleModelCatalogDismiss={handleDismissModelCatalogWarning} modelCatalogLoading={ !hasCodexCustomConfig && Boolean(runtimeModelLoading[currentAgentId]) diff --git a/components/AIChatSidePanelHelpers.test.tsx b/components/AIChatSidePanelHelpers.test.tsx index 3dda4ed15..e55b73799 100644 --- a/components/AIChatSidePanelHelpers.test.tsx +++ b/components/AIChatSidePanelHelpers.test.tsx @@ -17,6 +17,7 @@ import { normalizeSdkRuntimeModelPresets, resolveSdkRuntimeCatalogDefaultModelId, reconcileRuntimeModelWarning, + isModelCatalogWarningVisible, toSdkRuntimeModelCatalog, shouldAdoptSdkCurrentModel, shouldLoadSdkRuntimeModels, @@ -685,6 +686,26 @@ test('reconcileRuntimeModelWarning clears only the banner that belongs to this c assert.equal(reconcileRuntimeModelWarning(current, 'copilot', 'k2', false, 'warn'), current); }); +test('isModelCatalogWarningVisible shows a matching, non-dismissed banner', () => { + const warning = { cacheKey: 'k1', message: 'cannot load models' }; + assert.equal(isModelCatalogWarningVisible(warning, 'k1', new Set()), 'cannot load models'); +}); + +test('isModelCatalogWarningVisible hides a dismissed cache key but re-arms on a new key', () => { + const warning = { cacheKey: 'k1', message: 'cannot load models' }; + const dismissed = new Set(['k1']); + assert.equal(isModelCatalogWarningVisible(warning, 'k1', dismissed), undefined); + // A config/agent switch produces a different cache key, which is not dismissed. + assert.equal(isModelCatalogWarningVisible({ cacheKey: 'k2', message: 'again' }, 'k2', dismissed), 'again'); +}); + +test('isModelCatalogWarningVisible never shows a warning for another cache key or without a target', () => { + const warning = { cacheKey: 'k1', message: 'cannot load models' }; + assert.equal(isModelCatalogWarningVisible(warning, 'k2', new Set()), undefined); + assert.equal(isModelCatalogWarningVisible(warning, undefined, new Set()), undefined); + assert.equal(isModelCatalogWarningVisible(undefined, 'k1', new Set()), undefined); +}); + test('cacheOnly hydration in AIChatSidePanel reconciles cached refresh warnings before applying persisted models', () => { const source = readFileSync(new URL('./AIChatSidePanel.tsx', import.meta.url), 'utf8'); assert.match( diff --git a/components/AIChatSidePanelHelpers.ts b/components/AIChatSidePanelHelpers.ts index af96c1b9e..7a78a833f 100644 --- a/components/AIChatSidePanelHelpers.ts +++ b/components/AIChatSidePanelHelpers.ts @@ -293,6 +293,25 @@ export const sdkRuntimeModelCache = createSdkRuntimeModelCache(); export type RuntimeModelWarnings = Record; +/** + * Whether a per-agent catalog warning should surface in the composer banner. + * + * A warning the user explicitly dismissed stays hidden for its cache key until + * a clean catalog is observed (the caller then drops the key from + * `dismissedKeys`). A warning belonging to a different cache key is never + * shown — config/agent switches must not inherit a stale dismissal. + */ +export function isModelCatalogWarningVisible( + warning: { cacheKey: string; message: string } | undefined, + cacheKey: string | undefined, + dismissedKeys: ReadonlySet, +): string | undefined { + if (!warning || !cacheKey) return undefined; + if (warning.cacheKey !== cacheKey) return undefined; + if (dismissedKeys.has(cacheKey)) return undefined; + return warning.message; +} + /** * Make the per-agent catalog warning banner match a catalog result. Used both * for cache reads and after a refresh settles: a refresh that coalesced onto From 444b3607276c06330ca6b9a84d766bc938d786fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:32:28 +0800 Subject: [PATCH 13/24] fix(vault): restore Host Details inheritance (#4441) (#4447) * fix(vault): restore Host Details inheritance (#4441) * fix(vault): keep Mosh/ET exclusive when restoring group transport --- application/i18n/locales/en/core.ts | 1 + application/i18n/locales/es/core.ts | 1 + application/i18n/locales/ru/core.ts | 1 + application/i18n/locales/zh-CN/core.ts | 1 + application/i18n/locales/zh-TW/core.ts | 1 + components/HostDetailsAdvancedSections.tsx | 87 +++++-- components/HostDetailsPanel.helpers.ts | 2 +- components/HostDetailsPanel.inherit.test.tsx | 222 ++++++++++++++++++ .../HostDetailsPanel.proxyProfile.test.tsx | 46 +++- components/HostDetailsPanel.tsx | 8 +- .../runtime/terminalBackspaceInput.test.ts | 1 + domain/groupConfig.test.ts | 7 + domain/models/connection.ts | 4 +- 13 files changed, 350 insertions(+), 32 deletions(-) create mode 100644 components/HostDetailsPanel.inherit.test.tsx diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index ba3368806..a9f786fd1 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -98,6 +98,7 @@ export const enCoreMessages: Messages = { 'common.apply': 'Apply', 'common.use': 'Use', 'common.useGlobal': 'Use global', + 'common.useGroup': 'Use group', 'common.saveChanges': 'Save Changes', 'common.advanced': 'Advanced', 'common.left': 'Left', diff --git a/application/i18n/locales/es/core.ts b/application/i18n/locales/es/core.ts index b9bd60953..1c7a985b9 100644 --- a/application/i18n/locales/es/core.ts +++ b/application/i18n/locales/es/core.ts @@ -98,6 +98,7 @@ export const esCoreMessages: Messages = { 'common.apply': 'Aplicar', 'common.use': 'Usar', 'common.useGlobal': 'Usar global', + 'common.useGroup': 'Usar grupo', 'common.saveChanges': 'Guardar cambios', 'common.advanced': 'Avanzado', 'common.left': 'Izquierda', diff --git a/application/i18n/locales/ru/core.ts b/application/i18n/locales/ru/core.ts index 400ad3d3b..56471acec 100644 --- a/application/i18n/locales/ru/core.ts +++ b/application/i18n/locales/ru/core.ts @@ -71,6 +71,7 @@ export const ruCoreMessages: Messages = { 'common.apply': 'Применить', 'common.use': 'Использовать', 'common.useGlobal': 'Использовать глобальное', + 'common.useGroup': 'Использовать настройки группы', 'common.saveChanges': 'Сохранить изменения', 'common.advanced': 'Дополнительно', 'common.left': 'Слева', diff --git a/application/i18n/locales/zh-CN/core.ts b/application/i18n/locales/zh-CN/core.ts index 669287bd5..518fcf5be 100644 --- a/application/i18n/locales/zh-CN/core.ts +++ b/application/i18n/locales/zh-CN/core.ts @@ -89,6 +89,7 @@ export const zhCNCoreMessages: Messages = { 'common.apply': '应用', 'common.use': '使用', 'common.useGlobal': '跟随全局', + 'common.useGroup': '跟随分组', 'common.left': '左侧', 'common.right': '右侧', 'common.more': '更多', diff --git a/application/i18n/locales/zh-TW/core.ts b/application/i18n/locales/zh-TW/core.ts index 14c61c3d9..2e2e510e7 100644 --- a/application/i18n/locales/zh-TW/core.ts +++ b/application/i18n/locales/zh-TW/core.ts @@ -89,6 +89,7 @@ export const zhTWCoreMessages: Messages = { 'common.apply': '套用', 'common.use': '使用', 'common.useGlobal': '跟隨全域', + 'common.useGroup': '跟隨群組', 'common.left': '左側', 'common.right': '右側', 'common.more': '更多', diff --git a/components/HostDetailsAdvancedSections.tsx b/components/HostDetailsAdvancedSections.tsx index 83f84d158..cbc8b27ab 100644 --- a/components/HostDetailsAdvancedSections.tsx +++ b/components/HostDetailsAdvancedSections.tsx @@ -24,10 +24,13 @@ import { // eslint-disable-next-line @typescript-eslint/no-explicit-any type HostDetailsAdvancedSectionsProps = Record; -const ToggleRow: React.FC<{ label: string; hint?: React.ReactNode; enabled: boolean; disabled?: boolean; onToggle: () => void }> = ({ label, hint, enabled, disabled, onToggle }) => { +const ToggleRow: React.FC<{ label: string; hint?: React.ReactNode; enabled: boolean; disabled?: boolean; onToggle: () => void; inheritance?: React.ReactNode }> = ({ label, hint, enabled, disabled, onToggle, inheritance }) => { return ( - onToggle()} /> +
+ {inheritance} + onToggle()} /> +
); }; @@ -49,6 +52,7 @@ export const HostDetailsAdvancedSections: React.FC { const inheritedDeviceType = effectiveGroupDefaults?.deviceType; const effectiveDeviceType = form.deviceType ?? inheritedDeviceType; + const effectiveMoshEnabled = form.moshEnabled ?? effectiveGroupDefaults?.moshEnabled; + const effectiveEtEnabled = form.etEnabled ?? effectiveGroupDefaults?.etEnabled; + const inheritedBackspaceBehavior = effectiveGroupDefaults?.backspaceBehavior; + const groupSettingControl = (key: "moshEnabled" | "etEnabled" | "deviceType" | "backspaceBehavior") => { + if (effectiveGroupDefaults?.[key] === undefined) return null; + return form[key] === undefined ? ( + + {t("vault.groups.details.inherited")} + + ) : ( + { + if ((key === "moshEnabled" || key === "etEnabled") && effectiveGroupDefaults[key] === true) { + setForm(prev => ({ + ...prev, + [key]: undefined, + [key === "moshEnabled" ? "etEnabled" : "moshEnabled"]: false, + })); + } else { + update(key, undefined); + } + }} /> + ); + }; const inheritedStartupCommandRunMode = effectiveGroupDefaults?.startupCommandRunMode ?? "paste"; const effectiveStartupCommandRunMode = form.startupCommandRunMode ?? inheritedStartupCommandRunMode; const systemSshAgentSupported = effectiveAuthMethod === "auto" || effectiveAuthMethod === "key"; @@ -197,9 +224,10 @@ export const HostDetailsAdvancedSections: React.FC { - const enabling = !form.moshEnabled; + const enabling = !effectiveMoshEnabled; if (enabling) { setForm(prev => ({ ...prev, @@ -220,9 +248,10 @@ export const HostDetailsAdvancedSections: React.FC { - const enabling = !form.etEnabled; + const enabling = !effectiveEtEnabled; if (enabling) { setForm(prev => ({ ...prev, @@ -235,7 +264,7 @@ export const HostDetailsAdvancedSections: React.FC - {form.etEnabled && ( + {effectiveEtEnabled && ( <> } title={t("hostDetails.section.deviceType")} > - {(!form.protocol || form.protocol === 'ssh') && !form.moshEnabled && !form.etEnabled && (<> + {(!form.protocol || form.protocol === 'ssh') && !effectiveMoshEnabled && !effectiveEtEnabled && (<> update("deviceType", effectiveDeviceType === 'network' ? 'general' : 'network')} /> {effectiveDeviceType === 'network' && ( @@ -485,7 +515,7 @@ export const HostDetailsAdvancedSections: React.FC update("showLineTimestamps", !form.showLineTimestamps)} /> - {(form.protocol === undefined || form.protocol === "ssh") && !form.moshEnabled && !form.etEnabled && ( + {(form.protocol === undefined || form.protocol === "ssh") && !effectiveMoshEnabled && !effectiveEtEnabled && ( <> )} - +
+ {form.backspaceBehavior !== undefined && groupSettingControl("backspaceBehavior")} + +
+ {form.backspaceBehavior === undefined && groupSettingControl("backspaceBehavior")} {/* Per-host keepalive override */} @@ -634,9 +668,14 @@ export const HostDetailsAdvancedSections: React.FC
) : ( - - {t("hostDetails.jumpHosts.direct")} - +
+ + {t("hostDetails.jumpHosts.direct")} + + {canRestoreHostChain && ( + + )} +
) } > diff --git a/components/HostDetailsPanel.helpers.ts b/components/HostDetailsPanel.helpers.ts index 19f8acb6d..36c65902e 100644 --- a/components/HostDetailsPanel.helpers.ts +++ b/components/HostDetailsPanel.helpers.ts @@ -225,7 +225,7 @@ export const nextFormAfterClearHostChain = ( groupDefaults && applyGroupDefaults({ ...prev, hostChain: undefined }, groupDefaults).hostChain?.hostIds?.length, ); - if (prev.hostChain === undefined || groupWouldRestore) { + if (prev.hostChain === undefined || (groupWouldRestore && prev.hostChain.hostIds?.length)) { return { ...prev, hostChain: { hostIds: [] } }; } const { hostChain: _hostChain, ...rest } = prev; diff --git a/components/HostDetailsPanel.inherit.test.tsx b/components/HostDetailsPanel.inherit.test.tsx new file mode 100644 index 000000000..810fd7e9f --- /dev/null +++ b/components/HostDetailsPanel.inherit.test.tsx @@ -0,0 +1,222 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import React from "react"; +import { act, create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer"; +import { I18nProvider } from "../application/i18n/I18nProvider"; +import { applyGroupDefaults } from "../domain/groupConfig"; +import type { GroupConfig, Host } from "../domain/models"; +import { resolveEffectiveTerminalProtocol } from "../domain/terminalProtocol"; +import HostDetailsPanel from "./HostDetailsPanel"; +import { ChainPanel } from "./host-details/ChainPanel"; +import { HostDetailsOverrideReset } from "./host-details/HostDetailsOverrideReset"; +import { HostDetailsSection, HostDetailsSettingRow } from "./host-details/HostDetailsSection"; +import { mapTerminalBackspaceInput } from "./terminal/runtime/terminalBackspaceInput"; +import { installDomEnvironment } from "./test-support/renderReactDom"; +import { AsidePanelFooter } from "./ui/aside-panel"; +import { Badge } from "./ui/badge"; +import { Button } from "./ui/button"; +import { Select } from "./ui/select"; +import { Switch } from "./ui/switch"; +import { TooltipProvider } from "./ui/tooltip"; + +const host: Host = { + id: "host-1", label: "Host", hostname: "example.com", username: "root", + password: "password", authMethod: "password", tags: [], os: "linux", + protocol: "ssh", group: "network", +}; + +const panelProps = (groupDefaults: Partial, initialData = host) => ({ + initialData, availableKeys: [], identities: [], proxyProfiles: [], + groups: ["network"], groupConfigs: [{ path: "network", ...groupDefaults }], + allHosts: [{ ...host, id: "jump-1", label: "Jump", hostname: "jump.example.com" }], + terminalThemeId: "default", terminalFontSize: 14, layout: "inline" as const, + onSave: (_value: Host) => {}, onCancel: () => {}, +}); + +async function withPanel( + groupDefaults: Partial, + run: (editor: { root: ReactTestInstance; save: () => Promise }) => Promise, + initialData = host, +) { + 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); + let renderer: ReactTestRenderer | undefined; + let saved: Host | undefined; + try { + await act(async () => { + renderer = create( + { saved = value; }} /> + ); + }); + await run({ + root: renderer!.root, + save: async () => { + saved = undefined; + await act(async () => { + const buttons = renderer!.root.findByType(AsidePanelFooter).findAllByType(Button); + await buttons[buttons.length - 1].props.onClick(); + }); + assert.ok(saved, "the actual panel save handler must emit a host"); + return saved; + }, + }); + } finally { + if (renderer) await act(async () => { renderer!.unmount(); }); + globalThis.requestAnimationFrame = previousRaf; + globalThis.cancelAnimationFrame = previousCancelRaf; + dom.cleanup(); + } +} + +function setting(root: ReactTestInstance, label: string) { + const row = root.findAllByType(HostDetailsSettingRow).find((node) => node.props.label === label); + assert.ok(row, `expected setting ${label}`); + return row; +} + +function assertInherited(row: ReactTestInstance) { + assert.ok(row.findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group")); + assert.equal(row.findAllByType(HostDetailsOverrideReset).length, 0); +} + +for (const [key, label] of [["moshEnabled", "Mosh"], ["etEnabled", "EternalTerminal"]] as const) { + test(`Host Details shows inherited ${label}, saves Off, and resets to the group`, async () => { + const group = { [key]: true }; + await withPanel(group, async ({ root, save }) => { + const row = () => setting(root, label); + assert.equal(row().findByType(Switch).props.checked, true); + assertInherited(row()); + assert.equal(root.findAllByType(HostDetailsSettingRow).some((node) => node.props.label === "Network Device Mode"), false); + if (key === "etEnabled") setting(root, "ET server port"); + + await act(async () => { row().findByType(Switch).props.onCheckedChange(false); }); + const off = await save(); + assert.equal(off[key], false); + assert.equal(applyGroupDefaults(off, group)[key], false); + assert.equal(row().findByType(Switch).props.checked, false); + assert.equal(row().findAllByType(Badge).length, 0); + if (key === "etEnabled") { + assert.equal(root.findAllByType(HostDetailsSettingRow).some((node) => node.props.label === "ET server port"), false); + } + + const reset = row().findByType(HostDetailsOverrideReset); + assert.equal(reset.props.label, "Use group"); + await act(async () => { reset.props.onClick(); }); + const inherited = await save(); + assert.equal(inherited[key], undefined); + assert.equal(applyGroupDefaults(inherited, group)[key], true); + assert.equal(row().findByType(Switch).props.checked, true); + assertInherited(row()); + }); + }); + + test(`Host Details restores inherited ${label} and disables the competing transport`, async () => { + const competingKey = key === "moshEnabled" ? "etEnabled" : "moshEnabled"; + const competingLabel = key === "moshEnabled" ? "EternalTerminal" : "Mosh"; + const group = { [key]: true }; + await withPanel(group, async ({ root, save }) => { + const row = () => setting(root, label); + assert.equal(row().findByType(Switch).props.checked, false); + assert.equal(setting(root, competingLabel).findByType(Switch).props.checked, true); + + const reset = row().findByType(HostDetailsOverrideReset); + assert.equal(reset.props.label, "Use group"); + await act(async () => { reset.props.onClick(); }); + const inherited = await save(); + assert.equal(inherited[key], undefined); + assert.equal(inherited[competingKey], false); + assert.equal(row().findByType(Switch).props.checked, true); + assertInherited(row()); + assert.equal(setting(root, competingLabel).findByType(Switch).props.checked, false); + + const effective = applyGroupDefaults(inherited, group); + assert.equal(effective[key], true); + assert.equal(effective[competingKey], false); + assert.equal(resolveEffectiveTerminalProtocol(effective), key === "moshEnabled" ? "mosh" : "et"); + }, { ...host, [key]: false, [competingKey]: true }); + }); +} + +test("Host Details device type override can return to the group", async () => { + const group = { deviceType: "network" as const }; + await withPanel(group, async ({ root, save }) => { + const row = () => setting(root, "Network Device Mode"); + assert.equal(row().findByType(Switch).props.checked, true); + assertInherited(row()); + await act(async () => { row().findByType(Switch).props.onCheckedChange(false); }); + assert.equal((await save()).deviceType, "general"); + assert.equal(row().findByType(Switch).props.checked, false); + await act(async () => { row().findByType(HostDetailsOverrideReset).props.onClick(); }); + const inherited = await save(); + assert.equal(inherited.deviceType, undefined); + assert.equal(applyGroupDefaults(inherited, group).deviceType, "network"); + assert.equal(row().findByType(Switch).props.checked, true); + assertInherited(row()); + }); +}); + +test("Host Details backspace shows inherited Ctrl-H and saves explicit DEL or Ctrl-H or inherit", async () => { + const group = { backspaceBehavior: "ctrl-h" as const }; + await withPanel(group, async ({ root, save }) => { + const select = () => setting(root, "Backspace Behavior").findByType(Select); + assert.equal(select().props.value, "ctrl-h"); + assert.ok(root.findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group")); + await act(async () => { select().props.onValueChange("default"); }); + const del = await save(); + assert.equal(del.backspaceBehavior, "default"); + const reloaded: Host = JSON.parse(JSON.stringify(del)); + assert.equal(mapTerminalBackspaceInput("\x7f", applyGroupDefaults(reloaded, group).backspaceBehavior), "\x7f"); + assert.equal(select().props.value, "default"); + await act(async () => { select().props.onValueChange("ctrl-h"); }); + assert.equal((await save()).backspaceBehavior, "ctrl-h"); + await act(async () => { setting(root, "Backspace Behavior").findByType(HostDetailsOverrideReset).props.onClick(); }); + const inherited = await save(); + assert.equal(inherited.backspaceBehavior, undefined); + assert.equal(applyGroupDefaults(inherited, group).backspaceBehavior, "ctrl-h"); + assert.equal(select().props.value, "ctrl-h"); + assert.ok(root.findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group")); + }); +}); + +test("Host Details keeps no-group toggle and Default backspace behavior", async () => { + await withPanel({}, async ({ root, save }) => { + const mosh = setting(root, "Mosh"); + assert.equal(mosh.findByType(Switch).props.checked, false); + assert.equal(mosh.findAllByType(HostDetailsOverrideReset).length, 0); + await act(async () => { mosh.findByType(Switch).props.onCheckedChange(true); }); + assert.equal((await save()).moshEnabled, true); + await act(async () => { setting(root, "Mosh").findByType(Switch).props.onCheckedChange(false); }); + assert.equal((await save()).moshEnabled, false); + assert.equal(setting(root, "Mosh").findAllByType(HostDetailsOverrideReset).length, 0); + const select = () => setting(root, "Backspace Behavior").findByType(Select); + await act(async () => { select().props.onValueChange("ctrl-h"); }); + assert.equal((await save()).backspaceBehavior, "ctrl-h"); + await act(async () => { select().props.onValueChange("default"); }); + assert.equal((await save()).backspaceBehavior, undefined); + }); +}); + +test("Host Details can restore group jump hosts from the empty-override Direct row", async () => { + const group = { hostChain: { hostIds: ["jump-1"] } }; + await withPanel(group, async ({ root, save }) => { + const section = () => root.findAllByType(HostDetailsSection).find((node) => node.props.title === "Proxy via Hosts")!; + await act(async () => { section().findAllByType("button").find((node) => node.props.className?.includes("cursor-pointer"))!.props.onClick(); }); + await act(async () => { root.findByType(ChainPanel).props.onClearChain(); }); + await act(async () => { root.findByType(ChainPanel).props.onBack(); }); + const direct = await save(); + assert.deepEqual(direct.hostChain, { hostIds: [] }); + assert.deepEqual(applyGroupDefaults(direct, group).hostChain, { hostIds: [] }); + assert.ok(section().findAllByType(Badge).some((badge) => badge.props.children === "Direct")); + + const reset = section().findByType(HostDetailsOverrideReset); + assert.equal(reset.props.label, "Use group"); + await act(async () => { reset.props.onClick(); }); + const inherited = await save(); + assert.equal(inherited.hostChain, undefined); + assert.deepEqual(applyGroupDefaults(inherited, group).hostChain, group.hostChain); + assert.ok(section().findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group")); + }); +}); diff --git a/components/HostDetailsPanel.proxyProfile.test.tsx b/components/HostDetailsPanel.proxyProfile.test.tsx index 69cf8a5ab..9f38f5ccd 100644 --- a/components/HostDetailsPanel.proxyProfile.test.tsx +++ b/components/HostDetailsPanel.proxyProfile.test.tsx @@ -4,9 +4,10 @@ import React from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { I18nProvider } from "../application/i18n/I18nProvider.tsx"; -import type { Host, Identity } from "../types.ts"; +import type { Host, Identity, ProxyProfile } from "../types.ts"; import HostDetailsPanel, { parseOptionalPortInput } from "./HostDetailsPanel.tsx"; import { applyGroupDefaults } from "../domain/groupConfig.ts"; +import { getActiveGlobalDefaultProxyProfileId, publishActiveGlobalDefaultProxyProfileId } from "../domain/globalDefaultProxy.ts"; import { mapProxySaveErrorKey, prepareProxyConfigForSave, @@ -37,7 +38,7 @@ const hostWithMissingProxyProfile: Host = { const renderHostDetails = ( initialData: Host = hostWithMissingProxyProfile, - options: { identities?: Identity[] } = {}, + options: { identities?: Identity[]; proxyProfiles?: ProxyProfile[] } = {}, ) => renderToStaticMarkup( React.createElement( @@ -50,7 +51,7 @@ const renderHostDetails = ( initialData, availableKeys: [], identities: options.identities ?? [], - proxyProfiles: [], + proxyProfiles: options.proxyProfiles ?? [], groups: [], managedSources: [], allTags: [], @@ -101,6 +102,31 @@ test("HostDetailsPanel labels command proxy summaries consistently", () => { assert.doesNotMatch(markup, /--token secret/); }); +test("HostDetailsPanel displays the inherited global default proxy without a group proxy", () => { + const previous = getActiveGlobalDefaultProxyProfileId(); + try { + publishActiveGlobalDefaultProxyProfileId("global-proxy"); + const markup = renderHostDetails({ ...hostWithMissingProxyProfile, proxyProfileId: undefined }, { + proxyProfiles: [{ + id: "global-proxy", + label: "Global Office Proxy", + config: { type: "http", host: "global-proxy.example.com", port: 8080 }, + createdAt: 1, + }], + }); + + assert.match(markup, /Global Office Proxy/); + assert.match(markup, /Inherited from group/); + assert.doesNotMatch(markup, /Configure proxy/); + + const direct = renderHostDetails({ ...hostWithMissingProxyProfile, proxyProfileId: undefined, directProxy: true }); + assert.match(direct, /Direct \(no proxy\)/); + assert.doesNotMatch(direct, /Global Office Proxy|Inherited from group/); + } finally { + publishActiveGlobalDefaultProxyProfileId(previous); + } +}); + test("HostDetailsPanel keeps explicitly cleared telnet credentials empty", () => { const markup = renderHostDetails({ ...hostWithMissingProxyProfile, @@ -698,6 +724,19 @@ test("clearing an inherited-only chain keeps an empty override instead of restor assert.deepEqual(applyGroupDefaults(cleared, group).hostChain, { hostIds: [] }); }); +test("clearing an empty host-chain override restores group hops on the second clear", () => { + const group = { hostChain: { hostIds: ["jump-1", "jump-host"] } }; + for (const hostChain of [undefined, { hostIds: ["jump-host"] }]) { + const cleared = nextFormAfterClearHostChain({ ...networkSshHost, hostChain }, group); + assert.deepEqual(cleared.hostChain, { hostIds: [] }); + + const restored = nextFormAfterClearHostChain(cleared, group); + assert.equal(restored.hostChain, undefined); + assert.equal(Object.hasOwn(restored, "hostChain"), false); + assert.deepEqual(applyGroupDefaults(restored, group).hostChain, group.hostChain); + } +}); + test("HostDetailsPanel custom proxy draft hides the inherited saved proxy", () => { const markup = renderToStaticMarkup( React.createElement( @@ -749,6 +788,7 @@ test("HostDetailsPanel empty jump-host override hides the inherited group chain" assert.doesNotMatch(markup, /bastion\.example\.com/); assert.doesNotMatch(markup, /edge\.example\.com/); assert.doesNotMatch(markup, /Inherited from group/); + assert.match(markup, /aria-label="Use group"/); }); test("mapProxySaveErrorKey maps every proxy save validation error to its i18n key", () => { diff --git a/components/HostDetailsPanel.tsx b/components/HostDetailsPanel.tsx index e09e6b401..be898498b 100644 --- a/components/HostDetailsPanel.tsx +++ b/components/HostDetailsPanel.tsx @@ -378,7 +378,7 @@ const HostDetailsPanel: React.FC = ({ }, [defaultGroup, form.group, groupConfigs, groupDefaults]); const effectiveAuthHost = useMemo( - () => effectiveGroupDefaults ? applyGroupDefaults(form, effectiveGroupDefaults) : form, + () => applyGroupDefaults(form, effectiveGroupDefaults ?? {}), [effectiveGroupDefaults, form], ); @@ -449,7 +449,7 @@ const HostDetailsPanel: React.FC = ({ const hasMissingProxyProfile = Boolean(displayProxyProfileId && !selectedProxyProfile); const proxyInherited = !hasHostProxyOverride && Boolean( displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command, - ) && Boolean(effectiveGroupDefaults?.proxyProfileId || effectiveGroupDefaults?.proxyConfig); + ); const proxySummaryType = hasMissingProxyProfile ? t("hostDetails.proxyPanel.missing") : formatProxyConfigType(selectedProxyProfile?.config || displayProxyConfig) || "HTTP"; @@ -794,6 +794,9 @@ const HostDetailsPanel: React.FC = ({ [effectiveAuthHost.hostChain?.hostIds, form.hostChain], ); const hostChainInherited = form.hostChain === undefined && displayHostChainIds.length > 0; + const canRestoreHostChain = form.hostChain !== undefined + && !form.hostChain.hostIds?.length + && resolveFormHostChainIds({ ...form, hostChain: undefined }, effectiveGroupDefaults).length > 0; const availableHostsForChain = useMemo(() => { const chainedIds = new Set(displayHostChainIds); @@ -1262,6 +1265,7 @@ const HostDetailsPanel: React.FC = ({ setShowAlgorithmOverrides={setShowAlgorithmOverrides} chainedHosts={chainedHosts} hostChainInherited={hostChainInherited} + canRestoreHostChain={canRestoreHostChain} setActiveSubPanel={setActiveSubPanel} clearHostChain={clearHostChain} proxySummaryType={proxySummaryType} diff --git a/components/terminal/runtime/terminalBackspaceInput.test.ts b/components/terminal/runtime/terminalBackspaceInput.test.ts index 5f1f1f37b..5de44b283 100644 --- a/components/terminal/runtime/terminalBackspaceInput.test.ts +++ b/components/terminal/runtime/terminalBackspaceInput.test.ts @@ -21,5 +21,6 @@ test("Ctrl-H mode makes Backspace delete on network-device serial consoles", () test("default mode preserves xterm Backspace and ordinary input", () => { assert.equal(mapTerminalBackspaceInput("\x7f", undefined), "\x7f"); + assert.equal(mapTerminalBackspaceInput("\x7f", "default"), "\x7f"); assert.equal(mapTerminalBackspaceInput("show version", "ctrl-h"), "show version"); }); diff --git a/domain/groupConfig.test.ts b/domain/groupConfig.test.ts index 1dd21974e..db4b5eb02 100644 --- a/domain/groupConfig.test.ts +++ b/domain/groupConfig.test.ts @@ -63,6 +63,13 @@ test("applyGroupDefaults lets host device type override group device type", () = assert.equal(result.deviceType, "general"); }); +test("applyGroupDefaults preserves explicit DEL over group Ctrl-H after persistence", () => { + const groupDefaults: Partial = { backspaceBehavior: "ctrl-h" }; + const saved: Host = JSON.parse(JSON.stringify(host({ backspaceBehavior: "default" }))); + assert.equal(applyGroupDefaults(saved, groupDefaults).backspaceBehavior, "default"); + assert.equal(applyGroupDefaults(host(), groupDefaults).backspaceBehavior, "ctrl-h"); +}); + test("applyGroupDefaults skips remote-only device type for local shell hosts", () => { const result = applyGroupDefaults(host({ protocol: "local" }), { deviceType: "network" }); diff --git a/domain/models/connection.ts b/domain/models/connection.ts index a9d23a4c5..b28f56028 100644 --- a/domain/models/connection.ts +++ b/domain/models/connection.ts @@ -314,8 +314,8 @@ export interface Host { // Show local timestamps for this host beside terminal output rows. // Kept per-host because timestamp visibility is usually a host/workflow preference. showLineTimestamps?: boolean; - // What the Backspace key sends: undefined = xterm default (no interception), 'ctrl-h' = ^H (0x08) - backspaceBehavior?: 'ctrl-h'; + // Undefined inherits; 'default' sends DEL (0x7F), 'ctrl-h' sends ^H (0x08). + backspaceBehavior?: 'default' | 'ctrl-h'; // When true, tab titles stay on the connection label instead of following the // shell-reported window title (OSC 0/2). Useful when many hosts share one // bastion profile name. From cde4274041e6216d8c82ff1cdb31abd137233d88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:32:32 +0800 Subject: [PATCH 14/24] fix(terminal): keep compose bar cwd label across command submit (#4422) --- .../state/useComposeDirectoryPicker.test.ts | 85 +++++++++++++++++++ .../state/useComposeDirectoryPicker.ts | 30 ++++--- .../terminal/ComposeDirectoryPicker.test.tsx | 53 ++++++++++++ .../terminal/ComposeDirectoryPicker.tsx | 8 +- domain/composeDirectoryDisplay.ts | 23 +++++ 5 files changed, 185 insertions(+), 14 deletions(-) create mode 100644 components/terminal/ComposeDirectoryPicker.test.tsx create mode 100644 domain/composeDirectoryDisplay.ts diff --git a/application/state/useComposeDirectoryPicker.test.ts b/application/state/useComposeDirectoryPicker.test.ts index 4a06e93c3..aa2dc97ea 100644 --- a/application/state/useComposeDirectoryPicker.test.ts +++ b/application/state/useComposeDirectoryPicker.test.ts @@ -10,6 +10,89 @@ import { DirectoryPickerError, directoryChangeCommand } from '../../domain/direc Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); +for (const home of [null, '/tmp'] as const) { + test(`command invalidation retains only the compose display (home=${home})`, async t => { + const id = 'hook-sticky-cwd-' + home; + let cwd = '/tmp/test_dir'; + const writes: string[] = []; + const controller = createTerminalDirectoryController({ + sessionId: id, isCurrent: () => true, isReady: () => true, + io: { cwd: async () => cwd, home: async () => home, realpath: async path => path, + write: data => { writes.push(data); }, + list: async () => ({ home, entries: [{ name: 'child', path: cwd + '/child', hidden: false }] }) }, + publish: path => terminalCwdStore.setCwd(id, path, 'backend-strict'), + }); + const unregister = registerTerminalDirectory(id, controller); + let model!: ReturnType; + function Harness() { model = useComposeDirectoryPicker(id); return null; } + let root!: ReactTestRenderer; + await act(async () => { root = create(React.createElement(Harness)); }); + t.after(async () => { await act(async () => { root.unmount(); }); unregister(); }); + await act(async () => { model.setOpen(true); }); + const label = home ? '~/test_dir' : cwd; + assert.equal(model.display?.label, label); + assert.equal(model.display?.title, cwd); + assert.equal(model.display?.ariaPath, label); + const revision = terminalCwdStore.getSessionRevision(id); + await act(async () => { terminalCwdStore.setCwd(id, null); }); + assert.equal(model.cwd, null); + assert.equal(model.home, null); + assert.equal(terminalCwdStore.getCwd(id), null); + assert.equal(terminalCwdStore.getSource(id), undefined); + assert.ok(terminalCwdStore.getSessionRevision(id) > revision); + assert.equal(model.display?.label, label); + assert.equal(model.display?.title, cwd); + assert.equal(model.display?.ariaPath, label); + assert.equal(model.parent, null); + assert.deepEqual(model.entries, []); + await act(async () => { await model.change('/tmp'); }); + assert.equal(model.error, 'unavailable'); + await assert.rejects(controller.change('/tmp', new AbortController().signal, () => {}, cwd), { code: 'unavailable' }); + assert.deepEqual(writes, []); + await act(async () => { await controller.refresh(); }); + assert.equal(model.display?.label, label, 'restoring the same path preserves its home abbreviation'); + await act(async () => { cwd = '/tmp/next'; await controller.refresh(); }); + assert.equal(model.display?.label, home ? '~/next' : cwd); + assert.equal(model.display?.title, cwd); + }); +} + +for (const transition of ['session', 'controller', 'disconnect'] as const) { + test(`compose display never crosses a ${transition} boundary`, async t => { + const id = 'hook-display-boundary-' + transition; + const makeController = (sessionId: string, initial: boolean) => createTerminalDirectoryController({ + sessionId, isCurrent: () => true, isReady: () => true, + io: { cwd: async () => { if (!initial) throw new DirectoryPickerError('unknown'); return '/old/path'; }, + home: async () => '/old', realpath: async path => path, write() {}, list: async () => ({ home: null, entries: [] }) }, + publish: path => terminalCwdStore.setCwd(sessionId, path, 'backend-strict'), + }); + const unregister = registerTerminalDirectory(id, makeController(id, true)); + let unregisterNext = () => {}; + const renders: Array['display']> = []; + let model!: ReturnType; + function Harness({ session }: { session: string }) { + model = useComposeDirectoryPicker(session); renders.push(model.display); return null; + } + let root!: ReactTestRenderer; + await act(async () => { root = create(React.createElement(Harness, { session: id })); }); + t.after(async () => { await act(async () => { root.unmount(); }); unregister(); unregisterNext(); }); + assert.equal(model.display?.label, '~/path'); + renders.length = 0; + await act(async () => { + if (transition === 'session') { + unregisterNext = registerTerminalDirectory(id + '-next', makeController(id + '-next', false)); + root.update(React.createElement(Harness, { session: id + '-next' })); + } else if (transition === 'controller') { + // Leave the old backend value in the store: a new controller has not confirmed it. + unregisterNext = registerTerminalDirectory(id, makeController(id, false)); + } else unregister(); + }); + assert.equal(model.cwd, null); + assert.equal(model.display, null); + assert.ok(renders.every(display => display === null), 'even the first render must discard the old display'); + }); +} + for (const outcome of ['complete', 'close', 'switch', 'repeated-reports'] as const) { test(`unchanged OSC 7 during directory loading retries within the active menu (${outcome})`, async t => { const id = 'hook-list-revision-' + outcome; @@ -89,9 +172,11 @@ test('PowerShell non-filesystem reports clear an open menu and recover after ret assert.equal(model.pathFlavor, 'win32'); assert.equal(model.parent, 'C:\\'); assert.equal(model.entries.length, 1); + assert.equal(model.display?.title, 'C:\\base'); await act(async () => { filesystem = false; await controller.refresh().catch(() => {}); }); assert.equal(model.cwd, null); assert.equal(model.home, null); + assert.equal(model.display, null, 'native provider failures must not retain a filesystem label'); assert.equal(model.error, 'nonFilesystem'); assert.deepEqual(model.entries, []); await act(async () => { filesystem = true; await controller.refresh(); }); diff --git a/application/state/useComposeDirectoryPicker.ts b/application/state/useComposeDirectoryPicker.ts index ae445d8f8..82981f4cd 100644 --- a/application/state/useComposeDirectoryPicker.ts +++ b/application/state/useComposeDirectoryPicker.ts @@ -1,5 +1,6 @@ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import { DirectoryPickerError, directoryParent, filterDirectories, isDirectoryPath, type DirectoryEntry, type DirectoryPickerErrorCode } from '../../domain/directoryPicker'; +import { resolveComposeDirectoryDisplay, type ComposeDirectoryDisplay } from '../../domain/composeDirectoryDisplay'; import { terminalCwdStore } from './terminalCwdStore'; import { getTerminalDirectory, observeTerminalDirectory, subscribeTerminalDirectories } from './terminalDirectoryRegistry'; @@ -7,7 +8,8 @@ export function useComposeDirectoryPicker(sessionId: string) { const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null); const pathFlavor = controller?.target.pathFlavor ?? 'posix'; useSyncExternalStore(terminalCwdStore.subscribe, terminalCwdStore.getVersion, terminalCwdStore.getVersion); - const [confirmed, setConfirmed] = useState(false); + const [confirmation, setConfirmation] = useState<{ sessionId: string; controller: typeof controller } | null>(null); + const confirmed = confirmation?.sessionId === sessionId && confirmation.controller === controller; const observedCwd = terminalCwdStore.getCwd(sessionId); const cwd = controller && isDirectoryPath(observedCwd, pathFlavor) && (confirmed || controller.hasConfirmedCwd() || (pathFlavor === 'posix' && terminalCwdStore.getSource(sessionId) === 'osc7')) @@ -16,7 +18,15 @@ export function useComposeDirectoryPicker(sessionId: string) { const [query, setQuery] = useState(''); const [showHidden, setShowHidden] = useState(false); const [entries, setEntries] = useState([]); - const [home, setHome] = useState(null); + const [homeResult, setHomeResult] = useState<{ sessionId: string; controller: typeof controller; value: string | null } | null>(null); + const home = homeResult?.sessionId === sessionId && homeResult.controller === controller ? homeResult.value : null; + const setHome = useCallback((value: string | null) => setHomeResult({ sessionId, controller, value }), [sessionId, controller]); + // Controller identity scopes the display to one connected shell generation. + const displayCache = useRef<{ sessionId: string; controller: typeof controller; value: ComposeDirectoryDisplay | null } | null>(null); + const previousDisplay = displayCache.current?.sessionId === sessionId && displayCache.current.controller === controller + ? displayCache.current.value : null; + const display = resolveComposeDirectoryDisplay(previousDisplay, cwd, home, pathFlavor); + useEffect(() => { displayCache.current = { sessionId, controller, value: display }; }, [sessionId, controller, display]); const [loading, setLoading] = useState(false); const [pending, setPending] = useState(false); const listingBase = useRef(null); @@ -35,25 +45,25 @@ export function useComposeDirectoryPicker(sessionId: string) { const stopObserving = observeTerminalDirectory(sessionId); lifetime.current = new AbortController(); sending.current = false; - setConfirmed(false); setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]); + setConfirmation(null); setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]); listingBase.current = null; listingRevision.current = null; if (controller) void Promise.all([controller.refresh(), controller.home()]).then(([, nextHome]) => { - if (generation.current === id) { setConfirmed(true); setHome(nextHome); } + if (generation.current === id) { setConfirmation({ sessionId, controller }); setHome(nextHome); } }).catch(failure => { if (generation.current === id) report(failure, 'unknown'); }); return () => { generation.current = id + 1; lifetime.current.abort(); read.current?.abort(); stopObserving(); }; - }, [sessionId, controller, report]); + }, [sessionId, controller, report, setHome]); const refresh = useCallback(async () => { if (!controller) { setError('unavailable'); return; } const id = generation.current; setError(null); - try { await controller.refresh(); if (generation.current === id) setConfirmed(true); } + try { await controller.refresh(); if (generation.current === id) setConfirmation({ sessionId, controller }); } catch (failure) { if (generation.current === id) report(failure, 'unknown'); } - }, [controller, report]); + }, [controller, report, sessionId]); const load = useCallback(async () => { if (!controller || !cwd) return; @@ -76,7 +86,7 @@ export function useComposeDirectoryPicker(sessionId: string) { } catch (failure) { if (!task.signal.aborted && id === generation.current) report(failure, 'readFailed'); } finally { if (!task.signal.aborted && id === generation.current) setLoading(false); } - }, [controller, cwd, report, sessionId]); + }, [controller, cwd, report, sessionId, setHome]); useEffect(() => { if (!cwd) { @@ -87,7 +97,7 @@ export function useComposeDirectoryPicker(sessionId: string) { } if (open) { setQuery(''); void load(); } return () => { read.current?.abort(); }; - }, [open, load, cwd]); + }, [open, load, cwd, setHome]); const change = useCallback(async (path: string) => { if (!controller) { setError('unavailable'); return; } @@ -110,7 +120,7 @@ export function useComposeDirectoryPicker(sessionId: string) { const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]); const cwdError = controller?.getCwdError() ?? null; const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable' || error === 'nonFilesystem'; - return { cwd, home, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered, + return { cwd, home, display, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered, parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending, error: cwdError ?? (cwd && waitsForCwd ? null : error), available: !!controller?.capabilities.listDirectories && !!controller.capabilities.changeDirectory && !!controller.capabilities.confirmChange, diff --git a/components/terminal/ComposeDirectoryPicker.test.tsx b/components/terminal/ComposeDirectoryPicker.test.tsx new file mode 100644 index 000000000..8af2430a8 --- /dev/null +++ b/components/terminal/ComposeDirectoryPicker.test.tsx @@ -0,0 +1,53 @@ +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'; +import { loadLocaleMessages } from '../../application/i18n/messages'; +import { terminalCwdStore } from '../../application/state/terminalCwdStore'; +import { createTerminalDirectoryController } from '../../application/state/terminalDirectoryController'; +import { registerTerminalDirectory } from '../../application/state/terminalDirectoryRegistry'; +import { ComposeDirectoryPicker } from './ComposeDirectoryPicker'; +import type { ComposeBarTheme } from './TerminalComposeBar'; + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +for (const home of [null, '/tmp'] as const) { + test(`chip text, title and ARIA retain the confirmed display during a null cwd (home=${home})`, async t => { + await loadLocaleMessages('zh-CN'); + const sessionId = 'chip-display-' + home; + const cwd = '/tmp/test_dir'; + let root!: ReactTestRenderer; + let unregister = () => {}; + t.after(async () => { await act(async () => { root.unmount(); }); unregister(); }); + await act(async () => { + root = create( + {}} /> + ); + }); + const chip = () => root.root.findByType('button'); + const text = () => root.root.findByProps({ className: 'truncate' }).children.join(''); + assert.equal(text(), '\u76ee\u5f55\u672a\u77e5'); + assert.equal(chip().props.title, text()); + assert.ok(chip().props['aria-label'].includes(text())); + + await act(async () => { + unregister = registerTerminalDirectory(sessionId, createTerminalDirectoryController({ + sessionId, isCurrent: () => true, isReady: () => true, + io: { cwd: async () => cwd, home: async () => home, realpath: async path => path, + write() { assert.fail('display updates must not write to the terminal'); }, list: async () => ({ home, entries: [] }) }, + publish: path => terminalCwdStore.setCwd(sessionId, path, 'backend-strict'), + })); + }); + const label = home ? '~/test_dir' : cwd; + assert.equal(text(), label); + const aria = chip().props['aria-label']; + assert.ok(aria.includes(label)); + assert.equal(chip().props.title, cwd); + await act(async () => { terminalCwdStore.setCwd(sessionId, null); }); + assert.equal(terminalCwdStore.getCwd(sessionId), null); + assert.equal(text(), label); + assert.equal(chip().props.title, cwd); + assert.equal(chip().props['aria-label'], aria); + }); +} diff --git a/components/terminal/ComposeDirectoryPicker.tsx b/components/terminal/ComposeDirectoryPicker.tsx index 665d4fe1c..78533d2ff 100644 --- a/components/terminal/ComposeDirectoryPicker.tsx +++ b/components/terminal/ComposeDirectoryPicker.tsx @@ -2,7 +2,7 @@ import { ArrowUp, ChevronDown, Folder, LoaderCircle, RefreshCw } from 'lucide-re import { memo, useEffect, useId, useRef, useState } from 'react'; import { useI18n } from '../../application/i18n/I18nProvider'; import { useComposeDirectoryPicker } from '../../application/state/useComposeDirectoryPicker'; -import { directoryDisplayName, directoryLabel } from '../../domain/directoryPicker'; +import { directoryDisplayName } from '../../domain/directoryPicker'; import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'; import type { ComposeBarTheme } from './TerminalComposeBar'; @@ -51,8 +51,8 @@ export const ComposeDirectoryPicker = memo(function ComposeDirectoryPicker({ ses { if (value) outside.current = false; model.setOpen(value); }}> diff --git a/domain/composeDirectoryDisplay.ts b/domain/composeDirectoryDisplay.ts new file mode 100644 index 000000000..fc89f6b58 --- /dev/null +++ b/domain/composeDirectoryDisplay.ts @@ -0,0 +1,23 @@ +import { directoryDisplayName, directoryLabel } from './directoryPicker'; +import type { DirectoryPathFlavor } from './directoryPath'; + +export type ComposeDirectoryDisplay = { + home: string | null; + label: string; + title: string; + ariaPath: string; +}; + +/** Display only: a retained label must never be used as a live cwd. */ +export function resolveComposeDirectoryDisplay( + previous: ComposeDirectoryDisplay | null, + cwd: string | null, + home: string | null, + flavor: DirectoryPathFlavor, +): ComposeDirectoryDisplay | null { + // Native Windows nulls can mean a non-filesystem provider or integration failure. + if (!cwd) return flavor === 'posix' ? previous : null; + const displayHome = home ?? previous?.home ?? null; + const ariaPath = directoryLabel(cwd, displayHome, flavor); + return { home: displayHome, label: directoryDisplayName(ariaPath), title: directoryDisplayName(cwd), ariaPath }; +} From 5360385c41d7aafd2323e9151baf230d07a14987 Mon Sep 17 00:00:00 2001 From: Radwan Selo <133098464+RadwanSelo@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:32:36 +0900 Subject: [PATCH 15/24] fix(vault): normalize the vault_hosts_list group filter and explain empty group results (#4418) * fix(vault): normalize the vault_hosts_list group filter and explain empty group results The group filter only trimmed whitespace and trailing slashes, while saved group paths are normalized (backslashes to "/", segments trimmed, empty segments dropped). A filter like "/prod", "prod / web", "prod\web" or "prod//db" silently returned no hosts. - Normalize the filter with normalizeGroupTargetPath, the same rules used for saved groups. "/" still means no filter. - When the group filter alone leaves the list empty, add a note so an agent can tell a mistyped group from an empty one: a case-only mismatch suggests the right name, an unknown group points to vault_groups_list, and a known group without hosts says so. Results with hosts, and empty results caused by the query, are unchanged. * fix(vault): normalize stored host group paths in the vault_hosts_list group filter Host Details saves a typed group verbatim apart from outer whitespace, so hosts can carry noncanonical paths such as "prod / web" or "prod//db". Normalizing only the filter made an exact match on such a value return no hosts and report that the group exists but is empty. Normalize the stored path the same way before comparing, so the exact stored value, its canonical spelling, and parent filters all find the host. * fix(vault): list known group names in the unknown-group note vault_groups_list returns only saved groups, so pointing to it dead-ended for groups that exist only through host paths. List the known group names (saved groups and host paths, capped at 20) in the note instead. --- .../ai/vaultAgentBridgeClient.test.ts | 94 +++++++++++++++++++ infrastructure/ai/vaultAgentBridgeClient.ts | 64 ++++++++++++- 2 files changed, 153 insertions(+), 5 deletions(-) diff --git a/infrastructure/ai/vaultAgentBridgeClient.test.ts b/infrastructure/ai/vaultAgentBridgeClient.test.ts index 8848b3000..4436db746 100644 --- a/infrastructure/ai/vaultAgentBridgeClient.test.ts +++ b/infrastructure/ai/vaultAgentBridgeClient.test.ts @@ -490,6 +490,17 @@ describe('handleVaultAgentOp vault hosts', () => { assert.deepEqual(await listIds({ group: 'prod/db//' }), ['h2']); }); + it('normalizes the group filter like saved group paths', async () => { + assert.deepEqual(await listIds({ group: '/prod' }), ['h1', 'h2', 'h5']); + assert.deepEqual(await listIds({ group: '/prod/web/' }), ['h1']); + assert.deepEqual(await listIds({ group: 'prod / web' }), ['h1']); + assert.deepEqual(await listIds({ group: 'prod\\web' }), ['h1']); + assert.deepEqual(await listIds({ group: 'prod//db' }), ['h2']); + // Normalizing never widens a path-boundary match. + assert.deepEqual(await listIds({ group: '/production-old' }), ['h3']); + assert.deepEqual(await listIds({ group: '/prod/we' }), []); + }); + it('group is case-sensitive and ignores ungrouped hosts', async () => { assert.deepEqual(await listIds({ group: 'PROD' }), []); assert.equal((await listIds({ group: 'prod' })).includes('h4'), false); @@ -529,6 +540,89 @@ describe('handleVaultAgentOp vault hosts', () => { assert.deepEqual(result, { ok: true, hosts: [] }); }); + it('matches hosts whose stored group path is noncanonical', async () => { + // Host Details saves a typed group verbatim apart from outer whitespace. + const stored: Host[] = [ + { id: 'n1', label: 'api-1', hostname: '10.1.0.1', username: 'ops', port: 22, group: 'prod / web', tags: [], os: 'linux' }, + { id: 'n2', label: 'db-2', hostname: '10.1.0.2', username: 'ops', port: 22, group: 'prod//db', tags: [], os: 'linux' }, + { id: 'n3', label: 'misc', hostname: '10.1.0.3', username: 'ops', port: 22, group: 'production', tags: [], os: 'linux' }, + ]; + const list = async (group: string) => { + const result = await handleVaultAgentOp('host.list', { group }, createDeps({ hosts: stored })); + const typed = result as { hosts: Array<{ id: string }>; note?: string }; + return { ids: typed.hosts.map((host) => host.id), note: typed.note }; + }; + // The exact stored value keeps working (it did before normalization). + assert.deepEqual(await list('prod / web'), { ids: ['n1'], note: undefined }); + assert.deepEqual(await list('prod//db'), { ids: ['n2'], note: undefined }); + // Canonical spellings find the same hosts instead of a false "exists but has no hosts". + assert.deepEqual(await list('prod/web'), { ids: ['n1'], note: undefined }); + assert.deepEqual(await list('/prod/db/'), { ids: ['n2'], note: undefined }); + // Parent filters still respect path boundaries. + assert.deepEqual(await list('prod'), { ids: ['n1', 'n2'], note: undefined }); + }); + + describe('empty group results explain themselves', () => { + async function list(params: Record, customGroups: string[] = []) { + const result = await handleVaultAgentOp('host.list', params, createDeps({ hosts, customGroups })); + assert.equal(result.ok, true); + return result as { ok: true; hosts: unknown[]; note?: string }; + } + + it('suggests the right case for a case-only mismatch', async () => { + const result = await list({ group: 'PROD' }); + assert.deepEqual(result.hosts, []); + assert.equal(result.note, 'No group "PROD". Did you mean "prod"? Group names are case-sensitive.'); + assert.equal( + (await list({ group: 'Prod/Web' })).note, + 'No group "Prod/Web". Did you mean "prod/web"? Group names are case-sensitive.', + ); + }); + + it('lists known group names for an unknown group, including groups that exist only through hosts', async () => { + // No saved groups: every name comes from host paths (vault_groups_list would return none). + const known = '"prod", "prod/db", "prod/web", "production-old"'; + const result = await list({ group: 'prd' }); + assert.deepEqual(result.hosts, []); + assert.equal(result.note, `No group "prd". Known groups: ${known}.`); + // A path-boundary near miss is still unknown, not a subgroup match. + assert.equal((await list({ group: 'prod/we' })).note, `No group "prod/we". Known groups: ${known}.`); + }); + + it('caps the listed group names and says when the vault has none', async () => { + const many = Array.from({ length: 25 }, (_, index) => `g${String(index).padStart(2, '0')}`); + const result = await handleVaultAgentOp('host.list', { group: 'zzz' }, createDeps({ hosts: [], customGroups: many })); + const note = (result as { note?: string }).note ?? ''; + assert.match(note, /^No group "zzz"\. Known groups \(20 of 25\): "g00", /); + assert.equal(note.includes('"g19"'), true); + assert.equal(note.includes('"g20"'), false); + const empty = await handleVaultAgentOp('host.list', { group: 'zzz' }, createDeps({ hosts: [] })); + assert.equal((empty as { note?: string }).note, 'No group "zzz". The vault has no groups.'); + }); + + it('says when a saved group has no hosts', async () => { + const result = await list({ group: '/staging/' }, ['staging']); + assert.deepEqual(result.hosts, []); + assert.equal(result.note, 'Group "staging" exists but has no hosts.'); + // Saved subgroups make their parents known too. + assert.equal((await list({ group: 'qa' }, ['qa/api'])).note, 'Group "qa" exists but has no hosts.'); + }); + + it('adds no note when hosts are found or the query causes the empty result', async () => { + assert.equal('note' in (await list({ group: 'prod' })), false); + assert.equal('note' in (await list({ group: 'prod', query: 'zzz' })), false); + assert.equal('note' in (await list({ query: 'zzz' })), false); + assert.equal('note' in (await list({})), false); + }); + + it('still explains an unknown group when a query is also given', async () => { + assert.equal( + (await list({ group: 'prd', query: 'root' })).note, + 'No group "prd". Known groups: "prod", "prod/db", "prod/web", "production-old".', + ); + }); + }); + it('combines query and group', async () => { // h2 matches via username, h5 via its label; h3/h4 match the query but sit outside the group. assert.deepEqual(await listIds({ group: 'prod', query: 'root' }), ['h2', 'h5']); diff --git a/infrastructure/ai/vaultAgentBridgeClient.ts b/infrastructure/ai/vaultAgentBridgeClient.ts index 689c4e695..1fd4d3e4d 100644 --- a/infrastructure/ai/vaultAgentBridgeClient.ts +++ b/infrastructure/ai/vaultAgentBridgeClient.ts @@ -2,6 +2,7 @@ import { readScreenContext } from "../scripts/screenSnapshotRegistry"; import { normalizeTerminalContextRange } from "../../domain/terminalContextRead"; import { resolveHostOs } from '../../domain/host'; import { isSavedVaultHost } from '../../domain/ephemeralHosts'; +import { normalizeGroupTargetPath } from '../../domain/hostGroupPathMutations'; import type { GroupConfig, Host, Identity, KnownHost, ManagedSource, PortForwardingRule, ProxyProfile, Snippet, SSHKey, TerminalSettings, VaultNote } from '../../domain/models'; import type { RememberImportedKeyPassphraseResult } from '../../application/defaultKeyPassphrases'; import { @@ -158,13 +159,60 @@ function summarizeHostForList(host: Host) { type HostListSummary = ReturnType; -/** Empty filter matches everything. Matches the group itself or any subgroup, on a path boundary. */ +/** + * Empty filter matches everything. Matches the group itself or any subgroup, on a path boundary. + * `group` is already normalized; the stored path is normalized the same way because hosts can + * carry noncanonical paths (e.g. "prod / web" saved verbatim from Host Details). + */ function hostMatchesGroupFilter(host: HostListSummary, group: string): boolean { if (!group) return true; - const hostGroup = host.group ?? ''; + const hostGroup = typeof host.group === 'string' ? normalizeGroupTargetPath(host.group) : ''; return hostGroup === group || hostGroup.startsWith(`${group}/`); } +/** Every known group path: saved groups plus every host's group and its parent paths. */ +function collectKnownGroupPaths(customGroups: readonly string[], hosts: readonly HostListSummary[]): Set { + const known = new Set(); + const addWithParents = (raw: unknown) => { + if (typeof raw !== 'string') return; + const path = normalizeGroupTargetPath(raw); + if (!path) return; + const parts = path.split('/'); + for (let i = 1; i <= parts.length; i++) known.add(parts.slice(0, i).join('/')); + }; + customGroups.forEach(addWithParents); + hosts.forEach((host) => addWithParents(host.group)); + return known; +} + +const MAX_LISTED_GROUPS = 20; + +/** + * Explain an empty result caused by the group filter, so an agent can tell a + * mistyped group from an empty one. Returns undefined when the group has hosts + * (an empty result then comes from the query, which is self-explanatory). + */ +function describeEmptyGroupResult( + group: string, + allHosts: readonly HostListSummary[], + customGroups: readonly string[], +): string | undefined { + if (allHosts.some((host) => hostMatchesGroupFilter(host, group))) return undefined; + const known = collectKnownGroupPaths(customGroups, allHosts); + if (known.has(group)) return `Group "${group}" exists but has no hosts.`; + const lowered = group.toLocaleLowerCase(); + const caseMatch = [...known].sort().find((path) => path.toLocaleLowerCase() === lowered); + if (caseMatch) { + return `No group "${group}". Did you mean "${caseMatch}"? Group names are case-sensitive.`; + } + // List the names here: vault_groups_list returns only saved groups, not paths used only by hosts. + if (known.size === 0) return `No group "${group}". The vault has no groups.`; + const names = [...known].sort(); + const shown = names.slice(0, MAX_LISTED_GROUPS); + const count = shown.length < names.length ? ` (${shown.length} of ${names.length})` : ''; + return `No group "${group}". Known groups${count}: ${shown.map((name) => `"${name}"`).join(', ')}.`; +} + /** Every term must appear (case-insensitive) in label, hostname, username, or tags. Group is deliberately excluded. */ function hostMatchesQueryTerms(host: HostListSummary, terms: string[]): boolean { if (terms.length === 0) return true; @@ -716,11 +764,17 @@ export async function handleVaultAgentOp( const queryTerms = typeof rawQuery === 'string' ? rawQuery.toLowerCase().split(/\s+/).filter(Boolean) : []; - const group = typeof rawGroup === 'string' ? rawGroup.trim().replace(/\/+$/, '') : ''; - const hosts = deps + // Same normalization as saved group paths: "/prod", "prod / web", "prod\web" all work. + const group = typeof rawGroup === 'string' ? normalizeGroupTargetPath(rawGroup) : ''; + const allHosts = deps .getHosts() - .map((host) => summarizeHostForList(deps.resolveEffectiveHost(host))) + .map((host) => summarizeHostForList(deps.resolveEffectiveHost(host))); + const hosts = allHosts .filter((host) => hostMatchesGroupFilter(host, group) && hostMatchesQueryTerms(host, queryTerms)); + if (group && hosts.length === 0) { + const note = describeEmptyGroupResult(group, allHosts, deps.getCustomGroups()); + if (note) return { ok: true, hosts, note }; + } return { ok: true, hosts }; } case 'host.open': { From 6e6e22460d55e4261993f081a3c8925d93414093 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:32:41 +0800 Subject: [PATCH 16/24] fix(hotkeys): keep custom Open Local Terminal shortcuts ahead of Reopen Closed Tab (#4414) * fix(hotkeys): keep custom Open Local Terminal shortcuts ahead of the new Reopen Closed Tab default Fixes #4411 * fix(hotkeys): evict conflicting default shortcuts only within the same input context --- application/state/useSettingsState.ts | 18 ++-- domain/customKeyBindings.test.ts | 120 ++++++++++++++++++++++++++ domain/customKeyBindings.ts | 37 +++++++- 3 files changed, 162 insertions(+), 13 deletions(-) diff --git a/application/state/useSettingsState.ts b/application/state/useSettingsState.ts index 7cb5c2808..2edee0b92 100644 --- a/application/state/useSettingsState.ts +++ b/application/state/useSettingsState.ts @@ -11,7 +11,7 @@ import { publishTerminalSettingsSnapshot, registerTerminalSettingsActions, } from './terminalSettingsStore'; -import { SyncConfig, TerminalSettings, HotkeyScheme, CustomKeyBindings, DEFAULT_KEY_BINDINGS, KeyBinding, UILanguage, SessionLogFormat, normalizeTerminalSettings } from '../../domain/models'; +import { SyncConfig, TerminalSettings, HotkeyScheme, CustomKeyBindings, DEFAULT_KEY_BINDINGS, UILanguage, SessionLogFormat, normalizeTerminalSettings } from '../../domain/models'; import { normalizeAppLockTimeoutMinutes, type AppLockSettings, @@ -97,6 +97,7 @@ import { nextCustomKeyBindingsSyncVersion, parseCustomKeyBindingsStorageRecord, resetCustomKeyBinding, + resolveKeyBindings, serializeCustomKeyBindingsStorageRecord, shouldApplyIncomingCustomKeyBindingsRecord, updateCustomKeyBinding as updateCustomKeyBindingRecord, @@ -1939,17 +1940,10 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable }, []); // Get merged key bindings (defaults + custom overrides) - const keyBindings = useMemo((): KeyBinding[] => { - return DEFAULT_KEY_BINDINGS.map(binding => { - const custom = customKeyBindings[binding.id]; - if (!custom) return binding; - return { - ...binding, - mac: custom.mac ?? binding.mac, - pc: custom.pc ?? binding.pc, - }; - }); - }, [customKeyBindings]); + const keyBindings = useMemo( + () => resolveKeyBindings(DEFAULT_KEY_BINDINGS, customKeyBindings), + [customKeyBindings], + ); // Update a single key binding const updateKeyBinding = useCallback((bindingId: string, scheme: 'mac' | 'pc', newKey: string) => { diff --git a/domain/customKeyBindings.test.ts b/domain/customKeyBindings.test.ts index 4db40eef1..ef9b66c5e 100644 --- a/domain/customKeyBindings.test.ts +++ b/domain/customKeyBindings.test.ts @@ -6,10 +6,130 @@ import { nextCustomKeyBindingsSyncVersion, parseCustomKeyBindingsStorageRecord, resetCustomKeyBinding, + resolveKeyBindings, serializeCustomKeyBindingsStorageRecord, shouldApplyIncomingCustomKeyBindingsRecord, updateCustomKeyBinding, } from './customKeyBindings.ts'; +import { DEFAULT_KEY_BINDINGS, keyStringToKeyboardEvent } from './models/keyBindings.ts'; +import { checkAppShortcut } from '../application/state/useGlobalHotkeys.ts'; + +function shortcut(key: string, bindings = DEFAULT_KEY_BINDINGS, isMac = false) { + const event = keyStringToKeyboardEvent(key); + assert.ok(event); + return checkAppShortcut(event, bindings, isMac)?.action ?? null; +} + +test('resolving defaults preserves reopen, new tab, and local terminal shortcuts', () => { + const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {}); + + assert.deepEqual(bindings, DEFAULT_KEY_BINDINGS); + assert.equal(shortcut('Ctrl + Shift + T', bindings), 'reopenClosedTab'); + assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'reopenClosedTab'); + assert.equal(shortcut('Ctrl + T', bindings), 'newTab'); + assert.equal(shortcut('\u2318 + L', bindings, true), 'openLocal'); +}); + +test('custom PC open-local evicts the conflicting reopen default only on PC', () => { + const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, { + 'open-local': { pc: 'Ctrl + Shift + T' }, + }); + + assert.equal(bindings.find(binding => binding.id === 'open-local')?.pc, 'Ctrl + Shift + T'); + assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Disabled'); + assert.equal(shortcut('Ctrl + Shift + T', bindings), 'openLocal'); + assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'reopenClosedTab'); +}); + +test('custom macOS open-local evicts the conflicting reopen default only on macOS', () => { + const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, { + 'open-local': { mac: '\u2318 + Shift + T' }, + }); + + assert.equal(bindings.find(binding => binding.id === 'open-local')?.mac, '\u2318 + Shift + T'); + assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.mac, 'Disabled'); + assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'openLocal'); + assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Ctrl + Shift + T'); + assert.equal(shortcut('Ctrl + Shift + T', bindings), 'reopenClosedTab'); +}); + +test('unrelated custom shortcuts leave reopen defaults intact', () => { + const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, { + 'open-local': { pc: 'Ctrl + L' }, + }); + + assert.equal(shortcut('Ctrl + L', bindings), 'openLocal'); + assert.equal(shortcut('Ctrl + Shift + T', bindings), 'reopenClosedTab'); + assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'reopenClosedTab'); +}); + +for (const [id, key] of [['copy', 'C'], ['paste', 'V']]) { + test(`recording the terminal ${id} default preserves the SFTP default`, () => { + const chord = `\u2318 + ${key}`; + const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, { + [id]: { mac: chord }, + }); + + assert.equal(bindings.find(binding => binding.id === id)?.mac, chord); + assert.equal(bindings.find(binding => binding.id === `sftp-${id}`)?.mac, chord); + }); +} + +test('custom SFTP chords preserve conflicting app-level defaults on both schemes', () => { + const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, { + 'sftp-copy': { mac: '\u2318 + Shift + T', pc: 'Ctrl + Shift + T' }, + }); + + for (const id of ['sftp-copy', 'reopen-closed-tab']) { + assert.equal(bindings.find(binding => binding.id === id)?.mac, '\u2318 + Shift + T'); + assert.equal(bindings.find(binding => binding.id === id)?.pc, 'Ctrl + Shift + T'); + } +}); + +test('custom SFTP chords still evict conflicting defaults within SFTP', () => { + const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, { + 'sftp-copy': { mac: '\u2318 + V', pc: 'Ctrl + V' }, + }); + + assert.equal(bindings.find(binding => binding.id === 'sftp-copy')?.mac, '\u2318 + V'); + assert.equal(bindings.find(binding => binding.id === 'sftp-copy')?.pc, 'Ctrl + V'); + assert.equal(bindings.find(binding => binding.id === 'sftp-paste')?.mac, 'Disabled'); + assert.equal(bindings.find(binding => binding.id === 'sftp-paste')?.pc, 'Disabled'); + assert.equal(bindings.find(binding => binding.id === 'paste')?.mac, '\u2318 + V'); +}); + +test('conflicting custom shortcuts remain while uncustomized defaults are evicted', () => { + const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, { + 'open-local': { pc: 'Ctrl + Shift + T' }, + 'open-hosts': { pc: 'Ctrl + Shift + T' }, + }); + + assert.equal(bindings.find(binding => binding.id === 'open-local')?.pc, 'Ctrl + Shift + T'); + assert.equal(bindings.find(binding => binding.id === 'open-hosts')?.pc, 'Ctrl + Shift + T'); + assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Disabled'); +}); + +test('an explicitly customized reopen binding retains its conflicting chord', () => { + const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, { + 'open-local': { pc: 'Ctrl + Shift + T' }, + 'reopen-closed-tab': { pc: 'Ctrl + Shift + T' }, + }); + + assert.equal(bindings.find(binding => binding.id === 'open-local')?.pc, 'Ctrl + Shift + T'); + assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Ctrl + Shift + T'); +}); + +test('resolving conflicts does not mutate defaults or custom overrides', () => { + const defaults = structuredClone(DEFAULT_KEY_BINDINGS); + const custom = { 'open-local': { pc: 'Ctrl + Shift + T', mac: 'Disabled' } }; + const originalCustom = structuredClone(custom); + + const bindings = resolveKeyBindings(defaults, custom); + + assert.equal(bindings.find(binding => binding.id === 'open-local')?.mac, 'Disabled'); + assert.deepEqual(defaults, DEFAULT_KEY_BINDINGS); + assert.deepEqual(custom, originalCustom); +}); test('parses legacy stored custom key bindings without sync metadata', () => { const parsed = parseCustomKeyBindingsStorageRecord('{"open":{"mac":"Cmd+K"}}'); diff --git a/domain/customKeyBindings.ts b/domain/customKeyBindings.ts index e1c915878..990d6c3a1 100644 --- a/domain/customKeyBindings.ts +++ b/domain/customKeyBindings.ts @@ -1,4 +1,39 @@ -import { CustomKeyBindings } from './models'; +import { CustomKeyBindings, KeyBinding } from './models'; + +export const resolveKeyBindings = ( + defaults: readonly KeyBinding[], + customKeyBindings: CustomKeyBindings, +): KeyBinding[] => { + let merged = defaults.map(binding => { + const custom = customKeyBindings[binding.id]; + if (!custom) return binding; + return { + ...binding, + mac: custom.mac ?? binding.mac, + pc: custom.pc ?? binding.pc, + }; + }); + + for (const scheme of ['mac', 'pc'] as const) { + const customChords = { sftp: new Set(), app: new Set() }; + for (const binding of merged) { + if (customKeyBindings[binding.id]?.[scheme] != null && binding[scheme] !== 'Disabled') { + customChords[binding.category === 'sftp' ? 'sftp' : 'app'].add(binding[scheme]); + } + } + + // SFTP has its own input context; all other categories share the app-level handler. + // Custom shortcuts win over defaults in that context; custom conflicts remain unchanged. + merged = merged.map(binding => ( + customKeyBindings[binding.id]?.[scheme] == null && + customChords[binding.category === 'sftp' ? 'sftp' : 'app'].has(binding[scheme]) + ? { ...binding, [scheme]: 'Disabled' } + : binding + )); + } + + return merged; +}; const SYNC_VERSION_FIELD = '__netcattySyncVersion'; const SYNC_ORIGIN_FIELD = '__netcattySyncOrigin'; From 7b36f574f4a6fe4fcc4b6c909847b10f906d557d Mon Sep 17 00:00:00 2001 From: Radwan Selo <133098464+RadwanSelo@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:32:45 +0900 Subject: [PATCH 17/24] fix(mcp): tighten terminal_execute_bulk text and output budget, drop the lone toolset hint (#4425) - terminal_execute_bulk description: drop the sentence that repeated the summary, and stop promising a separate stderr. On interactive terminals stderr is part of stdout, so the field is almost always empty. - terminal_execute_bulk output: stdout and stderr shared each group's budget as a fixed 75%/25% split, so with empty stderr a quarter was never used and stdout was cut early. Apply tailLines first, then give each stream's unused share to the other. The per-group cap is unchanged. - load_netcatty_tools: terminal_bulk was the only toolset with a hint. Remove it so every toolset is listed the same way, and test that the description names every toolset. --- docs/features/terminal-execute-bulk.md | 3 +- electron/bridges/mcpServerBridge/execBulk.cjs | 26 +++++++-- .../bridges/mcpServerBridge/execBulk.test.cjs | 53 +++++++++++++++++++ electron/capabilities/schemas/toolInputs.cjs | 2 +- electron/mcp/progressiveMcpTools.cjs | 2 +- electron/mcp/progressiveMcpTools.test.cjs | 16 ++++++ 6 files changed, 95 insertions(+), 7 deletions(-) diff --git a/docs/features/terminal-execute-bulk.md b/docs/features/terminal-execute-bulk.md index c56c74f79..d17095e67 100644 --- a/docs/features/terminal-execute-bulk.md +++ b/docs/features/terminal-execute-bulk.md @@ -106,7 +106,8 @@ are grouped, which keeps the response small on large fleets. `cancelled`, `connection_lost`, `error`, or `not_sent`. - `exitCode` is a number only for `completed`. A non-zero exit code is a normal result, not a tool failure. Serial and network-device sessions have no exit code (`null`). -- `stderr` and `error` are omitted when empty. +- `stderr` and `error` are omitted when empty. On interactive terminals stderr is part of stdout, so `stderr` usually + appears only for sessions that run the command over an SSH exec channel. - Output is grouped on the full, untruncated result, so two hosts that differ only in the part that was cut off are never merged. `tailLines` and a per-group size cap are then applied; a cut group has `outputTruncated: true` (also set when the exec layer had already dropped the beginning of a very large output) and, when lines were dropped, diff --git a/electron/bridges/mcpServerBridge/execBulk.cjs b/electron/bridges/mcpServerBridge/execBulk.cjs index c4bd38b6b..ef30c4add 100644 --- a/electron/bridges/mcpServerBridge/execBulk.cjs +++ b/electron/bridges/mcpServerBridge/execBulk.cjs @@ -202,6 +202,18 @@ function tailText(text, tailLines, maxChars) { return { text: kept, omittedLines, truncated }; } +/** + * Split one group's character budget between stdout and stderr. stderr keeps up to a + * quarter when it needs it; whatever one stream does not use goes to the other (on + * interactive terminals stderr is part of stdout, so stdout usually gets it all). + * @returns {{ stdoutChars: number, stderrChars: number }} + */ +function splitGroupBudget(stdoutLength, stderrLength, total) { + let stderrChars = Math.min(stderrLength, Math.floor(total * 0.25)); + if (stdoutLength < total - stderrChars) stderrChars = Math.min(stderrLength, total - stdoutLength); + return { stdoutChars: total - stderrChars, stderrChars }; +} + /** * Group identical per-host results (compared on the full raw output, before * truncation) and build the public payload. @@ -240,10 +252,15 @@ function groupBulkResults(entries, options = {}) { const groups = []; for (const { normalized, hosts } of groupsByKey.values()) { // One budget per group, shared by both streams, so the response stays under the cap. - const stdoutChars = Math.floor(perGroupChars * 0.75); - const out = tailText(normalized.stdout, tailLines, stdoutChars); - const err = tailText(normalized.stderr, tailLines, perGroupChars - stdoutChars); - const omittedLines = out.omittedLines + err.omittedLines; + // Apply tailLines first, so only text that can still be shown competes for the budget. + const outLines = tailText(normalized.stdout, tailLines, Infinity); + const errLines = tailText(normalized.stderr, tailLines, Infinity); + const { stdoutChars, stderrChars } = splitGroupBudget(outLines.text.length, errLines.text.length, perGroupChars); + const outCut = tailText(outLines.text, Infinity, stdoutChars); + const errCut = tailText(errLines.text, Infinity, stderrChars); + const out = { text: outCut.text, truncated: outLines.truncated || outCut.truncated }; + const err = { text: errCut.text, truncated: errLines.truncated || errCut.truncated }; + const omittedLines = outLines.omittedLines + outCut.omittedLines + errLines.omittedLines + errCut.omittedLines; const group = { hosts, status: normalized.status, @@ -576,5 +593,6 @@ module.exports = { formatPreflightFailure, groupBulkResults, parseBulkExecParams, + splitGroupBudget, tailText, }; diff --git a/electron/bridges/mcpServerBridge/execBulk.test.cjs b/electron/bridges/mcpServerBridge/execBulk.test.cjs index 50e294a48..f48410d28 100644 --- a/electron/bridges/mcpServerBridge/execBulk.test.cjs +++ b/electron/bridges/mcpServerBridge/execBulk.test.cjs @@ -14,6 +14,7 @@ const { formatPreflightFailure, groupBulkResults, parseBulkExecParams, + splitGroupBudget, tailText, } = require("./execBulk.cjs"); @@ -784,3 +785,55 @@ test("explicit no-send codes thrown by the exec layer, and closed streams, are c assert.equal(classifyHostResult({ ok: false, thrown: true, error: "boom" }).status, "error"); assert.equal(classifyHostResult({ ok: false, thrown: true, code: "SHELL_PROMPT_PENDING", error: "x" }).status, "not_sent"); }); + +// ── stdout/stderr budget ── + +test("splitGroupBudget gives a stream's unused share to the other", () => { + // No stderr (interactive terminals): stdout gets the whole budget. + assert.deepEqual(splitGroupBudget(30_000, 0, 32_000), { stdoutChars: 32_000, stderrChars: 0 }); + // Small stderr keeps what it needs; stdout gets the rest. + assert.deepEqual(splitGroupBudget(30_000, 1_000, 32_000), { stdoutChars: 31_000, stderrChars: 1_000 }); + // Small stdout leaves room for a large stderr. + assert.deepEqual(splitGroupBudget(1_000, 30_000, 32_000), { stdoutChars: 2_000, stderrChars: 30_000 }); + // Both large: stderr keeps a quarter, as before. + assert.deepEqual(splitGroupBudget(50_000, 50_000, 32_000), { stdoutChars: 24_000, stderrChars: 8_000 }); + for (const [out, err] of [[0, 0], [5, 5], [40_000, 3], [3, 40_000], [20_000, 20_000]]) { + const { stdoutChars, stderrChars } = splitGroupBudget(out, err, 32_000); + assert.ok(stdoutChars + stderrChars <= 32_000, `${out}/${err}`); + } +}); + +test("groupBulkResults keeps stdout beyond three quarters when stderr is empty", () => { + // One line per 100 chars, under the tailLines limit so only the character cap applies. + const line = `${"o".repeat(99)}\n`; + const stdout = line.repeat(300); // 30,000 chars, 300 lines + const payload = groupBulkResults([ + { sessionId: "a", label: "web1", result: { ok: true, stdout, stderr: "", exitCode: 0 } }, + ], { tailLines: 2000 }); + assert.equal(payload.groups[0].stdout, stdout, "all 30,000 chars fit in the 32 KB group budget"); + assert.equal(payload.groups[0].outputTruncated, undefined); +}); + +test("groupBulkResults applies tailLines before sharing the budget", () => { + const stdout = Array.from({ length: 500 }, (_, i) => `out-${i}`).join("\n"); + const stderr = `${"e".repeat(99)}\n`.repeat(200); // 20,000 chars of stderr + const payload = groupBulkResults([ + { sessionId: "a", label: "web1", result: { ok: true, stdout, stderr, exitCode: 1 } }, + ], { tailLines: 10 }); + const group = payload.groups[0]; + // stdout is cut to 10 short lines, so stderr may use the space stdout does not need. + assert.equal(group.stdout.split("\n").length, 10); + assert.equal(group.stderr.split("\n").filter(Boolean).length, 10, "stderr also keeps its last 10 lines"); + assert.equal(group.outputTruncated, true); + assert.equal(group.omittedLines, 490 + 190); +}); + +test("groupBulkResults never exceeds the per-group budget", () => { + const big = "x".repeat(100_000); + const payload = groupBulkResults([ + { sessionId: "a", label: "", result: { ok: true, stdout: big, stderr: big, exitCode: 0 } }, + ], { tailLines: 2000 }); + const group = payload.groups[0]; + assert.ok(group.stdout.length + (group.stderr || "").length <= 32 * 1024); + assert.equal(group.outputTruncated, true); +}); diff --git a/electron/capabilities/schemas/toolInputs.cjs b/electron/capabilities/schemas/toolInputs.cjs index 3dbea23a5..0a9419939 100644 --- a/electron/capabilities/schemas/toolInputs.cjs +++ b/electron/capabilities/schemas/toolInputs.cjs @@ -435,7 +435,7 @@ const MODEL_DESCRIPTION_HINTS = Object.freeze({ "terminal.execute": "Use this instead of the local shell when the command is intended for a Netcatty terminal or remote host. Call get_environment first to resolve the sessionId. Use only for commands expected to finish within about 60 seconds. For long-running commands use terminal_start and terminal_poll. Commands run in an isolated subshell of the visible terminal: the user sees the output live, but shell state such as cd, export, or set does not persist between calls — use absolute paths or combine cd with the command (cd /path && cmd). If the shell prompt cannot be recognized while the connection is alive and no busy signal is present, the command is NOT sent and the tool returns SHELL_READINESS_UNKNOWN (a recoverable, non-terminal result, not a failed command): do not blind-type into a possible password prompt — inspect the terminal read-only with get_environment or terminal_read_context, re-check readiness after the user presses Enter, reuse another idle session, or ask the user to confirm the prompt before retrying.", "terminal.executeBulk": - "Run the same command on several terminal sessions in parallel and wait for all of them. Call get_environment first to resolve sessionIds, and pass them as a JSON array of 2-20 unique ids. All ids are checked before anything is sent: if any id is out of scope, disconnected, busy or blocked by the safety policy, the call fails and no command runs on any host. Use only for commands expected to finish within about 60 seconds; every host gets the same timeout. Hosts with identical results are grouped, each group reports status, exitCode, stdout and stderr. A non-zero exitCode is a normal result, not a tool failure. Each confirm-mode call needs a fresh user approval listing every host. For a single session use terminal_execute; this tool rejects fewer than 2.", + "Call get_environment first to resolve sessionIds, and pass them as a JSON array of 2-20 unique ids. All ids are checked before anything is sent: if any id is out of scope, disconnected, busy or blocked by the safety policy, the call fails and no command runs on any host. Use only for commands expected to finish within about 60 seconds; every host gets the same timeout. Hosts with identical results are grouped; each group reports status, exitCode and stdout. A non-zero exitCode is a normal result, not a tool failure. Each confirm-mode call needs a fresh user approval listing every host. For a single session use terminal_execute; this tool rejects fewer than 2.", "terminal.start": "Use this instead of the local shell for long-running commands on a Netcatty terminal or remote host. Call get_environment first to resolve the sessionId. Prefer for builds, scans, log-following, or anything likely to exceed about 2 minutes. Shell state such as cd or export does not persist between calls — combine cd with the command.", "terminal.poll": diff --git a/electron/mcp/progressiveMcpTools.cjs b/electron/mcp/progressiveMcpTools.cjs index 9a0e70b8d..60871afa0 100644 --- a/electron/mcp/progressiveMcpTools.cjs +++ b/electron/mcp/progressiveMcpTools.cjs @@ -151,7 +151,7 @@ function registerProgressiveMcpTools(server, deps, toolDefs = listMcpTools()) { server.tool( MCP_TOOL_LOADER_NAME, - "Load more Netcatty tools by category. Choose terminal_bulk (run one command on many sessions at once), sessions, attachments, sftp_advanced, vault_hosts, vault_notes, snippets, scripts, portforward, or all. Newly loaded tools appear immediately without restarting the MCP server.", + "Load more Netcatty tools by category. Choose terminal_bulk, sessions, attachments, sftp_advanced, vault_hosts, vault_notes, snippets, scripts, portforward, or all. Newly loaded tools appear immediately without restarting the MCP server.", { toolset: z.enum(LOADABLE_MCP_TOOLSET_NAMES).describe("Netcatty tool category to load"), }, diff --git a/electron/mcp/progressiveMcpTools.test.cjs b/electron/mcp/progressiveMcpTools.test.cjs index da1eec067..1607d280f 100644 --- a/electron/mcp/progressiveMcpTools.test.cjs +++ b/electron/mcp/progressiveMcpTools.test.cjs @@ -11,6 +11,7 @@ const { listMcpTools } = require("../capabilities/codegen/toolSurfaces.cjs"); const { CORE_MCP_TOOL_NAMES, DEFERRED_MCP_TOOLSETS, + LOADABLE_MCP_TOOLSET_NAMES, MCP_TOOL_LOADER_NAME, buildProgressiveMcpCatalog, registerProgressiveMcpTools, @@ -154,3 +155,18 @@ test("MCP clients receive the updated tool list without reconnecting", async () await client.close(); } }); + +test("the loader description names every toolset", () => { + const server = createFakeServer(); + let description = ""; + const register = server.tool.bind(server); + server.tool = (name, desc, ...rest) => { + if (name === MCP_TOOL_LOADER_NAME) description = desc; + return register(name, desc, ...rest); + }; + registerProgressiveMcpTools(server, createDeps()); + assert.ok(description, "loader registered"); + for (const toolset of LOADABLE_MCP_TOOLSET_NAMES) { + assert.match(description, new RegExp(`\\b${toolset}\\b`), toolset); + } +}); From 1d6c9fc693bb7aef9afc02bf6c38c9a347ee1d5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:40:50 +0800 Subject: [PATCH 18/24] fix(terminal): sync vaultInitialized with VaultHost props to avoid stale key boot (#4428) (#4458) --- application/app/AppView.tsx | 3 +- application/app/hosts/VaultHost.tsx | 2 + .../app/vaultInitTerminalSync.test.tsx | 233 ++++++++++++++++++ components/TerminalLayer.tsx | 2 + .../terminalLayer/TerminalLayerSupport.tsx | 7 + .../TerminalLayerWorkspaceSection.tsx | 2 + .../terminalLayer/terminalLayerViewMemo.ts | 1 + components/terminalLayerMemo.ts | 1 + 8 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 application/app/vaultInitTerminalSync.test.tsx diff --git a/application/app/AppView.tsx b/application/app/AppView.tsx index 3d306b0f0..c5005480e 100644 --- a/application/app/AppView.tsx +++ b/application/app/AppView.tsx @@ -281,7 +281,7 @@ function AppViewInner({ domains }: AppViewProps) { handleEndSessionDrag, handleFollowAppTerminalThemeChange, handleHostConnectWithProtocolCheck, handleHotkeyAction, handleKeyboardInteractiveCancel, handleKeyboardInteractiveSubmit, handleOpenHostFromVaultNote, handleOpenQuickSwitcher, handleOpenSettings, handleOpenVaultHostFromChat, handleOpenVaultNoteFromChat, handleOpenVaultSectionFromChat, handleOpenVaultSnippetFromChat, handleRootContextMenu, handlePassphraseCancel, handlePassphraseSkip, handlePassphraseSubmit, handleFidoPromptSubmit, handleFidoPromptCancel, handleProtocolSelect, handleRequestCloseEditorTabRef, handleSessionStatusChange, handleSyncNowManual, handleTerminalDataCapture, handleUpdateHostFromTerminal, - hostById, hosts, terminalHosts, updateTerminalHosts, hotkeyScheme, identities, importOrReuseKey, isBroadcastEnabled, isComposeSendToAll, onToggleComposeSendTarget, isGlobalBroadcastEnabled, isGlobalComposeSendToAll, onToggleGlobalBroadcast, onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen, + hostById, hosts, terminalHosts, updateTerminalHosts, hotkeyScheme, identities, importOrReuseKey, isVaultInitialized, isBroadcastEnabled, isComposeSendToAll, onToggleComposeSendTarget, isGlobalBroadcastEnabled, isGlobalComposeSendToAll, onToggleGlobalBroadcast, onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen, keyBindings, keyboardInteractiveQueue, keys, logViews, managedSources, navigateToSection, openLogView, openNoteRequest, orderedTabsWithEditors, orphanSessions, passphraseQueue, fidoPromptQueue, protocolSelectHost, proxyProfiles, portForwardingRules, removeSessionFromWorkspace, reorderWorkTabs, reorderWorkspaceSessions, resolveEmptyVaultConflict, resolveSessionAppearance, runSnippet, sessionLogsDir, sessionLogsEnabled, sessionLogsFormat, sessionLogsTimestampsEnabled, sessionRenameTarget, sshDebugLogsEnabled, @@ -734,6 +734,7 @@ function AppViewInner({ domains }: AppViewProps) { /> (); +Object.defineProperty(globalThis, 'localStorage', { + configurable: true, + value: { + getItem: (key: string) => storageBacking.get(key) ?? null, + setItem: (key: string, value: string) => { + storageBacking.set(key, value); + }, + removeItem: (key: string) => { + storageBacking.delete(key); + }, + clear: () => { + storageBacking.clear(); + }, + }, +}); + +const { VaultHost } = await import('./hosts/VaultHost.tsx'); + +test('VaultHost keeps isVaultInitialized synchronized with hydrated hosts, keys, and identities for Terminal boot (#4428)', async () => { + const dom = new JSDOM('
'); + const prevWindow = globalThis.window; + const prevDocument = globalThis.document; + const prevActEnv = (globalThis as Record).IS_REACT_ACT_ENVIRONMENT; + + (globalThis as Record).window = dom.window; + (globalThis as Record).document = dom.window.document; + (globalThis as Record).IS_REACT_ACT_ENVIRONMENT = true; + + const host: Host = { + id: 'host-1', + label: 'test-myhost', + hostname: '10.243.2.249', + port: 22, + username: 'user1', + authMethod: 'key', + identityFileId: 'key-1', + tags: [], + createdAt: 0, + }; + const key: SSHKey = { + id: 'key-1', + label: 'Imported Key', + type: 'ED25519', + privateKey: '-----BEGIN OPENSSH PRIVATE KEY-----\ntest\n-----END OPENSSH PRIVATE KEY-----', + publicKey: 'ssh-ed25519 AAAA test', + passphrase: 'secret', + source: 'imported', + category: 'key', + created: 0, + }; + const identity: Identity = { + id: 'id-1', + label: 'User Identity', + username: 'user1', + authMethod: 'key', + keyId: 'key-1', + createdAt: 0, + }; + + publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT); + registerAppHandlers({} as never); + + // Mirror TerminalHost's layout-effect slice publication order (sibling after VaultHost). + function TerminalHostMirror() { + const vault = useVaultSnapshot(); + useLayoutEffect(() => { + publishAppShellDomainSlice('terminal', { terminalHosts: vault.hosts }); + }, [vault.hosts]); + return null; + } + + const syncedBoots: Array<{ + hostCount: number; + keyCount: number; + identityCount: number; + hasPrivateKey: boolean; + }> = []; + + function SyncedTerminal({ + vaultInitializedOverride, + hosts, + keys, + identities, + }: { + vaultInitializedOverride: boolean; + hosts: readonly Host[]; + keys: readonly SSHKey[]; + identities: readonly Identity[]; + }) { + const sharedVaultInitialized = useVaultSnapshotField('isVaultInitialized'); + const vaultInitialized = resolveTerminalVaultInitialized( + sharedVaultInitialized, + vaultInitializedOverride, + ); + + useEffect(() => { + if (!vaultInitialized) return; + syncedBoots.push({ + hostCount: hosts.length, + keyCount: keys.length, + identityCount: identities.length, + hasPrivateKey: Boolean(keys[0]?.privateKey), + }); + // Intentionally matches useTerminalEffects' boot effect dep shape (gated on vaultInitialized, not keys). + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [vaultInitialized]); + + return null; + } + + function ShellHarness() { + const { domains } = useAppShellProps(); + const vaultDomain = domains?.vault as + | { isVaultInitialized?: boolean; keys?: readonly SSHKey[]; identities?: readonly Identity[] } + | undefined; + const terminalDomain = domains?.terminal as + | { terminalHosts?: readonly Host[] } + | undefined; + + return React.createElement( + React.Fragment, + null, + React.createElement(VaultHost), + React.createElement(TerminalHostMirror), + vaultDomain && terminalDomain + ? React.createElement(SyncedTerminal, { + vaultInitializedOverride: vaultDomain.isVaultInitialized ?? false, + hosts: terminalDomain.terminalHosts ?? [], + keys: vaultDomain.keys ?? [], + identities: vaultDomain.identities ?? [], + }) + : null, + ); + } + + const root = createRoot(dom.window.document.getElementById('root')!); + try { + await React.act(async () => { + root.render(React.createElement(ShellHarness)); + }); + assert.equal(syncedBoots.length, 0, 'restored terminal must not boot before vault hydration'); + + // Publish hydrated hosts, keys, identities, and isVaultInitialized together. + await React.act(async () => { + publishVaultSnapshot({ + ...EMPTY_VAULT_SNAPSHOT, + isVaultInitialized: true, + hosts: [host], + keys: [key], + identities: [identity], + }); + }); + + assert.deepEqual(syncedBoots, [ + { + hostCount: 1, + keyCount: 1, + identityCount: 1, + hasPrivateKey: true, + }, + ]); + } finally { + await React.act(async () => { + root.unmount(); + }); + publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT); + registerAppHandlers(null); + (globalThis as Record).window = prevWindow; + (globalThis as Record).document = prevDocument; + (globalThis as Record).IS_REACT_ACT_ENVIRONMENT = prevActEnv; + } +}); + +test('terminal layer memo comparators propagate isVaultInitialized changes', () => { + const baseLayerProps = { + isVaultInitialized: false, + hosts: [], + sessions: [], + }; + assert.equal( + terminalLayerAreEqual(baseLayerProps, { ...baseLayerProps, isVaultInitialized: true }), + false, + ); + assert.equal( + terminalLayerWorkspaceCtxEqual( + { isVaultInitialized: false }, + { isVaultInitialized: true }, + ), + false, + ); + assert.equal( + terminalLayerViewCtxEqual( + { isVaultInitialized: false }, + { isVaultInitialized: true }, + ), + false, + ); + + const appViewSource = readFileSync(new URL('./AppView.tsx', import.meta.url), 'utf8'); + const supportSource = readFileSync( + new URL('../../components/terminalLayer/TerminalLayerSupport.tsx', import.meta.url), + 'utf8', + ); + assert.match(appViewSource, / = ({ + isVaultInitialized, hosts, portForwardingRules = [], customGroups, @@ -2802,6 +2803,7 @@ const TerminalLayerInner: React.FC = ({ onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isComposeBarOpen, + isVaultInitialized, keyBindings, keys, knownHosts, diff --git a/components/terminalLayer/TerminalLayerSupport.tsx b/components/terminalLayer/TerminalLayerSupport.tsx index 57cbaa4be..5d2ee0516 100644 --- a/components/terminalLayer/TerminalLayerSupport.tsx +++ b/components/terminalLayer/TerminalLayerSupport.tsx @@ -682,6 +682,7 @@ export const AIChatPanelsHost = memo(AIChatPanelsHostInner, aiChatPanelsHostAreE AIChatPanelsHost.displayName = 'AIChatPanelsHost'; export interface TerminalLayerProps { + isVaultInitialized?: boolean; hosts: Host[]; portForwardingRules?: import('../../domain/models').PortForwardingRule[]; customGroups: string[]; @@ -821,6 +822,7 @@ interface TerminalPaneProps { splitVerticalHandlersRef: React.MutableRefObject void>>; resolveSessionAppearance: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance; hostMap: Map; + isVaultInitialized?: boolean; keys: SSHKey[]; identities: Identity[]; snippets: Snippet[]; @@ -960,6 +962,7 @@ const terminalPanePropsAreEqual = ( prev.splitHorizontalHandlersRef === next.splitHorizontalHandlersRef && prev.splitVerticalHandlersRef === next.splitVerticalHandlersRef && getPaneAppearanceThemeId(prev) === getPaneAppearanceThemeId(next) && + prev.isVaultInitialized === next.isVaultInitialized && prev.keys === next.keys && prev.identities === next.identities && prev.snippets === next.snippets && @@ -1252,6 +1255,7 @@ const TerminalPane: React.FC = memo(({ splitVerticalHandlersRef, resolveSessionAppearance, hostMap, + isVaultInitialized, keys, identities, snippets, @@ -1679,6 +1683,7 @@ const TerminalPane: React.FC = memo(({ sessionId={session.id} workspaceId={session.workspaceId} restoreState={session.restoreState} + vaultInitializedOverride={isVaultInitialized} pendingInitialCwd={session.pendingInitialCwd} shellType={session.shellType} lastCwd={session.lastCwd} @@ -1775,6 +1780,7 @@ interface TerminalPanesHostProps { splitVerticalHandlersRef: React.MutableRefObject void>>; resolveSessionAppearance: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance; hostMap: Map; + isVaultInitialized?: boolean; keys: SSHKey[]; identities: Identity[]; snippets: Snippet[]; @@ -1870,6 +1876,7 @@ const terminalPanesHostPropsAreEqual = ( if (prev.splitVerticalHandlersRef !== next.splitVerticalHandlersRef) return false; if (prev.resolveSessionAppearance !== next.resolveSessionAppearance) return false; if (prev.hostMap !== next.hostMap) return false; + if (prev.isVaultInitialized !== next.isVaultInitialized) return false; if (prev.keys !== next.keys) return false; if (prev.identities !== next.identities) return false; if (prev.snippets !== next.snippets) return false; diff --git a/components/terminalLayer/TerminalLayerWorkspaceSection.tsx b/components/terminalLayer/TerminalLayerWorkspaceSection.tsx index 10051624c..6a7447800 100644 --- a/components/terminalLayer/TerminalLayerWorkspaceSection.tsx +++ b/components/terminalLayer/TerminalLayerWorkspaceSection.tsx @@ -62,6 +62,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext }) splitVerticalHandlersRef, resolveSessionAppearance, hostMap, + isVaultInitialized, keys, identities, snippets, @@ -230,6 +231,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext }) splitVerticalHandlersRef={splitVerticalHandlersRef} resolveSessionAppearance={resolveSessionAppearance} hostMap={hostMap} + isVaultInitialized={isVaultInitialized} keys={keys} identities={identities} snippets={snippets} diff --git a/components/terminalLayer/terminalLayerViewMemo.ts b/components/terminalLayer/terminalLayerViewMemo.ts index 97a8fb65d..38e756197 100644 --- a/components/terminalLayer/terminalLayerViewMemo.ts +++ b/components/terminalLayer/terminalLayerViewMemo.ts @@ -383,6 +383,7 @@ const WORKSPACE_CTX_KEYS = [ 'splitVerticalHandlersRef', 'resolveSessionAppearance', 'hostMap', + 'isVaultInitialized', 'keys', 'identities', 'snippets', diff --git a/components/terminalLayerMemo.ts b/components/terminalLayerMemo.ts index 1d51394d3..d6bed97d3 100644 --- a/components/terminalLayerMemo.ts +++ b/components/terminalLayerMemo.ts @@ -4,6 +4,7 @@ export const terminalLayerAreEqual = ( prev: Record, next: Record, ): boolean => ( + prev.isVaultInitialized === next.isVaultInitialized && prev.hosts === next.hosts && prev.customGroups === next.customGroups && prev.groupConfigs === next.groupConfigs && From 883313f483de861fc68747c0689ec461b260e97f Mon Sep 17 00:00:00 2001 From: GOUKI9999 Date: Thu, 26 Nov 2026 22:51:40 +0800 Subject: [PATCH 19/24] fix(ui): keep per-pane close button visible at narrow widths (#4448) Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com> --- .../TerminalLayerSidePanelSection.test.ts | 18 ++++++++++++++++++ .../TerminalLayerSidePanelSection.tsx | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/components/terminalLayer/TerminalLayerSidePanelSection.test.ts b/components/terminalLayer/TerminalLayerSidePanelSection.test.ts index c7e082f85..d8d5ad55b 100644 --- a/components/terminalLayer/TerminalLayerSidePanelSection.test.ts +++ b/components/terminalLayer/TerminalLayerSidePanelSection.test.ts @@ -20,6 +20,24 @@ import { resolveSidePanelPortalTarget, } from './terminalLayerSidePanelSlots.tsx'; +test('per-pane close button keeps shrink-0 so a narrow pane cannot squeeze it away', () => { + const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); + const paneHost = source.slice( + source.indexOf('function SidePanelPaneHost'), + source.indexOf('function TerminalLayerSidePanelInner'), + ); + assert.ok(paneHost.length > 0, 'SidePanelPaneHost source slice must exist'); + // The close button is the only button in the pane header; it must not shrink + // when the pane label is truncated at narrow split widths. + const closeButton = paneHost.match(/ { const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); const chromeStart = source.indexOf('className="absolute inset-3'); diff --git a/components/terminalLayer/TerminalLayerSidePanelSection.tsx b/components/terminalLayer/TerminalLayerSidePanelSection.tsx index 609cfc9db..0cba06e44 100644 --- a/components/terminalLayer/TerminalLayerSidePanelSection.tsx +++ b/components/terminalLayer/TerminalLayerSidePanelSection.tsx @@ -168,7 +168,7 @@ function SidePanelPaneHost({ {label} + + +
+
+ {formatHostPort(activeRule.bindAddress, activeRule.localPort)} + {' → '} + {formatHostPort( + activeRule.remoteHost || resolveForwardRemoteHost(port), + activeRule.remotePort ?? port.port, + )} +
+
+ {activeRule.status === 'connecting' + ? (activeRule.error || t('systemManager.ports.forwarding')) + : t('systemManager.ports.clickToCopy')} +
+
+
+ + ) : ( + + {port.protocol.toUpperCase()} + + ); + + const hasActions = canForwardRow || (allowMutations && port.pid != null); + + return ( + + {canForwardRow ? ( + activeRule ? ( + void handleStopForward(activeRule)} + > + + + ) : ( + openForwardDialog(port)} + > + + + ) + ) : null} + {allowMutations && port.pid != null ? ( + setPendingKillPid(port.pid)} + > + + + ) : null} + + ) : null} + /> + ); + })} )} + { + if (!open && !forwardBusy) { + setForwardDialogPort(null); + setForwardError(null); + } + }} + onSubmit={(values) => void handleSubmitForward(values)} + /> + void; + onSubmit: (values: { localPort: number; bindAddress: string }) => void; +} + +export const QuickPortForwardDialog = memo(function QuickPortForwardDialog({ + open, + port, + hostLabel, + initialLocalPort, + initialBindAddress, + rules, + excludeRuleId, + busy = false, + error, + onOpenChange, + onSubmit, +}: QuickPortForwardDialogProps) { + const { t } = useI18n(); + const [localPortText, setLocalPortText] = useState(String(initialLocalPort)); + const [bindAddressText, setBindAddressText] = useState(initialBindAddress); + const [localError, setLocalError] = useState(null); + const localPortInputRef = useRef(null); + + useEffect(() => { + if (!open) return; + setLocalPortText(String(initialLocalPort)); + setBindAddressText(initialBindAddress || DEFAULT_QUICK_FORWARD_BIND_ADDRESS); + setLocalError(null); + }, [initialBindAddress, initialLocalPort, open, port?.id]); + + useEffect(() => { + if (!open) return; + const timer = window.setTimeout(() => { + const input = localPortInputRef.current; + input?.focus(); + input?.select(); + }, 50); + return () => window.clearTimeout(timer); + }, [open, port?.id]); + + if (!port) return null; + + const remoteHost = resolveForwardRemoteHost(port); + const remoteEndpoint = formatHostPort(remoteHost, port.port); + const previewBind = bindAddressText.trim() || DEFAULT_QUICK_FORWARD_BIND_ADDRESS; + const parsedPreviewPort = Number(localPortText.trim()); + const localPreviewEndpoint = Number.isInteger(parsedPreviewPort) && parsedPreviewPort >= 1 && parsedPreviewPort <= 65535 + ? formatHostPort(previewBind, parsedPreviewPort) + : `${previewBind}:${localPortText.trim() || '?'}`; + + const handleSubmit = (event: React.FormEvent) => { + event.preventDefault(); + if (busy) return; + const validation = validateQuickForwardInput({ + localPortText, + bindAddressText, + rules, + excludeRuleId, + }); + if ('error' in validation) { + if (validation.error.code === 'invalidPort') { + setLocalError(t('systemManager.ports.forwardInvalidPort')); + } else if (validation.error.code === 'invalidBindAddress') { + setLocalError(t('systemManager.ports.forwardInvalidBindAddress')); + } else { + setLocalError( + t('systemManager.ports.forwardPortInUse', { + port: String(localPortText.trim()), + label: validation.error.conflictRule.label, + }), + ); + } + return; + } + setLocalError(null); + onSubmit({ + localPort: validation.localPort, + bindAddress: validation.bindAddress, + }); + }; + + const displayError = localError || error; + const trimmedBind = bindAddressText.trim(); + + return ( + { if (!busy || nextOpen) onOpenChange(nextOpen); }}> + + + {t('systemManager.ports.forwardTitle')} + + {hostLabel + ? t('systemManager.ports.forwardDescWithHost', { host: hostLabel }) + : t('systemManager.ports.forwardDesc')} + + + +
+
+
+ {localPreviewEndpoint} + + {remoteEndpoint} +
+
+ {port.processName + ? `${port.processName}${port.pid != null ? ` · PID ${port.pid}` : ''} · ${port.protocol.toUpperCase()}` + : `${port.protocol.toUpperCase()}${port.pid != null ? ` · PID ${port.pid}` : ''}`} +
+
+ +
+ + { + setLocalPortText(event.target.value); + if (localError) setLocalError(null); + }} + placeholder={String(initialLocalPort)} + className="h-9 font-mono text-sm" + disabled={busy} + /> +
+ +
+
+ +
+ {BIND_ADDRESS_PRESETS.map((preset) => ( + + ))} +
+
+ { + setBindAddressText(event.target.value); + if (localError) setLocalError(null); + }} + placeholder={DEFAULT_QUICK_FORWARD_BIND_ADDRESS} + className="h-9 font-mono text-sm" + spellCheck={false} + disabled={busy} + /> +
+ + {displayError && ( +

+ {displayError} +

+ )} + + + + + +
+
+
+ ); +}); diff --git a/components/systemManager/SystemManagerSidePanel.tsx b/components/systemManager/SystemManagerSidePanel.tsx index 8e9410436..e8528e7a2 100644 --- a/components/systemManager/SystemManagerSidePanel.tsx +++ b/components/systemManager/SystemManagerSidePanel.tsx @@ -3,6 +3,7 @@ import type { LucideIcon } from 'lucide-react'; import React, { memo, useCallback, useEffect, useLayoutEffect, useMemo, useState } from 'react'; import { useI18n } from '../../application/i18n/I18nProvider'; import { SYSTEM_MANAGER_TAB_LAYOUT_DEFAULTS } from '../../application/state/systemManagerTabLayout'; +import type { QuickPortForwardingContext } from '../../application/state/useQuickPortForwarding'; import { useSystemManagerBackend } from '../../application/state/useSystemManagerBackend'; import { useTerminalBackend } from '../../application/state/useTerminalBackend'; import { remoteSoftwareRequiresSingleChannel } from '@/domain/singleChannelSshBanner.shared.cjs'; @@ -69,6 +70,8 @@ interface SystemManagerSidePanelProps { terminalSettings: TerminalSettings; snippets: Snippet[]; onRequestTerminalFocus?: () => void; + /** Optional context enabling one-click SSH port forwarding from the Ports tab. */ + portForwardingContext?: QuickPortForwardingContext; } export const SystemManagerSidePanel = memo(function SystemManagerSidePanel({ @@ -79,6 +82,7 @@ export const SystemManagerSidePanel = memo(function SystemManagerSidePanel({ terminalSettings, snippets, onRequestTerminalFocus, + portForwardingContext, }: SystemManagerSidePanelProps) { const { t } = useI18n(); const backend = useSystemManagerBackend(); @@ -568,6 +572,7 @@ export const SystemManagerSidePanel = memo(function SystemManagerSidePanel({ backend={backend} refreshIntervalSec={terminalSettings.systemManagerProcessRefreshInterval} allowMutations={allowMutations} + portForwardingContext={portForwardingContext} />
) : null} diff --git a/components/terminalLayer/terminalLayerSidePanelSlots.tsx b/components/terminalLayer/terminalLayerSidePanelSlots.tsx index 544df18e1..975d1c4a7 100644 --- a/components/terminalLayer/terminalLayerSidePanelSlots.tsx +++ b/components/terminalLayer/terminalLayerSidePanelSlots.tsx @@ -47,6 +47,7 @@ const navigatorPlatform = typeof navigator !== 'undefined' ? navigator.platform const EMPTY_VAULT_NOTES: never[] = []; const EMPTY_VAULT_HOSTS: never[] = []; const EMPTY_VAULT_SNIPPETS: never[] = []; +const EMPTY_ARRAY: never[] = []; const subscribeShellHistoryNoop = () => () => {}; function useSidePanelLiveSnapshotForTab(tabId: string, subscribe: boolean) { @@ -337,10 +338,42 @@ function SidePanelSystemSlotInner({ ); const { + effectiveHosts, + hosts, + identities, + keys, + knownHosts, refocusActiveTerminalSession, + sftpAuthHostBySessionId, snippets, terminalSettings, } = ctx; + const authHosts = sftpAuthHostBySessionId as Map | undefined; + const authHost = systemSession ? (authHosts?.get(systemSession.id) ?? null) : null; + const portForwardingContext = React.useMemo( + () => ({ + session: systemSession, + sessionHost: systemHost, + authHost, + vaultHosts: (hosts ?? EMPTY_VAULT_HOSTS) as Host[], + effectiveHosts: (effectiveHosts ?? EMPTY_VAULT_HOSTS) as Host[], + keys: (keys ?? EMPTY_ARRAY) as import('../../domain/models').SSHKey[], + identities: (identities ?? EMPTY_ARRAY) as import('../../domain/models').Identity[], + knownHosts: (knownHosts ?? EMPTY_ARRAY) as import('../../domain/models').KnownHost[], + terminalSettings, + }), + [ + authHost, + effectiveHosts, + hosts, + identities, + keys, + knownHosts, + systemHost, + systemSession, + terminalSettings, + ], + ); return (
@@ -353,6 +386,7 @@ function SidePanelSystemSlotInner({ terminalSettings={terminalSettings} snippets={snippets} onRequestTerminalFocus={refocusActiveTerminalSession} + portForwardingContext={portForwardingContext} />
); diff --git a/domain/systemManager/portForwardQuick.test.ts b/domain/systemManager/portForwardQuick.test.ts new file mode 100644 index 000000000..d1e0d0509 --- /dev/null +++ b/domain/systemManager/portForwardQuick.test.ts @@ -0,0 +1,286 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import type { Host, PortForwardingRule } from '../models.ts'; +import type { TerminalSession } from '../../types.ts'; +import type { ListeningPortInfo } from './types.ts'; +import { + buildQuickForwardRuleLabel, + canQuickForwardSession, + findExactReusableForwardRule, + findLocalPortConflict, + formatCopyableLocalEndpoint, + formatHostPort, + isForwardableListeningPort, + matchListeningPortForwardRules, + resolveForwardRemoteHost, + suggestQuickForwardLocalPort, + validateQuickForwardInput, +} from './portForwardQuick.ts'; + +function makeHost(overrides: Partial = {}): Host { + return { + id: 'host-1', + label: 'prod-api', + hostname: '10.0.0.10', + username: 'root', + tags: [], + os: 'linux', + ...overrides, + }; +} + +function makeSession(overrides: Partial = {}): TerminalSession { + return { + id: 'session-1', + hostId: 'host-1', + hostLabel: 'prod-api', + username: 'root', + hostname: '10.0.0.10', + status: 'connected', + protocol: 'ssh', + ...overrides, + }; +} + +function makePort(overrides: Partial = {}): ListeningPortInfo { + const protocol = overrides.protocol ?? 'tcp'; + const address = overrides.address ?? '*'; + const port = overrides.port ?? 5432; + const pid = overrides.pid === undefined ? 1234 : overrides.pid; + return { + id: `${protocol}|${address}|${port}|${pid ?? '-'}`, + protocol, + address, + port, + pid, + processName: 'postgres', + ...overrides, + }; +} + +function makeRule(overrides: Partial = {}): PortForwardingRule { + return { + id: 'rule-1', + label: 'Rule 1', + type: 'local', + localPort: 5432, + bindAddress: '127.0.0.1', + remoteHost: '127.0.0.1', + remotePort: 5432, + hostId: 'host-1', + status: 'inactive', + createdAt: 1, + ...overrides, + }; +} + +test('canQuickForwardSession allows connected SSH and Mosh remote sessions only', () => { + assert.equal(canQuickForwardSession(makeHost(), makeSession()), true); + assert.equal(canQuickForwardSession(makeHost({ protocol: 'mosh' }), makeSession({ protocol: 'mosh' })), true); + assert.equal(canQuickForwardSession(makeHost(), makeSession({ status: 'disconnected' })), false); + assert.equal(canQuickForwardSession(makeHost({ protocol: 'local' }), makeSession({ protocol: 'local' })), false); + assert.equal(canQuickForwardSession(makeHost({ protocol: 'telnet' }), makeSession({ protocol: 'telnet' })), false); + assert.equal(canQuickForwardSession(makeHost({ protocol: 'serial' }), makeSession({ protocol: 'serial' })), false); + assert.equal(canQuickForwardSession(makeHost({ protocol: 'et' }), makeSession({ protocol: 'et' })), false); + assert.equal(canQuickForwardSession(makeHost({ hostname: ' ' }), makeSession()), false); + assert.equal(canQuickForwardSession(null, makeSession()), false); +}); + +test('isForwardableListeningPort accepts TCP and TCP6 valid ports and rejects UDP', () => { + assert.equal(isForwardableListeningPort(makePort({ protocol: 'tcp', port: 8080 })), true); + assert.equal(isForwardableListeningPort(makePort({ protocol: 'tcp6', port: 443 })), true); + assert.equal(isForwardableListeningPort(makePort({ protocol: 'udp', port: 53 })), false); + assert.equal(isForwardableListeningPort(makePort({ protocol: 'udp6', port: 5353 })), false); + assert.equal(isForwardableListeningPort(makePort({ protocol: 'unknown', port: 80 })), false); + assert.equal(isForwardableListeningPort(makePort({ protocol: 'tcp', port: 0 })), false); + assert.equal(isForwardableListeningPort(makePort({ protocol: 'tcp', port: 65536 })), false); +}); + +test('resolveForwardRemoteHost preserves IPv4/IPv6 address family for wildcards and keeps explicit addresses', () => { + assert.equal(resolveForwardRemoteHost(makePort({ address: '*', protocol: 'tcp' })), '127.0.0.1'); + assert.equal(resolveForwardRemoteHost(makePort({ address: '0.0.0.0', protocol: 'tcp' })), '127.0.0.1'); + assert.equal(resolveForwardRemoteHost(makePort({ address: '*', protocol: 'tcp6' })), '::1'); + assert.equal(resolveForwardRemoteHost(makePort({ address: '::', protocol: 'tcp6' })), '::1'); + assert.equal(resolveForwardRemoteHost(makePort({ address: '::', protocol: 'tcp' })), '::1'); + assert.equal(resolveForwardRemoteHost(makePort({ address: '127.0.0.1' })), '127.0.0.1'); + assert.equal(resolveForwardRemoteHost(makePort({ address: '::1', protocol: 'tcp6' })), '::1'); + assert.equal(resolveForwardRemoteHost(makePort({ address: '[::1]', protocol: 'tcp6' })), '::1'); + assert.equal(resolveForwardRemoteHost(makePort({ address: '10.0.0.5' })), '10.0.0.5'); + assert.equal(resolveForwardRemoteHost(makePort({ address: 'fe80::1%eth0', protocol: 'tcp6' })), 'fe80::1'); +}); + +test('formatHostPort and formatCopyableLocalEndpoint bracket IPv6 and map wildcards', () => { + assert.equal(formatHostPort('127.0.0.1', 8080), '127.0.0.1:8080'); + assert.equal(formatHostPort('::1', 8080), '[::1]:8080'); + assert.equal(formatHostPort('*', 80), '*:80'); + assert.equal(formatCopyableLocalEndpoint('0.0.0.0', 8080), '127.0.0.1:8080'); + assert.equal(formatCopyableLocalEndpoint('::', 8080), '[::1]:8080'); + assert.equal(formatCopyableLocalEndpoint('127.0.0.1', 3000), '127.0.0.1:3000'); + assert.equal(formatCopyableLocalEndpoint('::1', 3000), '[::1]:3000'); +}); + +test('suggestQuickForwardLocalPort avoids privileged ports and existing rule collisions', () => { + assert.equal(suggestQuickForwardLocalPort(3000, []), 3000); + assert.equal(suggestQuickForwardLocalPort(80, []), 8080); + assert.equal(suggestQuickForwardLocalPort(443, []), 8443); + assert.equal(suggestQuickForwardLocalPort(22, []), 10022); + assert.equal( + suggestQuickForwardLocalPort(80, [makeRule({ localPort: 8080 })]), + 10080, + ); + assert.equal( + suggestQuickForwardLocalPort(3000, [ + makeRule({ id: 'r1', localPort: 3000 }), + makeRule({ id: 'r2', localPort: 3001 }), + ]), + 3002, + ); + // Remote forwarding rules bind on the remote host, so they do not occupy a local port. + assert.equal( + suggestQuickForwardLocalPort(3000, [makeRule({ type: 'remote', localPort: 3000 })]), + 3000, + ); +}); + +test('matchListeningPortForwardRules matches active, connecting, and reusable rules per address family', () => { + const ipv4Port = makePort({ address: '*', protocol: 'tcp', port: 5432 }); + const ipv6Port = makePort({ address: '*', protocol: 'tcp6', port: 5432 }); + const rules = [ + makeRule({ id: 'other-host', hostId: 'host-2', status: 'active', localPort: 5432, remotePort: 5432 }), + makeRule({ id: 'connecting-rule', status: 'connecting', localPort: 15432, remoteHost: 'localhost', remotePort: 5432 }), + makeRule({ id: 'active-rule', status: 'active', localPort: 25432, remoteHost: '127.0.0.1', remotePort: 5432 }), + makeRule({ id: 'inactive-v4-rule', status: 'inactive', localPort: 35432, remoteHost: '127.0.0.1', remotePort: 5432 }), + makeRule({ id: 'active-v6-rule', status: 'active', localPort: 45432, remoteHost: '::1', remotePort: 5432 }), + ]; + + const v4Matches = matchListeningPortForwardRules(ipv4Port, 'host-1', rules); + assert.deepEqual( + v4Matches.activeRules.map((r) => r.id), + ['active-rule', 'connecting-rule'], + ); + assert.equal(v4Matches.primaryActiveRule?.id, 'active-rule'); + assert.equal(v4Matches.reusableInactiveRule?.id, 'inactive-v4-rule'); + + // IPv6 wildcard row matches ::1 rules only and does not cross-match IPv4 127.0.0.1 rules. + const v6Matches = matchListeningPortForwardRules(ipv6Port, 'host-1', rules); + assert.deepEqual( + v6Matches.activeRules.map((r) => r.id), + ['active-v6-rule'], + ); + assert.equal(v6Matches.primaryActiveRule?.id, 'active-v6-rule'); + assert.equal(v6Matches.reusableInactiveRule, undefined); + + // Specific IP listener does not match a 127.0.0.1 rule. + const specificPort = makePort({ address: '10.0.0.5', port: 5432 }); + assert.equal(matchListeningPortForwardRules(specificPort, 'host-1', rules).activeRules.length, 0); +}); + +test('findExactReusableForwardRule only reuses inactive rules with identical connection params', () => { + const inactive = makeRule({ + id: 'inactive-exact', + status: 'inactive', + hostId: 'host-1', + remoteHost: '127.0.0.1', + remotePort: 5432, + localPort: 15432, + bindAddress: '127.0.0.1', + }); + const active = makeRule({ ...inactive, id: 'active-exact', status: 'active' }); + + assert.equal( + findExactReusableForwardRule([active, inactive], { + hostId: 'host-1', + remoteHost: '127.0.0.1', + remotePort: 5432, + localPort: 15432, + bindAddress: '127.0.0.1', + })?.id, + 'inactive-exact', + ); + + // Different local port should NOT silently reuse/mutate the existing rule. + assert.equal( + findExactReusableForwardRule([inactive], { + hostId: 'host-1', + remoteHost: '127.0.0.1', + remotePort: 5432, + localPort: 25432, + bindAddress: '127.0.0.1', + }), + undefined, + ); +}); + +test('findLocalPortConflict and validateQuickForwardInput catch invalid input and overlapping binds', () => { + const activeWildcard = makeRule({ + id: 'wild', + status: 'active', + bindAddress: '0.0.0.0', + localPort: 8080, + }); + const activeLoopback = makeRule({ + id: 'loop', + status: 'connecting', + bindAddress: '127.0.0.1', + localPort: 9090, + }); + const inactiveLoopback = makeRule({ + id: 'idle', + status: 'inactive', + bindAddress: '127.0.0.1', + localPort: 7070, + }); + + const rules = [activeWildcard, activeLoopback, inactiveLoopback]; + assert.equal(findLocalPortConflict(rules, '127.0.0.1', 8080)?.id, 'wild'); + assert.equal(findLocalPortConflict(rules, 'localhost', 9090)?.id, 'loop'); + assert.equal(findLocalPortConflict(rules, '127.0.0.1', 7070), undefined); + assert.equal(findLocalPortConflict(rules, '127.0.0.1', 9090, 'loop'), undefined); + + assert.deepEqual( + validateQuickForwardInput({ localPortText: '0', bindAddressText: '127.0.0.1', rules }), + { ok: false, error: { code: 'invalidPort' } }, + ); + assert.deepEqual( + validateQuickForwardInput({ localPortText: 'abc', bindAddressText: '127.0.0.1', rules }), + { ok: false, error: { code: 'invalidPort' } }, + ); + assert.deepEqual( + validateQuickForwardInput({ localPortText: '7070', bindAddressText: 'bad host', rules }), + { ok: false, error: { code: 'invalidBindAddress' } }, + ); + const conflict = validateQuickForwardInput({ + localPortText: '8080', + bindAddressText: '127.0.0.1', + rules, + }); + assert.equal(conflict.ok, false); + if ('error' in conflict) { + assert.equal(conflict.error.code, 'localPortInUse'); + } + + assert.deepEqual( + validateQuickForwardInput({ localPortText: '7070', bindAddressText: '', rules }), + { ok: true, localPort: 7070, bindAddress: '127.0.0.1' }, + ); +}); + +test('buildQuickForwardRuleLabel creates descriptive human-readable labels', () => { + assert.equal( + buildQuickForwardRuleLabel('prod-db', makePort({ port: 5432, processName: 'postgres' }), 5432, '127.0.0.1'), + 'prod-db · postgres (:5432)', + ); + assert.equal( + buildQuickForwardRuleLabel('prod-db', makePort({ port: 5432, processName: '' }), 5432, '127.0.0.1'), + 'prod-db :5432', + ); + assert.equal( + buildQuickForwardRuleLabel('', makePort({ port: 5432, processName: 'redis-server' }), 6379, '127.0.0.1'), + 'redis-server (:5432)', + ); + assert.equal( + buildQuickForwardRuleLabel('', makePort({ port: 5432, processName: '' }), 15432, '::1'), + 'Local:15432 -> [::1]:5432', + ); +}); diff --git a/domain/systemManager/portForwardQuick.ts b/domain/systemManager/portForwardQuick.ts new file mode 100644 index 000000000..6a53d5b45 --- /dev/null +++ b/domain/systemManager/portForwardQuick.ts @@ -0,0 +1,326 @@ +import type { Host, PortForwardingRule } from '../models'; +import type { TerminalSession } from '../../types'; +import type { ListeningPortInfo } from './types'; + +export const DEFAULT_QUICK_FORWARD_BIND_ADDRESS = '127.0.0.1'; + +const WILDCARD_ADDRESSES = new Set(['', '*', '0.0.0.0', '::']); +const ACTIVE_STATUSES = new Set(['active', 'connecting']); + +function stripAddressDecoration(address: string): string { + let normalized = address.trim(); + if (normalized.startsWith('[') && normalized.endsWith(']')) { + normalized = normalized.slice(1, -1); + } + const zoneIndex = normalized.indexOf('%'); + if (zoneIndex >= 0) { + normalized = normalized.slice(0, zoneIndex); + } + return normalized.trim(); +} + +export function normalizeEndpointHost(address: string | undefined): string { + return stripAddressDecoration(String(address ?? '')).toLowerCase(); +} + +export function isWildcardAddress(address: string | undefined): boolean { + return WILDCARD_ADDRESSES.has(normalizeEndpointHost(address)); +} + +export function formatHostPort(host: string, port: number): string { + const cleaned = stripAddressDecoration(host) || '*'; + if (cleaned.includes(':')) { + return `[${cleaned}]:${port}`; + } + return `${cleaned}:${port}`; +} + +/** + * Format a copyable local address from a local bind address + port. + * Wildcard binds (0.0.0.0 / :: / *) map to loopback so the copied endpoint can + * be pasted directly into a browser or client. + */ +export function formatCopyableLocalEndpoint(bindAddress: string, localPort: number): string { + const normalized = normalizeEndpointHost(bindAddress); + if (normalized === '::') { + return `[::1]:${localPort}`; + } + if (isWildcardAddress(normalized)) { + return `127.0.0.1:${localPort}`; + } + return formatHostPort(bindAddress, localPort); +} + +/** + * Only connected remote SSH-capable sessions support SSH local port forwarding. + * Local shells, Telnet, Serial, ET, and plugin transports do not use SSH forwardOut. + */ +export function canQuickForwardSession( + host: Host | null | undefined, + session: TerminalSession | null | undefined, +): boolean { + if (!host || !session || session.status !== 'connected') return false; + const protocol = host.protocol ?? session.protocol ?? 'ssh'; + if (protocol !== 'ssh' && protocol !== 'mosh') return false; + return Boolean(host.hostname?.trim()); +} + +/** + * SSH direct-tcpip forwarding supports TCP listening sockets with a valid port. + */ +export function isForwardableListeningPort(port: ListeningPortInfo): boolean { + if (port.protocol !== 'tcp' && port.protocol !== 'tcp6') return false; + return Number.isInteger(port.port) && port.port >= 1 && port.port <= 65535; +} + +/** + * Resolve the remote target host passed to SSH forwardOut for a listening port. + * Preserves address family for wildcard listeners: IPv6 wildcards (`tcp6` or + * `::`) target `::1`, while IPv4 wildcards (`tcp` / `0.0.0.0` / `*`) target + * `127.0.0.1`. Explicit interface or loopback binds keep their exact address. + */ +export function resolveForwardRemoteHost(port: ListeningPortInfo): string { + const cleaned = stripAddressDecoration(port.address); + if (isWildcardAddress(cleaned)) { + const isIPv6 = port.protocol === 'tcp6' || normalizeEndpointHost(cleaned) === '::'; + return isIPv6 ? '::1' : DEFAULT_QUICK_FORWARD_BIND_ADDRESS; + } + return cleaned; +} + +export function isValidPortNumber(value: number): boolean { + return Number.isInteger(value) && value >= 1 && value <= 65535; +} + +export function normalizeQuickForwardBindAddress(value: string): string { + const trimmed = stripAddressDecoration(value); + return trimmed || DEFAULT_QUICK_FORWARD_BIND_ADDRESS; +} + +export function isValidQuickForwardBindAddress(value: string): boolean { + const trimmed = value.trim(); + if (!trimmed) return true; // Empty falls back to 127.0.0.1 + if (/\s/.test(trimmed)) return false; + // Reject control characters and obvious path/URL separators. + if (/[/?#@\\]/.test(trimmed)) return false; + return true; +} + +function bindAddressesOverlap(a: string, b: string): boolean { + const normA = normalizeEndpointHost(a || DEFAULT_QUICK_FORWARD_BIND_ADDRESS); + const normB = normalizeEndpointHost(b || DEFAULT_QUICK_FORWARD_BIND_ADDRESS); + if (isWildcardAddress(normA) || isWildcardAddress(normB)) return true; + if (normA === normB) return true; + if ( + (normA === 'localhost' && normB === '127.0.0.1') + || (normA === '127.0.0.1' && normB === 'localhost') + ) { + return true; + } + return false; +} + +/** + * Find an active or connecting local/dynamic rule whose local bind + port + * conflicts with the requested local endpoint. + */ +export function findLocalPortConflict( + rules: readonly PortForwardingRule[], + bindAddress: string, + localPort: number, + excludeRuleId?: string, +): PortForwardingRule | undefined { + return rules.find((rule) => { + if (excludeRuleId && rule.id === excludeRuleId) return false; + if (!ACTIVE_STATUSES.has(rule.status)) return false; + if (rule.type !== 'local' && rule.type !== 'dynamic') return false; + if (rule.localPort !== localPort) return false; + return bindAddressesOverlap(rule.bindAddress, bindAddress); + }); +} + +export interface ListeningPortForwardMatches { + activeRules: PortForwardingRule[]; + primaryActiveRule: PortForwardingRule | undefined; + reusableInactiveRule: PortForwardingRule | undefined; +} + +function remoteHostMatchesPort(ruleRemoteHost: string | undefined, port: ListeningPortInfo): boolean { + const normRuleHost = normalizeEndpointHost(ruleRemoteHost); + if (!normRuleHost) return false; + const targetHost = normalizeEndpointHost(resolveForwardRemoteHost(port)); + if (normRuleHost === targetHost) return true; + // Treat 127.0.0.1 and localhost as equivalent for IPv4 loopback targets + // without crossing IPv4/IPv6 address families. + if ( + (targetHost === '127.0.0.1' && normRuleHost === 'localhost') + || (targetHost === 'localhost' && normRuleHost === '127.0.0.1') + ) { + return true; + } + return false; +} + +/** + * Match existing local port-forwarding rules for the current host against a + * remote listening port row. + */ +export function matchListeningPortForwardRules( + port: ListeningPortInfo, + hostId: string | undefined, + rules: readonly PortForwardingRule[], +): ListeningPortForwardMatches { + if (!hostId || !isForwardableListeningPort(port)) { + return { + activeRules: [], + primaryActiveRule: undefined, + reusableInactiveRule: undefined, + }; + } + + const matching = rules.filter( + (rule) => + rule.type === 'local' + && rule.hostId === hostId + && rule.remotePort === port.port + && remoteHostMatchesPort(rule.remoteHost, port), + ); + + const activeRules = matching + .filter((rule) => ACTIVE_STATUSES.has(rule.status)) + .sort((a, b) => { + if (a.status === b.status) return a.localPort - b.localPort; + return a.status === 'active' ? -1 : 1; + }); + + const reusableInactiveRule = matching.find((rule) => !ACTIVE_STATUSES.has(rule.status)); + + return { + activeRules, + primaryActiveRule: activeRules[0], + reusableInactiveRule, + }; +} + +/** + * Reuse an existing inactive/error rule only when every connection parameter + * matches so we never silently mutate a user's saved rule. + */ +export function findExactReusableForwardRule( + rules: readonly PortForwardingRule[], + params: { + hostId: string; + remoteHost: string; + remotePort: number; + localPort: number; + bindAddress: string; + }, +): PortForwardingRule | undefined { + const normRemote = normalizeEndpointHost(params.remoteHost); + const normBind = normalizeEndpointHost(params.bindAddress); + return rules.find( + (rule) => + rule.type === 'local' + && !ACTIVE_STATUSES.has(rule.status) + && rule.hostId === params.hostId + && rule.remotePort === params.remotePort + && rule.localPort === params.localPort + && normalizeEndpointHost(rule.remoteHost) === normRemote + && normalizeEndpointHost(rule.bindAddress) === normBind, + ); +} + +/** + * Pick a sensible default local port for quick forwarding: + * - Avoid privileged ports (< 1024) by default (80 -> 8080, 443 -> 8443, others -> +10000). + * - Avoid ports already used by existing local/dynamic rules. + */ +export function suggestQuickForwardLocalPort( + remotePort: number, + existingRules: readonly PortForwardingRule[], +): number { + const usedLocalPorts = new Set(); + for (const rule of existingRules) { + if (rule.type === 'local' || rule.type === 'dynamic') { + usedLocalPorts.add(rule.localPort); + } + } + + let candidate: number; + if (remotePort === 80) { + candidate = usedLocalPorts.has(8080) ? 10080 : 8080; + } else if (remotePort === 443) { + candidate = usedLocalPorts.has(8443) ? 10443 : 8443; + } else if (remotePort < 1024) { + candidate = remotePort + 10000; + } else if (remotePort <= 65535) { + candidate = remotePort; + } else { + candidate = 8080; + } + + const start = candidate; + while (usedLocalPorts.has(candidate)) { + candidate = candidate >= 65535 ? 1024 : candidate + 1; + if (candidate === start) break; + } + + return candidate; +} + +export function buildQuickForwardRuleLabel( + hostLabel: string | undefined, + port: ListeningPortInfo, + localPort: number, + remoteHost: string, +): string { + const hostPrefix = hostLabel?.trim(); + const processName = port.processName?.trim(); + if (hostPrefix && processName) { + return `${hostPrefix} · ${processName} (:${port.port})`; + } + if (hostPrefix) { + return `${hostPrefix} :${port.port}`; + } + if (processName) { + return `${processName} (:${port.port})`; + } + return `Local:${localPort} -> ${formatHostPort(remoteHost, port.port)}`; +} + +export type QuickForwardValidationError = + | { code: 'invalidPort' } + | { code: 'invalidBindAddress' } + | { code: 'localPortInUse'; conflictRule: PortForwardingRule }; + +export function validateQuickForwardInput(params: { + localPortText: string; + bindAddressText: string; + rules: readonly PortForwardingRule[]; + excludeRuleId?: string; +}): + | { ok: true; localPort: number; bindAddress: string } + | { ok: false; error: QuickForwardValidationError } { + const trimmedPort = params.localPortText.trim(); + if (!/^\d+$/.test(trimmedPort)) { + return { ok: false, error: { code: 'invalidPort' } }; + } + const localPort = Number(trimmedPort); + if (!isValidPortNumber(localPort)) { + return { ok: false, error: { code: 'invalidPort' } }; + } + if (!isValidQuickForwardBindAddress(params.bindAddressText)) { + return { ok: false, error: { code: 'invalidBindAddress' } }; + } + const bindAddress = normalizeQuickForwardBindAddress(params.bindAddressText); + const conflictRule = findLocalPortConflict( + params.rules, + bindAddress, + localPort, + params.excludeRuleId, + ); + if (conflictRule) { + return { ok: false, error: { code: 'localPortInUse', conflictRule } }; + } + return { ok: true, localPort, bindAddress }; +} From 07f721ba2a2b5670f4c631ba5ae0b9db6cef9d76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:42:04 +0800 Subject: [PATCH 24/24] perf(plugins): accelerate plugin startup, view updates, and image loading pipeline (#4462) --- application/state/useHostDrawnPluginView.ts | 13 +- .../plugins/LazyPluginHostDrawnPage.tsx | 14 +- .../plugins/PluginRemoteSurface.test.tsx | 57 ++++++ components/plugins/PluginRemoteSurface.tsx | 28 ++- components/plugins/PluginVaultPages.tsx | 4 +- domain/pluginViewStylePolicy.cjs | 29 ++- electron/plugins/contributionIconService.cjs | 83 ++++++-- electron/plugins/hostService.cjs | 29 ++- electron/plugins/packageStore.cjs | 178 +++++++++++++----- electron/plugins/packageStore.test.cjs | 36 ++++ electron/plugins/pluginProtocol.cjs | 34 +++- electron/plugins/viewResourceService.cjs | 114 +++++++++-- electron/plugins/viewResourceService.test.cjs | 63 +++++++ packages/plugin-cli/src/archive.ts | 7 +- 14 files changed, 584 insertions(+), 105 deletions(-) diff --git a/application/state/useHostDrawnPluginView.ts b/application/state/useHostDrawnPluginView.ts index 6f7b0f7ca..a3d37c782 100644 --- a/application/state/useHostDrawnPluginView.ts +++ b/application/state/useHostDrawnPluginView.ts @@ -11,7 +11,11 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context, }) { const contextKey = JSON.stringify(context); const key = JSON.stringify([viewId, version, slot, contextKey]); - const [state, setState] = useState<{ key: string; snapshot: PluginViewSnapshot }>({ key: '', snapshot: initial() }); + const [state, setState] = useState<{ + key: string; + snapshot: PluginViewSnapshot; + image?: (path: string) => Promise; + }>({ key: '', snapshot: initial() }); const [hidden, setHidden] = useState(false); const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable; const sessionRef = useRef<{ key: string; image(path: string): Promise; send(event: HostDrawnViewEvent): void } | null>(null); @@ -22,17 +26,18 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context, const scopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` }); try { const session = pluginViewSessions.acquire(JSON.stringify([scopeId, key]), bridge, { viewId, scopeId, context: JSON.parse(contextKey) }); - const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot }); if (snapshot.error) unavailableRef.current(); }; - const stop = session.subscribe(update); update(); setHidden(false); sessionRef.current = { key, send: session.send, image: session.image }; + const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot, image: session.image }); if (snapshot.error) unavailableRef.current(); }; + const stop = session.subscribe(update); update(); setHidden(false); const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); }); return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); }; } catch { unavailableRef.current(); } }, [active, contextKey, key, slot, subscribeHidden, viewId]); - const loadImage = useCallback((path: string) => { + const fallbackLoadImage = useCallback((path: string) => { const session = sessionRef.current; return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable')); }, [active, key]); + const loadImage = active && state.key === key && state.image ? state.image : fallbackLoadImage; const sendEvent = useCallback((event: HostDrawnViewEvent) => { const session = sessionRef.current; if (active && session?.key === key) session.send(event); }, [active, key]); diff --git a/components/plugins/LazyPluginHostDrawnPage.tsx b/components/plugins/LazyPluginHostDrawnPage.tsx index d9dbf8c7e..28ff5d970 100644 --- a/components/plugins/LazyPluginHostDrawnPage.tsx +++ b/components/plugins/LazyPluginHostDrawnPage.tsx @@ -1,9 +1,17 @@ import React, { Suspense } from 'react'; import type { PluginHostDrawnPageProps } from './PluginHostDrawnPage'; -const PluginHostDrawnPageImpl = React.lazy(() => - import('./PluginHostDrawnPage').then((module) => ({ default: module.PluginHostDrawnPage })), -); +let preloadPromise: Promise | null = null; +const loadPluginHostDrawnPage = () => { + preloadPromise ??= import('./PluginHostDrawnPage').then((module) => ({ default: module.PluginHostDrawnPage })); + return preloadPromise as Promise<{ default: typeof import('./PluginHostDrawnPage').PluginHostDrawnPage }>; +}; + +export function preloadPluginHostDrawnPage(): void { + void loadPluginHostDrawnPage().catch(() => { preloadPromise = null; }); +} + +const PluginHostDrawnPageImpl = React.lazy(loadPluginHostDrawnPage); /** * Lazy boundary for host-drawn plugin views so css-tree, mdn-data, and diff --git a/components/plugins/PluginRemoteSurface.test.tsx b/components/plugins/PluginRemoteSurface.test.tsx index 1ee059b1a..9634234bc 100644 --- a/components/plugins/PluginRemoteSurface.test.tsx +++ b/components/plugins/PluginRemoteSurface.test.tsx @@ -647,3 +647,60 @@ test('PluginDataGrid FK jump, hiddenColumns, keyboard shortcuts, and PluginErCan Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); } }); + +test('RemoteImageElement renders a transparent placeholder while loading and never shows a broken img', async () => { + const dom = new JSDOM('
', { url: 'http://localhost', pretendToBeVisual: true }); + const saved = new Map(); + for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', '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 }); + + 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 } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { PluginRemoteSurface } = await import('./PluginRemoteSurface'); + + let resolveImage!: (url: string) => void; + const loadImage = () => new Promise((resolve) => { resolveImage = resolve; }); + const root = createRoot(document.getElementById('root')!); + try { + await act(async () => { + root.render( + {}} + />, + ); + }); + const img = shadows[0]?.querySelector('img'); + assert.ok(img, 'img element rendered'); + assert.equal(img!.getAttribute('data-plugin-image-loading'), 'true'); + assert.match(img!.getAttribute('src') ?? '', /^data:image\/gif;base64,/); + assert.equal(img!.getAttribute('alt'), '', 'alt text hidden while placeholder loads'); + + const resolvedUrl = 'data:image/png;base64,iVBORw0KGgo='; + await act(async () => { + resolveImage(resolvedUrl); + await Promise.resolve(); + }); + assert.equal(img!.getAttribute('data-plugin-image-loading'), null); + assert.equal(img!.getAttribute('src'), resolvedUrl); + assert.equal(img!.getAttribute('alt'), 'PostgreSQL'); + } 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'); + } +}); diff --git a/components/plugins/PluginRemoteSurface.tsx b/components/plugins/PluginRemoteSurface.tsx index 3b217b833..f3aa945fd 100644 --- a/components/plugins/PluginRemoteSurface.tsx +++ b/components/plugins/PluginRemoteSurface.tsx @@ -181,7 +181,8 @@ const RemoteSlottedWidgetElement = memo(function RemoteSlottedWidgetElement({ no }); const resolvedImageCache = new WeakMap<(path: string) => Promise, Map>(); -const IMAGE_RETRY_DELAYS_MS = [200, 600] as const; +const IMAGE_RETRY_DELAYS_MS = [150, 400, 1000] as const; +const TRANSPARENT_PLACEHOLDER_SRC = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; function getCachedImageUrl(loader: ((path: string) => Promise) | undefined, imagePath: string | undefined): string | undefined { if (!loader || !imagePath) return undefined; @@ -236,7 +237,15 @@ const RemoteImageElement = memo(function RemoteImageElement({ node }: { node: Re }; }, [imagePath, loadImage]); const props = buildRemoteElementProps(node); - props.src = imageUrl; + if (imageUrl) { + props.src = imageUrl; + } else { + // Use a transparent 1x1 placeholder while loading so Chromium never flashes + // a broken-image icon or raw alt text before the rasterized asset arrives. + props.src = TRANSPARENT_PLACEHOLDER_SRC; + props.alt = ''; + props['data-plugin-image-loading'] = 'true'; + } return React.createElement('img', props); }); @@ -329,17 +338,22 @@ function readSelectionRange( /** 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; onEvent(event: PluginSurfaceEvent): void }) { - const checked = useMemo(() => { + const checkedTree = useMemo(() => { try { validatePluginRemoteTree(tree); - return { tree: tree as { children: RemoteNode[] }, css: validatePluginStylesheet(css) }; + return tree as { children: RemoteNode[] }; } catch { return null; } - }, [tree, css]); - if (!checked) return

Unable to display plugin view.

; + }, [tree]); + const checkedCss = useMemo(() => { + try { + return validatePluginStylesheet(css); + } catch { return null; } + }, [css]); + if (!checkedTree || checkedCss === null) return

Unable to display plugin view.

; return ( Unable to display plugin view.

}> - +
); diff --git a/components/plugins/PluginVaultPages.tsx b/components/plugins/PluginVaultPages.tsx index 1b1061ba8..0344667db 100644 --- a/components/plugins/PluginVaultPages.tsx +++ b/components/plugins/PluginVaultPages.tsx @@ -3,7 +3,7 @@ import { useI18n } from '../../application/i18n/I18nProvider'; import type { usePluginVaultPages } from '../../application/state/usePluginVaultPages'; import { PluginContributionIcon } from './PluginContributionIcon'; import { Button } from '../ui/button'; -import { LazyPluginHostDrawnPage } from './LazyPluginHostDrawnPage'; +import { LazyPluginHostDrawnPage, preloadPluginHostDrawnPage } from './LazyPluginHostDrawnPage'; type VaultPages = ReturnType; const subscribeHidden = (hide: () => void) => activeTabStore.subscribeSync((id) => { if (id !== 'vault') hide(); }); @@ -17,6 +17,8 @@ export function PluginVaultNavigation({ model, collapsed }: { model: VaultPages; title={`${page.title} — ${page.pluginName}`} aria-label={`${page.title} — ${page.pluginName}`} aria-current={model.selected?.key === page.key ? 'page' : undefined} + onMouseEnter={preloadPluginHostDrawnPage} + onFocus={preloadPluginHostDrawnPage} onClick={() => model.select(page.key)}> {!collapsed && {page.title}} diff --git a/domain/pluginViewStylePolicy.cjs b/domain/pluginViewStylePolicy.cjs index 8328e287c..6e631d4de 100644 --- a/domain/pluginViewStylePolicy.cjs +++ b/domain/pluginViewStylePolicy.cjs @@ -27,10 +27,35 @@ const HOST_TOKENS = new Set([ "--radius", "--font-sans", "--font-mono", ]); const decode = (name) => cssTree.ident.decode(name).toLowerCase(); +const MAX_STYLESHEET_CACHE_ENTRIES = 32; +const MAX_INLINE_STYLE_CACHE_ENTRIES = 256; +const validatedStylesheetCache = new Map(); +const validatedInlineStyleCache = new Map(); + +function getCachedCss(cache, source) { + if (!cache.has(source)) return undefined; + const value = cache.get(source); + cache.delete(source); + cache.set(source, value); + return value; +} + +function setCachedCss(cache, limit, source, value) { + if (cache.has(source)) cache.delete(source); + while (cache.size >= limit) { + const oldest = cache.keys().next().value; + if (oldest === undefined) break; + cache.delete(oldest); + } + cache.set(source, value); +} /** Returns canonical CSS only if every construct is safe for a clipped shadow root. */ function validatePluginCss(source, context = "stylesheet") { if (typeof source !== "string" || source.length > MAX_CSS_LENGTH || source.includes("\0")) throw new TypeError("Invalid plugin stylesheet"); + const cache = context === "stylesheet" ? validatedStylesheetCache : validatedInlineStyleCache; + const cached = getCachedCss(cache, source); + if (cached !== undefined) return cached; let ast; try { ast = cssTree.parse(source, { context, parseCustomProperty: true, positions: false }); } catch { throw new TypeError("Invalid plugin stylesheet"); } @@ -60,7 +85,9 @@ function validatePluginCss(source, context = "stylesheet") { } } }); - return cssTree.generate(ast); + const canonical = cssTree.generate(ast); + setCachedCss(cache, context === "stylesheet" ? MAX_STYLESHEET_CACHE_ENTRIES : MAX_INLINE_STYLE_CACHE_ENTRIES, source, canonical); + return canonical; } function validatePluginStylesheet(source) { return validatePluginCss(source); } diff --git a/electron/plugins/contributionIconService.cjs b/electron/plugins/contributionIconService.cjs index b29847257..82059238c 100644 --- a/electron/plugins/contributionIconService.cjs +++ b/electron/plugins/contributionIconService.cjs @@ -1,10 +1,11 @@ "use strict"; const path = require("node:path"); -const { createHash } = require("node:crypto"); +const fs = require("node:fs/promises"); +const { createHash, randomUUID } = require("node:crypto"); const { readContainedFile } = require("./pluginProtocol.cjs"); -const { createIsolatedContributionIconRasterizer } = require("./contributionIconRasterizer.cjs"); +const { createPooledContributionIconRasterizer } = require("./contributionIconRasterizer.cjs"); const MAX_ICON_SOURCE_BYTES = 512 * 1024; const MAX_ICON_PNG_BYTES = 512 * 1024; @@ -182,17 +183,64 @@ class PluginContributionIconService { constructor(options) { this.database = options.database; this.packageStore = options.packageStore; - const rasterizeIcon = options.rasterizeIcon ?? createIsolatedContributionIconRasterizer({ - BrowserWindow: options.BrowserWindow, - }); - this.rasterizeIcon = createBoundedIconRasterizer(rasterizeIcon, { + this.ownsRasterizer = typeof options.rasterizeIcon !== "function"; + this.pooledRasterizer = this.ownsRasterizer + ? createPooledContributionIconRasterizer({ BrowserWindow: options.BrowserWindow }) + : options.rasterizeIcon; + this.rasterizeIcon = createBoundedIconRasterizer(this.pooledRasterizer, { maxConcurrent: options.maxConcurrentRasterizations, maxQueued: options.maxQueuedRasterizations, }); + this.cacheDir = typeof options.cacheDir === "string" && options.cacheDir.length > 0 ? options.cacheDir : null; + this.cacheDirReady = null; this.cache = new Map(); this.pending = new Map(); } + dispose() { + if (this.ownsRasterizer) this.pooledRasterizer?.dispose?.(); + this.cache.clear(); + this.pending.clear(); + } + + #diskCachePath(plugin, packagePath, brand) { + if (!this.cacheDir || !plugin?.id || !plugin?.activeVersion || !plugin?.archiveSha256) return null; + const digest = createHash("sha256") + .update(JSON.stringify(["contrib-v1", brand ? "brand" : "contrib", plugin.id, plugin.activeVersion, plugin.archiveSha256, packagePath, MAX_ICON_EDGE])) + .digest("hex"); + return path.join(this.cacheDir, `${digest}.png`); + } + + async #readDiskCachedIcon(plugin, packagePath, brand) { + const filePath = this.#diskCachePath(plugin, packagePath, brand); + if (!filePath) return null; + try { + const png = await fs.readFile(filePath); + if (!png.length || png.length > MAX_ICON_PNG_BYTES) return null; + inspectContributionIconSource(png, ".png", MAX_ICON_EDGE); + return `data:image/png;base64,${png.toString("base64")}`; + } catch { + return null; + } + } + + async #writeDiskCachedIcon(plugin, packagePath, brand, png) { + const filePath = this.#diskCachePath(plugin, packagePath, brand); + if (!filePath) return; + try { + this.cacheDirReady ??= fs.mkdir(this.cacheDir, { recursive: true, mode: 0o700 }); + await this.cacheDirReady; + const tempPath = path.join(this.cacheDir, `.tmp-${randomUUID()}.png`); + try { + await fs.writeFile(tempPath, png, { mode: 0o600 }); + await fs.rename(tempPath, filePath); + } catch (error) { + await fs.unlink(tempPath).catch(() => {}); + throw error; + } + } catch { /* best-effort disk cache */ } + } + async resolve(payload) { const pluginId = typeof payload?.pluginId === "string" && payload.pluginId.length <= 256 ? payload.pluginId @@ -245,10 +293,11 @@ class PluginContributionIconService { } async #resolveUncached({ pluginId, plugin, icon, cacheKey }) { - const packageRoot = await this.packageStore.preparePackageRoot(plugin); + const useSingleFileVerify = typeof this.packageStore.readVerifiedPackageFile === "function"; + const packageRoot = useSingleFileVerify ? null : await this.packageStore.preparePackageRoot(plugin); const result = Object.freeze({ - light: await this.#readIcon(packageRoot, icon.light), - ...(icon.dark ? { dark: await this.#readIcon(packageRoot, icon.dark) } : {}), + light: await this.#readIcon(plugin, packageRoot, icon.light), + ...(icon.dark ? { dark: await this.#readIcon(plugin, packageRoot, icon.dark) } : {}), }); const current = this.database.getActivePlugin(pluginId); if (!current?.enabled || current.runtime?.quarantinedAt != null @@ -274,9 +323,10 @@ class PluginContributionIconService { if (this.cache.has(key)) return this.cache.get(key); if (this.pending.has(key)) return this.pending.get(key); const pending = (async () => { - const root = await this.packageStore.preparePackageRoot(plugin); - const result = { light: await this.#readIcon(root, icon.light, true), - ...(icon.dark ? { dark: await this.#readIcon(root, icon.dark, true) } : {}) }; + const useSingleFileVerify = typeof this.packageStore.readVerifiedPackageFile === "function"; + const root = useSingleFileVerify ? null : await this.packageStore.preparePackageRoot(plugin); + const result = { light: await this.#readIcon(plugin, root, icon.light, true), + ...(icon.dark ? { dark: await this.#readIcon(plugin, root, icon.dark, true) } : {}) }; const current = this.database.getActivePlugin(pluginId); if (!current || current.runtime?.quarantinedAt != null || identity !== JSON.stringify([current.activeVersion, current.archiveSha256, current.manifest?.icon])) { throw new Error("Plugin brand icon ownership changed while loading"); @@ -289,9 +339,13 @@ class PluginContributionIconService { return pending; } - async #readIcon(packageRoot, packagePath, brand = false) { + async #readIcon(plugin, packageRoot, packagePath, brand = false) { + const diskHit = await this.#readDiskCachedIcon(plugin, packagePath, brand); + if (diskHit) return diskHit; const segments = packagePath.split("/"); - const file = await readContainedFile(packageRoot, segments); + const file = typeof this.packageStore.readVerifiedPackageFile === "function" + ? await this.packageStore.readVerifiedPackageFile(plugin, segments, MAX_ICON_SOURCE_BYTES) + : await readContainedFile(packageRoot, segments); if (file.body.byteLength > MAX_ICON_SOURCE_BYTES) throw new Error("Plugin contribution icon is too large"); const extension = path.extname(file.filePath).toLowerCase(); const inspected = brand @@ -304,6 +358,7 @@ class PluginContributionIconService { }); if (!png.length || png.length > MAX_ICON_PNG_BYTES) throw new Error("Plugin contribution icon output is too large"); inspectContributionIconSource(png, ".png", MAX_ICON_EDGE); + void this.#writeDiskCachedIcon(plugin, packagePath, brand, png); return `data:image/png;base64,${png.toString("base64")}`; } } diff --git a/electron/plugins/hostService.cjs b/electron/plugins/hostService.cjs index 96a7d29f7..0426ff6c8 100644 --- a/electron/plugins/hostService.cjs +++ b/electron/plugins/hostService.cjs @@ -17,6 +17,7 @@ const { PluginCredentialCatalog } = require("./credentialCatalog.cjs"); const { PluginContributionService } = require("./contributionService.cjs"); const { PluginViewResources } = require("./viewResourceService.cjs"); const { HostDrawnViewHost } = require("./hostDrawnViewHost.cjs"); +const { createPooledContributionIconRasterizer } = require("./contributionIconRasterizer.cjs"); const { PluginContributionIconService } = require("./contributionIconService.cjs"); const { PluginFilesystemBroker } = require("./filesystemBroker.cjs"); const { createDefaultPluginHostRpcRegistry } = require("./hostRpcRegistry.cjs"); @@ -126,11 +127,16 @@ function createPluginHostService(options) { apiVersion: PLUGIN_API_VERSION, supportedFeatures, }); + const imageCacheDir = path.join(paths.root, "image-cache"); + const sharedIconRasterizer = typeof options.rasterizeContributionIcon === "function" + ? null + : createPooledContributionIconRasterizer(options.electron); const contributionIconService = new PluginContributionIconService({ database, packageStore, BrowserWindow: options.electron.BrowserWindow, - rasterizeIcon: options.rasterizeContributionIcon, + rasterizeIcon: options.rasterizeContributionIcon ?? sharedIconRasterizer, + cacheDir: imageCacheDir, }); const moduleResources = options.moduleResources ? normalizePluginModuleResources(options.moduleResources) @@ -171,8 +177,8 @@ function createPluginHostService(options) { const filesystemBroker = new PluginFilesystemBroker({ quotaManager, openDirectoryHandle: options.openPluginDirectoryHandle, - protectedDirectories: [paths.logs, path.join(paths.root, "agent-chats")], - protectedReadDirectories: [path.join(paths.root, "agent-chats")], + protectedDirectories: [paths.logs, path.join(paths.root, "agent-chats"), imageCacheDir], + protectedReadDirectories: [path.join(paths.root, "agent-chats"), imageCacheDir], protectedFiles: [logService.preferencesPath, `${logService.preferencesPath}.tmp`], }); const networkBroker = new PluginNetworkBroker({ @@ -493,7 +499,20 @@ function createPluginHostService(options) { quotaManager.setViolationHandler((identity, error) => ( runtimeSupervisor.enforcePolicyViolation(identity, error) )); - const hostDrawnViewHost = options.electron.ipcMain ? new HostDrawnViewHost({ electron: options.electron, contributionService, resources: new PluginViewResources({ electron: options.electron, packageStore }), isLocked: options.isAppLocked, subscribeLock: options.subscribeAppLock }) : null; + const hostDrawnViewHost = options.electron.ipcMain + ? new HostDrawnViewHost({ + electron: options.electron, + contributionService, + resources: new PluginViewResources({ + electron: options.electron, + packageStore, + rasterizeIcon: options.rasterizeContributionIcon ?? sharedIconRasterizer, + cacheDir: imageCacheDir, + }), + isLocked: options.isAppLocked, + subscribeLock: options.subscribeAppLock, + }) + : null; const themeService = new PluginThemeService({database,packageStore,contributionService}); manager = new PluginManager({ secretStore, @@ -513,6 +532,8 @@ function createPluginHostService(options) { extensionProviderService.shutdown(); credentialResolver.shutdown?.(); await hostDrawnViewHost?.shutdown(); + contributionIconService.dispose?.(); + sharedIconRasterizer?.dispose?.(); await companionSupervisor.shutdown(); leaseStore.shutdown(); permissionDecisionHost.shutdown(); diff --git a/electron/plugins/packageStore.cjs b/electron/plugins/packageStore.cjs index c94a72f92..0b9cb1bb1 100644 --- a/electron/plugins/packageStore.cjs +++ b/electron/plugins/packageStore.cjs @@ -25,6 +25,7 @@ const { const { assertBrowserOnlyPlugin } = require("../../domain/pluginRuntimePolicy.cjs"); const { assertCatalogManifest } = require("./catalogPolicy.cjs"); +const { readContainedFile } = require("./pluginProtocol.cjs"); const INSTALL_METADATA_FILE = "install.json"; const ARCHIVE_SNAPSHOT_FILE = "package.ncpkg"; @@ -66,7 +67,8 @@ async function syncDirectoryTree(directory) { await syncDirectory(directory); } -async function copyImmutableArchive(sourcePath, destinationPath, maxBytes) { +async function copyImmutableArchive(sourcePath, destinationPath, maxBytes, options = {}) { + const syncDestination = options.sync !== false; const sourcePathStats = await lstat(sourcePath); if (!sourcePathStats.isFile() || sourcePathStats.isSymbolicLink()) { throw new Error("Plugin package source must be a regular non-symbolic file"); @@ -104,7 +106,7 @@ async function copyImmutableArchive(sourcePath, destinationPath, maxBytes) { ) { throw new Error("Plugin package source changed while it was staged"); } - await destination.sync(); + if (syncDestination) await destination.sync(); return { bytes: position, sha256: sha256.digest("hex") }; } finally { await destination?.close(); @@ -151,6 +153,8 @@ class PackageStore { this.logger = options.logger ?? console; this.syncDirectory = options.syncDirectory ?? syncDirectory; this.verifiedArchives = new Map(); + this.pendingArchives = new Map(); + this.pendingPreparations = new Map(); } async initialize() { @@ -328,6 +332,7 @@ class PackageStore { archiveSha256: snapshot.sha256, contentSha256: validation.contentSha256, manifest, + ...(validation.fileHashes ? { fileHashes: validation.fileHashes } : {}), })); return this.database.getActivePlugin(pluginId); } finally { @@ -387,6 +392,7 @@ class PackageStore { } await rm(stagedPath, { recursive: true, force: true }); } + const verifiedInRecover = new Set(); const pluginDirectories = await readdir(this.paths.packages, { withFileTypes: true }); for (const pluginEntry of pluginDirectories) { if (!pluginEntry.isDirectory()) continue; @@ -417,6 +423,7 @@ class PackageStore { path.join(versionDirectory, PACKAGE_DIRECTORY), ), }); + verifiedInRecover.add(`${metadata.pluginId}\0${metadata.version}\0${metadata.archiveSha256}`); if (!committedVersion) { const packageDirectory = path.join(versionDirectory, PACKAGE_DIRECTORY); this.database.installVersion({ @@ -453,6 +460,14 @@ class PackageStore { } for (const plugin of this.database.listPlugins()) { if (!plugin.packageRelativePath) continue; + if (verifiedInRecover.has(`${plugin.id}\0${plugin.activeVersion}\0${plugin.archiveSha256}`)) { + try { + this.resolvePackageRoot(plugin); + continue; + } catch { + // Fall through to full preparePackageRoot to record failure state. + } + } try { await this.preparePackageRoot(plugin); } catch (error) { @@ -494,57 +509,73 @@ class PackageStore { const key = this.#versionKey(identity.pluginId, identity.version); const cached = this.verifiedArchives.get(key); if (options.refresh !== true && cached?.archiveSha256 === identity.archiveSha256) return cached; - - const pluginCli = await loadPluginCli(); - const versionDirectory = resolveInstalledVersionDirectory( - this.paths, - identity.pluginId, - identity.version, - ); - const metadata = validateInstallMetadata(JSON.parse(await readFile( - path.join(versionDirectory, INSTALL_METADATA_FILE), - "utf8", - ))); - if ( - metadata.pluginId !== identity.pluginId - || metadata.version !== identity.version - || metadata.archiveSha256 !== identity.archiveSha256 - ) { - throw new Error("Plugin install metadata does not match its database record"); + const inflightKey = `${key}\0${identity.archiveSha256}`; + if (options.refresh !== true && this.pendingArchives.has(inflightKey)) { + return this.pendingArchives.get(inflightKey); } - const verificationDirectory = path.join(this.paths.staging, `verify-${randomUUID()}`); - const verificationSnapshot = path.join(verificationDirectory, ARCHIVE_SNAPSHOT_FILE); - await mkdir(verificationDirectory, { recursive: false, mode: 0o700 }); - try { - const snapshot = await copyImmutableArchive( - path.join(versionDirectory, ARCHIVE_SNAPSHOT_FILE), - verificationSnapshot, - pluginCli.PACKAGE_LIMITS.archiveBytes, + const task = (async () => { + const pluginCli = await loadPluginCli(); + const versionDirectory = resolveInstalledVersionDirectory( + this.paths, + identity.pluginId, + identity.version, ); - if (snapshot.sha256 !== identity.archiveSha256) { - throw new Error("Retained plugin archive hash does not match its database record"); - } - const validation = await pluginCli.validatePluginPackage(verificationSnapshot); - if (validation.contentSha256 !== metadata.contentSha256) { - throw new Error("Retained plugin archive content does not match install metadata"); - } + const metadata = validateInstallMetadata(JSON.parse(await readFile( + path.join(versionDirectory, INSTALL_METADATA_FILE), + "utf8", + ))); if ( - validation.manifest.id !== identity.pluginId - || validation.manifest.version !== identity.version + metadata.pluginId !== identity.pluginId + || metadata.version !== identity.version + || metadata.archiveSha256 !== identity.archiveSha256 ) { - throw new Error("Retained plugin archive identity does not match its database record"); + throw new Error("Plugin install metadata does not match its database record"); } - const verified = Object.freeze({ - archiveSha256: identity.archiveSha256, - contentSha256: validation.contentSha256, - manifest: validation.manifest, - }); - this.verifiedArchives.set(key, verified); - return verified; - } finally { - await rm(verificationDirectory, { recursive: true, force: true }); + + const verificationDirectory = path.join(this.paths.staging, `verify-${randomUUID()}`); + const verificationSnapshot = path.join(verificationDirectory, ARCHIVE_SNAPSHOT_FILE); + await mkdir(verificationDirectory, { recursive: false, mode: 0o700 }); + try { + const snapshot = await copyImmutableArchive( + path.join(versionDirectory, ARCHIVE_SNAPSHOT_FILE), + verificationSnapshot, + pluginCli.PACKAGE_LIMITS.archiveBytes, + { sync: false }, + ); + if (snapshot.sha256 !== identity.archiveSha256) { + throw new Error("Retained plugin archive hash does not match its database record"); + } + const validation = await pluginCli.validatePluginPackage(verificationSnapshot); + if (validation.contentSha256 !== metadata.contentSha256) { + throw new Error("Retained plugin archive content does not match install metadata"); + } + if ( + validation.manifest.id !== identity.pluginId + || validation.manifest.version !== identity.version + ) { + throw new Error("Retained plugin archive identity does not match its database record"); + } + const verified = Object.freeze({ + archiveSha256: identity.archiveSha256, + contentSha256: validation.contentSha256, + manifest: validation.manifest, + ...(validation.fileHashes ? { fileHashes: validation.fileHashes } : {}), + }); + this.verifiedArchives.set(key, verified); + return verified; + } finally { + await rm(verificationDirectory, { recursive: true, force: true }); + } + })(); + + if (options.refresh !== true) { + this.pendingArchives.set(inflightKey, task); + task.finally(() => { + if (this.pendingArchives.get(inflightKey) === task) this.pendingArchives.delete(inflightKey); + }).catch(() => {}); } + return task; } async verifyInstalledVersion(record, options = {}) { @@ -577,21 +608,64 @@ class PackageStore { } async preparePackageRoot(plugin) { - try { - await this.verifyInstalledVersion(plugin); - return this.resolvePackageRoot(plugin); - } catch (error) { + const identity = this.#recordIdentity(plugin); + const inflightKey = `${identity.pluginId}\0${identity.version}\0${identity.archiveSha256}`; + if (this.pendingPreparations.has(inflightKey)) { + return this.pendingPreparations.get(inflightKey); + } + const task = (async () => { + try { + await this.verifyInstalledVersion(plugin); + return this.resolvePackageRoot(plugin); + } catch (error) { + const active = this.database.getActivePlugin(identity.pluginId); + if (active?.activeVersion === identity.version) { + this.database.setEnabled(identity.pluginId, false); + this.database.setRuntimeState(identity.pluginId, "error", { + pluginVersion: identity.version, + error: `Installed package integrity check failed: ${error?.message ?? String(error)}`, + }); + } + throw error; + } + })(); + this.pendingPreparations.set(inflightKey, task); + task.finally(() => { + if (this.pendingPreparations.get(inflightKey) === task) { + this.pendingPreparations.delete(inflightKey); + } + }).catch(() => {}); + return task; + } + + /** + * Reads a single contained package file and cryptographically verifies its + * exact SHA-256 digest against the retained archive's verified file manifest. + * Avoids re-hashing every file in the package directory on concurrent asset loads. + */ + async readVerifiedPackageFile(plugin, segments, maxBytes = Infinity) { + const relativePath = segments.join("/"); + const expected = await this.#loadVerifiedArchive(plugin); + if (!expected.fileHashes || !Object.hasOwn(expected.fileHashes, relativePath)) { + const root = await this.preparePackageRoot(plugin); + return readContainedFile(root, segments, maxBytes); + } + const root = this.resolvePackageRoot(plugin); + const file = await readContainedFile(root, segments, maxBytes); + const actualSha256 = createHash("sha256").update(file.body).digest("hex"); + if (actualSha256 !== expected.fileHashes[relativePath]) { const identity = this.#recordIdentity(plugin); const active = this.database.getActivePlugin(identity.pluginId); if (active?.activeVersion === identity.version) { this.database.setEnabled(identity.pluginId, false); this.database.setRuntimeState(identity.pluginId, "error", { pluginVersion: identity.version, - error: `Installed package integrity check failed: ${error?.message ?? String(error)}`, + error: `Installed package integrity check failed: Installed plugin file does not match the retained package archive (${relativePath})`, }); } - throw error; + throw new Error("Installed plugin files do not match the retained package archive"); } + return file; } async clearUninstalledPrivateFiles(pluginId) { diff --git a/electron/plugins/packageStore.test.cjs b/electron/plugins/packageStore.test.cjs index 296d375f2..f4ce25860 100644 --- a/electron/plugins/packageStore.test.cjs +++ b/electron/plugins/packageStore.test.cjs @@ -456,3 +456,39 @@ test("normal release refuses advanced local imports and disables previously inst await assert.rejects(fixture.store.install(archive.archive), /browser-only packages/); await assert.rejects(fixture.store.assertCompatible(installed), /browser-only packages/); }); + +test("readVerifiedPackageFile verifies single files against retained archive hashes and rejects tampering", async (context) => { + const fixture = createStore(context); + await fixture.store.initialize(); + const pluginPackage = await createPackage(fixture.root); + const installed = await fixture.store.install(pluginPackage.archive, { enable: true }); + + // Coalesce concurrent preparePackageRoot calls into one verification pass. + let verifyCalls = 0; + const origVerify = fixture.store.verifyInstalledVersion.bind(fixture.store); + fixture.store.verifyInstalledVersion = async (...args) => { + verifyCalls += 1; + return origVerify(...args); + }; + const roots = await Promise.all([ + fixture.store.preparePackageRoot(installed), + fixture.store.preparePackageRoot(installed), + fixture.store.preparePackageRoot(installed), + ]); + assert.equal(verifyCalls, 1); + assert.equal(roots[0], roots[1]); + assert.equal(roots[1], roots[2]); + + // Single-file read verifies exact SHA-256 without running a full directory scan. + const file = await fixture.store.readVerifiedPackageFile(installed, ["dist", "index.js"]); + assert.equal(file.body.toString("utf8"), "export default {};\n"); + assert.equal(verifyCalls, 1); + + // Tampering with that file fails closed and disables the plugin. + await fs.promises.writeFile(path.join(roots[0], "dist", "index.js"), "export default { evil: true };\n"); + await assert.rejects( + fixture.store.readVerifiedPackageFile(installed, ["dist", "index.js"]), + /do not match the retained package archive/, + ); + assert.equal(fixture.database.getActivePlugin(installed.id).enabled, false); +}); diff --git a/electron/plugins/pluginProtocol.cjs b/electron/plugins/pluginProtocol.cjs index fd993c76e..a870a67cc 100644 --- a/electron/plugins/pluginProtocol.cjs +++ b/electron/plugins/pluginProtocol.cjs @@ -41,10 +41,12 @@ function decodeRequestPath(pathname) { return segments; } -async function readContainedFile(root, segments, maxBytes = Infinity) { +async function readContainedFile(root, segments, maxBytes = Infinity, realRootOverride = null) { const candidate = path.resolve(root, ...segments); if (!isPathInside(root, candidate)) throw new Error("Plugin resource escapes its root"); - const [realRoot, realCandidate] = await Promise.all([fs.realpath(root), fs.realpath(candidate)]); + const [realRoot, realCandidate] = realRootOverride + ? [realRootOverride, await fs.realpath(candidate)] + : await Promise.all([fs.realpath(root), fs.realpath(candidate)]); if (!isPathInside(realRoot, realCandidate)) throw new Error("Plugin resource follows a symlink outside its root"); const stats = await fs.lstat(realCandidate); if (!stats.isFile() || stats.isSymbolicLink()) throw new Error("Plugin resource is not a regular file"); @@ -54,15 +56,25 @@ async function readContainedFile(root, segments, maxBytes = Infinity) { return { body, filePath: realCandidate }; } -function htmlForRuntime(token, moduleResources) { +function escapeHtmlAttr(value) { + return String(value).replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); +} + +function htmlForRuntime(token, moduleResources, entryUrl) { const imports = Object.fromEntries(moduleResources.map((resource) => [ resource.specifier, `${PLUGIN_PROTOCOL_SCHEME}://${token}/__host/modules/${resource.route}/${resource.entry}`, ])); const runtime = `${PLUGIN_PROTOCOL_SCHEME}://${token}/__host/runtime/browserRuntime.mjs`; + const peer = `${PLUGIN_PROTOCOL_SCHEME}://${token}/__host/runtime/runtimePeer.mjs`; + const expectedPrefix = `${PLUGIN_PROTOCOL_SCHEME}://${token}/package/`; + const preloadEntry = typeof entryUrl === "string" && entryUrl.startsWith(expectedPrefix) + ? `` + : ""; return ` Netcatty plugin runtime -`; + +${preloadEntry}`; } class PluginProtocol { @@ -79,6 +91,15 @@ class PluginProtocol { this.moduleResourcesByRoute = new Map(this.moduleResources.map((resource) => [resource.route, resource])); this.registrations = new Map(); this.sessions = new WeakSet(); + this.realRoots = new Map(); + } + + async #resolveRealRoot(root) { + if (this.realRoots.has(root)) return this.realRoots.get(root); + const resolved = await fs.realpath(root); + if (this.realRoots.size >= 64) this.realRoots.clear(); + this.realRoots.set(root, resolved); + return resolved; } registerSession(session) { @@ -133,7 +154,7 @@ class PluginProtocol { const segments = decodeRequestPath(url.pathname); const csp = `default-src 'none'; script-src 'self' ${PLUGIN_PROTOCOL_SCHEME}: 'nonce-${registration.token}'; connect-src 'self' ${PLUGIN_PROTOCOL_SCHEME}:; img-src 'self' ${PLUGIN_PROTOCOL_SCHEME}:; style-src 'none'; font-src 'none'; media-src 'none'; object-src 'none'; frame-src 'none'; worker-src 'none'; child-src 'none'; base-uri 'none'; form-action 'none'`; if (segments.length === 1 && segments[0] === "index.html") { - return respond(htmlForRuntime(registration.token, this.moduleResources), 200, "text/html; charset=utf-8", { + return respond(htmlForRuntime(registration.token, this.moduleResources, registration.config?.entryUrl), 200, "text/html; charset=utf-8", { "Content-Security-Policy": csp, "Permissions-Policy": "camera=(), microphone=(), geolocation=(), display-capture=(), usb=(), serial=(), hid=(), payment=(), fullscreen=(), clipboard-read=(), clipboard-write=()", }); @@ -160,7 +181,8 @@ class PluginProtocol { if (!fileSegments.length || (!packageResource && fileSegments.some((segment) => segment.startsWith(".")))) { return respond("Not Found", 404); } - const file = await readContainedFile(root, fileSegments); + const realRoot = await this.#resolveRealRoot(root); + const file = await readContainedFile(root, fileSegments, Infinity, realRoot); const contentType = CONTENT_TYPES.get(path.extname(file.filePath).toLowerCase()) ?? "application/octet-stream"; return respond(file.body, 200, contentType); diff --git a/electron/plugins/viewResourceService.cjs b/electron/plugins/viewResourceService.cjs index ed5066b14..2f7cd9bc4 100644 --- a/electron/plugins/viewResourceService.cjs +++ b/electron/plugins/viewResourceService.cjs @@ -1,4 +1,6 @@ "use strict"; +const { createHash, randomUUID } = require("node:crypto"); +const fs = require("node:fs/promises"); const path = require("node:path"); const { readContainedFile } = require("./pluginProtocol.cjs"); const { inspectContributionIconSource, createBoundedIconRasterizer } = require("./contributionIconService.cjs"); @@ -6,17 +8,34 @@ const { createPooledContributionIconRasterizer } = require("./contributionIconRa const MAX_VIEW_RESOURCE_CACHE_ENTRIES = 256; const MAX_VIEW_RESOURCE_CACHE_BYTES = 24 * 1024 * 1024; +const MAX_DISK_CACHE_FILES = 512; +const VIEW_IMAGE_MAX_EDGE = 2048; function buildCacheKey(plugin, resource) { if (!plugin || typeof plugin.id !== "string" || typeof plugin.activeVersion !== "string") return null; return JSON.stringify([plugin.id, plugin.activeVersion, plugin.archiveSha256 ?? "", resource]); } +function buildDiskCacheFilename(plugin, resource) { + if (!plugin || typeof plugin.id !== "string" || typeof plugin.activeVersion !== "string" + || typeof plugin.archiveSha256 !== "string" || !plugin.archiveSha256) return null; + const digest = createHash("sha256") + .update(JSON.stringify(["view-v1", plugin.id, plugin.activeVersion, plugin.archiveSha256, resource, VIEW_IMAGE_MAX_EDGE])) + .digest("hex"); + return `${digest}.png`; +} + class PluginViewResources { - constructor({ electron, packageStore }) { + constructor({ electron, packageStore, rasterizeIcon, cacheDir }) { this.packageStore = packageStore; - this.pooledRasterizer = createPooledContributionIconRasterizer(electron); + this.ownsRasterizer = typeof rasterizeIcon !== "function"; + this.pooledRasterizer = this.ownsRasterizer + ? createPooledContributionIconRasterizer(electron) + : rasterizeIcon; this.rasterize = createBoundedIconRasterizer(this.pooledRasterizer, { maxConcurrent: 8, maxQueued: 256 }); + this.cacheDir = typeof cacheDir === "string" && cacheDir.length > 0 ? cacheDir : null; + this.cacheDirReady = null; + this.diskWritesSincePrune = 0; this.cache = new Map(); this.cacheBytes = 0; this.pending = new Map(); @@ -48,24 +67,95 @@ class PluginViewResources { this.cacheBytes += size; } + async #readDiskCache(plugin, resource) { + if (!this.cacheDir) return null; + const filename = buildDiskCacheFilename(plugin, resource); + if (!filename) return null; + try { + const filePath = path.join(this.cacheDir, filename); + const png = await fs.readFile(filePath); + if (!png.length || png.length > 4 * 1024 * 1024) return null; + inspectContributionIconSource(png, ".png", VIEW_IMAGE_MAX_EDGE); + return { url: `data:image/png;base64,${png.toString("base64")}` }; + } catch { + return null; + } + } + + async #writeDiskCache(plugin, resource, png) { + if (!this.cacheDir) return; + const filename = buildDiskCacheFilename(plugin, resource); + if (!filename) return; + try { + this.cacheDirReady ??= fs.mkdir(this.cacheDir, { recursive: true, mode: 0o700 }); + await this.cacheDirReady; + const targetPath = path.join(this.cacheDir, filename); + const tempPath = path.join(this.cacheDir, `.tmp-${randomUUID()}.png`); + try { + await fs.writeFile(tempPath, png, { mode: 0o600 }); + await fs.rename(tempPath, targetPath); + } catch (error) { + await fs.unlink(tempPath).catch(() => {}); + throw error; + } + if (++this.diskWritesSincePrune >= 32) { + this.diskWritesSincePrune = 0; + void this.#pruneDiskCache(); + } + } catch { + // Disk cache is best-effort; memory cache already holds the decoded image. + } + } + + async #pruneDiskCache() { + if (!this.cacheDir) return; + try { + const names = (await fs.readdir(this.cacheDir)).filter((name) => name.endsWith(".png") && !name.startsWith(".tmp-")); + if (names.length <= MAX_DISK_CACHE_FILES) return; + const entries = await Promise.all(names.map(async (name) => { + const fullPath = path.join(this.cacheDir, name); + const stat = await fs.stat(fullPath).catch(() => null); + return stat ? { fullPath, mtimeMs: stat.mtimeMs } : null; + })); + const valid = entries.filter(Boolean).sort((a, b) => a.mtimeMs - b.mtimeMs); + const excess = valid.length - MAX_DISK_CACHE_FILES; + for (let i = 0; i < excess; i += 1) { + await fs.unlink(valid[i].fullPath).catch(() => {}); + } + } catch { /* best-effort prune */ } + } + + async #readPackageImage(plugin, segments) { + if (typeof this.packageStore.readVerifiedPackageFile === "function") { + return this.packageStore.readVerifiedPackageFile(plugin, segments, 512 * 1024); + } + const root = await this.packageStore.preparePackageRoot(plugin); + return readContainedFile(root, segments, 512 * 1024); + } + async image(plugin, resource) { - if (typeof resource !== 'string' || resource.length > 256 || !/^[a-zA-Z0-9_-][a-zA-Z0-9_./-]*$/.test(resource) - || resource.split('/').some((part) => !part || part === '.' || part === '..')) throw new TypeError('Invalid plugin image path'); + if (typeof resource !== "string" || resource.length > 256 || !/^[a-zA-Z0-9_-][a-zA-Z0-9_./-]*$/.test(resource) + || resource.split("/").some((part) => !part || part === "." || part === "..")) throw new TypeError("Invalid plugin image path"); const cacheKey = buildCacheKey(plugin, resource); const cached = this.#getCached(cacheKey); if (cached) return cached; if (cacheKey && this.pending.has(cacheKey)) return this.pending.get(cacheKey); const task = (async () => { - const root = await this.packageStore.preparePackageRoot(plugin); - const file = await readContainedFile(root, resource.split('/'), 512 * 1024); - if (path.extname(resource).toLowerCase() === '.svg' && / 4 * 1024 * 1024) throw new Error('Plugin image exceeds size limit'); - inspectContributionIconSource(png, '.png', 2048); - const result = { url: `data:image/png;base64,${png.toString('base64')}` }; + const png = await this.rasterize({ body: file.body, ...inspected, maxEdge: VIEW_IMAGE_MAX_EDGE }); + if (png.length > 4 * 1024 * 1024) throw new Error("Plugin image exceeds size limit"); + inspectContributionIconSource(png, ".png", VIEW_IMAGE_MAX_EDGE); + const result = { url: `data:image/png;base64,${png.toString("base64")}` }; this.#setCached(cacheKey, result); + void this.#writeDiskCache(plugin, resource, png); return result; })(); @@ -79,7 +169,7 @@ class PluginViewResources { } dispose() { - this.pooledRasterizer?.dispose?.(); + if (this.ownsRasterizer) this.pooledRasterizer?.dispose?.(); this.cache.clear(); this.cacheBytes = 0; this.pending.clear(); diff --git a/electron/plugins/viewResourceService.test.cjs b/electron/plugins/viewResourceService.test.cjs index e00c13251..c67e177e5 100644 --- a/electron/plugins/viewResourceService.test.cjs +++ b/electron/plugins/viewResourceService.test.cjs @@ -49,3 +49,66 @@ test('view images cache decoded results by plugin version/hash and never cache t assert.equal(attempts, 2); resources.dispose(); }); + +test('view images persist validated PNGs to disk cache and recover cleanly from corrupt cache files', async (t) => { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'netcatty-view-image-disk-')); + t.after(() => fs.rm(directory, { recursive: true, force: true })); + const root = path.join(directory, 'package'); + const cacheDir = path.join(directory, 'image-cache'); + await fs.mkdir(root); + const pngHeader = Buffer.from([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, + 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, + 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, + ]); + await fs.writeFile(path.join(root, 'db.png'), pngHeader); + const plugin = { id: 'com.test.db', activeVersion: '0.3.0', archiveSha256: 'a'.repeat(64) }; + let rasterizeCalls = 0; + const rasterizeIcon = async () => { + rasterizeCalls += 1; + return pngHeader; + }; + const firstResources = new PluginViewResources({ + electron: {}, + packageStore: { preparePackageRoot: async () => root }, + rasterizeIcon, + cacheDir, + }); + const cold = await firstResources.image(plugin, 'db.png'); + assert.equal(rasterizeCalls, 1); + // Wait briefly for best-effort atomic disk cache write. + for (let i = 0; i < 40; i += 1) { + const files = await fs.readdir(cacheDir).catch(() => []); + if (files.some((f) => f.endsWith('.png') && !f.startsWith('.tmp-'))) break; + await new Promise((resolve) => setTimeout(resolve, 10)); + } + firstResources.dispose(); + + // Second instance (simulating app restart) hits disk cache with 0 rasterize calls. + const secondResources = new PluginViewResources({ + electron: {}, + packageStore: { preparePackageRoot: async () => { throw new Error('should not touch package on disk hit'); } }, + rasterizeIcon, + cacheDir, + }); + const warm = await secondResources.image(plugin, 'db.png'); + assert.equal(warm.url, cold.url); + assert.equal(rasterizeCalls, 1); + secondResources.dispose(); + + // Corrupt the cached PNG on disk -> third instance rejects corrupt bytes and re-rasterizes cleanly. + const cachedFiles = (await fs.readdir(cacheDir)).filter((f) => f.endsWith('.png')); + assert.equal(cachedFiles.length, 1); + await fs.writeFile(path.join(cacheDir, cachedFiles[0]), Buffer.from('not-a-png')); + const thirdResources = new PluginViewResources({ + electron: {}, + packageStore: { preparePackageRoot: async () => root }, + rasterizeIcon, + cacheDir, + }); + const recovered = await thirdResources.image(plugin, 'db.png'); + assert.equal(recovered.url, cold.url); + assert.equal(rasterizeCalls, 2); + thirdResources.dispose(); +}); diff --git a/packages/plugin-cli/src/archive.ts b/packages/plugin-cli/src/archive.ts index 0b29b59c8..c7a60e2a1 100644 --- a/packages/plugin-cli/src/archive.ts +++ b/packages/plugin-cli/src/archive.ts @@ -73,6 +73,7 @@ export interface PackageValidationResult { readonly fileCount: number; readonly uncompressedBytes: number; readonly contentSha256: string; + readonly fileHashes?: Readonly>; } export type PluginDirectoryValidationResult = PackageValidationResult; @@ -501,6 +502,7 @@ export async function validatePluginDirectory( fileCount: files.length, uncompressedBytes: files.reduce((sum, file) => sum + file.size, 0), contentSha256: computePackageContentSha256(files), + fileHashes: Object.freeze(Object.fromEntries(files.map((file) => [file.packagePath, file.sha256]))), }; } @@ -797,7 +799,10 @@ async function inspectPluginPackage( executable: declaredCompanions.has(packagePath), })), ); - return { manifest, fileCount: entries.size, uncompressedBytes: totalBytes, contentSha256 }; + const fileHashes = Object.freeze( + Object.fromEntries([...entries].map(([packagePath, entry]) => [packagePath, entry.sha256])), + ); + return { manifest, fileCount: entries.size, uncompressedBytes: totalBytes, contentSha256, fileHashes }; } finally { zipFile.close(); } }