Heuristic:23blocks OS Ai maestro Terminal Init Once On Mount
| Knowledge Sources | |
|---|---|
| Domains | Terminal, Client |
| Last Updated | 2026-10-26 18:00 GMT |
Overview
Initialise the xterm.js terminal exactly once on component mount with an empty dependency array; never re-add `session.id` to the effect, or the terminal re-initialises and loses state.
Description
The `useTerminal` hook (`hooks/useTerminal.ts`) creates the xterm instance, loads addons, calls `open()`, then `fitAddon.fit()`, inside a single `useEffect` with an empty dependency array `[]`. Adding `session.id` (or any changing value) to that effect would tear down and recreate the terminal on every session switch, discarding scrollback and breaking the WS pipe. Instead, the terminal instance is created once; the WS data source is swapped when the session changes, not the terminal. This is a hard rule in CLAUDE.md: "Terminals initialise once on mount; do not add `session.id` to that effect."
Usage
Use this heuristic for any terminal-emulator-in-React integration. Initialise once; swap data sources, not instances.
The Insight (Rule of Thumb)
- Action: `useEffect(() => { createTerm(); return dispose }, [])` — empty deps.
- Value: One terminal per mount; data source changes feed the existing instance.
- Trade-off: Session-specific resize handling must be done in a separate effect.
Reasoning
xterm.js holds scrollback, addon state, and a DOM attachment. Recreating it on session change resets all of that and flickers. A stable instance with a swappable data source preserves history across session switches while still updating content.