restores Helder in all its glory

This commit is contained in:
2026-09-28 11:34:49 +02:00
parent c2b38b853c
commit 1d29d0952d
280 changed files with 29205 additions and 7 deletions
@@ -0,0 +1,13 @@
import Foundation
/// Polls a main-actor condition, so tests wait for async work without fixed sleeps.
@MainActor
func eventually(timeout: Duration = .seconds(5), _ condition: () -> Bool) async -> Bool {
let clock = ContinuousClock()
let deadline = clock.now + timeout
while clock.now < deadline {
if condition() { return true }
try? await Task.sleep(for: .milliseconds(10))
}
return condition()
}
@@ -0,0 +1,24 @@
import Foundation
import HelderCore
import HelderServices
/// A config service whose answer the test can change, as if `.helder/config.json` was edited.
final class FakeConfig: ConfigServicing, @unchecked Sendable {
private let state: Locked<(config: HelderConfig, resolves: Int)>
init(_ config: HelderConfig = .defaults) {
state = Locked((config, 0))
}
var resolves: Int { state.current.resolves }
func set(_ config: HelderConfig) { state.mutate { $0.config = config } }
func resolve() async -> HelderConfig {
state.mutate { state in
state.resolves += 1
return state.config
}
}
func current() async -> HelderConfig { state.current.config }
}
@@ -0,0 +1,169 @@
import Foundation
import HelderCore
import HelderServices
/// An in-memory project: a tree for the Explorer and file texts for the editor. Records every disk change.
final class FakeFiles: FileServicing, @unchecked Sendable {
private struct State {
var tree: FileNode
var contents: [String: String]
var images: [String: Data] = [:]
var binary: Set<String> = []
var treeLoads = 0
var childReads: [String] = []
var writes: [(path: String, text: String)] = []
var created: [String] = []
var createdDirectories: [String] = []
var renamed: [(String, String)] = []
var deleted: [String] = []
var failWrites = false
}
let root: URL
private let state: Locked<State>
private let gates = Locked([String: [ReadGate]]())
init(tree: FileNode = FileNode(name: "project", kind: .directory, path: "", children: []),
contents: [String: String] = [:], root: URL = URL(fileURLWithPath: "/fake")) {
self.root = root
state = Locked(State(tree: tree, contents: contents))
}
var treeLoads: Int { state.current.treeLoads }
var childReads: [String] { state.current.childReads }
var writes: [(path: String, text: String)] { state.current.writes }
var created: [String] { state.current.created }
var createdDirectories: [String] { state.current.createdDirectories }
var renamed: [(String, String)] { state.current.renamed }
var deleted: [String] { state.current.deleted }
/// Makes every write, create, rename and delete throw.
var failWrites: Bool {
get { state.current.failWrites }
set { state.mutate { $0.failWrites = newValue } }
}
func setTree(_ tree: FileNode) { state.mutate { $0.tree = tree } }
func set(_ path: String, _ text: String) { state.mutate { $0.contents[path] = text } }
func setImage(_ path: String, _ data: Data) { state.mutate { $0.images[path] = data } }
/// Makes a path read as binary, as a file with NUL bytes does.
func setBinary(_ path: String) { state.mutate { $0.binary.insert(path) } }
func current(_ path: String) -> String? { state.current.contents[path] }
/// The file disappears from disk, as when another program deletes it.
func remove(_ path: String) { state.mutate { $0.contents[path] = nil } }
/// The next read of `path` takes the contents it finds at once but returns only when the gate opens.
func holdNextRead(_ path: String) -> ReadGate {
let gate = ReadGate()
gates.mutate { $0[path, default: []].append(gate) }
return gate
}
func tree() async -> FileNode {
state.mutate { state in
state.treeLoads += 1
return state.tree
}
}
func children(of directory: String) async -> [FileNode] {
state.mutate { state in
state.childReads.append(directory)
return FileTree.find(directory, in: state.tree)?.children ?? []
}
}
func read(_ path: String) async throws -> String {
let text = state.current.contents[path]
let gate: ReadGate? = gates.mutate { gates in
guard var waiting = gates[path], !waiting.isEmpty else { return nil }
let first = waiting.removeFirst()
gates[path] = waiting
return first
}
await gate?.wait()
guard let text else { throw CocoaError(.fileNoSuchFile) }
return text
}
func readText(_ path: String) async throws -> FileContents {
if state.current.binary.contains(path) { return .binary }
return .text(try await read(path))
}
func readImage(_ path: String) async -> Data? { state.current.images[path] }
func write(_ path: String, contents text: String) async throws {
try change { state in
state.contents[path] = text
state.writes.append((path, text))
}
}
func createFile(_ path: String) async throws {
try change { $0.created.append(path) }
}
func createDirectory(_ path: String) async throws {
try change { $0.createdDirectories.append(path) }
}
func rename(_ path: String, to name: String) async throws -> String {
try change { $0.renamed.append((path, name)) }
return PathUtils.join(PathUtils.dirname(path), name)
}
func delete(_ path: String) async throws {
try change { $0.deleted.append(path) }
}
private func change(_ apply: (inout State) -> Void) throws {
try state.mutate { state in
if state.failWrites { throw FakeError() }
apply(&state)
}
}
}
func dir(_ path: String, _ children: [FileNode] = []) -> FileNode {
FileNode(name: PathUtils.basename(path), kind: .directory, path: path, children: children)
}
func file(_ path: String) -> FileNode {
FileNode(name: PathUtils.basename(path), kind: .file, path: path)
}
/// root/ ├ .github/ci.yml ├ src/ (Http/Kernel.php, app.php) ├ empty/ ├ .env └ README.md
func sampleTree() -> FileNode {
FileNode(name: "project", kind: .directory, path: "", children: [
dir(".github", [file(".github/ci.yml")]),
dir("src", [dir("src/Http", [file("src/Http/Kernel.php")]), file("src/app.php")]),
dir("empty"),
file(".env"),
file("README.md"),
])
}
/// Holds one read until the test opens it, so a slower read can be made to land last.
final class ReadGate: @unchecked Sendable {
private let stream: AsyncStream<Void>
private let continuation: AsyncStream<Void>.Continuation
private let started = Locked(false)
init() {
(stream, continuation) = AsyncStream.makeStream()
}
/// True once a read is waiting on the gate.
var isWaiting: Bool { started.current }
func open() {
continuation.yield()
continuation.finish()
}
func wait() async {
started.mutate { $0 = true }
for await _ in stream { break }
}
}
@@ -0,0 +1,72 @@
import Foundation
import HelderCore
import HelderServices
/// Records every git call; `load` returns queued snapshots first (each after its delay), then the current one.
final class FakeGit: GitServicing, @unchecked Sendable {
private struct State {
var loads = 0
var staged: [[String]] = []
var unstaged: [[String]] = []
var commits: [String] = []
var discarded: [[String]] = []
var pushes = 0
var queued: [(GitSnapshot?, Duration)] = []
var current: GitSnapshot?
var failCommit = false
var pushResult = PushResult(ok: true, message: "main -> main")
}
private let state: Locked<State>
init(_ snapshot: GitSnapshot? = nil) {
state = Locked(State(current: snapshot))
}
var loads: Int { state.current.loads }
var staged: [[String]] { state.current.staged }
var unstaged: [[String]] { state.current.unstaged }
var commits: [String] { state.current.commits }
var discarded: [[String]] { state.current.discarded }
var pushes: Int { state.current.pushes }
func set(_ snapshot: GitSnapshot?) { state.mutate { $0.current = snapshot } }
func queue(_ snapshot: GitSnapshot?, after delay: Duration) { state.mutate { $0.queued.append((snapshot, delay)) } }
func setFailCommit(_ value: Bool) { state.mutate { $0.failCommit = value } }
func setPushResult(_ value: PushResult) { state.mutate { $0.pushResult = value } }
func load() async throws -> GitSnapshot? {
let (snapshot, delay): (GitSnapshot?, Duration) = state.mutate { state in
state.loads += 1
return state.queued.isEmpty ? (state.current, .zero) : state.queued.removeFirst()
}
if delay > .zero { try? await Task.sleep(for: delay) }
return snapshot
}
func stage(_ paths: [String]) async throws { state.mutate { $0.staged.append(paths) } }
func unstage(_ paths: [String]) async throws { state.mutate { $0.unstaged.append(paths) } }
func commit(message: String) async throws {
try state.mutate { state in
if state.failCommit { throw FakeError() }
state.commits.append(message)
}
}
func push() async -> PushResult {
state.mutate { state in
state.pushes += 1
return state.pushResult
}
}
func discard(_ paths: [String]) async throws { state.mutate { $0.discarded.append(paths) } }
}
/// A snapshot with one change per row: (path, status, staged).
func snapshot(_ rows: [(String, GitStatus, Bool)], branch: String = "main") -> GitSnapshot {
GitSnapshot(branch: branch, ahead: 0, canPush: false, changes: rows.map {
GitFileChange(path: $0.0, status: $0.1, staged: $0.2, original: "a", updated: "b")
})
}
@@ -0,0 +1,26 @@
import Foundation
import HelderCore
import HelderServices
@testable import HelderUI
/// Column layouts per project, in memory instead of UserDefaults.
final class FakeLayouts: LayoutPersisting, @unchecked Sendable {
private let state = Locked([String: ColumnLayoutSnapshot]())
var saved: [String: ColumnLayoutSnapshot] {
get { state.current }
set { state.mutate { $0 = newValue } }
}
func load(root: String) -> ColumnLayoutSnapshot? { state.current[root] }
func save(_ snapshot: ColumnLayoutSnapshot, root: String) { state.mutate { $0[root] = snapshot } }
private let zoom = Locked(0.0)
var zoomLevel: Double {
get { zoom.current }
set { zoom.mutate { $0 = newValue } }
}
func loadZoom() -> Double { zoom.current }
func saveZoom(_ level: Double) { zoom.mutate { $0 = level } }
}
@@ -0,0 +1,33 @@
import Foundation
import HelderCore
import HelderServices
/// The project note in memory; records every write.
final class FakeNotes: NotesServicing, @unchecked Sendable {
private let state: Locked<(stored: String, writes: [String], failWrites: Bool)>
init(_ stored: String = "") {
state = Locked((stored, [], false))
}
var writes: [String] { state.current.writes }
var onDisk: String { state.current.stored }
var failWrites: Bool {
get { state.current.failWrites }
set { state.mutate { $0.failWrites = newValue } }
}
/// Another program rewrote the note file.
func setOnDisk(_ text: String) { state.mutate { $0.stored = text } }
func read() async -> String { state.current.stored }
func write(_ text: String) async throws {
try state.mutate { state in
if state.failWrites { throw CocoaError(.fileWriteNoPermission) }
state.writes.append(text)
state.stored = text
}
}
}
@@ -0,0 +1,17 @@
import Foundation
import HelderCore
import HelderServices
/// The per-project recent-files list.
final class FakeRecentFiles: RecentFilesStoring, @unchecked Sendable {
private let state: Locked<[String]>
init(_ paths: [String] = []) {
state = Locked(paths)
}
var paths: [String] { state.current }
func load() async -> [String] { state.current }
func save(_ paths: [String]) async { state.mutate { $0 = paths } }
}
@@ -0,0 +1,20 @@
import Foundation
import HelderCore
import HelderServices
/// The machine-wide recent-projects list; never the user's real one.
final class FakeRecentProjects: RecentProjectsStoring, @unchecked Sendable {
private let state: Locked<[RecentProject]>
init(_ projects: [RecentProject] = []) {
state = Locked(projects)
}
var projects: [RecentProject] { state.current }
func list() async -> [RecentProject] { state.current }
func add(_ path: String) async {
state.mutate { $0 = RecentLists.pushing(RecentProject(path: path, name: PathUtils.basename(path)), onto: $0) }
}
}
@@ -0,0 +1,36 @@
import Foundation
import HelderCore
import HelderServices
/// Canned search answers, an optional delay per query, and a log of what was asked.
final class FakeSearch: SearchServicing, @unchecked Sendable {
private let results: [String: [ContentGroup]]
private let delays: [String: Duration]
private let files: [String]
private let available: Bool
private let queries = Locked<[String]>([])
private let answered = Locked<[String]>([])
init(results: [String: [ContentGroup]] = [:], delays: [String: Duration] = [:], files: [String] = [],
available: Bool = true) {
self.results = results
self.delays = delays
self.files = files
self.available = available
}
var contentQueries: [String] { queries.current }
/// Queries whose answer has been returned, in the order they finished.
var answeredQueries: [String] { answered.current }
func isAvailable() async -> Bool { available }
func searchContent(_ query: String) async -> [ContentGroup] {
queries.mutate { $0.append(query) }
if let delay = delays[query] { try? await Task.sleep(for: delay) }
answered.mutate { $0.append(query) }
return results[query] ?? []
}
func listFiles(under directory: String?) async -> [String] { files }
}
@@ -0,0 +1,21 @@
import Foundation
import HelderCore
import HelderServices
@testable import HelderUI
/// Sessions and the agent split, in memory instead of UserDefaults.
final class FakeSession: SessionStoring, @unchecked Sendable {
private let state = Locked((sessions: [String: SessionState](), layout: LayoutState()))
var sessions: [String: SessionState] {
get { state.current.sessions }
set { state.mutate { $0.sessions = newValue } }
}
var layout: LayoutState { state.current.layout }
func loadSession(root: String) -> SessionState? { state.current.sessions[root] }
func saveSession(_ session: SessionState, root: String) { state.mutate { $0.sessions[root] = session } }
func loadLayout() -> LayoutState { state.current.layout }
func saveLayout(_ layout: LayoutState) { state.mutate { $0.layout = layout } }
}
@@ -0,0 +1,38 @@
import Foundation
import HelderCore
import HelderServices
/// Declared class names and lookups set by the test; counts invalidations.
final class FakeSymbols: SymbolServicing, @unchecked Sendable {
private struct State {
var declared: Set<String> = []
var lookups: [String: SymbolLookup] = [:]
var invalidations = 0
var nameLoads = 0
}
private let state = Locked(State())
var declared: Set<String> {
get { state.current.declared }
set { state.mutate { $0.declared = newValue } }
}
var lookups: [String: SymbolLookup] {
get { state.current.lookups }
set { state.mutate { $0.lookups = newValue } }
}
var invalidations: Int { state.current.invalidations }
var nameLoads: Int { state.current.nameLoads }
func names() async -> Set<String> {
state.mutate { state in
state.nameLoads += 1
return state.declared
}
}
func lookup(_ name: String) async -> SymbolLookup { state.current.lookups[name] ?? .empty(name) }
func invalidate() async { state.mutate { $0.invalidations += 1 } }
}
@@ -0,0 +1,30 @@
import Foundation
import HelderCore
@testable import HelderUI
/// Dialogs, pasteboard and Finder, recorded instead of shown.
@MainActor
final class FakeSystem: SystemActing {
var chosenFolder: URL?
var unsavedCloseChoice = UnsavedCloseChoice.cancel
var clipboard: String?
private(set) var copied: [String] = []
private(set) var revealed: [URL] = []
private(set) var unsavedCloseQuestions: [String] = []
/// Each `openNewInstance` call's folder; nil for the launcher.
private(set) var newInstances: [URL?] = []
func chooseFolder() async -> URL? { chosenFolder }
func copy(_ text: String) { copied.append(text) }
func pasteboardText() -> String? { clipboard }
func revealInFinder(_ url: URL) { revealed.append(url) }
func confirmUnsavedClose(_ path: String) -> UnsavedCloseChoice {
unsavedCloseQuestions.append(path)
return unsavedCloseChoice
}
func openLog() {}
func revealLog() {}
func openNewInstance(_ root: URL?) { newInstances.append(root) }
}
@@ -0,0 +1,18 @@
import Foundation
import HelderCore
@testable import HelderUI
/// A terminal pane without a PTY: records what the store sends and spawns.
@MainActor
final class FakeTerminal: TerminalSessionHandle {
var sent: [String] = []
var starts: [(launch: TerminalLaunch, argv0: String)] = []
var terminations = 0
var selectedText: String?
var pasted: [String] = []
func send(_ text: String) { sent.append(text) }
func terminate() { terminations += 1 }
func paste(_ text: String) { pasted.append(text) }
func start(_ launch: TerminalLaunch, argv0: String) { starts.append((launch, argv0)) }
}
@@ -0,0 +1,18 @@
import Foundation
import HelderCore
import HelderServices
/// A watcher the test fires by hand.
final class FakeWatcher: FileWatching {
private(set) var root: URL?
private(set) var stopped = false
private var handler: (@Sendable (WatchEvent) -> Void)?
func start(root: URL, handler: @escaping @Sendable (WatchEvent) -> Void) {
self.root = root
self.handler = handler
}
func stop() { stopped = true }
func emit(_ event: WatchEvent) { handler?(event) }
}
@@ -0,0 +1,22 @@
import Foundation
/// A value behind a lock, so a fake can be `Sendable` and still be read synchronously from a test.
final class Locked<Value>: @unchecked Sendable {
private let lock = NSLock()
private var value: Value
init(_ value: Value) {
self.value = value
}
var current: Value { lock.withLock { value } }
@discardableResult
func mutate<T>(_ change: (inout Value) throws -> T) rethrows -> T {
lock.lock()
defer { lock.unlock() }
return try change(&value)
}
}
struct FakeError: Error {}
@@ -0,0 +1,10 @@
import HelderCore
import HelderUI
/// The labels of a menu's action entries, separators left out.
func menuLabels(_ request: ContextMenuRequest) -> [String] {
request.entries.compactMap { entry -> String? in
guard case let .action(_, label) = entry else { return nil }
return label
}
}
@@ -0,0 +1,78 @@
import Foundation
import HelderCore
import HelderServices
@testable import HelderUI
/// A simple stand-in for `GitDerivation.derive`: one row per change, no diffs.
enum TestDerivation {
static func derive(_ snapshot: GitSnapshot?) -> GitWorkingState {
guard let snapshot else { return GitWorkingState() }
let changes = snapshot.changes.map {
Change(path: $0.path, status: $0.status, added: $0.updated.isEmpty ? 0 : 1,
removed: $0.original.isEmpty ? 0 : 1, staged: $0.staged)
}
return GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush,
changes: changes, stagedPaths: Set(changes.filter(\.staged).map(\.path)),
isRepository: true)
}
}
/// Collects a store's toasts, plus the pasteboard and Finder calls it makes through `system`.
@MainActor
final class Recorder {
let system = FakeSystem()
var toasts: [(String, String?)] = []
var toastTitles: [String] { toasts.map(\.0) }
var copied: [String] { system.copied }
var revealed: [URL] { system.revealed }
func notify(_ title: String, _ detail: String?) {
toasts.append((title, detail))
}
}
/// A whole-file diff built by hand, for tests that only need "this file changed".
func makeDiff(original: String, updated: String, added: Int = 1, removed: Int = 0,
isAddedFile: Bool = false, isDeletedFile: Bool = false) -> Diff {
Diff(rows: [], left: [], right: [], split: [], added: added, removed: removed,
isDeletedFile: isDeletedFile, isAddedFile: isAddedFile, original: original, updated: updated)
}
/// The git state an EditorStore follows, mutable from a test.
@MainActor
final class GitStateBox {
var state = GitWorkingState.empty
func change(_ path: String, _ diff: Diff) {
state.fileDiffs[path] = diff
}
}
@MainActor
final class OverlayRecorder {
var presented: [Overlay] = []
var diffDismissals = 0
}
/// An EditorStore on fakes, with its overlay hooks recorded.
@MainActor
struct EditorHarness {
let files: FakeFiles
let git = GitStateBox()
let session = FakeSession()
let recent: FakeRecentFiles
let store: EditorStore
let overlays = OverlayRecorder()
init(files: [String: String] = [:], recent: [String] = []) {
self.files = FakeFiles(contents: files)
self.recent = FakeRecentFiles(recent)
let git = self.git
store = EditorStore(root: "/fake", files: self.files, gitState: { git.state },
session: session, recentFiles: self.recent)
let overlays = self.overlays
store.presentOverlay = { overlays.presented.append($0) }
store.dismissDiffOverlay = { overlays.diffDismissals += 1 }
}
}
+6
View File
@@ -0,0 +1,6 @@
import Testing
extension Tag {
/// Spawns a real process in a pseudo-terminal.
@Tag static var realProcess: Self
}
@@ -0,0 +1,83 @@
import Foundation
import HelderCore
import HelderServices
@testable import HelderUI
/// A workspace wired entirely to fakes (no disk, no git, no user defaults), with a handle on each fake.
@MainActor
struct WorkspaceHarness {
let root: URL
let model: WorkspaceModel
let git: FakeGit
let files: FakeFiles
let config: FakeConfig
let notes: FakeNotes
let symbols: FakeSymbols
let recentFiles: FakeRecentFiles
let recents: FakeRecentProjects
let session: FakeSession
let layouts: FakeLayouts
let system: FakeSystem
let watchers: WatcherBox
let agent = FakeTerminal()
final class WatcherBox {
var made: [FakeWatcher] = []
var last: FakeWatcher? { made.last }
}
init(root: URL? = URL(fileURLWithPath: "/fake/project"), config: HelderConfig = .defaults, note: String = "",
git: GitSnapshot? = nil, tree: FileNode = sampleTree(), contents: [String: String] = [:],
recents: [RecentProject] = [], session: FakeSession = FakeSession()) {
let git = FakeGit(git)
let files = FakeFiles(tree: tree, contents: contents, root: root ?? URL(fileURLWithPath: "/"))
let config = FakeConfig(config)
let notes = FakeNotes(note)
let symbols = FakeSymbols()
let recentFiles = FakeRecentFiles()
let recentStore = FakeRecentProjects(recents)
let layouts = FakeLayouts()
let system = FakeSystem()
let watchers = WatcherBox()
let app = AppServices(
recentProjects: recentStore, session: session, layouts: layouts, system: system,
makeWorkspace: { _ in
WorkspaceServices(git: git, files: files, search: FakeSearch(), symbols: symbols,
config: config, notes: notes, recentFiles: recentFiles)
},
makeWatcher: {
let watcher = FakeWatcher()
watchers.made.append(watcher)
return watcher
}
)
model = WorkspaceModel(root: root, app: app, timings: .immediate)
self.root = root ?? URL(fileURLWithPath: "/")
self.git = git
self.files = files
self.config = config
self.notes = notes
self.symbols = symbols
self.recentFiles = recentFiles
self.recents = recentStore
self.session = session
self.layouts = layouts
self.system = system
self.watchers = watchers
model.terminal.attach(agent, as: .agent)
}
/// Starts the model and waits for everything it kicked off.
func start() async {
await model.start()
await model.settle()
}
/// Runs a command and waits for the work it started.
func perform(_ command: Command) async {
model.perform(command)
await model.settle()
}
var toastTitles: [String] { model.toasts.toasts.map(\.title) }
}