SPB Git

Repository Public

SPTERM-NEXT-AUDIT.md 22.6 KB 256 lines markdown

1# SP Term Next — Audit of the existing application and upgrade plan23Date: 2026-11-19 · Audited revision: `main` @ `0c6078b` (SP Term 1.0.0, build 1) · Branch of the upgrade: `next`4Machine: MacBook Pro, Apple M5 Max, macOS 27.0, Xcode 27.2.56This document was written before any code of the upgrade. Everything in it comes from reading the716 549 lines of Swift in the repository, the project files, the scripts and the existing reports, and8from running the test suites. Where something was not measured or not verified, it says so.910## 1. Existing functionality inventory1112State as documented in `IMPLEMENTATION_STATUS.md` and confirmed in the code. **All of it must survive the upgrade.**1314| Area | What exists in 1.0.0 | Where |15|---|---|---|16| Terminal core | Real PTY (`forkpty` + exec-mode `posix_spawn`), job control, resize, signals, clean environment; SwiftTerm 1.99.2 emulation (pinned), CoreGraphics renderer, optional Metal renderer (experimental, off) | `PTYProcess`, `TerminalCore` |17| Sessions | Local shell, command, SSH kinds; restart, duplicate, rename, export with secret masking; foreground job, cwd, CPU and memory sampling (1 Hz, `libproc`) | `TerminalSession`, `AppModel` |18| Tabs | Create, select, reorder (drag), rename, close, detach to a window, ⌘1…⌘9 | `AppModel`, `TabBarView` |19| Panes | Recursive n-ary splits, divider drag, keyboard resize, equalize, directional focus, zoom, swap and move by drag, move to tab or window without ending the process | `WorkspaceKit.LayoutNode`, `PaneViews` |20| Windows and displays | Several windows, placement engine, rescue on display change, move to display, merge windows, native full screen | `WindowManager`, `WorkspaceWindowController` |21| Workspaces | Autosave and restore of the layout, named workspaces, 9 presets, private mode | `SessionStore`, `Presets` |22| Safety | Paste guard, OSC 52 clipboard policy, link policy, broadcast input with confirmation and held destructive lines, close/quit confirmation | `PasteGuard`, `AppModel` |23| Search | Plain, case, regex, match counter, counts across sessions | `Actions.swift`, `SearchBarView` |24| Remote and tools | `~/.ssh/config` parser, host profiles and dashboard, known_hosts state, failure diagnosis and reconnect, read-only git panel, snippets with variables, tmux and zellij entries, agent CLI detection | `SPRemoteKit`, panels |25| Assistant | BYOK providers (Anthropic, OpenAI, compatible), Keychain, payload preview, secret redaction, risk analyzer, consent gate | `SPIntelligence` |26| Chrome | Custom tab bar in a transparent title bar, sidebar, 4 inspectors, status bar, pane headers, command palette, banners, 10 sheets, context menu | `App/Sources/SPTerm/Views` |27| Preferences | 6 settings panes, 6 themes (2 dark, 2 light, 2 high contrast), accent override, font, cursor, opacity, blur, customizable shortcuts | `SettingsModel`, `SettingsView` |28| Extras | Quick terminal on a global hotkey (Carbon), notifications, Finder "open folder" and Services entry, focus mode, presentation mode | `QuickTerminalController`, `Notifier`, `AppDelegate` |29| Distribution | XcodeGen project, universal Release build, Developer ID, hardened runtime, notarized and stapled app and DMG | `project.yml`, `Scripts/` |303164 actions are registered in one enum (`AppAction`) that feeds the menu bar, the palette, the context32menu and the shortcut editor.3334## 2. Architecture3536```37┌───────────────────────────── SP Term.app (App/Sources/SPTerm, 5 100 lines) ─────────────────────────────┐38│ AppDelegate ── menus built from AppAction ── Settings window                                             │39│      │                                                                                                    │40│      ▼                                                                                                    │41│ AppModel  @MainActor @Observable  (969 lines)                                                            │42│   sessions [PaneID: TerminalSession] · windows [WindowState] · settings · stores · 1 Hz timer (tick)     │43│      │                         │                              │                                           │44│      ▼                         ▼                              ▼                                           │45│ WindowState (@Observable)   WorkspaceWindowController     QuickTerminalController                         │46│   tabs [TabModel], UI flags   SPWindow (NSWindow)           SPWindow borderless, Carbon hotkey             │47│      │                         │ NSHostingView                                                            │48│      ▼                         ▼                                                                          │49│ WindowRootView (SwiftUI) ─ TabBarView · SidebarView · PaneCanvasView · InspectorView · StatusBarView      │50│                              PaneCanvasView → PaneView → TerminalHostView (NSViewRepresentable)           │51│                                                   └→ TerminalContainerView (NSView) hosts session.view    │52└──────────────────────────────────────────────────────────────────────────────────────────────────────────┘53        │                         │                         │54        ▼                         ▼                         ▼55 Packages/SPTermKit        Packages/SPRemoteKit      Packages/SPIntelligence56  PTYProcess                SSHKit                    AIAssistant57  TerminalCore ─ SwiftTerm  GitKit58  WorkspaceKit (pure)       SPProcess59  WindowManager (pure)60  SessionStore61  SettingsModel62  DesignSystem (themes, contrast, metrics)63```6465Data flow of a keystroke: `SPWindow.sendEvent` (marks user input) → SwiftTerm view → `TerminalSession.send`66→ `PTYProcess` write source. Output: PTY read source (serial queue) → SwiftTerm feed (thread-safe) →67engine draws on the main thread. Process state reaches the UI through a 1 Hz timer that bumps68`AppModel.tick`.6970Points 5 to 8 of the brief:7172- **PTY sessions**: one `PTYProcess` per session, three dispatch sources on one serial queue, `deinit` hangs up and reaps. Sound; not touched by the upgrade.73- **Process spawning and shell integration**: launch planning in `ShellSupport` (`TERM`, `TERM_PROGRAM`, login shell). OSC 7 (directory) and OSC 0/2 (title) are consumed. **There is no semantic shell integration (OSC 133)**: the app does not know where a prompt starts, where a command ends or what its exit status was. The end of a foreground job is inferred from `tcgetpgrp`.74- **Keyboard shortcuts**: 45 default chords, overrides stored per action, conflicts detected in the editor, applied by rebuilding the menu bar.75- **Windows and tabs**: `NSWindow` with `fullSizeContentView`, transparent title bar, system tabbing disabled, tabs are SwiftUI views.7677## 3. UI and UX assessment7879What the 1.0.0 interface is today (see `docs/evidence/*.png`): correct, flat and anonymous.8081| Topic | Finding |82|---|---|83| Visual identity | One flat chrome colour derived from the theme background, 1 pt separators everywhere, no depth, no material in the default configuration. The window does not look like any product in particular. |84| Translucency | Only "opacity + blur of the whole window", off by default. It dims the terminal text surface together with the chrome, which hurts readability, the opposite of what is wanted. |85| Typography and metrics | Font sizes are literals scattered in the views (9, 10, 11, 12, 13, 15 pt); `Metrics` holds only 12 numbers. No type scale, no radius scale, no elevation scale. |86| Motion | **None.** One `.transition(.opacity)` exists on the palette and never runs because no state change is wrapped in an animation. Tabs, panes, sidebar, inspector, banners and the palette appear and disappear in one frame. |87| Reduce Motion | Not read (there is nothing to reduce). |88| Title bar | Traffic lights sit at the system position of a 28 pt title bar while the tab bar is 34 pt: they are not vertically centred on the tabs. The spacer for them is a hard-coded 76 pt. |89| Full screen | `TabBarView` reads `controller.isFullScreen`, which is not observable: after entering or leaving full screen the traffic-light spacer is stale until something else redraws the bar. |90| Toolbar | Five fixed buttons; not customizable. |91| Modes | Focus mode and presentation mode exist but switch in one frame; presentation mode merely forces focus mode. No compact or expanded density. |92| Panes | Hairline gap, square corners, focused pane marked by a 1 pt accent rectangle and the others dimmed to 82 % (which lowers text contrast of unfocused panes). |93| Empty states | Plain sentences ("Save the current arrangement with ⌘S", "No matching command"). |94| Tooltips | System `.help` only, without the shortcut of the action. |95| Feedback | No feedback when a long command finishes, apart from an optional system notification. |96| Accessibility | Labels and traits are present on tabs, panes, palette rows and status items. Keyboard coverage is complete through the menu. VoiceOver was never run (unchanged by this audit). Colour is doubled by text or an icon in most places; the tab status dot relies on colour plus an accessibility label only. |97| Liquid Glass | Not used. The SDK of Xcode 27.2 exposes `glassEffect(_:in:)` (macOS 26+); the deployment target is macOS 14, so it needs an availability check and a material fallback. |9899## 4. Performance baseline100101Tests re-run for this audit on 2026-11-19 (same machine): SPTermKit, SPRemoteKit and SPIntelligence102package suites pass; the hosted app suite passes (all six XCTest suites, including `PerformanceTests`).103104Reference numbers, measured on 2026-11-17 on the signed Release build (`BENCHMARKS.md`; not re-measured today):105106| Measure | 1.0.0 |107|---|---|108| Launch to first window | 250–259 ms |109| Memory, 1 idle pane / 8 idle panes | 57 MB / 64 MB footprint |110| CPU, 8 idle panes | 1.2 % |111| `cat` of 51 MB (no drawing) | 0.51 s, about 100 MB/s |112| Echo latency to the screen buffer | median 0.26 ms |113| 300 resizes under output | 0.32 s |114115Typing latency to glass and drawing throughput were never measured. The upgrade must not degrade the116table above; section 8 says how that is checked.117118Bottlenecks and risks found in the code:1191201. **`tick` invalidates the whole chrome every second.** Tab items, every pane, the sidebar, the status bar and the hosts panel read `model.tick`. Each second SwiftUI re-evaluates them all, including `TerminalHostView.updateNSView`. Cheap today, but it is a fixed idle cost that grows with pane count, and any continuous animation added on top of it would multiply it.1212. **Scrollback search runs on the main thread** on every keystroke of the search field, without debounce (2.5 s for 200 000 lines).1223. **`searchCounts` scans every open session** from inside a `Menu` builder.1234. **The palette probes the file system when it opens** (`ToolLocator.agents()`, `ShellCatalog.installedShells()`, tmux, zellij): synchronous `isExecutableFile` calls over about ten directories.1245. **`viewDidBecomeFirstResponder`** looks up the pane by a linear scan of all sessions.1256. **`currentSnapshot()` mutates `window.tabs`** (it writes working directories) each time it is called, so every autosave invalidates every view observing the tabs.1267. **Resizing a terminal view resizes the PTY** (`TIOCSWINSZ`, `SIGWINCH`). Any animation that interpolates pane frames would send a resize per frame to the shell. This constrains how pane splitting can be animated (see 7.2).1278. The 1 Hz sampler keeps probing `libproc` for sessions of hidden tabs and when no window is open.128129## 5. Security assessment130131| Item | State |132|---|---|133| Sandbox | Off, by necessity for a terminal. Hardened runtime on. |134| Entitlements | One: `com.apple.security.automation.apple-events`. No JIT, no library-validation exception, no `get-task-allow` in Release. |135| Privacy strings | Present for Apple Events, Desktop, Documents, Downloads, removable and network volumes, local network. They describe programs run in a session, which is accurate. |136| Secrets | API keys in the Keychain only; provider file holds no key; history is opt-in and redacted; private mode writes nothing. Files 0600 in a 0700 directory. |137| Untrusted terminal output | Titles sanitized, OSC 52 write = ask and read = deny by default, links filtered by scheme, paste and drops guarded. |138| Child processes | No descriptor inherited, clean environment (tested). |139| Signing and notarization | Developer ID, timestamp, notarized and stapled app and DMG (1.0.0). |140| Updates | No update channel (no Sparkle): a fix reaches the user only by a manual download. |141| Not covered | Intel slice never executed; no installation test on another Mac. |142143Nothing in the upgrade needs a new entitlement or permission. Risk introduced by the upgrade: none on144this axis as long as the terminal view, PTY layer and policies are left as they are.145146## 6. Technical debt inventory147148| # | Debt | Severity |149|---|---|---|150| D1 | `AppModel` is a 969-line object owning sessions, windows, broadcast, paste, links, workspaces and display changes | Medium (works, tested; splitting it is not needed for this release) |151| D2 | No design tokens: literals for sizes, radii, opacities in every view | High for a redesign |152| D3 | Status logic (running, busy, ended → colour) written three times (tab, sidebar, pane header) | Low |153| D4 | `tick`-driven refresh instead of observing session properties (item 1 above) | Medium |154| D5 | Full-screen state not observable (stale tab bar) | Bug |155| D6 | `NSCursor.push()`/`pop()` in `DividerHandleView.onHover`: if the handle disappears while hovered the pop never happens and the resize cursor can stick | Bug |156| D7 | `AppModel.assistants[WindowID]` entries are never removed when a window closes | Small leak |157| D8 | Focus mode and presentation mode overlap; the "draggable strip" of focus mode is an empty 22 pt band | Low |158| D9 | `nonisolated(unsafe) static weak var current` in the quick terminal controller | Low, documented |159| D10 | Search on the main thread, no debounce | Medium |160| D11 | Settings window is a fixed 640×520 `TabView` | Low |161| D12 | No shell integration (OSC 133), so no exit status, no prompt marks, no command blocks | Feature gap, later phase |162| D13 | Interface in English only, VoiceOver not audited, no update channel | Known, out of scope here |163164Duplicated or incomplete functionality (point 16): D3 and D8 above; SFTP is only a tab running `sftp`;165streaming exists in the AI client but the panel does not use it; ligatures and line spacing have no setting.166167## 7. Prioritized improvements168169The brief received covers Phase 0 and Phase 1 (sections 1.1 to 1.3; the text stops inside 1.3). The plan is limited to that.170171### 7.1 Foundations (first, everything else depends on them)172173- `DesignSystem`: typed tokens (spacing, radii, type scale, elevation), motion tokens (durations and spring parameters as plain values), surface colours derived per theme, two new themes, a deterministic accent engine. Pure Swift, unit-tested, no UI import.174- `SettingsModel`: new preferences with tolerant decoding (chrome material, density, motion, dynamic accent, ambient gradient, toolbar items). An existing `settings.json` loads unchanged.175- App: one `Motion` helper that turns tokens into SwiftUI animations and returns no movement when Reduce Motion (system or setting) is on; shared surface, glass and tooltip components. Liquid Glass behind `#available(macOS 26, *)`, materials below.176177### 7.2 Visual design and motion (1.1, 1.2)178179| Item | Decision |180|---|---|181| Depth | Chrome becomes a material layer (vibrancy behind the window) and each pane a rounded, opaque card floating on it. The terminal text surface stays fully opaque by default: translucency is on the chrome, not under the text. |182| Focus | Accent ring and soft glow on the focused card; unfocused panes are no longer dimmed through their text (a thin veil on the header only). |183| Dynamic accent | Local sessions use the theme or user accent; each SSH host gets its own stable hue (derived from the host name, contrast-checked); broadcast uses the warning colour. The chrome tint follows the focused pane. |184| Ambient gradient | A low-contrast accent gradient in the chrome that drifts only on events (focus change, tab switch, command finished). No continuous animation, so no idle cost. |185| Tabs | Pill tabs, sliding selection, spring insertion and removal. |186| Pane splitting | New panes fade and scale in, closed panes fade out, dividers and focus ring animate. **Pane frames are not interpolated**, because each intermediate size would be sent to the shell as a terminal resize (item 7 of section 4). |187| Tab switch | Short cross-fade with a slight scale; terminal content itself is never animated. |188| Sidebar, inspector, banners, search bar | Spring slide with fade. |189| Palette | Scrim, spring scale-in, animated selection, glass surface, footer of key hints, designed empty state. |190| Tooltips | Own tooltip with the action name and its current shortcut. |191| Completion feedback | When a foreground command ends, the tab dot pulses and the status bar shows its name and duration for a few seconds. Without shell integration the exit status is unknown, so success or failure is **not** claimed. |192| Reduce Motion | System setting honoured, plus a setting to force reduced motion. Movement becomes a plain short fade. |193194### 7.3 Window architecture (1.3)195196| Item | Decision |197|---|---|198| Integrated title bar, native traffic lights | Kept native. An empty unified toolbar gives the title bar the height of the tab bar so the lights are vertically centred; their real position is measured instead of the hard-coded 76 pt. |199| Customizable toolbar | The toolbar buttons become a user-chosen, ordered set (settings and right-click on the bar). |200| Compact and expanded modes | Density setting: compact (single-line tabs) and expanded (taller bar, two-line tabs with the running program). |201| Distraction-free mode | Focus mode animated; chrome and traffic lights fade out and come back when the pointer reaches the top edge. Presentation mode kept. |202| Full-screen workspace mode | New action: native full screen with the overview sidebar and status bar shown, restored on exit. Full-screen state becomes observable (fixes D5). |203204### 7.4 Debt fixed in passing205206D2, D3, D5, D6, D7, D8, plus items 4 and 5 of section 4 (palette probes cached, first-responder lookup by view identity).207208### 7.5 Explicitly not in this release209210D1 (splitting `AppModel`), D4 as a whole (replacing `tick`), D10 (background search), D12 (OSC 133 shell integration), a GPU renderer by default, localization, an update channel. They belong to later phases of the brief, which were not received.211212## 8. Migration and compatibility plan213214| Subject | Rule |215|---|---|216| Features | Nothing is removed. Every `AppAction`, menu item, shortcut, sheet, panel and setting of 1.0.0 remains. New actions get no default shortcut that is already in use. |217| `settings.json` | Schema version unchanged. New keys are optional with defaults; unknown keys are still ignored, so going back to 1.0.0 with a newer file also works. `backgroundOpacity` and `backgroundBlur` keep their meaning. |218| Layout files | `last-session.json`, `workspaces.json`, `snippets.json`, `hosts.json`, `ai-providers.json` untouched. |219| Kits | `PTYProcess`, `TerminalCore` (except nothing), `WorkspaceKit`, `WindowManager`, `SessionStore`, `SPRemoteKit`, `SPIntelligence`: no behavioural change. Only `DesignSystem` and `SettingsModel` gain API. |220| Engine | SwiftTerm stays pinned at 1.99.2; default renderer unchanged. |221| System | Deployment target stays macOS 14. Liquid Glass on macOS 26 and later, materials before. |222| Tests | The existing suites must stay green without weakening an assertion. New unit tests for tokens, accent engine, settings decoding of old files, new actions. |223| Performance | `Scripts/bench.sh` and `PerformanceTests` on a Release build after the change, compared with section 4. |224| Version | 2.0.0 (build 2). Bundle identifier, signing identity and data directory unchanged, so the new build replaces the old one in place. |225| Rollback | Work happens on branch `next`; `main` and the published 1.0.0 DMG are untouched until the owner decides to release. |226227## 9. Verification status of this audit228229- Read: all app sources, `DesignSystem`, `SettingsModel`, `TerminalSession`, `SPTerminalView`, project, entitlements, Info.plist, scripts, existing reports.230- Read only by outline: `PTYProcess`, `LayoutNode`, `SSHKit`, `GitKit`, `AIAssistant` internals (not modified by this plan; their state is taken from their test suites, which pass).231- Run: the four test suites (pass). Not re-run: `bench.sh`, `smoke.sh`.232233## 10. Outcome (added after implementation, 2026-11-19)234235What was delivered against the plan of section 7, and where it differs.236237| Plan item | Outcome |238|---|---|239| 7.1 Foundations | Done. `Tokens.swift`, accent engine, two themes, eight new settings with tolerant decoding. |240| 7.2 Design and motion | Done as planned. Pane frames snap; cards, focus ring, dividers, tabs, sidebar, inspector, banners, search bar and palette move. |241| 7.3 Window architecture | Done. The hover return of the title bar in focus mode and the native full-screen transition of the workspace mode were not exercised live. |242| D2 design tokens | Partly: the window chrome, sidebar, palette and panes use the tokens. The four inspector panels, the sheets and the Settings window keep their literals. |243| D3, D5, D6, D7 | Fixed. |244| D8 | Partly: the focus-mode strip now has a function (drag, bring the title bar back); focus and presentation modes remain two actions. |245| Section 4, items 4 and 5 | Fixed (palette probes cached for one minute; first-responder lookup by view identity). |246| Section 4, items 1, 2, 3, 6, 8 | Not addressed, as stated in 7.5. |247248Found during implementation, not in the audit above: **the window controller was not retained by anything** and was released249right after a window opened, leaving the window without a delegate. The audit missed it because the code reads as if the250controller lived (`WindowState.controller` is used everywhere) and the hosted tests call the model directly. It was found when251the traffic lights refused to hide: a trace showed the controller's `deinit` immediately after launch. Fixed by making the252window state own the controller; one existing assertion had to tolerate a soft-wrapped line, because test windows now stay253alive and give panes their real width instead of the default 80 columns.254255Measured after the change: see "SP Term Next (2.0.0) against 1.0.0" in `BENCHMARKS.md`.256
Files main
Menu

Theme