108 lines
15 KiB
Markdown
108 lines
15 KiB
Markdown
# Architecture
|
||
|
||
Swift package at the repo root, macOS 14+, one project per window and one window per process. The behaviour spec is [behaviour.md](behaviour.md), the visual system [design/README.md](design/README.md).
|
||
|
||
## Layers
|
||
|
||
```
|
||
Helder (executable) → HelderUI → HelderServices → HelderCore
|
||
└→ SwiftTerm
|
||
```
|
||
|
||
| Target | May import | Rules |
|
||
|---|---|---|
|
||
| `HelderCore` | Foundation | Pure logic and value types, all `Sendable`. No AppKit, no SwiftUI, no disk, no processes. Swift 6 mode. |
|
||
| `HelderServices` | HelderCore, Foundation, CoreServices | Everything that touches disk or spawns `git`/`rg`, behind a protocol. Processes only through `ProcessRunning`. |
|
||
| `HelderUI` | Core, Services, SwiftUI, AppKit, SwiftTerm | `@Observable @MainActor` stores plus views. Never runs a process or touches project files directly, only through the service protocols (the SwiftTerm terminals are the one exception). |
|
||
| `Helder` | HelderUI | The `@main` app. Keep it tiny. |
|
||
|
||
## How a window works
|
||
|
||
- `WorkspaceModel` owns one window (`WorkspaceModel.swift`: state and `perform`; `+Commands`, `+ContextActions`, `+Lifecycle`, `+Refresh` hold the rest): the stores (`SourceControlStore`, `ExplorerStore`, `EditorStore`, `NoteStore`, `CleanCopyStore`, `TerminalStore`, `LayoutStore`, `OverlayStore`, `ToastStore`) and every action that spans more than one of them. A store never reaches into a sibling; `EditorStore` only reads the git state through a closure.
|
||
- **One entry point.** Views, the menu bar and the key router all call `WorkspaceModel.perform(Command)` (`Shell/Command.swift`). Context-menu items arrive as `.context(ContextAction)`; the model asks `SourceControlStore.confirmation(for:)` / `ExplorerStore.confirmation(for:)` first and shows the confirm overlay, and `.confirmPending` runs the action. The name prompt submits with `.submitName`, the pass-on prompt with `.passToAgent`, the note's ⌘P with `.passNote`.
|
||
- **Overlays never stack.** `OverlayStore.current` is one `Overlay` enum; only the model presents or dismisses it. `OverlayStore.onChange` lets the model run closing behaviour however an overlay went away (the note saves, the Diff gives back the mode it covered). `OverlayHost` draws the current overlay. `.launcher` is the ⇧⌘O "Open recent project" list; the bare window's launcher is part of the shell, not an overlay. The key router only sees `OverlayKind` (`none`, `note`, `diff(busy:)`, `other`): over the Diff the workspace keys keep working unless its own menu or prompt is open (`busy`). Toasts (`ToastStore`) may sit on top. The Diff draws its own right-click menu and pass-on prompt inside itself, so it stays open.
|
||
- **Stores report, the model shows.** Stores raise toasts through `notify`/`showToast` hooks the model wires to `ToastStore`; the model never toasts a second time for the same action.
|
||
- **Closing.** A window close, a project switch and ⌘Q all run `prepareToClose()` first: every unsaved file (at most the open one plus a vanished-file buffer) is asked about, and a cancel keeps everything open. Then `closeProject()` waits for running work, writes the note and session and ends the terminals.
|
||
- **Lifecycle.** `start()`: recents → config (applied to every store and the terminals) → git, tree, note and the `.clean-copy` baseline in parallel → `editor.restore` → watcher → git polling (`git.refreshInterval`) → the PHP class list 1.5 s later. Watcher events: `.cleanCopy` (`.clean-copy` in the root, 150 ms debounce, fired besides `.project`) makes `CleanCopyStore` re-read the file and opens the `.cleanCopy` overlay for new non-blank text (the text found at load is the baseline; another open overlay makes it wait, keeping only the newest); `.project` re-reads git, the tree, the open file and every unsaved buffer (the edits kept), invalidates the symbol index and reloads the class list 2 s after the last change; `.git` re-reads git; `.config` re-resolves and re-applies the config. ⌘R re-reads git and the tree and lets the disk win in the open file. A project switch or window close saves the note and the session, stops the watcher and polling, and ends both terminals.
|
||
- **Terminals.** `TerminalStore` owns both panes' handles. Ending a pane goes through the store (`terminateAll`, `restart`, or `release` when a pane's window closes), which signals the child and lets `ChildReaper` collect it, so no zombie or orphan is left. A pane whose child exited restarts on the next key press. Right-click raises `contextMenuRequested`; the model shows the app's own menu (`.terminal` target: Copy with a selection, Paste). Font size follows `layout.textScale` (⌘0/⌘+/⌘−) live.
|
||
- **Git and files.** Git gets paths as literal pathspecs (`GIT_LITERAL_PATHSPECS=1`, so `pages/[id].vue` is one file). A changed file over `FileLimits.maxDiffFileBytes` (1 MB) keeps its row but loads no text: `GitFileChange.isTooBig` → `Diff.isTooBig`, and the Diff shows "Too big.". Saves are atomic (temp file, then rename, keeping permissions). Writes, creates, renames and deletes are refused when the entry's folder resolves (symlinks included) outside the project (`containedURL`). The watcher drops `IgnoreRules.walkIgnoredNames`, framework caches (`storage/framework/`, `bootstrap/cache/`, `.phpunit*`) and `files.exclude`.
|
||
- **Processes.** Every new window (⇧⌘N, the Dock's New Window, Open Folder or Open Recent with no key window) is a new Helder process via `SystemActing.openNewInstance`: `NSWorkspace` with `createsNewApplicationInstance` in the bundle, `InstanceLauncher` (Foundation `Process`) under `swift run`. The folder travels as `-HelderProject <path>`, which `ProjectLocator.initialRoot` reads as its directory argument; a bare path could reach AppKit as a file to open. Switching projects (⌘O, Open Recent in a window) stays in the process. `AppName` renames the process to the project's title (the launcher is "Helder"), so Mission Control, the Dock and ⌘Tab tell projects apart. Windows are not restorable and `NSQuitAlwaysKeepsWindows` is off, so a launch opens exactly one window.
|
||
- **Editor.** `EditorStore` shows exactly one file (`activePath`); opening another replaces it, and there are no tabs. Every `open` (Git column, Explorer, search, recent files, links) re-reads the file from disk; the disk wins. Unsaved edits do not outlive switching: opening any file, the same one included, while the open file is dirty asks Save / Don't Save / Cancel (with `editor.autoSave` on it saves silently). Cancel moves nothing, Explorer selection included; a failed save keeps the dirty file open. `dirtyPaths` is therefore at most the open file plus a vanished-file buffer, and the close/quit flow asks about each. ⌘W closes the open file (asking first when dirty) and shows the empty state. `EditorBar` above the code shows the type badge, the path, the unsaved dot and `+N`/`−N`, then a Preview button for Markdown and a Diff button for a changed file (`EditorPresentation.barButtons`). A changed file shows Actual (the live buffer with changed lines marked), an unchanged one plain code; ⌘M only flips Markdown between code and preview. The session stores the open file and its mode and side; a stored `openTabs` list and unknown modes are ignored.
|
||
- **Focus.** `WorkspaceModel.focusRequest` names where the keyboard should go (a column, the commit box); the view that takes it calls `focusTaken(_:)`. The editor's text view follows `EditorStore.textFocusRequest`, which also moves when the Diff closes.
|
||
|
||
## Where things live
|
||
|
||
```
|
||
Sources/HelderCore/
|
||
Agent/ AgentReference, BracketedPaste, TerminalLaunch (`TERM_PROGRAM=Helder`), CleanCopy (file name, new-text rule)
|
||
Config/ HelderConfig (tolerant decoding), config resolution, .env title
|
||
Diff/ Diff models, LineDiff, DiffViews, ViewMode
|
||
Files/ FileNode + FileTree, PathUtils, FileType (language, badge), limits + ignore rules, ContextActions (menus)
|
||
Git/ GitStatus/Change/GitSnapshot, Porcelain parsing, GitDerivation (rows, grouping, commit text)
|
||
Highlight/ SyntaxHighlighter and one grammar per language
|
||
Markdown/ block/inline tree and parser
|
||
Search/ result models, Fuzzy, InFileSearch, rg --json parsing
|
||
Session/ SessionState, LayoutState, recents, ColumnLayout, Cursor/LineSelection/OpenOptions
|
||
Symbols/ PHP symbol models and line parsers
|
||
Sources/HelderServices/
|
||
Files/ FileServicing (read, readText → .binary), FileService, FSEventsWatcher + WatchDebounce
|
||
Git/ GitServicing, GitService, GitDirectory (worktrees)
|
||
Logging/ Log (unified log) + FileLogger (~/Library/Logs/Helder/helder.log)
|
||
Process/ ProcessRunner, ExecutableLocator, ChildReaper, InstanceLauncher
|
||
Project/ ConfigService, NotesService, RecentStores, SessionStore, ProjectLocator
|
||
Search/ SearchServicing + RipgrepSearchService, ProjectScanner (rg, or a Swift walk)
|
||
Symbols/ SymbolService
|
||
Sources/HelderUI/
|
||
State/ WorkspaceModel (+ extension files), WorkspaceServices/AppServices, one file per store
|
||
Shell/ AppDelegate, HelderScene (menus), WorkspaceWindow, WindowBridge (NSWindow, key monitor), AppName,
|
||
KeyRouter, Command, SystemActions, title bar, status bar, launcher, toasts, focus flash
|
||
Components/ OverlayShell/OverlayCard/OverlayHeader/OverlayFooter, ContextMenuPanel/Header/Row/Separator,
|
||
Keycap, EscChip, Primary/Secondary button styles, focusRing, SegmentButton, Splitter,
|
||
ButtonGroup (pane toggles, toolbar), Tooltip, TypeBadge, PanelLabel/PanelHeader, Hairline, selectableRow, Blink
|
||
SourceControl/ the git column and the commit box
|
||
Explorer/ the file tree column and the row glyphs
|
||
Editor/ the bar above the code, code/markdown/image panes, Diff overlay, pass-on panel, symbol popup
|
||
Terminal/ agent + shell panes over SwiftTerm
|
||
Overlays/ OverlayHost, search, note and clean copy (sharing OverlayTextEditor), shortcuts, recent files, context menu, name prompt, confirm, OverlayKeys
|
||
Theme/ Palette, Typography, Metrics, FontRegistry
|
||
Resources/Fonts/ IBM Plex Mono 400–700, Plex Sans 400/500/600/700/400i (WOFF2, OFL)
|
||
Tests/<Target>Tests/<same folders>/
|
||
Tests/HelderUITests/Support/ WorkspaceHarness, StoreHarnesses (EditorHarness, Recorder), Eventually, Tags
|
||
Tests/HelderUITests/Support/Fakes/ one fake per service protocol (FakeGit, FakeFiles, FakeSystem, …)
|
||
assets/icon.png the app icon; bundle.sh turns it into Helder.icns
|
||
vendor/ripgrep/rg ripgrep 15 for Apple silicon, from the @vscode/ripgrep build (its LICENSE beside it), bundled as Contents/Helpers/rg
|
||
docs/design/ design tokens, the design canvas and reference screenshots
|
||
```
|
||
|
||
## Commands
|
||
|
||
```bash
|
||
scripts/build.sh [--release]
|
||
scripts/test.sh [--filter Name] # e.g. --filter HelderUITests. or --filter WorkspaceModel
|
||
scripts/run.sh [project-folder]
|
||
scripts/bundle.sh [--install [--force]]
|
||
```
|
||
|
||
Always go through the scripts: they set the toolchain (see Gotchas). Every test runs; there is no skip switch.
|
||
|
||
## Tests
|
||
|
||
How the suites are organised and how to run one: see the Testing section of the [README](../README.md#testing).
|
||
|
||
- Stores and the model are tested on fakes (`WorkspaceHarness` wires a whole window to them). `AppServices` and `WorkspaceModel` take every store explicitly, so no test can reach the user's recents, sessions, layouts or the log file. Services tests use temp folders and temp git repos.
|
||
- Wait with `eventually { … }` or `model.settle()` / `editor.settle()`, never a sleep. The FSEvents tests are the exception: they need a quiet window to prove no event fired.
|
||
|
||
## Gotchas
|
||
|
||
- **Toolchain.** `scripts/env.sh` puts Xcode's toolchain on `PATH` but sets `DEVELOPER_DIR` to the Command Line Tools. With Xcode's developer dir, `/usr/bin/xcrun` and `/usr/bin/git` call the broken `xcodebuild`; SwiftPM then cannot read the manifest API's deployment target, compiles plugins for macOS 11, and SwiftTerm's `swift-argument-parser` plugin fails to build. `swift test` needs the extra Testing flags in `scripts/test.sh`.
|
||
- **`Bundle.module` is off limits** in HelderUI: its accessor looks next to the `.app`, not in `Contents/Resources`, and falls back to an absolute build path. `FontRegistry.fontsDirectory()` searches itself. SwiftTerm does the same for its own bundle.
|
||
- **Fonts.** CoreText registers the WOFF2 files directly. Use PostScript names (`PlexFace`); the Medium face reports its family as "IBM Plex Mono Medium".
|
||
- **ripgrep** is not on this machine's `PATH`. `bundle.sh` copies `$RG_BINARY`, else `vendor/ripgrep/rg`, else an `rg` on `PATH` into `Contents/Helpers/rg`, which `ExecutableLocator.standard` checks first. `$RG_BINARY` overrides it at runtime; the tests use it, else `vendor/ripgrep/rg`. Without any rg, search, the file list and the symbol index fall back to a Swift walk (slower, same results).
|
||
- **Own data.** The recent-projects list (`~/Library/Application Support/Helder/recent-projects.json`, read by ⇧⌘O and the launcher) and the log (`~/Library/Logs/Helder/helder.log`) belong to this app alone. Running it on a scratch folder adds that folder to the list; remove it afterwards. Under `swift run` the UserDefaults domain is `Helder` (sessions, layouts), in the bundle `nl.blijnder.helder`.
|
||
- **`bundle.sh --install`** refuses to replace a `~/Applications/Helder.app` with a different bundle id without `--force`.
|
||
- **⌘N** is the note, so "New Window" is ⇧⌘N. New Window starts a new process on the launcher, and the child never inherits `HELDER_PROJECT` (it would win over the folder argument). ⌘A is select-all in the focused view (in the code pane, the whole file); fluid columns are ⌘L.
|
||
- **Config.** `files.followGitignore` defaults to **false** (the main-process value). There is no CSS layer: code font and size come from config/Typography.
|
||
- **One file, no Original.** The editor deliberately has no tabs and no Original mode. `git.defaultDiffMode: "original"` in an older config decodes as `"updated"`.
|
||
- **SwiftTerm** has no line-height or letter-spacing setting, so `terminal.lineHeight`/`letterSpacing` from the config are ignored.
|
||
- **Pointer.** `Components/PointerPolicy.swift` is the one rule: I-beam, pointing hand or arrow. Text views conform to `PointerTextTarget`; a SwiftUI button or row gets the hand with `.pointerHand()` on the exact view a left click acts on, never on a container. Its region view takes no clicks and reads `\.isEnabled`, `disabledLook` and `\.pointerLayer` (`.overlay` under `OverlayHost` and the ⇧⌘O list), so a disabled button and every column behind an overlay keep the arrow. `updateCursor` asks the `PointerOwner` under the mouse first, so a text field inside a clickable row keeps the I-beam. AppKit hands a cursor update to the hit view, and a region view takes no hits, so `NSHostingView` would set the arrow; `PointerPolicy.installCursorUpdateMonitor()` (called at launch) swallows every cursor update in the key window, passes every mouse move on untouched, and for both runs `updateCursor` once afterwards (`scheduleUpdate`, coalesced per window). Inside an event SwiftUI's hit test returns its root view, so nothing calls `updateCursor` from inside an event, and the deferred call never resets cursor rects, which would fire new updates. Region views and the terminals keep a `PointerTracker` area (cursor update, enter, exit) so AppKit still sends an update when the mouse crosses their edge.
|