125 lines
21 KiB
Markdown
125 lines
21 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, AVFoundation | Everything that touches disk or spawns `git`/`rg`/`php`/`claude`, 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`, `CleanCopyStore`, `SchemaStore`, `TerminalStore`, `LayoutStore`, `OverlayStore`, `ToastStore`, `ReadAloudStore`) 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`.
|
||
- **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 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`, `search`, `diff(busy:)`, `other`): over the search only ⌘G/⌘D route (the rest stays with the search); 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.
|
||
- **Read aloud.** `.readAloudFile` reads the open file's buffer (unsaved edits included) or the file from disk, turns it into prose with `MarkdownSpeech`, and hands it to `ReadAloudStore`; `.readAloudText` speaks the selection (selected Markdown as prose). `ReadAloudStore` lives as long as the window, like `ToastStore`; its `isReading` shows the title bar's Stop, which runs `.stopReading`. `closeProject()` stops the reading.
|
||
- **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 session and ends the terminals.
|
||
- **Lifecycle.** `start()`: recents → config (applied to every store and the terminals) → git, tree 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 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. The Explorer's tail block is a third kind, `.tail` (`TerminalLaunch.tail`: `/usr/bin/tail -f <path>`, no shell): `startTail` ends the old one and bumps `tailGeneration`, which the block uses as its pane's `.id`, so each file gets a fresh view and process; `closeTail` and `terminateAll` end it, and `tailedPath` is never persisted.
|
||
- **Git view.** ⌘G toggles `LayoutStore.isGitViewOpen` (never persisted, reset on a project switch). With a search or Diff overlay up, `.toggleGit`/`.toggleSchemaView` (keys and View menu) dismiss it first and then open the view, never closing a view already open under the search. `WorkspaceView` draws `GitView` as an overlay over title bar, columns and status bar, under `OverlayHost`, so every overlay and toast sits above it; the columns stay mounted. `KeyContext.gitViewOpen` sends keys to `KeyRouter.gitViewKey` (column keys rest, ⌘↵ commits) and makes a bare Esc `.closeGitView` once no overlay is open; `inGitConsole` (first responder is a `GitConsoleFieldEditor`) keeps ⌘↵ from committing out of the console. `openGitView()` / `closeGitView()` in `+Commands` move the focus request (commit message in, previous `activePanel` out). Design source: `design/README.md`.
|
||
- **Schema view.** ⌘D toggles `LayoutStore.isSchemaViewOpen` (never persisted, reset on a project switch); `openGitView`/`openSchemaView` close each other. It exists only when `SchemaStore.isLaravelApp` (an `artisan` file): the title-bar toggle, `KeyContext.schemaAvailable` for ⌘D and the View menu item follow it. `WorkspaceView` draws `SchemaView` like `GitView`. `SchemaStore.body` picks the command-missing prompt, the no-dump state or the diagram. The watcher's `.project` events and ⌘R carry `RefreshScope.schema`: `refresh(readingDump:)` re-checks the command and re-reads the dump only when its modification date moved, keeping viewport and positions (`SchemaLayout.positions(_:saved:)`). Card positions go to `AppServices.schemaLayouts` when a drag ends; the first dump in a store fits once the canvas has a size. `run()` streams `SchemaServicing.runDump` like the Git console and toasts through `notify`. Esc over the view: selection (`.clearSchemaSelection`), then the search text while `SchemaSearchFieldEditor` has the keyboard (`.clearSchemaSearch`), then `.closeSchemaView`. The canvas lays each card out at 100% and scales it into its on-screen frame, so the click and `.pointerHand()` area stay unscaled; scroll and pinch arrive through a local event monitor (`SchemaScrollCatcher`), since the cards would take them otherwise. Contract: [schema.md](schema.md).
|
||
- **Git commands.** Every git write and every typed console command goes through `SourceControlStore.run`, which chains onto `commandTail` so two commands never race for `.git/index.lock`, logs `$ git …` and streams lines via `GitServicing.execute` → `ProcessRunning.stream` into the console (`GitOutputClassifier`, one per run). `execute` never throws and switches off prompts, editors and pagers (`GIT_TERMINAL_PROMPT=0`, `GIT_EDITOR=true`, `GIT_PAGER=cat`), so a run can never wait on input. Typed commands run without literal pathspecs (globs work); buttons always pass explicit paths, never `add -A`. Push/pull/fetch and typed commands get `remoteTimeout` (120 s). Commit always runs git, even when `canCommitNow` is false, so git's refusal is the error the user sees. Branch switching and merging are refused in the store while `isDirty`, without asking git. The status read (`load`) stays on `ProcessRunning.run`.
|
||
- **Commit message generation.** `.generateCommitMessage` → `SourceControlStore.generateCommitMessage()`: `GitServicing.stagedDiff()` (stat + patch, outside `commandTail` and the console), `CommitMessagePrompt.make` (patch cut at 60 000 characters), then `WorkspaceServices.commitMessages` (`ClaudeCommitMessageService`: the binary from `ExecutableLocator.agent`, its folder first on PATH, the prompt via `ProcessRunning.run(input:)`, cleaned with `CommitMessagePrompt.clean`). Success goes through `setCommitMessage` (so it is lowercased) and `focusMessage`; a `CommitMessageError` toasts through `notify`. `isGeneratingMessage` drives the label and ignores a second click. A window close cancels the run with the rest of `work`, which kills the child.
|
||
- **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 view, 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 Git view's commit message); 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 (incl. behind/upstream), GitDerivation (rows, commit text),
|
||
GitSections (the four sections, InlineDiff), GitConsole (echo, input parsing, line classifier), GitBranches,
|
||
GitCommitLog (recent commits, relative time), CommitMessagePrompt (staged-diff prompt, answer cleaning)
|
||
Schema/ SchemaDump (tolerant schema.json decoding), SchemaModel, SchemaLayout (default lanes), SchemaGeometry
|
||
(lines, fit, zoom, centre), SchemaHighlight + SchemaSearch, ArtisanConsole, SchemaCommandPrompt, SchemaPaths
|
||
Highlight/ SyntaxHighlighter and one grammar per language
|
||
Markdown/ block/inline tree and parser, MarkdownSpeech (the prose Read aloud speaks)
|
||
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
|
||
Agent/ CommitMessageGenerating + ClaudeCommitMessageService (`claude -p`, prompt on stdin, no tools, 90 s)
|
||
Git/ GitServicing, GitService, GitDirectory (worktrees)
|
||
Logging/ Log (unified log) + FileLogger (~/Library/Logs/Helder/helder.log)
|
||
Process/ ProcessRunner (`run`, `run(input:)` for stdin, `stream` for line-by-line output), ExecutableLocator
|
||
(`.agent` adds ~/.local/bin and ~/.claude/local), ChildReaper, InstanceLauncher
|
||
Project/ ConfigService, RecentStores, SessionStore, ProjectLocator
|
||
Schema/ SchemaServicing + SchemaService (`php artisan helder:schema` via PHPLocator, the dump), SchemaLayoutPersisting
|
||
Search/ SearchServicing + RipgrepSearchService, ProjectScanner (rg, or a Swift walk)
|
||
Speech/ SpeechServicing + SpeechService (AVSpeechSynthesizer, the system voice), shared by the window
|
||
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
|
||
GitView/ the full-screen Git view (⌘G): top bar, commit block, sections with inline diffs, console, branches, commits;
|
||
GitIcon and the console log/input the Schema view reuses
|
||
SchemaView/ the full-screen Schema view (⌘D): top bar, table list, canvas with cards and lines, detail panel,
|
||
artisan console, the no-dump and command-missing states
|
||
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, clean copy (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
|
||
design/ the design handoff (README.md) and the HTML prototype
|
||
```
|
||
|
||
## 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 unbound; "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.
|
||
- **Removed keys still decode.** `git.confirmStage` / `git.confirmUnstage` are gone from `HelderConfig.Git`; old configs load and ignore them. A saved `ColumnLayoutSnapshot` from the Git-column era still decodes; its `sourceControlWidth` and `gitVisible` are ignored. Keep both tolerant when touching these types.
|
||
- **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.
|