Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
perf(main): load ssh2 and electron-updater on first use, not at module scope
Brandon Bridges8cffc8357d77
diff --git a/CLAUDE.md b/CLAUDE.mdindex 734d31dba..e8ffa450f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -9284,6 +9284,12 @@ unix-socket forward and dev-server `-L` forward over it. POSIX keeps OpenSSH untA killed streaming child must never write to its ended pipes (an uncaught`ERR_STREAM_WRITE_AFTER_END` in main). A stream nobody reads never emits `close` — tests must`resume()` the channels they hold.+- **ssh2 is loaded on first use, never at module scope** (`ssh2()` in `native-mux.ts`; every other+ shipped import of it is `import type`). native-runtime → native-mux is on main's module-scope+ graph, which runs before Chromium's `ready`; a top-level import cost every launch 14–25 ms warm+ (~680 ms in one cold-cache sample) on machines that never open an SSH project (audit startup-6).+ Pinned by `native-mux.lazy.test.ts` (import does not evaluate ssh2) and+ `src/main/lazy-deps.source.test.ts` (no shipped value import).- **Tests run on every OS** against ssh2's own in-process `Server` (loopback, no sshd); thedirectory is in the `windows-latest` CI job. Live numbers (macOS, `NODETERM_NATIVE_SSH=1`,89-terminal project): 89/89 attached, 0 ssh processes, ~1 login per connect, main CPU 3–5% idle.@@ -10213,6 +10219,14 @@ update vX" item); on `update-downloaded` an OS notification also fires when theunfocused. Exposed via `window.nodeTerminal.updates` (`UpdateApi`). macOS *silent* self-installrequires a signed+notarized build; unsigned builds still surface the card for a manual download.Rules a refactor must not undo (pure + tested: `shared/update-gate.ts`, `renderer/lib/updateCardState.ts`):+- **electron-updater is never imported at module scope** (audit startup-6: 32–47 ms warm before+ `ready`, on every launch). `initUpdater` loads it through `UpdaterDeps.loadUpdater` (default: a+ plain `require`) only where it is used — at init for a build with a feed, on a restart click in+ dev, never for `no-channel` — and only AFTER the `appGetVersion` / `appGetStagedUpdate` /+ `appRestartToUpdate` handlers are registered, which stay eager on every build (the renderer+ invokes them on mount; an invoke with no handler rejects). Tests pass their double through+ `loadUpdater`, because `vi.mock` does not reach a `require()`. Pinned in+ `updater.no-channel.test.ts` and `src/main/lazy-deps.source.test.ts`.- **electron-updater keeps re-announcing a STAGED update** (the running binary is still old, so every6h check emits `update-available` → cached `update-downloaded` again, and on macOS re-stages the zipthrough Squirrel). The gate forwards and notifies **once per version**; once staged, `autoDownload`diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex c7745fa71..872200879 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1382,6 +1382,12 @@ bite most often:- Dispose every Monaco model your node creates when it unmounts. The TS/JS worker (a wholecompiler isolate) is only stopped once no TS/JS model is left (`renderer/editor/tsWorkerReaper.ts`).+**`ssh2` and `electron-updater` load on first use, never at main's module scope**, which runs+before Chromium's `ready` (together ~50–70 ms warm on every launch, audit startup-6). Use `import+type` for their types; values come from `ssh2()` in `native-mux.ts` and `initUpdater`'s+`loadUpdater`. `src/main/lazy-deps.source.test.ts` goes red on a value import. A `require()` is+not reached by `vi.mock`, so a test injects its double (see the updater tests).+**SSH projects on Windows** run over an in-process transport (`src/core/remote-ssh/native/`),not the ssh binary. If you add an ssh call site, route it through `useNativeSsh()` like theothers, and if you add an ssh option to `control-master.ts`, teach `ssh-argv.ts` about it (thediff --git a/src/core/remote-ssh/native/native-mux.lazy.test.ts b/src/core/remote-ssh/native/native-mux.lazy.test.tsnew file mode 100644index 000000000..64184d330--- /dev/null+++ b/src/core/remote-ssh/native/native-mux.lazy.test.ts@@ -0,0 +1,26 @@+// ssh2 must not load when the native transport is merely IMPORTED (audit startup-6 / roadmap #34).+// native-runtime → native-mux sits on main's module-scope import graph, and main's module scope runs+// before Chromium's `ready`: a top-level ssh2 import cost every launch 14–25 ms warm (~680 ms in one+// cold-cache sample) for a transport that only runs on Windows or with NODETERM_NATIVE_SSH=1.+//+// This file deliberately imports nothing from ssh2 itself (not even test-keys.ts), so the module+// cache it inspects is this file's alone — the other native-* suites import ssh2 directly. It is in+// this directory so it rides the windows-latest CI job with the rest of the transport.+import { createRequire } from 'module'+import { describe, expect, it } from 'vitest'++const req = createRequire(import.meta.url)+const ssh2Entry = req.resolve('ssh2')++describe('native SSH transport: ssh2 is loaded lazily', () => {+ it('importing native-runtime (and so native-mux) does not evaluate ssh2', async () => {+ // A cached entry from elsewhere in this worker would make the assertion meaningless; drop it so+ // only this import can put it back. (Node's ESM loader of a CJS package populates this cache.)+ delete req.cache[ssh2Entry]+ const runtime = await import('./native-runtime')+ const mux = await import('./native-mux')+ expect(typeof runtime.useNativeSsh).toBe('function')+ expect(typeof mux.NativeMux).toBe('function')+ expect(req.cache[ssh2Entry]).toBeUndefined()+ })+})diff --git a/src/core/remote-ssh/native/native-mux.ts b/src/core/remote-ssh/native/native-mux.tsindex 3bc57a049..488dac15a 100644--- a/src/core/remote-ssh/native/native-mux.ts+++ b/src/core/remote-ssh/native/native-mux.ts@@ -36,7 +36,8 @@ import net from 'net'import os from 'os'import type { Duplex } from 'stream'import fs from 'fs'-import { Client, createAgent, utils, type Channel, type ClientChannel, type ConnectConfig, type UNIXConnectionDetails, type ParsedKey, type SFTPWrapper } from 'ssh2'+// Type-only: ssh2 itself is required on first use (`ssh2()` below), never at module scope.+import type { Client, Channel, ClientChannel, ConnectConfig, UNIXConnectionDetails, ParsedKey, SFTPWrapper, createAgent } from 'ssh2'import type { LocalForward, ParsedSsh, ReverseForward, SshOptions, SshTarget } from './ssh-argv'import { parseProxyJump, resolveForwardAgent, type HostQuery, type JumpSpec, type ResolvedHost } from './ssh-config'import { WINDOWS_OPENSSH_AGENT_PIPE, resolveWindowsIdentityAgent } from './windows-agent-discovery'@@ -44,6 +45,20 @@ import { expandProxyTokens, proxyCommandSocket, type ProxySpawn } from './proxy-import { acceptNewHostKey } from './known-hosts'import { addKeyToAgent, type AgentAddResult } from './agent-add'+/**+ * ssh2, loaded on first use. This module sits on main's module-scope import graph (via+ * native-runtime / native-invoke), so a top-level `import { Client } from 'ssh2'` evaluated ssh2 on+ * every launch, before Chromium's `ready`: 14–25 ms warm, ~680 ms in one cold-cache sample (audit startup-6 /+ * roadmap #34) — for a transport that only runs on Windows or with `NODETERM_NATIVE_SSH=1`. A plain+ * `require` stays a runtime require in both bundles: electron-vite externalises dependencies, and+ * `server:build` passes `--external:ssh2` (server-build.test.ts). Pinned by native-mux.lazy.test.ts.+ */+let ssh2Module: typeof import('ssh2') | undefined+function ssh2(): typeof import('ssh2') {+ // eslint-disable-next-line @typescript-eslint/no-var-requires+ return (ssh2Module ??= require('ssh2') as typeof import('ssh2'))+}+/** Result of one remote command, in the shape execFile callers already handle. */export interface ExecResult {code: number | null@@ -637,6 +652,7 @@ export class NativeMux {mode: { interactive: boolean },via?: Conn): Conn {+ const { Client } = ssh2()const client = new Client()let resolveClosed!: (why: string) => voidconst closed = new Promise<string>((r) => (resolveClosed = r))@@ -731,7 +747,7 @@ export class NativeMux {: await connectSocket(hops[0].host.hostname, hops[0].host.port, firstTimeoutMs)for (let i = 0; i < hops.length; i++) {const hop = hops[i]- const jump = new Client()+ const jump = new (ssh2().Client)()built.push(jump)// A jump client with no 'error' listener would throw from its emitter after the handshake.jump.on('error', (e: Error) => this.deps.log?.(`[native-ssh] jump ${hop.query.host}: ${e.message}`))@@ -954,6 +970,7 @@ export class NativeMux {if (cachedKey) return { type: 'publickey', username, key: cachedKey }const data = read(file)if (!data) return null+ const { utils } = ssh2()let key = utils.parseKey(data)let prompted = falseif (key instanceof Error && /encrypted|passphrase/i.test(key.message)) {@@ -1016,6 +1033,7 @@ export function resolveAgentPath(configured: string | undefined, fallback: strin/** An agent that only offers keys whose public blob is in `pubs` (IdentitiesOnly). */function filteredAgent(agentPath: string, pubFiles: Buffer[]): ReturnType<typeof createAgent> {+ const { createAgent, utils } = ssh2()const base = createAgent(agentPath)const wanted = pubFiles.map((b) => {diff --git a/src/main/lazy-deps.source.test.ts b/src/main/lazy-deps.source.test.tsnew file mode 100644index 000000000..3cc516711--- /dev/null+++ b/src/main/lazy-deps.source.test.ts@@ -0,0 +1,46 @@+// Source-level pin (audit startup-6 / roadmap #34): `ssh2` and `electron-updater` are never+// VALUE-imported by shipped main/core/shared/server code. Main's module scope runs before Chromium's+// `ready`, and the two used to cost every launch 14–25 ms (ssh2) + 32–47 ms (electron-updater) warm+// there. Each now loads at first use — `ssh2()` in native-mux.ts, `UpdaterDeps.loadUpdater` in+// updater.ts — and a value import anywhere on the graph would quietly put the cost back. `import+// type` is fine (erased). The behavioural half is native-mux.lazy.test.ts and the "loaded lazily"+// block of updater.no-channel.test.ts.+import { readdirSync, readFileSync } from 'fs'+import path from 'path'+import { describe, expect, it } from 'vitest'++const SRC = path.join(__dirname, '..')+const ROOTS = ['main', 'core', 'shared', 'server']+const LAZY = ['ssh2', 'electron-updater']++function shippedSources(dir: string): string[] {+ const out: string[] = []+ for (const e of readdirSync(dir, { withFileTypes: true })) {+ const p = path.join(dir, e.name)+ if (e.isDirectory()) out.push(...shippedSources(p))+ // Tests (and test-keys.ts, a test-only helper) may import ssh2 directly.+ else if (/\.tsx?$/.test(e.name) && !/\.test\.tsx?$/.test(e.name) && e.name !== 'test-keys.ts') out.push(p)+ }+ return out+}++describe('lazily loaded main-process dependencies', () => {+ const files = ROOTS.flatMap((r) => shippedSources(path.join(SRC, r)))++ it('scans the real tree', () => {+ expect(files.some((f) => f.endsWith(path.join('remote-ssh', 'native', 'native-mux.ts')))).toBe(true)+ expect(files.some((f) => f.endsWith(path.join('main', 'updater.ts')))).toBe(true)+ })++ for (const dep of LAZY) {+ it(`no shipped module value-imports '${dep}'`, () => {+ const esc = dep.replace(/[-/]/g, '\\$&')+ // `import x from`, `import { a } from`, `import 'dep'`, `export … from` — but not `import type`.+ // `[^'"]` (not `[^;]`: this codebase has no semicolons) keeps a match inside one statement —+ // it cannot run past an earlier import's own specifier — while still spanning a multi-line `{ … }`.+ const value = new RegExp(`^[ \\t]*(?:import\\s+(?!type\\b)[^'"]*?from\\s*|import\\s*|export\\s+(?!type\\b)[^'"]*?from\\s*)['"]${esc}['"]`, 'm')+ const offenders = files.filter((f) => value.test(readFileSync(f, 'utf8'))).map((f) => path.relative(SRC, f))+ expect(offenders).toEqual([])+ })+ }+})diff --git a/src/main/updater.no-channel.test.ts b/src/main/updater.no-channel.test.tsindex 55beae52e..aa0701570 100644--- a/src/main/updater.no-channel.test.ts+++ b/src/main/updater.no-channel.test.ts@@ -40,8 +40,7 @@ vi.mock('electron', () => ({autoUpdater: { on: () => {} }}))-// `vi.mock` factories are hoisted above every const, so the double the factory returns has to be-// hoisted with them.+// The electron-updater double, handed to `initUpdater` through its loader seam (below).const { updaterEvents, autoUpdater } = vi.hoisted(() => {const events: Record<string, (...a: unknown[]) => void> = {}return {@@ -58,14 +57,18 @@ const { updaterEvents, autoUpdater } = vi.hoisted(() => {}}})-vi.mock('electron-updater', () => ({ autoUpdater }))vi.mock('./main-window', () => ({getMainWindow: () => null,sendToMain: (channel: string, payload?: unknown) => sent.push({ channel, payload })}))vi.mock('./notifications', () => ({ retainUntilDismissed: () => {} }))-import { describeCheckFailure, initUpdater, lastUpdateCheck } from './updater'+import { describeCheckFailure, initUpdater as initUpdaterReal, lastUpdateCheck, type UpdaterHooks } from './updater'++// electron-updater is loaded lazily with `require` (startup-6), which `vi.mock` does not reach, so+// the double goes in through the loader seam instead of a module mock.+const initUpdater = (hooks?: UpdaterHooks) =>+ initUpdaterReal(hooks, { loadUpdater: () => autoUpdater as unknown as import('electron-updater').AppUpdater })const realReadFileSync = fs.readFileSync@@ -332,6 +335,65 @@ describe('restart-to-update elsewhere', () => {})})+/**+ * Audit startup-6 / roadmap #34: electron-updater is no longer required at main's module scope+ * (32–47 ms warm, before Chromium's `ready`, on every launch). It is loaded only on a path that uses+ * it, and the IPC handlers stay registered first whatever the build: the renderer invokes them on+ * mount, and an invoke with no handler rejects.+ */+describe('electron-updater is loaded lazily, after the IPC handlers', () => {+ const EAGER = [IPC.appGetVersion, IPC.appGetStagedUpdate, IPC.appRestartToUpdate, IPC.appCheckForUpdates]+ const registered = (): string[] => [...Object.keys(ipcHandle), ...Object.keys(ipcOn)]++ it('a dev build never loads it at init, and still answers every eager handler', () => {+ appMock.isPackaged = false+ packageWith(undefined)+ const loadUpdater = vi.fn(() => autoUpdater as unknown as import('electron-updater').AppUpdater)+ initUpdaterReal({}, { loadUpdater })+ expect(loadUpdater).not.toHaveBeenCalled()+ expect(registered()).toEqual(expect.arrayContaining(EAGER))+ })++ it('a no-channel build never loads it, not even on a check or a restart click', () => {+ setPlatform('win32')+ packageWith('disabled')+ const loadUpdater = vi.fn(() => autoUpdater as unknown as import('electron-updater').AppUpdater)+ initUpdaterReal({}, { loadUpdater })+ check()+ restart()+ expect(loadUpdater).not.toHaveBeenCalled()+ expect(registered()).toEqual(expect.arrayContaining(EAGER))+ })++ it('dev loads it only when restart-to-update is clicked (the historical no-op quitAndInstall)', () => {+ appMock.isPackaged = false+ packageWith(undefined)+ const loadUpdater = vi.fn(() => autoUpdater as unknown as import('electron-updater').AppUpdater)+ initUpdaterReal({}, { loadUpdater })+ restart()+ restart()+ expect(loadUpdater).toHaveBeenCalledTimes(1)+ expect(autoUpdater.quitAndInstall).toHaveBeenCalledTimes(2)+ })++ it('a release with a feed loads it once at init — after the version/staged/restart handlers exist', () => {+ setPlatform('darwin')+ packageWith(undefined)+ let registeredAtLoad: string[] = []+ const loadUpdater = vi.fn(() => {+ registeredAtLoad = registered()+ return autoUpdater as unknown as import('electron-updater').AppUpdater+ })+ initUpdaterReal({}, { loadUpdater })+ expect(loadUpdater).toHaveBeenCalledTimes(1)+ expect(registeredAtLoad).toEqual(expect.arrayContaining([IPC.appGetVersion, IPC.appGetStagedUpdate, IPC.appRestartToUpdate]))+ // The manual-check handler is registered once the module is in hand, still synchronously+ // inside initUpdater, so it exists before the renderer can send anything.+ expect(registered()).toEqual(expect.arrayContaining(EAGER))+ expect(autoUpdater.checkForUpdates).toHaveBeenCalledTimes(1)+ })+})+describe('describeCheckFailure', () => {it('names a 404 on a latest*.yml as a missing feed file', () => {expect(describeCheckFailure('HttpError: 404 Not Found ... latest.yml')).toMatch(/feed is missing/)diff --git a/src/main/updater.restart.test.ts b/src/main/updater.restart.test.tsindex 55bd80ff2..0a5d93b26 100644--- a/src/main/updater.restart.test.ts+++ b/src/main/updater.restart.test.ts@@ -67,14 +67,18 @@ const { autoUpdater } = vi.hoisted(() => {})}})-vi.mock('electron-updater', () => ({ autoUpdater }))vi.mock('./main-window', () => ({getMainWindow: () => null,sendToMain: (channel: string, payload?: unknown) => sent.push({ channel, payload })}))vi.mock('./notifications', () => ({ retainUntilDismissed: () => {} }))-import { initUpdater, PREPARE_TIMEOUT_MS } from './updater'+import { initUpdater as initUpdaterReal, PREPARE_TIMEOUT_MS, type UpdaterHooks } from './updater'++// electron-updater is loaded lazily with `require` (startup-6), which `vi.mock` does not reach, so+// the double goes in through the loader seam instead of a module mock.+const initUpdater = (hooks?: UpdaterHooks) =>+ initUpdaterReal(hooks, { loadUpdater: () => autoUpdater as unknown as import('electron-updater').AppUpdater })const realReadFileSync = fs.readFileSyncconst realPlatform = process.platformdiff --git a/src/main/updater.ts b/src/main/updater.tsindex 996241e85..48c276f2b 100644--- a/src/main/updater.ts+++ b/src/main/updater.ts@@ -8,9 +8,11 @@import { app, autoUpdater as nativeUpdater, ipcMain, Notification } from 'electron'import fs from 'fs'import path from 'path'-// Named import — the default-import + destructure pattern returns undefined under-// electron-vite v5's CJS interop.-import { autoUpdater } from 'electron-updater'+// electron-updater is NOT imported at module scope (audit startup-6 / roadmap #34): main's module+// scope runs before Chromium's `ready`, and requiring electron-updater there measured 32–47 ms warm+// on every launch — including dev and `no-channel` builds that never touch it. It is loaded by+// `initUpdater` (after createWindow) only on a path that uses it; see `UpdaterDeps`. Type-only here.+import type { AppUpdater } from 'electron-updater'import { IPC } from '../shared/ipc'import {installReadiness,@@ -118,6 +120,26 @@ export interface UpdaterHooks {flushRenderer?: () => Promise<unknown>}+export interface UpdaterDeps {+ /**+ * Returns electron-updater's `autoUpdater`. Called at most once per `initUpdater`, and only on a+ * path that uses it: at init for a build with a feed, on a restart click in dev, never for a+ * `no-channel` build. Injectable because vitest's `vi.mock` does not reach a `require()` — the+ * tests pass their double here. The default is a plain `require`, which electron-vite leaves+ * verbatim in the CJS main bundle (electron-updater is an externalised dependency), as it does+ * for `require('ws')` in relay-socket.ts.+ */+ loadUpdater?: () => AppUpdater+}++/** The production loader. A property read, not a default-import + destructure (that returned+ * undefined under electron-vite v5's CJS interop); the `autoUpdater` getter constructs the+ * platform updater (MacUpdater, NsisUpdater…) on first access, so that cost moves here too. */+function requireAutoUpdater(): AppUpdater {+ // eslint-disable-next-line @typescript-eslint/no-var-requires+ return (require('electron-updater') as typeof import('electron-updater')).autoUpdater+}+export interface UpdaterHandle {/** The one guarded restart-to-update path, shared by the card (IPC) and the tray item. */restartToUpdate(): void@@ -130,7 +152,9 @@ export interface UpdaterHandle {* shipped — an update finishing downloading after a close→dock-reopen crashed the main process on* `win.isFocused()`.*/-export function initUpdater(hooks: UpdaterHooks = {}): UpdaterHandle {+export function initUpdater(hooks: UpdaterHooks = {}, deps: UpdaterDeps = {}): UpdaterHandle {+ let loaded: AppUpdater | undefined+ const updater = (): AppUpdater => (loaded ??= (deps.loadUpdater ?? requireAutoUpdater)())const send = (channel: string, payload?: unknown) => sendToMain(channel, payload)const flushRenderer =hooks.flushRenderer ?? (() => requestRendererFlush(getMainWindow()?.webContents, ipcMain))@@ -201,7 +225,7 @@ export function initUpdater(hooks: UpdaterHooks = {}): UpdaterHandle {restart.beforeRestartRan = truehooks.onBeforeRestart?.()try {- autoUpdater.quitAndInstall()+ updater().quitAndInstall()} catch (err) {console.error('[updater] quitAndInstall failed:', err)abortRestart(err instanceof Error ? err.message : String(err))@@ -220,7 +244,7 @@ export function initUpdater(hooks: UpdaterHooks = {}): UpdaterHandle {if (delivery === 'dev') {// Historical dev behaviour: nothing is ever staged, the call is a logged no-op.hooks.onBeforeRestart?.()- autoUpdater.quitAndInstall()+ updater().quitAndInstall()return}if (restart.requested) return@@ -253,7 +277,9 @@ export function initUpdater(hooks: UpdaterHooks = {}): UpdaterHandle {)}- // Always available, even in dev: current version, manual check, restart.+ // Always available, even in dev: current version, manual check, restart. Registered BEFORE+ // electron-updater is loaded and whatever the build: the renderer invokes these on mount, and an+ // invoke with no handler rejects — the lazy load must never delay or skip them.ipcMain.handle(IPC.appGetVersion, () => app.getVersion())ipcMain.on(IPC.appRestartToUpdate, () => restartToUpdate())// A renderer that (re)loads after the one-time announcement — ⌘R, a window recreated after a@@ -279,6 +305,10 @@ export function initUpdater(hooks: UpdaterHooks = {}): UpdaterHandle {return handle}+ // From here on the build has a feed: load electron-updater now (the one place it is loaded on+ // these builds), after every IPC handler above is registered.+ const autoUpdater = updater()+// A Linux .deb/.rpm install (no APPIMAGE env) cannot self-install and would re-download the// full AppImage every 6h only to throw on install; the unsigned Windows beta must not// self-install. Degrade both to a manual-download link: don't auto-download; surface