SPB Git

Repository Public

ARCHITECTURE.md 10.1 KB

# SP Term — Architecture

SP Term is a native macOS terminal: Swift 6 (strict concurrency), SwiftUI for the chrome, AppKit for windows, focus, menus, screens and the terminal view. Minimum system: macOS 14 (the app relies on the Observation framework and on SwiftUI APIs introduced in macOS 14; the emulation engine itself needs macOS 13).

# Modules

text
SP Term.app  (App/Sources/SPTerm — AppKit lifecycle, SwiftUI views)
 │
 ├── Packages/SPTermKit           core, unit-tested with `swift test`
 │    ├── PTYProcess              pseudo-terminal + child process (forkpty → posix_spawn SETEXEC)
 │    ├── TerminalCore            session = PTY + emulator view; launch planning, paste/broadcast guards
 │    │     └── SwiftTerm 1.99.2  terminal emulation engine: VT/xterm parser + renderer (MIT, pinned)
 │    ├── WorkspaceKit            pure model: recursive split tree, tabs, windows, snapshots, presets
 │    ├── WindowManager           pure geometry: placement on displays, reachability, rescue, tiling
 │    ├── SessionStore            versioned JSON files, migrations, corruption recovery, opt-in history
 │    ├── SettingsModel           preferences (tolerant decoding), key chords
 │    └── DesignSystem            themes (original palettes), contrast maths, metrics
 ├── Packages/SPRemoteKit
 │    ├── SSHKit                  ~/.ssh/config parser, profiles, argv builder for the system ssh/sftp,
 │    │                           known_hosts inspector, error classifier (no crypto of its own)
 │    └── GitKit                  read-only git context (allow-listed subcommands only)
 └── Packages/SPIntelligence
      └── AIAssistant             BYOK clients (Anthropic, OpenAI, OpenAI-compatible), Keychain store,
                                  secret redactor, command risk analyzer, consent gate, network policy

How the names of the brief map to the code: TerminalParser and TerminalRenderer are the SwiftTerm engine (integrated, not rewritten — see "Engine choice"); SPTermApp, Settings (UI) and Distribution live in the app target and Scripts/; everything else is a module of the same name.

Dependency rule: models (WorkspaceKit, WindowManager, SettingsModel, DesignSystem) import no UI framework beyond CoreGraphics types and never touch NSScreen/NSWindow, which is what lets the multi-monitor logic be tested with simulated displays.

# Engine choice

Option Decision
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.
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.
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.

What is "home-made" on top of the engine: the PTY layer, the session object, launch planning, paste and broadcast guards, the whole window/tab/pane/workspace system, persistence, SSH/Git/AI modules and the UI. ConformanceTests pin the engine behaviours SP Term depends on (15 tests incl. malformed input and fuzzing).

# PTY and process lifecycle (PTYProcess)

text
PTYProcess.init
  forkpty(&master, termios(IUTF8…), winsize)        new session + controlling terminal on fds 0/1/2
    child: posix_spawn(POSIX_SPAWN_SETEXEC | CLOEXEC_DEFAULT | SETSIGDEF | SETSIGMASK, chdir)
           → the program replaces the child; it inherits no descriptor of the app
           → on failure errno is written to a close-on-exec pipe and the launch throws
  parent: master is O_NONBLOCK; three dispatch sources on one serial queue
           read  → onOutput(bytes)            EOF cancels the source and polls for the exit
           write → pending buffer flushed when the PTY accepts more (never blocks the UI)
           proc  → waitpid → drain remaining output → onExit(status)   (output always before exit)
  • Only async-signal-safe calls happen between forkpty and exec; argv/envp/attributes are built before.
  • resize = TIOCSWINSZ (the kernel raises SIGWINCH); terminate = SIGHUP to the session, then SIGKILL after a grace period; deinit hangs up and reaps, so no zombie and no orphan survives.
  • Foreground job detection uses tcgetpgrp on the master; cwd/CPU/memory come from libproc.

An earlier design used posix_spawn alone with POSIX_SPAWN_SETSID. Tests showed that on macOS the slave is then not acquired as controlling terminal (zsh lost job control), hence forkpty.

# Session (TerminalCore.TerminalSession)

