# SevenTTY

SSH client, local shell, and terminal emulator for classic Mac OS 7/8/9.
Fork of [ssheven](https://github.com/cy384/ssheven) by cy384. GitHub: LXXero/SevenTTY

## Build Environment

### Retro68 Cross-Compiler

SevenTTY builds with [Retro68](https://github.com/autc04/Retro68/), a GCC cross-compiler for classic Macintosh. The toolchain lives at:

```
~/git/Retro68-build/toolchain/
├── m68k-apple-macos/     # 68K toolchain
│   └── cmake/retro68.toolchain.cmake
└── powerpc-apple-macos/  # PPC toolchain
    └── cmake/retroppc.toolchain.cmake
```

Retro68 provides Universal Interfaces headers (Mac Toolbox APIs) and the `add_application()` cmake macro which handles Mac resource forks, MacBinary packaging, and HFS disk image creation.

### Building

Always delete and recreate build directories when cmake config changes (target rename, new files, etc.) — stale CMakeCache.txt causes cryptic errors.

```bash
# 68K build
mkdir build-m68k && cd build-m68k
cmake .. -DCMAKE_TOOLCHAIN_FILE=~/git/Retro68-build/toolchain/m68k-apple-macos/cmake/retro68.toolchain.cmake
cmake --build . --parallel $(nproc)

# PPC build
mkdir build-ppc && cd build-ppc
cmake .. -DCMAKE_TOOLCHAIN_FILE=~/git/Retro68-build/toolchain/powerpc-apple-macos/cmake/retroppc.toolchain.cmake
cmake --build . --parallel $(nproc)

# Fat binary (both architectures combined)
./build-fat.bash
```

Build outputs: `SevenTTY.bin` (MacBinary), `SevenTTY.dsk` (HFS disk image), `SevenTTY.APPL` (raw application)

### Deploy to QEMU Emulator

```bash
hmount ~/git/quadra800/full-os8.1.hda
hdel :SevenTTY 2>/dev/null
hcopy -m build-m68k/SevenTTY.bin :
humount
# Then run: ~/git/quadra800/run.sh
```

The `hcopy -m` flag reads MacBinary format. The embedded app name comes from the cmake target name (`SevenTTY`). Use `hls -l` to verify files on the HFS image.

## Dependencies (git submodules, built automatically)

- **opentransport-mbedtls** — TLS library patched for classic Mac OS (no real RNG, uses mediocre entropy)
- **opentransport-libssh2** — SSH library patched to use Open Transport instead of BSD sockets
- **libvterm** — terminal emulator library (VT100/xterm), patched with cmake build

Do NOT modify files inside these submodule directories.

## Source File Layout

| File | Lines | Purpose |
|------|-------|---------|
| `app.c` | ~2800 | Main event loop, window/session management, menus, preferences, connection, key batching |
| `app.h` | ~270 | All shared types: `struct session` (incl. `thread_id`), `struct window_context`, `struct console_metrics`, `struct preferences` |
| `console.c` | ~1900 | Terminal drawing (color + fast mode), symbol font, 256-color/RGB, font metrics, scrollback, cursor, mouse selection, tab bar |
| `console.h` | ~42 | Console function prototypes (incl. `output_callback`) |
| `shell.c` | ~10400 | Local shell: 30+ commands (ls, cd, cat, cp, mv, rm, mkdir, ps, free, df, etc.), tab completion, history, FTP client, wget/scp file transfer |
| `shell.h` | ~12 | Shell function prototypes |
| `telnet.c` | ~985 | Telnet and raw TCP (nc): OT connection, telnet IAC negotiation, read threads, inline nc |
| `telnet.h` | ~17 | Telnet/nc function prototypes (incl. `tcp_output_callback`) |
| `net.c` | ~730 | SSH networking: Open Transport TCP, libssh2 session, read thread, known hosts, EAGAIN handling |
| `net.h` | ~12 | Network function prototypes |
| `debug.c` | ~200 | libssh2 and Open Transport error code to string conversion |
| `debug.h` | ~12 | Debug macros: `OT_CHECK()`, `SSH_CHECK()` |
| `unicode.h` | ~4400 | Mac Roman ↔ Unicode translation table (auto-generated by `tools/generate_unicode_table.py`) |
| `symbolfont.r` | ~1660 | Custom bitmap NFNT/FOND resource for box drawing, block elements, geometric shapes (auto-generated by `tools/generate_symbolfont.py`) |
| `constants.r` | ~135 | All `#define` constants: version, resource IDs, menu IDs, dialog IDs |
| `resources.r` | ~632 | Rez resource definitions: dialogs, alerts, menus, SIZE, version, icons |
| `icons.r` | ~490 | Application and file icon pixel data |
| `build-fat.bash` | ~48 | Script to build combined 68K+PPC fat binary |
| `tools/generate_symbolfont.py` | ~1180 | Generates `symbolfont.r` bitmap font at 7 sizes |
| `tools/generate_unicode_table.py` | ~370 | Generates `unicode.h` translation table |
| `tools/itermcolors2sttheme.py` | ~36 | Converts iTerm2 color schemes to `.sttheme` format |

## Architecture

### Multi-Window / Multi-Session

```
windows[MAX_WINDOWS=8]        sessions[MAX_SESSIONS=8]
┌─────────────────────┐       ┌──────────────────────┐
│ window_context      │       │ session              │
│   win (WindowPtr)   │──────▶│   type (SSH/LOCAL)   │
│   session_ids[]     │       │   vterm/vts          │
│   num_sessions      │       │   scrollback[][]     │
│   active_session_idx│       │   shell state        │
│   size_x, size_y    │       │   SSH channel/endpoint│
└─────────────────────┘       │   window_id          │
                              └──────────────────────┘
```

- Each window has its own tab bar and can hold multiple sessions
- Sessions are `SESSION_SSH`, `SESSION_TELNET`, `SESSION_NETCAT` (threaded network I/O) or `SESSION_LOCAL` (shell interpreter)
- Telnet opens in a new tab; nc runs inline in the local shell session (same vterm, thread reads into it)
- Convenience macros: `ACTIVE_WIN`, `ACTIVE_S` — use these to access current window/session
- Helper functions: `find_window_context(WindowPtr)`, `window_for_session(idx)`, `active_session_global()`

### Scrollback

Compact ring buffer per session: `struct sb_cell scrollback[100][80]` = 32KB/session.
Each `sb_cell` is 4 bytes (char, fg, bg, attrs) vs ~36 bytes for `VTermScreenCell`.

- `sb_pushline()` / `sb_popline()` — vterm callbacks when lines scroll off screen
- `get_cell_scrolled()` — returns cell from scrollback or live screen based on `scroll_offset`
- Shift+PageUp/Down to scroll, any other key snaps back to live

### Local Shell

Shell commands are dispatched in `shell_execute()` via a long if/else chain (not a function table).
Each command is `static void cmd_foo(int idx, int argc, char* argv[])` where `idx` is the session index.

Output goes through `vt_write(idx, str)` (null-terminated) and `vt_print_long(idx, num)`.
The shell has its own working directory per session (`shell_vRefNum`, `shell_dirID`).

### SSH Threading

SSH uses cooperative threads via the Mac Thread Manager. The read thread polls `libssh2_channel_read()` and writes data into the session's vterm. The main thread handles keyboard input → `libssh2_channel_write()`.

Thread lifecycle is tracked per session via `thread_id` (ThreadID). `session_reap_thread()` safely disposes threads using `GetThreadState()`/`DisposeThread()`. The event loop calls `reap_detached_sessions()` periodically to clean up leaked resources from sessions whose threads finished after the session was closed.

### Key Repeat Batching

Rapid key repeat (autoKey events) for network sessions is batched to prevent escape sequence fragmentation. The vterm output callback is nulled, up to 5 pending autoKey events are drained from the Mac event queue, then the accumulated vterm output is flushed in a single `session_write()`. This prevents remote TUIs from misinterpreting a bare `ESC` (split from `ESC [ B`) as an Escape keypress. The batch cap (4 extra events) prevents TUI list overshoot.

### Symbol Font

Custom bitmap font (`symbolfont.r`) for Unicode characters that don't exist in Mac Roman: box drawing (U+2500-U+257F), block elements (U+2580-U+259F), geometric shapes, and some CP437 characters. Generated by `tools/generate_symbolfont.py` at 7 sizes (9, 10, 12, 14, 18, 24, 36pt) with metrics matched to Monaco. Font family ID 29183 (high random value to avoid classic Mac font ID conflicts). The renderer switches fonts mid-draw-run when a symbol character is encountered (flagged in scrollback attrs bit 4).

## Classic Mac OS API Quick Reference

### Memory Manager (used by `free` command)
- `ApplicationZone()`, `SystemZone()` — heap zone pointers
- `FreeMem()`, `FreeMemSys()` — free bytes in app/system heap
- `MaxBlock()` — largest contiguous free block
- `TempFreeMem()`, `TempMaxMem(&grow)` — temporary memory (outside app heap)

### Process Manager (used by `ps` command)
- `GetNextProcess(&psn)` — iterate running processes
- `GetProcessInformation(&psn, &info)` — get ProcessInfoRec
- `MacGetCurrentProcess(&psn)` — identify self

### File Manager (used by shell file commands)
- `PBHGetVInfo()` — volume info (for `df`)
- `PBGetCatInfo()` — file/folder metadata
- `HCreate()`, `HDelete()`, `HRename()`, `FileCopy()` — file operations
- `FSSpec` + `vRefNum`/`dirID` — how classic Mac OS identifies files

### Open Transport (networking)
- `OTOpenEndpoint()` — create TCP endpoint
- `OTConnect()` — TCP connect
- `OTSnd()` / `OTRcv()` — send/receive data

## Constants Naming Convention

All constants live in `constants.r` (shared by C code and Rez resources):

- `APP_*` — application-level: version, partition size, icon IDs
- `SSH_BUFFER_SIZE` — network buffer size
- `DEFAULT_TERM_STRING` — terminal type ("xterm-256color")
- `MBAR_MAIN` — menu bar resource ID
- `MENU_*` — menu resource IDs
- `FMENU_*` — File menu item indices
- `DLOG_*` / `DITL_*` / `ALRT_*` — dialog/alert resource IDs
- `CNTL_PREF_*` — preferences dialog control IDs

## Color Theme System

### Architecture
- 16-color ANSI palette stored in `prefs.palette[16]` as `RGBColor` (16-bit per channel)
- Theme bg/fg/cursor stored in `prefs.theme_fg`, `prefs.theme_bg`, `prefs.theme_cursor`
- Original theme colors (before overrides) stored in `prefs.orig_theme_bg`, `prefs.orig_theme_fg`
- Color overrides: `prefs.fg_color`/`prefs.bg_color` = `COLOR_FROM_THEME` (-1) means use theme colors, otherwise a QD color constant
- Built-in palettes: `init_dark_palette()` (black bg, VGA ANSI), `init_light_palette()` (white bg, VGA ANSI)

### Theme File Format (`.sttheme`)
20 lines of text, parsed by `load_theme_file()`:
```
STTY1           <- magic
000000          <- background (6-char hex, 8-bit per channel)
F2F2F2          <- foreground
4D4D4D          <- cursor
2A2A2A          <- ANSI 0 through ANSI 15 (16 lines)
...
```
Converter: `tools/itermcolors2sttheme.py`

### Prefs Persistence (Resource Fork)
- Prefs stored as `'PREF'` resource 128 in `System Folder:Preferences:SevenTTY Preferences`
- Binary `struct disk_prefs` — no text parsing, no field desync bugs
- `save_prefs()`: `FSpCreateResFile` / `FSpOpenResFile` / `AddResource` / `WriteResource`
- `load_prefs()`: `FSpOpenResFile` / `Get1Resource` / size+version check / `ReleaseResource`
- Handles old text-based prefs file: if `FSpOpenResFile` fails, deletes and recreates as resource file
- Version field allows future migration; mismatched version silently uses defaults
- Flow: `init_prefs()` → `load_prefs()` → `apply_color_overrides()` at startup

### Rendering (console.c)
- Sentinel values: `COLOR_DEFAULT_FG=-1`, `COLOR_DEFAULT_BG=-2` (negative ints, no collision with 0-255 palette)
- Packed RGB: `COLOR_PACK_RGB(r,g,b)` sets bit 24, always > 255 so no collision with palette or sentinels
- `extract_fg()`/`extract_bg()`: Convert VTermScreenCell color to abstract ID (sentinel, palette index 0-255, or packed RGB)
- `set_draw_fg()`/`set_draw_bg()`: Map sentinel to `prefs.theme_fg`/`theme_bg`, 0-15 to `prefs.palette[]`, 16-231 to xterm 6x6x6 cube, 232-255 to grayscale ramp, packed RGB to direct color. **Must handle BOTH sentinels** — reverse video swaps fg↔bg
- `xterm256_to_rgb()`: Converts palette index 16-255 to Mac `RGBColor` (16-bit per channel)
- `rgb_to_xterm256()`: Approximates 8-bit RGB to nearest xterm index for scrollback storage (scrollback only has 1 byte per color)
- Uses `RGBForeColor()`/`RGBBackColor()` exclusively (Color QuickDraw). **Never use indexed `BackColor()`/`ForeColor()`** — on a CGrafPort, once RGB colors are set, indexed calls don't reliably override the RGB fields, causing stale color bleed
- `draw_screen_fast()` (monochrome mode) unchanged, ignores theme colors

### Dirty Row Tracking
- Per-session fields: `dirty_start_row`, `dirty_end_row` (inclusive/exclusive range), `force_full_redraw`, `scrollbar_dirty`
- `mark_dirty(session, start, end)` — union with existing dirty range; `mark_full_dirty()` — sets force flag; `clear_dirty()` — resets after draw
- `console_mark_full_dirty(session_idx)` — public, called from app.c on resize/tab switch/update events
- `draw_screen_color()` and `draw_screen_fast()` only loop `dirty_start_row..dirty_end_row` instead of all rows
- Performance: cursor blink redraws 1 row instead of 24 (~24x fewer cells), single char echo = 1 row
- Every full-window `InvalRect` path must also call `mark_full_dirty` or `console_mark_full_dirty`

### Vertical Scrollbar
- `ControlHandle vscroll` per `window_context`, created in `new_window()` with `scrollBarProc`
- Window width += 16px to accommodate scrollbar; terminal `size_x` computed from `(width - 4 - 16) / cell_width`
- `sync_scrollbar(wc)` maps `scroll_offset` ↔ control value, called from scroll functions and event handlers
- `scrollbar_dirty` flag set from `sb_pushline`/`sb_popline` callbacks (no control API from worker threads); main event loop drains flag
- Scrollbar click handling: `FindControl` → `TrackControl` with action proc for arrows/page parts, direct value read for thumb
- `ControlActionUPP` cached as module-level global (created once at init, disposed at shutdown)

### GWorld Offscreen Row Buffer (Flicker-Free Rendering)
- 32-bit GWorld (`g_row_gworld`) holds one row; each dirty row composed offscreen then blitted via `CopyBits`
- `ensure_row_gworld(width, height)` — creates/reuses GWorld; `cleanup_row_gworld()` — disposed at app exit
- **CRITICAL: `SetGWorld(g_row_gworld, saved_gd)` — pass the WINDOW's GDevice, NOT NULL**
  - `SetGWorld(gw, NULL)` uses GWorld's own GDevice which has `gdType=clutType` (indexed)
  - Color2Index then does CLUT lookup instead of direct RGB truncation → shifted/wrong colors
  - Apple TN: "Attaching direct pixMaps to indexed devices often yields rather blue results"
  - `saved_gd` obtained from `GetGWorld(&saved_port, &saved_gd)` before switching to GWorld
- Background fills: `set_draw_bg()` + `EraseRect()` (works correctly with window's directType GDevice)
- Text rendering: `TextMode(srcOr)` — paints foreground pixels only, background from EraseRect
- Per-row pipeline: SetGWorld → EraseRect (bg) → per-run EraseRect+DrawText → SetGWorld back → CopyBits
- CopyBits: `(BitMap*)*row_pm` → `&wc->win->portBits`, srcCopy, NULL region
- Cursor drawn directly on window after CopyBits (InvertRect is already atomic)
- Memory: ~13KB at 8bpp, ~38KB at 24bpp for one row buffer. Negligible
- Graceful degradation: if `NewGWorld` or `LockPixels` fails, falls back to direct window drawing

### VTerm Color Internals
- `VTermColor` is a tagged union: `uint8_t type` at offset 0, `indexed.idx`/`rgb.red` at offset 1 (overlap!)
- Type flags: `VTERM_COLOR_RGB=0x00`, `VTERM_COLOR_INDEXED=0x01`, `VTERM_COLOR_DEFAULT_FG=0x02`, `VTERM_COLOR_DEFAULT_BG=0x04`
- After `vterm_state_reset` → `vterm_state_newpen`: defaults are **RGB** not indexed: `default_fg={type=0x02, rgb=(240,240,240)}`, `default_bg={type=0x04, rgb=(0,0,0)}`
- `vterm_screen_set_default_colors()` updates screen pen AND existing buffer cells (use this, not state-level)
- `vterm_state_set_default_colors()` only updates state internals (insufficient alone)
- In `setup_session_vterm()`: MUST call `vterm_screen_reset()` BEFORE setting default colors, otherwise reset undoes them

### Bugs Fixed
- **sscanf prefs parsing catastrophe**: The original `load_prefs` used one giant `sscanf` with `\n` in the format. In C, `\n` in scanf matches ANY whitespace, so empty fields (hostname, username) caused all subsequent fields to desync — "THEME" ended up as username, hex data in other fields. Fix: per-line `read_line()` parsing.
- **read_line multi-newline skip**: `read_line()` originally skipped ALL consecutive `\n`/`\r`, merging empty lines. Empty privkey+pubkey fields got collapsed. Fix: skip exactly one line ending (`\r`, `\n`, or `\r\n`).
- **Scrollback color type fields**: `get_cell_scrolled()` and `sb_popline()` set `cell->fg.indexed.idx` but not the `type` field — type stayed 0 from memset, so `VTERM_COLOR_IS_INDEXED` returned false and all scrollback colors were lost. Fix: set `VTERM_COLOR_INDEXED` or `VTERM_COLOR_DEFAULT_FG/BG` type flags.
- **extract_fg/bg false defaults**: `extract_fg` treated indexed color 7 as default, `extract_bg` treated indexed color 0 as default. This incorrectly converted explicit `\033[37m`/`\033[40m` ANSI colors to theme fg/bg. Fix: only use `VTERM_COLOR_IS_DEFAULT_FG/BG` flag check.
- **Paul Millr bg = 000000**: Same as default dark palette, making theme load failures invisible. Use Adventure Time (bg=1E1C44) or Atelier Sulphurpool (bg=202746) to verify theme bg rendering.
- **Corrupt prefs file**: If a buggy version saved garbled data, all subsequent loads are broken. Delete `System Folder:Preferences:SevenTTY Preferences` to reset.
- **Reverse video sentinel leak**: `set_draw_bg()` only checked for `COLOR_DEFAULT_BG`, so when reverse video passed `COLOR_DEFAULT_FG` (0xFE), it fell through to `palette[0xFE & 0x0F]` = palette[14] = bright cyan. Fix: both `set_draw_fg` and `set_draw_bg` must handle both `COLOR_DEFAULT_FG` and `COLOR_DEFAULT_BG`.
- **Indexed QuickDraw color bleed**: `draw_tab_bar()` used `BackColor(whiteColor)` which doesn't override the RGB fields on a CGrafPort after `RGBBackColor()` was used. Fix: use `RGBBackColor()`/`RGBForeColor()` everywhere, never indexed calls.
- **Numpad Enter = Ctrl+C**: `kEnterCharCode` = 0x03 = ETX, same value as Ctrl+C. Shell's `if (c == 3)` caught numpad Enter. Fix: only treat 0x03 as Ctrl+C when `controlKey` modifier is set.
- **Right arrow = Ctrl+]**: `kRightArrowCharCode` = 0x1D = GS, same as Ctrl+]. Fix: check virtual keycode 0x1E (physical `]` key), not charcode.
- **Right-Ctrl sends no modifier**: QEMU sends control codes without `controlKey` modifier flag for right-Ctrl. Fix: heuristic — if charcode < 32, no controlKey, and virtual keycode maps to the letter that would produce that code, treat as Ctrl+key.
- **nc inline stuck after cancel**: If `nc_inline_disconnect` can't wait for thread to finish, `recv_buffer` stays non-NULL, trapping shell in nc mode forever. Fix: force-free buffers from main thread (safe under cooperative threading — thread is suspended).
- **Thread must set DONE before returning**: Both `telnet_read_thread` and `nc_read_thread` must set `thread_state = DONE` at end of all exit paths, otherwise disconnect functions can't detect thread completion.
- **Escape sequence fragmentation on key repeat**: Holding arrow keys sent each `ESC [ B` as a separate SSH write. Remote TUIs (e.g. `claude --resume`) split reads mid-sequence, interpreting bare `ESC` as Escape keypress. Fix: batch up to 5 autoKey events into single coalesced write. Cap at 4 extra events to prevent TUI list overshoot.
- **Session teardown crash (Type 1 bus error)**: Key batching code accessed `sessions[sid].vterm` after `handle_keypress` could tear down the session (e.g. Option-D disconnect). Fix: re-check `vterm != NULL` and `thread_state == OPEN` before flushing.
- **Telnet callback restore after batching**: Key batching always restored `output_callback` (SSH), but telnet sessions use `tcp_output_callback`. Fix: check session type when restoring.
- **ssh_write_s EAGAIN = fatal disconnect**: `libssh2_channel_write` returns `LIBSSH2_ERROR_EAGAIN` (-37) in non-blocking mode, but was treated as fatal (r < 1). Fix: yield and retry on EAGAIN.
- **ssh_write_s partial writes**: Single `libssh2_channel_write` call could return fewer bytes than requested. Remaining bytes silently dropped. Fix: loop until all bytes written.
- **Right-Ctrl broken in local shell**: Ctrl+C (cancel line), Ctrl+D (close tab), and nc disconnect all required `controlKey` modifier, but QEMU right-Ctrl sends charcode without modifier. Fix: accept bare charcode 3/4, exclude numpad Enter (vkeycode 0x4C) and End key (vkeycode 0x77) by vkeycode.
- **Thread lifecycle leaks**: Session slots reused while thread still running. `DisposeThread` never called. Fix: track `thread_id` per session, require `thread_id == kNoThreadID` for slot reuse, `session_reap_thread()` for safe disposal.
- **Copy selection memory leak**: `get_selection()` allocated buffer but caller never freed it. Fix: `free(selection)` after `PutScrap`.
- **GWorld offscreen color mapping**: `SetGWorld(gworld, NULL)` sets TheGDevice to the GWorld's own device, which has `gdType=clutType` (indexed). Color2Index uses CLUT lookup instead of direct RGB truncation, producing completely wrong colors (blue→orange, default fg invisible on dark bg). Fix: `SetGWorld(gworld, saved_gd)` — pass the window's screen GDevice (directType) so Color QuickDraw maps RGB correctly. Also, `PaintRect` + `PenPat(&qd.white)` doesn't reliably fill backgrounds in GWorlds with a foreign GDevice; use `set_draw_bg()` + `EraseRect()` instead.

## Gotchas and Lessons Learned

- **Memory is precious**: 2MB partition. Scrollback uses compact 4-byte cells, not full VTermScreenCells (would be ~950KB/session)
- **Page keys as control chars**: `kPageDownCharCode` = 0x0C = form feed. Must intercept page up/down/home/end in `shell_input()` before they reach vterm
- **Shift keys are separate bits**: `shiftKey` (0x0200) is left shift only. Must check `(shiftKey | rightShiftKey)` for both
- **`hcopy -m` filename length**: HFS has a 31-char filename limit. If the source path is too long, copy to /tmp first with a shorter name
- **cmake cache after renames**: Always nuke `build-*/` when renaming source files or the cmake target
- **C89 only**: Retro68 targets C89/C90. No `//` comments in headers shared with Rez, no mixed declarations and code, no VLAs
- **Rez resource compiler**: `.r` files are processed by Rez, not the C compiler. They share `constants.r` via `#include` but use Rez syntax for resource definitions
- **Thread Manager**: Required for SSH (cooperative multitasking). System 7.5+ has it built in; 7.1-7.4 need the extension
- **Open Transport**: Required for networking. Not available on very old System 7 installs. Local shell works without it
- **kEnterCharCode = 0x03**: Numpad Enter char code is ETX (same as Ctrl+C). Always check `controlKey` modifier to distinguish them
- **Never use indexed `BackColor()`/`ForeColor()`**: On CGrafPort (color windows), use `RGBBackColor()`/`RGBForeColor()` exclusively. Indexed calls don't reliably override RGB state
- **`#include <Resources.h>`**: Required for Resource Manager calls (`FSpCreateResFile`, `FSpOpenResFile`, `Get1Resource`, `AddResource`, etc.)
- **Cooperative threading = no true concurrency**: Only one thread runs at a time. Safe to free shared buffers from main thread as long as the thread checks for NULL when it resumes. But never set `thread_state = DONE` from main thread — only the thread itself should do that (prevents use-after-free of endpoint)
- **OTCancelSynchronousCalls from notifier**: The reliable way to cancel a blocking `OTConnect`. Set a deadline, check it in `tcp_ot_notifier` on `kOTSyncIdleEvent`, call `OTCancelSynchronousCalls` from there
- **OTUseSyncIdleEvents must be false during read loop**: Otherwise `OTRcv` blocks instead of returning `kOTNoDataErr`
- **`#include <Threads.h>`**: Required for `YieldToAnyThread()` — needed in any file that uses threading
- **libssh2 non-blocking mode**: Session is set non-blocking (`libssh2_session_set_blocking(s, 0)`). All libssh2 calls can return `LIBSSH2_ERROR_EAGAIN` (-37) which must be retried, not treated as fatal
- **vterm output callback vs buffer**: When outfunc is set, vterm calls it immediately. When NULL, buffers internally (4096 bytes). Drain with `vterm_output_read()`. Used by key batching to coalesce writes
- **Restoring vterm output callback**: SSH sessions use `output_callback`, telnet sessions use `tcp_output_callback`, local sessions use `local_output_callback`. Must restore the correct one per session type
- **autoKey batching cap**: Draining ALL pending autoKey events causes TUI list overshoot (sends too many arrows at once). Cap at 4 extra events per batch
- **Charcode 3 = numpad Enter AND Ctrl+C**: Use vkeycode 0x4C to distinguish. Charcode 4 = End key AND Ctrl+D: use vkeycode 0x77 to distinguish. This applies to both SSH handler (app.c) and local shell (shell.c)
- **session_reap_thread safety**: Never dispose the currently-running thread. Check `MacGetCurrentThread()` first. Handle `threadNotFoundErr` (thread already gone). Force-stop only as last resort
- **Symbol font rendering**: `symbolfont.r` defines NFNT resources at IDs 29183-29189. Font family FOND at ID 29183, name "SevenTTY Symbols". Uses a high random ID to avoid classic Mac font ID conflicts with system or third-party fonts. Glyph metrics must exactly match Monaco at each size for seamless tiling
- **GWorld + SetGWorld GDevice parameter**: Always `SetGWorld(gw, window_gd)`, NEVER `SetGWorld(gw, NULL)`. NULL uses the GWorld's own GDevice (often clutType/indexed), causing Color2Index to use CLUT lookup instead of direct RGB. The window's GDevice is directType and gives correct color mapping. Get it with `GetGWorld(&saved_port, &saved_gd)` before switching. See Apple TN "Realistic Color for Real-World Applications" (1990)
- **GWorld background fills**: Use `RGBBackColor()` + `EraseRect()`, not `PaintRect` + `PenPat(&qd.white)` hack. The PenPat trick doesn't work reliably in GWorlds with a foreign (window) GDevice. EraseRect works fine once the correct directType GDevice is active
