Repository Public
1# SP Term — Architecture23SP Term is a native macOS terminal: Swift 6 (strict concurrency), SwiftUI for the chrome, AppKit for4windows, focus, menus, screens and the terminal view. Minimum system: **macOS 14** (the app relies on5the Observation framework and on SwiftUI APIs introduced in macOS 14; the emulation engine itself6needs macOS 13).78## Modules910```11SP Term.app (App/Sources/SPTerm — AppKit lifecycle, SwiftUI views)12 │13 ├── Packages/SPTermKit core, unit-tested with `swift test`14 │ ├── PTYProcess pseudo-terminal + child process (forkpty → posix_spawn SETEXEC)15 │ ├── TerminalCore session = PTY + emulator view; launch planning, paste/broadcast guards16 │ │ └── SwiftTerm 1.99.2 terminal emulation engine: VT/xterm parser + renderer (MIT, pinned)17 │ ├── WorkspaceKit pure model: recursive split tree, tabs, windows, snapshots, presets18 │ ├── WindowManager pure geometry: placement on displays, reachability, rescue, tiling19 │ ├── SessionStore versioned JSON files, migrations, corruption recovery, opt-in history20 │ ├── SettingsModel preferences (tolerant decoding), key chords21 │ └── DesignSystem themes (original palettes), contrast maths, metrics22 ├── Packages/SPRemoteKit23 │ ├── SSHKit ~/.ssh/config parser, profiles, argv builder for the system ssh/sftp,24 │ │ known_hosts inspector, error classifier (no crypto of its own)25 │ └── GitKit read-only git context (allow-listed subcommands only)26 └── Packages/SPIntelligence27 └── AIAssistant BYOK clients (Anthropic, OpenAI, OpenAI-compatible), Keychain store,28 secret redactor, command risk analyzer, consent gate, network policy29```3031How the names of the brief map to the code: `TerminalParser` and `TerminalRenderer` are the SwiftTerm32engine (integrated, not rewritten — see "Engine choice"); `SPTermApp`, `Settings` (UI) and33`Distribution` live in the app target and `Scripts/`; everything else is a module of the same name.3435Dependency rule: models (`WorkspaceKit`, `WindowManager`, `SettingsModel`, `DesignSystem`) import no UI36framework beyond CoreGraphics types and never touch `NSScreen`/`NSWindow`, which is what lets the37multi-monitor logic be tested with simulated displays.3839## Engine choice4041| Option | Decision |42|---|---|43| Write a VT/xterm emulator from scratch | Rejected: a correct emulator (alternate screen, scroll regions, wide/combining text, mouse modes, bracketed paste, OSC 8/52, reflow…) is years of work; claiming one after a short build would be dishonest. |44| libghostty | Not used: no stable public embedding API at the time of writing; building it needs the Zig toolchain and (on this machine) a Metal toolchain component that was missing when it was evaluated for a previous project. |45| **SwiftTerm 1.99.2** | **Chosen.** MIT licence, pure Swift, actively maintained, native `NSView`, thread-safe feed, built-in search, accessibility service, optional Metal renderer. Pinned to an exact version. |4647What is "home-made" on top of the engine: the PTY layer, the session object, launch planning, paste and48broadcast guards, the whole window/tab/pane/workspace system, persistence, SSH/Git/AI modules and the UI.49`ConformanceTests` pin the engine behaviours SP Term depends on (15 tests incl. malformed input and fuzzing).5051## PTY and process lifecycle (`PTYProcess`)5253```54PTYProcess.init55 forkpty(&master, termios(IUTF8…), winsize) new session + controlling terminal on fds 0/1/256 child: posix_spawn(POSIX_SPAWN_SETEXEC | CLOEXEC_DEFAULT | SETSIGDEF | SETSIGMASK, chdir)57 → the program replaces the child; it inherits no descriptor of the app58 → on failure errno is written to a close-on-exec pipe and the launch throws59 parent: master is O_NONBLOCK; three dispatch sources on one serial queue60 read → onOutput(bytes) EOF cancels the source and polls for the exit61 write → pending buffer flushed when the PTY accepts more (never blocks the UI)62 proc → waitpid → drain remaining output → onExit(status) (output always before exit)63```6465- Only async-signal-safe calls happen between `forkpty` and exec; argv/envp/attributes are built before.66- `resize` = `TIOCSWINSZ` (the kernel raises `SIGWINCH`); `terminate` = `SIGHUP` to the session, then67 `SIGKILL` after a grace period; `deinit` hangs up and reaps, so no zombie and no orphan survives.68- Foreground job detection uses `tcgetpgrp` on the master; cwd/CPU/memory come from `libproc`.6970An earlier design used `posix_spawn` alone with `POSIX_SPAWN_SETSID`. Tests showed that on macOS the71slave is then *not* acquired as controlling terminal (zsh lost job control), hence `forkpty`.7273## Session (`TerminalCore.TerminalSession`)7475`@MainActor @Observable`. Owns one `SPTerminalView` (a `SwiftTerm.TerminalView` subclass) and one76`PTYProcess`. PTY output is fed to the engine straight from the PTY queue (`TerminalFeedSender` is77thread-safe); byte counters are sampled once per second on the main actor, so heavy output never floods78the main thread with observation updates. The session implements `TerminalViewDelegate`: size changes,79title (sanitized), OSC 7 directory, link requests, OSC 52 clipboard requests (handed to the app's policy),80bell. A session is independent from windows: moving a pane only re-parents `view`.8182`UserInputScope` marks key-event dispatch (`SPWindow.sendEvent`), pastes and drops; only bytes sent83inside that scope are offered to "broadcast input", so automatic terminal replies are never mirrored.8485## Workspace model (`WorkspaceKit`)8687`LayoutNode` is an n-ary split tree (value type): `.pane(id)` or `.split(axis, fractions, children)`,88always normalized (no single-child split, no nested split of the same axis, fractions sum to 1).89Operations: split, remove, swap, move-to-edge, divider resize, keyboard resize, equalize, geometric90neighbour lookup, frames/dividers for a rectangle, grid builders. `TabModel` = tree + pane descriptors +91focus + temporary zoom; `WindowModel` adds frame, display reference and full-screen flag;92`WorkspaceSnapshot` is what is saved. Only launch metadata is stored (kind of session, directory, title).9394## Windows and displays (`WindowManager` + app)9596`PlacementEngine` guarantees that every frame it returns is reachable (title bar inside the visible97area of an existing display). `resolve` restores a saved window (same display → kept; same display with98another resolution → rescaled; display id changed → matched by name+size; display gone → moved to the99main display keeping proportions). `rescue` is called on `didChangeScreenParametersNotification` and100moves only windows that became unreachable. `arrange` maps preset "screen slots" to displays and tiles101windows that would otherwise stack. The app reads `NSScreen` in exactly one place (`ScreenReader`).102103`AppModel` (main actor, observable) owns sessions (`[PaneID: TerminalSession]`), window states and all104operations (tabs, splits, detach/merge, focus, broadcast, paste/clipboard/link policies, workspaces,105display changes). `WorkspaceWindowController` hosts the SwiftUI root in an `SPWindow`.106`TerminalContainerView` owns the frame of the hosted terminal view and starts the process once the view107has its real size.108109## Storage (`SessionStore`)110111Directory `~/Library/Application Support/SP Term/` (0700), files 0600, each a versioned envelope112`{"schemaVersion": N, "payload": …}` written atomically (temp file + rename):113114| File | Content |115|---|---|116| `settings.json` | preferences and shortcut overrides |117| `last-session.json` | layout autosaved while running (schema 2; schema 1 is migrated) |118| `workspaces.json` | named workspaces |119| `snippets.json` | command snippets |120| `hosts.json` | SSH profiles added in the app (no secrets) |121| `ai-providers.json` | provider label, URL, model — never the key |122| `history.jsonl` | opt-in command history (snippets/assistant/broadcast only) |123124An unreadable or newer-schema file is renamed `*.unreadable-<timestamp>` and defaults are used; a damaged125layout is repaired tab by tab. API keys are in the Keychain. Terminal output is never written to disk126unless the user exports a session.127128## Concurrency129130Swift 6 language mode with complete checking in every target. UI state is `@MainActor`. `PTYProcess`131confines its mutable state to one serial queue (`@unchecked Sendable`, documented). Git and AI calls are132`async`; AI requests can only be built from an `ApprovedPreview`, commands can only run from an133`ApprovedCommand` — both types have no public initializer.134135## SP Term Next chrome (2.0.0)136137- `DesignSystem/Tokens.swift`: `Radius`, `Space`, `TypeScale`, `MotionSpec` (spring parameters as plain values), `ChromeMetrics`138 per density, `AccentEngine` (FNV-1a host hash → hue 80°–340°, pushed to a 3:1 contrast against the chrome). No UI import.139- `Views/Styling.swift`: `Palette`, `Motion` (tokens → SwiftUI animations; fades only when motion is reduced), `ChromeContext`140 in the environment, `floatingSurface` (Liquid Glass on macOS 26+, material otherwise), `IconButton`, `StatusDot`, `EmptyStateView`.141- Layering of a window: `ChromeBackground` (material, theme tint, ambient light) → title bar, sidebar, status bar drawn directly142 on it → pane cards and inspector card (opaque) → floating surfaces (palette, tooltips).143- **Motion rule**: `.animation` is attached to chrome only. `PaneCanvasView` and every pane are wrapped in `snapGeometry()`144 (transaction without animation), because a terminal view that changes size resizes its PTY. Cards appear and disappear with a145 transition applied outside that wrapper; the ambient light moves only on events, so an idle window animates nothing.146- Title bar: an empty unified `NSToolbar` gives the system title bar the height of the tab bar (compact or expanded); the147 controller measures that height and the traffic-light inset and publishes them in `WindowState`.148- Ownership: `AppModel.windows` → `WindowState` → `WorkspaceWindowController` → `NSWindow`. The model clears149 `WindowState.controller` when a window is removed.150