@MainActor @Observable. Owns one SPTerminalView (a SwiftTerm.TerminalView subclass) and one PTYProcess. PTY output is fed to the engine straight from the PTY queue (TerminalFeedSender is thread-safe); byte counters are sampled once per second on the main actor, so heavy output never floods the main thread with observation updates. The session implements TerminalViewDelegate: size changes, title (sanitized), OSC 7 directory, link requests, OSC 52 clipboard requests (handed to the app's policy), bell. A session is independent from windows: moving a pane only re-parents view.

UserInputScope marks key-event dispatch (SPWindow.sendEvent), pastes and drops; only bytes sent inside that scope are offered to "broadcast input", so automatic terminal replies are never mirrored.

# Workspace model (WorkspaceKit)

LayoutNode is an n-ary split tree (value type): .pane(id) or .split(axis, fractions, children), always normalized (no single-child split, no nested split of the same axis, fractions sum to 1). Operations: split, remove, swap, move-to-edge, divider resize, keyboard resize, equalize, geometric neighbour lookup, frames/dividers for a rectangle, grid builders. TabModel = tree + pane descriptors + focus + temporary zoom; WindowModel adds frame, display reference and full-screen flag; WorkspaceSnapshot is what is saved. Only launch metadata is stored (kind of session, directory, title).

# Windows and displays (WindowManager + app)

PlacementEngine guarantees that every frame it returns is reachable (title bar inside the visible area of an existing display). resolve restores a saved window (same display → kept; same display with another resolution → rescaled; display id changed → matched by name+size; display gone → moved to the main display keeping proportions). rescue is called on didChangeScreenParametersNotification and moves only windows that became unreachable. arrange maps preset "screen slots" to displays and tiles windows that would otherwise stack. The app reads NSScreen in exactly one place (ScreenReader).

AppModel (main actor, observable) owns sessions ([PaneID: TerminalSession]), window states and all operations (tabs, splits, detach/merge, focus, broadcast, paste/clipboard/link policies, workspaces, display changes). WorkspaceWindowController hosts the SwiftUI root in an SPWindow. TerminalContainerView owns the frame of the hosted terminal view and starts the process once the view has its real size.

# Storage (SessionStore)

Directory ~/Library/Application Support/SP Term/ (0700), files 0600, each a versioned envelope {"schemaVersion": N, "payload": …} written atomically (temp file + rename):

File Content
settings.json preferences and shortcut overrides
last-session.json layout autosaved while running (schema 2; schema 1 is migrated)
workspaces.json named workspaces
snippets.json command snippets
hosts.json SSH profiles added in the app (no secrets)
ai-providers.json provider label, URL, model — never the key
history.jsonl opt-in command history (snippets/assistant/broadcast only)

An unreadable or newer-schema file is renamed *.unreadable-<timestamp> and defaults are used; a damaged layout is repaired tab by tab. API keys are in the Keychain. Terminal output is never written to disk unless the user exports a session.

# Concurrency

Swift 6 language mode with complete checking in every target. UI state is @MainActor. PTYProcess confines its mutable state to one serial queue (@unchecked Sendable, documented). Git and AI calls are async; AI requests can only be built from an ApprovedPreview, commands can only run from an ApprovedCommand — both types have no public initializer.

# SP Term Next chrome (2.0.0)

  • DesignSystem/Tokens.swift: Radius, Space, TypeScale, MotionSpec (spring parameters as plain values), ChromeMetrics per density, AccentEngine (FNV-1a host hash → hue 80°–340°, pushed to a 3:1 contrast against the chrome). No UI import.
  • Views/Styling.swift: Palette, Motion (tokens → SwiftUI animations; fades only when motion is reduced), ChromeContext in the environment, floatingSurface (Liquid Glass on macOS 26+, material otherwise), IconButton, StatusDot, EmptyStateView.
  • Layering of a window: ChromeBackground (material, theme tint, ambient light) → title bar, sidebar, status bar drawn directly on it → pane cards and inspector card (opaque) → floating surfaces (palette, tooltips).
  • Motion rule: .animation is attached to chrome only. PaneCanvasView and every pane are wrapped in snapGeometry() (transaction without animation), because a terminal view that changes size resizes its PTY. Cards appear and disappear with a transition applied outside that wrapper; the ambient light moves only on events, so an idle window animates nothing.
  • Title bar: an empty unified NSToolbar gives the system title bar the height of the tab bar (compact or expanded); the controller measures that height and the traffic-light inset and publishes them in WindowState.
  • Ownership: AppModel.windows → WindowState → WorkspaceWindowController → NSWindow. The model clears WindowState.controller when a window is removed.
Files main
Menu

Theme