Files
Netcatty/electron/bridges/terminalEncoding.cjs
T
陈大猫 3998add458 perf(memory): Phase 3 deep business-code memory optimization across main, renderer, and active terminals
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
2026-11-27 10:04:36 +00:00

121 lines
5.3 KiB
JavaScript

/**
* Terminal encoding helpers — the single source of truth for turning a
* user-facing charset name into an iconv-lite identifier and for keeping the
* terminal input (keystrokes → remote) and output (remote → display) paths on
* the *same* encoding.
*
* Background (issue #1216): the output path already decodes remote bytes with
* an iconv decoder built from the user's configured charset (GB18030, etc.),
* but the input path used to serialize keystrokes as UTF-8 unconditionally.
* On a non-UTF-8 device that made input and output asymmetric — typing Chinese
* showed up garbled on the device while the device's own output decoded fine
* (or vice-versa, depending on which side the user matched). Encoding input
* with the *same* charset closes that gap.
*/
let _iconv = null;
function getIconv() {
if (!_iconv) _iconv = require("iconv-lite");
return _iconv;
}
// Normalize user-facing charset names into an iconv-lite encoding identifier.
// iconv-lite accepts a wide range of aliases directly ("utf-8", "gbk", etc.),
// so mostly this just lowercases + collapses non-alphanumerics and maps a few
// obvious GB* variants to gb18030 which is the superset we ship the encoding
// switcher with. Anything iconv doesn't recognize falls back to utf-8.
function normalizeTerminalEncoding(charset) {
if (!charset) return "utf-8";
const raw = String(charset).trim().toLowerCase();
const localeCodeset = raw.match(/\.([^@]+)(?:@.*)?$/)?.[1];
const candidates = [raw, localeCodeset].filter(Boolean);
for (const candidate of candidates) {
const normalized = candidate.replace(/[^a-z0-9]/g, "");
if (normalized === "utf8") return "utf-8";
if (["gb18030", "gbk", "gb2312", "cp936", "ms936"].includes(normalized)) {
return "gb18030";
}
if (getIconv().encodingExists(candidate)) return candidate;
}
return "utf-8";
}
// True when the encoding is UTF-8 (the JS/Node default for string → bytes).
// Callers use this to skip the iconv round-trip on the hot input path: for
// UTF-8 the platform's native string serialization is already correct, so
// there is nothing to convert.
function isUtf8Encoding(encoding) {
if (!encoding) return true;
return /^utf-?8$/i.test(String(encoding).trim());
}
// Cache of encoding identifier -> whether it is ASCII-compatible (each ASCII
// byte encodes to exactly itself, one byte). iconv probing is cheap but this is
// the keystroke hot path, so memoize it.
const asciiCompatibleCache = new Map();
// A terminal speaks ASCII control bytes: CR, LF, ESC and the bytes of CSI
// escape sequences (Enter, arrows, Ctrl-C, …). Encodings like GB18030 / GBK /
// Big5 / Shift_JIS / EUC / latin1 are ASCII supersets, so those bytes survive
// untouched and only the non-ASCII characters change. But ASCII-incompatible
// multi-byte encodings (UTF-16LE/BE, UCS-2, UTF-32, …) would turn "\r" into
// `0d 00` and "\x1b[A" into `1b 00 5b 00 41 00`, breaking line discipline and
// escape parsing on the remote. We probe a representative ASCII control byte
// and refuse to use iconv for input on encodings that don't preserve it.
function isAsciiCompatibleEncoding(encoding) {
const cached = asciiCompatibleCache.get(encoding);
if (cached !== undefined) return cached;
let compatible = false;
try {
// \r and ESC cover the control bytes we care about; a single C0 probe is
// enough since ASCII-incompatible encodings widen every code point.
const cr = getIconv().encode("\r", encoding);
const esc = getIconv().encode("\x1b", encoding);
compatible = cr.length === 1 && cr[0] === 0x0d && esc.length === 1 && esc[0] === 0x1b;
} catch {
compatible = false;
}
asciiCompatibleCache.set(encoding, compatible);
return compatible;
}
/**
* Encode a terminal input string for the wire using the session's charset.
*
* Returns the original string unchanged for UTF-8 (let the transport's native
* string handling serialize it) and a Buffer encoded with iconv-lite for any
* other ASCII-compatible charset. ASCII control bytes (CR, ESC, Ctrl-C, the
* bytes of CSI escape sequences, …) stay single-byte under those encodings, so
* encoding the whole string is safe — only the non-ASCII characters change.
*
* `encoding` is expected to already be a normalized iconv identifier (what
* normalizeTerminalEncoding returns and what sessions store on
* `session.encoding`). Falls back to the UTF-8 string — i.e. today's behavior —
* for unknown encodings and for ASCII-incompatible ones (UTF-16/UCS-2/…) where
* widening the control bytes would break Enter / arrows / Ctrl-C on the remote.
*/
function encodeTerminalInput(data, encoding) {
if (typeof data !== "string") return data;
if (isUtf8Encoding(encoding)) return data;
if (!getIconv().encodingExists(encoding)) return data;
if (!isAsciiCompatibleEncoding(encoding)) return data;
return getIconv().encode(data, encoding);
}
// Only expand a single Backspace. Other input (including plugin replacements)
// must retain its normal meaning. The caller restricts this to serial sessions.
function expandSerialBackspace(data, char, encoding) {
if ((data !== "\x7f" && data !== "\b") || typeof char !== "string" || !char) return data;
const encoded = encodeTerminalInput(char, encoding);
return data.repeat(Buffer.byteLength(encoded));
}
module.exports = {
normalizeTerminalEncoding,
isUtf8Encoding,
encodeTerminalInput,
expandSerialBackspace,
};