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(editor): stop the Monaco TS/JS worker once no TS/JS model remains
Brandon Bridges95c1ebfdf0e0
diff --git a/CLAUDE.md b/CLAUDE.mdindex 99b3716bb..afc51301f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2404,6 +2404,14 @@ raw-HTML tokens as escaped TEXT (a program's `<stdin>` is not markup; parsed asstripped it) and trims capture-pane's trailing padding. The escape is on the `html` token, never aglobal pre-escape of `<`, which would double-escape code spans/fences.+**The TS/JS worker is reaped, not idled** (`renderer/editor/tsWorkerReaper.ts`, audit #18). Monaco+0.57 stops the css/html/json workers after 2 min idle but never the TypeScript one (separate TS and JS+managers can pin two compiler isolates, order of 70-100 MB each). monaco-setup stops it with a no-op+`setCompilerOptions` on `monaco.typescript.*Defaults` (`onDidChange` → `_stopWorker`; the next request+restarts it lazily) 2 min after the last TS/JS model is disposed or changes language.+`noSemanticValidation` does not stop it. This only works if every node **disposes its models on+unmount**: one leaked `.ts` model pins the worker for the session.+**The rendered-Markdown font is a setting** (`markdownFontFamily` / `markdownFontSize`, Settings →Appearance; `@shared/markdown-font`). App.tsx publishes it as `--md-font-family` / `--md-font-size`on <html>, plus `--md-code-font-family` = the TERMINAL font family; styles.css keeps the defaults ondiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b12c54587..9f6c9532d 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1372,6 +1372,8 @@ bite most often:hibernation and the WebGL budget.- Search big in-memory text with one escaped `RegExp(q, 'iu')` per query, never `toLowerCase()`per entry (transcript index: 20-52 ms + 7-15 MB garbage → 2-13 ms + 0 MB per search).+- Dispose every Monaco model your node creates when it unmounts. The TS/JS worker (a whole+ compiler isolate) is only stopped once no TS/JS model is left (`renderer/editor/tsWorkerReaper.ts`).**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 thediff --git a/src/renderer/editor/monaco-setup.ts b/src/renderer/editor/monaco-setup.tsindex 0be8dfbdb..90850bb7f 100644--- a/src/renderer/editor/monaco-setup.ts+++ b/src/renderer/editor/monaco-setup.ts@@ -4,6 +4,7 @@ import JsonWorker from 'monaco-editor/language/json/json.worker.js?worker'import CssWorker from 'monaco-editor/language/css/css.worker.js?worker'import HtmlWorker from 'monaco-editor/language/html/html.worker.js?worker'import TsWorker from 'monaco-editor/language/typescript/ts.worker.js?worker'+import { createTsWorkerReaper } from './tsWorkerReaper'// Bundle Monaco's language workers locally (no CDN) so it works offline in Electron.// The un-prefixed paths are monaco >= 0.56 'exports' entries ("./*" -> "./esm/vs/*.js");@@ -18,4 +19,28 @@ self.MonacoEnvironment = {}}+// The TS/JS worker never idles out on its own (audit #18, startup-4): stop it once the last+// TS/JS model is gone. `monaco.typescript` is the 0.57 namespace; `monaco.languages.typescript`+// is a deprecated stub there. See tsWorkerReaper.ts for the mechanism and the grace period.+const tsDefaults = {+ typescript: monaco.typescript.typescriptDefaults,+ javascript: monaco.typescript.javascriptDefaults+} as const+const tsWorkerReaper = createTsWorkerReaper({+ liveLanguageIds: () => monaco.editor.getModels().map((m) => m.getLanguageId()),+ stopWorker: (language) => {+ const defaults = tsDefaults[language]+ defaults.setCompilerOptions(defaults.getCompilerOptions())+ }+})+// Models created before this ran (none today: this module is what loads Monaco) would be missed;+// seed from the live list so the reaper never under-counts.+for (const model of monaco.editor.getModels()) tsWorkerReaper.modelEntered(model.getLanguageId())+monaco.editor.onDidCreateModel((model) => tsWorkerReaper.modelEntered(model.getLanguageId()))+monaco.editor.onWillDisposeModel((model) => tsWorkerReaper.modelLeft(model.getLanguageId()))+monaco.editor.onDidChangeModelLanguage(({ model, oldLanguage }) => {+ tsWorkerReaper.modelLeft(oldLanguage)+ tsWorkerReaper.modelEntered(model.getLanguageId())+})+export { monaco }diff --git a/src/renderer/editor/tsWorkerReaper.test.ts b/src/renderer/editor/tsWorkerReaper.test.tsnew file mode 100644index 000000000..64c60a691--- /dev/null+++ b/src/renderer/editor/tsWorkerReaper.test.ts@@ -0,0 +1,113 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { createTsWorkerReaper, TS_WORKER_STOP_GRACE_MS, type TsWorkerLanguage } from './tsWorkerReaper'++// The reaper's decision, driven the way monaco-setup.ts drives it: `live` stands in for+// `editor.getModels()`, and — like Monaco's `onWillDisposeModel` — a model is still in `live`+// when `modelLeft` fires and only removed after.+describe('tsWorkerReaper (audit #18: stop the TS/JS worker once no TS/JS model remains)', () => {+ let live: string[]+ let stopped: TsWorkerLanguage[]+ let reaper: ReturnType<typeof createTsWorkerReaper>++ const open = (language: string): void => {+ live.push(language)+ reaper.modelEntered(language)+ }+ const close = (language: string): void => {+ reaper.modelLeft(language) // fires before the model leaves getModels()+ live.splice(live.indexOf(language), 1)+ }++ beforeEach(() => {+ vi.useFakeTimers()+ live = []+ stopped = []+ reaper = createTsWorkerReaper({ liveLanguageIds: () => live, stopWorker: (l) => stopped.push(l) })+ })+ afterEach(() => {+ reaper.dispose()+ vi.useRealTimers()+ })++ it('stops the TS worker after the grace period once the last TS model is disposed', () => {+ open('typescript')+ close('typescript')+ vi.advanceTimersByTime(TS_WORKER_STOP_GRACE_MS - 1)+ expect(stopped).toEqual([])+ vi.advanceTimersByTime(1)+ expect(stopped).toEqual(['typescript'])+ })++ it('does not stop while another model of the language is live (DiffNode: one of two models gone)', () => {+ open('typescript')+ open('typescript')+ close('typescript')+ vi.advanceTimersByTime(TS_WORKER_STOP_GRACE_MS)+ expect(stopped).toEqual([])+ })++ it('does not stop when a TS file is reopened inside the grace window (switching files)', () => {+ open('typescript')+ close('typescript')+ vi.advanceTimersByTime(TS_WORKER_STOP_GRACE_MS / 2)+ open('typescript')+ vi.advanceTimersByTime(TS_WORKER_STOP_GRACE_MS)+ expect(stopped).toEqual([])+ })++ it('treats TS and JS separately: JS keeps its worker while a JS model is live', () => {+ open('typescript')+ open('javascript')+ close('typescript')+ vi.advanceTimersByTime(TS_WORKER_STOP_GRACE_MS)+ expect(stopped).toEqual(['typescript'])+ close('javascript')+ vi.advanceTimersByTime(TS_WORKER_STOP_GRACE_MS)+ expect(stopped).toEqual(['typescript', 'javascript'])+ })++ it('stops both when both go, with one timer for repeated leaves (one stop each, not N)', () => {+ open('typescript')+ open('typescript')+ open('javascript')+ close('typescript')+ close('javascript')+ close('typescript')+ vi.advanceTimersByTime(TS_WORKER_STOP_GRACE_MS)+ expect(stopped.sort()).toEqual(['javascript', 'typescript'])+ expect(vi.getTimerCount()).toBe(0)+ })++ it('counts a language change away from TS as leaving', () => {+ open('typescript')+ reaper.modelLeft('typescript')+ live[0] = 'markdown'+ reaper.modelEntered('markdown')+ vi.advanceTimersByTime(TS_WORKER_STOP_GRACE_MS)+ expect(stopped).toEqual(['typescript'])+ })++ it('never kicks a language that has no worker: other languages, or TS already stopped', () => {+ open('json')+ close('json')+ expect(vi.getTimerCount()).toBe(0)+ open('typescript')+ close('typescript')+ vi.advanceTimersByTime(TS_WORKER_STOP_GRACE_MS)+ expect(stopped).toEqual(['typescript'])+ // Already stopped and nothing reopened: a stray leave event must not stop it again.+ reaper.modelLeft('typescript')+ vi.advanceTimersByTime(TS_WORKER_STOP_GRACE_MS)+ expect(stopped).toEqual(['typescript'])+ })++ it('re-arms after a stop: a TS file opened later is reaped again when it closes', () => {+ open('typescript')+ close('typescript')+ vi.advanceTimersByTime(TS_WORKER_STOP_GRACE_MS)+ open('typescript')+ close('typescript')+ vi.advanceTimersByTime(TS_WORKER_STOP_GRACE_MS)+ expect(stopped).toEqual(['typescript', 'typescript'])+ })+})diff --git a/src/renderer/editor/tsWorkerReaper.ts b/src/renderer/editor/tsWorkerReaper.tsnew file mode 100644index 000000000..8c500cf12--- /dev/null+++ b/src/renderer/editor/tsWorkerReaper.ts@@ -0,0 +1,89 @@+// Stop Monaco's TypeScript / JavaScript worker once no model of that language is left.+//+// Why (audit roadmap #18, startup-4): in monaco-editor 0.57 the css/html/json WorkerManagers stop+// their worker after 2 min idle, but the TypeScript WorkerManager has NO idle path — it only stops+// when its defaults fire `onDidChange` (or on dispose), and it is created with `keepIdleModels`.+// So the first .ts/.tsx/.js file opened in an EditorNode or DiffNode starts a worker isolate holding+// the TS compiler (13.3 MB unminified script), lib.d.ts and a language service for the rest of the+// session; TS and JS have SEPARATE managers, so both can be pinned at once (order of 70-100 MB each,+// unmeasured). The supported way to stop one is a no-op `setCompilerOptions(getCompilerOptions())`:+// `onDidChange` -> `WorkerManager._stopWorker()`, and the next request lazily starts a fresh worker+// with the same options and extra libs (both live on the defaults, not the worker).+// `noSemanticValidation` does NOT stop the worker (REPORT §4.9) — don't reach for it here.+//+// The decision is kept Monaco-free so it is testable in node: monaco-setup.ts passes the real+// model list and the real stop; tests pass fakes and fake timers.++/** The languages whose worker Monaco never idles out. Each has its own WorkerManager. */+export const TS_WORKER_LANGUAGES = ['typescript', 'javascript'] as const+export type TsWorkerLanguage = (typeof TS_WORKER_LANGUAGES)[number]++/**+ * Grace period after the last TS/JS model leaves before the worker is stopped. Matches Monaco's+ * own `STOP_WHEN_IDLE_FOR` (2 min) for the css/html/json workers, so closing one .ts file and+ * opening another — or a project switch that remounts every editor — reuses the warm worker+ * instead of recompiling lib.d.ts. Every model event re-arms it, so it is one timer, not N.+ */+export const TS_WORKER_STOP_GRACE_MS = 2 * 60 * 1000++export interface TsWorkerReaperDeps {+ /** Language ids of every LIVE model (Monaco: `editor.getModels().map(m => m.getLanguageId())`). */+ liveLanguageIds(): readonly string[]+ /** Stop that language's worker (Monaco: the no-op `setCompilerOptions` kick). */+ stopWorker(language: TsWorkerLanguage): void+ setTimer?: (fn: () => void, ms: number) => unknown+ clearTimer?: (handle: unknown) => void+ graceMs?: number+}++export interface TsWorkerReaper {+ /** A model of `language` was created or changed TO `language`: a worker may now exist. */+ modelEntered(language: string): void+ /** A model of `language` is being disposed or changed AWAY from `language`. */+ modelLeft(language: string): void+ /** Cancel any pending check (tests / teardown). */+ dispose(): void+}++function isTsWorkerLanguage(language: string): language is TsWorkerLanguage {+ return (TS_WORKER_LANGUAGES as readonly string[]).includes(language)+}++export function createTsWorkerReaper(deps: TsWorkerReaperDeps): TsWorkerReaper {+ const setTimer = deps.setTimer ?? ((fn: () => void, ms: number) => setTimeout(fn, ms))+ const clearTimer = deps.clearTimer ?? ((h: unknown) => clearTimeout(h as ReturnType<typeof setTimeout>))+ const graceMs = deps.graceMs ?? TS_WORKER_STOP_GRACE_MS+ // Languages that have had a model since their worker was last stopped. Only these are kicked:+ // a no-op setCompilerOptions on a language that never started a worker is harmless, but it is+ // also pointless work (it re-runs that language's diagnostics pass over every model).+ const armed = new Set<TsWorkerLanguage>()+ let timer: unknown = null++ const check = (): void => {+ timer = null+ // Re-read the truth now rather than keeping a counter: `onWillDisposeModel` fires BEFORE the+ // model leaves `getModels()`, so a count taken at the event is off by one, and a file reopened+ // inside the grace window simply shows up here as a live model.+ const live = new Set(deps.liveLanguageIds())+ for (const language of [...armed]) {+ if (live.has(language)) continue+ armed.delete(language)+ deps.stopWorker(language)+ }+ }++ return {+ modelEntered(language) {+ if (isTsWorkerLanguage(language)) armed.add(language)+ },+ modelLeft(language) {+ if (!isTsWorkerLanguage(language) || !armed.has(language)) return+ if (timer !== null) clearTimer(timer)+ timer = setTimer(check, graceMs)+ },+ dispose() {+ if (timer !== null) clearTimer(timer)+ timer = null+ }+ }+}