mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-27 20:00:51 +00:00
Completes exhaustive business-code memory optimization stacked on Phase 1-2 (#4476), reaching the business-code floor before Electron-level optimization: Round 1 - Renderer Cold Start & Preload Minification: - Enable esbuild minification in scripts/build-preload.mjs (368 KB -> 103 KB, -72%) - Remove eager requestIdleCallback TerminalLayer mount in AppMounts.tsx - Add compact capability lookup maps to toolNameIndex.json so permissionGrants drops static cattyToolSpecs.json (126 KB) from startup - Lazy-load pinyin-pro (447 KB) on first CJK text via usePinyinMatcherVersion hook (synchronous createRequire in Node/test mode, zero top-level await) Round 2 & 3 - Main Process & terminalWorker Zero-Dead-Weight Startup: - Lazy-load all third-party npm packages on startup (0 npm packages loaded at boot; require.cache 657 -> 234 modules, -64.4%; main heapTotal 54 -> 23.3 MiB): ajv/ajv-formats/plugin-contract schema, electron-updater, jsqr, ws, webmDurationPatch, terminalPerformanceDiagnostics, ssh2, ssh2-sftp-client, iconv-lite, zmodem.js, node-pty/serialport (Electron-gated so Node Module._load mocks stay 100% intact), 11 AI SDK drivers, CodexAppServerRuntime, codebuddy, aiPrivacyService, re2js, external MCP setup, 17 capability modules, and 7 systemManager/*Ops modules - Clean up windowManager readiness/unhealthy maps on BrowserWindow closed Round 4 - Renderer Startup Bundle Decomposition: - Lazy-load HostDetailsPanel (134 KB), GroupDetailsPanel (29 KB), KnownHostsManager, QuickConnectWizard, SerialConnectModal, Serial/LocalHostDetailsPanel, ImportVaultDialog, VaultImportProgressPanel, domain/vaultImport (55 KB), TerminalHostTreeSidebar (35 KB), ToolCall (26 KB), vaultAgentBridgeClient (47 KB) - Tree-shake package.json in cloudSync (-32 KB from useUpdateCheck) - Main App-*.js chunk: 1,550 KB -> 714.6 KB (-53.9%) Round 5 - Active Multi-Terminal Memory Optimization: - Remove unconditional requestIdleCallback preload of AIChatSidePanel (~1.5 MB JS / vendor-ai + globalAgentRuntime + tool specs) in TerminalLayerSupport.tsx - Remove eager 67-spec Fig autocomplete preloading (1.25 MB raw JS imported into main-process ESM cache + renderer specCache) in useTerminalAutocomplete.ts; specs load on demand via completionEngine.ts loadSpec() Verified Clean-VM Benchmarks (0-host idle, 3x median, vs Blank Electron 97.6 MiB PrivDirty): - Total Private Dirty RAM: 324.8 -> 234.6 (Phase 1-2) -> 184.2 MiB (-43.3%, 61.9% of all Netcatty overhead above Blank Electron eliminated) - Renderer v8/main/heap: 24.84 -> 9.35 MiB (-62.4%); jsHeapUsedMB: 35.98 -> 12.76 MiB (only +3.22 MiB above about:blank) - Active 5 local terminals + 1,000-line ANSI burst: Peak PrivDirty -25.6 MiB (395.9 -> 370.3 MiB), main PrivDirty -11.3 MiB, renderer PrivDirty -14.2 MiB, zero xterm/canvas/listener/per-session heap leaks across 2x5 open/close cycles
162 lines
5.5 KiB
JavaScript
162 lines
5.5 KiB
JavaScript
"use strict";
|
|
|
|
const path = require("node:path");
|
|
|
|
const { assertPluginJsonValue } = require("./jsonBoundary.cjs");
|
|
const {
|
|
PLUGIN_RPC_MAX_JSON_BYTES,
|
|
PLUGIN_STREAM_MAX_FRAME_JSON_BYTES,
|
|
} = require("./constants.cjs");
|
|
|
|
let contractAjv = null;
|
|
let cachedSchema = null;
|
|
const compiledDefinitions = new Map();
|
|
|
|
function getContractSchema() {
|
|
if (!cachedSchema) {
|
|
cachedSchema = require("./generated/plugin-contract.schema.json");
|
|
}
|
|
return cachedSchema;
|
|
}
|
|
|
|
/**
|
|
* One Ajv instance per process with the generated plugin contract registered
|
|
* once. Loading Ajv + schema is deferred until the first validation call so
|
|
* zero-plugin startups do not pay ~5 MiB of Ajv/schema compilation overhead.
|
|
*/
|
|
function getContractAjv() {
|
|
if (!contractAjv) {
|
|
const Ajv2020 = require("ajv/dist/2020").default;
|
|
const addFormats = require("ajv-formats").default;
|
|
contractAjv = new Ajv2020({ allErrors: true, strict: false, validateFormats: true });
|
|
addFormats(contractAjv);
|
|
contractAjv.addSchema(getContractSchema());
|
|
}
|
|
return contractAjv;
|
|
}
|
|
|
|
function compileDefinition(definitionName) {
|
|
let compiled = compiledDefinitions.get(definitionName);
|
|
if (!compiled) {
|
|
const schema = getContractSchema();
|
|
if (!schema.$defs?.[definitionName]) {
|
|
throw new Error(`Unknown plugin contract definition: ${definitionName}`);
|
|
}
|
|
compiled = getContractAjv().getSchema(`${schema.$id}#/$defs/${definitionName}`);
|
|
if (typeof compiled !== "function") throw new Error(`Unable to compile plugin contract definition: ${definitionName}`);
|
|
compiledDefinitions.set(definitionName, compiled);
|
|
}
|
|
return compiled;
|
|
}
|
|
|
|
/**
|
|
* Returns a validator for one contract definition. Schema loading and
|
|
* compilation are deferred to the first call and shared by every validator of
|
|
* the same definition; each returned function still exposes its own `.errors`
|
|
* from its latest call.
|
|
*/
|
|
function createDefinitionValidator(definitionName) {
|
|
let compiled = null;
|
|
const validate = (value) => {
|
|
compiled ??= compileDefinition(definitionName);
|
|
const valid = compiled(value);
|
|
validate.errors = compiled.errors ?? null;
|
|
return valid;
|
|
};
|
|
validate.errors = null;
|
|
return validate;
|
|
}
|
|
|
|
function formatValidationErrors(errors) {
|
|
return (errors ?? [])
|
|
.slice(0, 8)
|
|
.map((error) => `${error.instancePath || "/"} ${error.message ?? "is invalid"}`)
|
|
.join("; ");
|
|
}
|
|
|
|
const rpcMessageValidator = createDefinitionValidator("RpcMessage");
|
|
const initializeResultValidator = createDefinitionValidator("RuntimeInitializeResult");
|
|
const terminalInterceptorAttachmentParamsValidator = createDefinitionValidator("TerminalInterceptorAttachmentParams");
|
|
const terminalInterceptorAttachmentResultValidator = createDefinitionValidator("TerminalInterceptorAttachmentResult");
|
|
const terminalInterceptorFrameValidator = createDefinitionValidator("TerminalInterceptorFrame");
|
|
const providerRequestValidator = createDefinitionValidator("ProviderRequest");
|
|
const providerResultValidator = createDefinitionValidator("ProviderResult");
|
|
const streamFrameValidator = createDefinitionValidator("StreamFrame");
|
|
|
|
function assertContractValue(validator, value, label) {
|
|
if (!validator(value)) {
|
|
throw new TypeError(`${label} violates the plugin contract: ${formatValidationErrors(validator.errors)}`);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function assertRpcMessage(value) {
|
|
assertPluginJsonValue(value, { maxBytes: PLUGIN_RPC_MAX_JSON_BYTES });
|
|
return assertContractValue(rpcMessageValidator, value, "RPC message");
|
|
}
|
|
|
|
function assertInitializeResult(value) {
|
|
assertPluginJsonValue(value, { maxBytes: PLUGIN_RPC_MAX_JSON_BYTES });
|
|
return assertContractValue(initializeResultValidator, value, "Initialize result");
|
|
}
|
|
|
|
function assertTerminalInterceptorAttachmentParams(value) {
|
|
assertPluginJsonValue(value, { maxBytes: PLUGIN_RPC_MAX_JSON_BYTES });
|
|
return assertContractValue(
|
|
terminalInterceptorAttachmentParamsValidator,
|
|
value,
|
|
"Terminal interceptor attachment params",
|
|
);
|
|
}
|
|
|
|
function assertTerminalInterceptorAttachmentResult(value) {
|
|
assertPluginJsonValue(value, { maxBytes: PLUGIN_RPC_MAX_JSON_BYTES });
|
|
return assertContractValue(
|
|
terminalInterceptorAttachmentResultValidator,
|
|
value,
|
|
"Terminal interceptor attachment result",
|
|
);
|
|
}
|
|
|
|
function assertTerminalInterceptorFrameSchema(value) {
|
|
return assertContractValue(
|
|
terminalInterceptorFrameValidator,
|
|
value,
|
|
"Terminal interceptor frame",
|
|
);
|
|
}
|
|
|
|
function assertProviderRequest(value) {
|
|
assertPluginJsonValue(value, { maxBytes: PLUGIN_RPC_MAX_JSON_BYTES });
|
|
return assertContractValue(providerRequestValidator, value, "Provider request");
|
|
}
|
|
|
|
function assertProviderResult(value) {
|
|
assertPluginJsonValue(value, { maxBytes: PLUGIN_RPC_MAX_JSON_BYTES });
|
|
return assertContractValue(providerResultValidator, value, "Provider result");
|
|
}
|
|
|
|
function assertStreamFrameSchema(value) {
|
|
assertPluginJsonValue(value, { maxBytes: PLUGIN_STREAM_MAX_FRAME_JSON_BYTES });
|
|
return assertContractValue(streamFrameValidator, value, "Stream frame");
|
|
}
|
|
|
|
function resolveContractRuntimePath(...segments) {
|
|
return path.join(__dirname, "..", "..", "node_modules", "@netcatty", "plugin-contract", "dist", ...segments);
|
|
}
|
|
|
|
module.exports = {
|
|
assertInitializeResult,
|
|
assertTerminalInterceptorAttachmentParams,
|
|
assertTerminalInterceptorAttachmentResult,
|
|
assertTerminalInterceptorFrameSchema,
|
|
assertProviderRequest,
|
|
assertProviderResult,
|
|
assertRpcMessage,
|
|
assertStreamFrameSchema,
|
|
createDefinitionValidator,
|
|
formatValidationErrors,
|
|
getContractAjv,
|
|
resolveContractRuntimePath,
|
|
};
|