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,159 @@
import HelderCore
import HelderServices
@testable import HelderUI
import Testing
private struct MemorySession: SessionStoring {
func loadSession(root: String) -> SessionState? { nil }
func saveSession(_ session: SessionState, root: String) {}
func loadLayout() -> LayoutState { LayoutState(agentFraction: 0.9) }
func saveLayout(_ layout: LayoutState) {}
}
@MainActor
@Suite struct LayoutStoreTests {
@Test func restoresAClampedAgentSplit() {
#expect(LayoutStore(session: MemorySession()).agentFraction == 0.82)
}
@Test func draggingLocksTheColumns() {
let layout = LayoutStore(session: MemorySession())
layout.windowResized(width: 1760)
#expect(layout.fluid)
layout.dragExplorer(by: 1000)
#expect(!layout.fluid)
#expect(layout.widths.explorer == 520)
}
@Test func sourceControlDragsStayInsideTheirRange() {
let layout = LayoutStore(session: MemorySession())
layout.dragSourceControl(by: -1000)
#expect(layout.widths.sourceControl == 160)
layout.dragSourceControl(by: 5000)
#expect(layout.widths.sourceControl == 460)
}
@Test func theAgentColumnNeverSqueezesTheEditorBelowItsMinimum() {
let layout = LayoutStore(session: MemorySession())
layout.windowResized(width: 1760)
layout.dragAgent(by: -5000)
let editor = 1760 - 3 - layout.widths.sourceControl - layout.widths.explorer - layout.widths.agent
#expect(editor >= ColumnLayout.minEditorWidth)
}
@Test func roomyWindowsUseTheDesignProportions() {
let layout = LayoutStore(session: MemorySession())
layout.windowResized(width: 1760)
#expect(layout.widths == ColumnWidths(sourceControl: 236, explorer: 289, agent: 480))
}
@Test func focusChangesTheFluidWidthsOnlyBelow1600() {
let layout = LayoutStore(session: MemorySession())
layout.windowResized(width: 1500)
layout.focus(.terminal)
#expect(layout.widths.agent == 750)
layout.focus(.editor)
#expect(layout.widths.agent == 300)
layout.windowResized(width: 1800)
layout.focus(.terminal)
#expect(layout.widths.agent == (1800 * 0.273).rounded())
}
@Test func autoFitBackOnRefitsImmediately() {
let layout = LayoutStore(session: MemorySession())
layout.windowResized(width: 1760)
layout.dragExplorer(by: 100)
#expect(!layout.fluid)
layout.toggleFluid()
#expect(layout.fluid)
#expect(layout.widths.explorer == 289)
}
@Test func lockedColumnsShrinkToKeepTheEditorWhenTheWindowNarrows() {
let layout = LayoutStore(session: MemorySession())
layout.windowResized(width: 1760)
layout.dragExplorer(by: 0)
layout.windowResized(width: 1100)
let total = layout.widths.sourceControl + layout.widths.explorer + layout.widths.agent
#expect(total <= 1100 - 3 - ColumnLayout.minEditorWidth)
}
@Test func hidingGitDropsItsFocus() {
let layout = LayoutStore(session: MemorySession())
layout.focus(.sourceControl)
layout.toggleGit()
#expect(layout.activePanel == nil)
layout.focus(.sourceControl)
#expect(layout.activePanel == nil)
}
@Test func aProjectsColumnsSurviveARestart() {
let store = FakeLayouts()
let first = LayoutStore(session: MemorySession(), persistence: store)
first.restore(root: "/p")
first.windowResized(width: 1760)
first.dragExplorer(by: 40)
first.endDrag()
first.toggleGit()
let second = LayoutStore(session: MemorySession(), persistence: store)
second.windowResized(width: 1760)
second.restore(root: "/p")
#expect(!second.fluid)
#expect(!second.gitVisible)
#expect(second.widths.explorer == first.widths.explorer)
#expect(second.widths.agent == first.widths.agent)
}
@Test func projectsKeepSeparateLayouts() {
let store = FakeLayouts()
let layout = LayoutStore(session: MemorySession(), persistence: store)
layout.restore(root: "/a")
layout.toggleGit()
layout.restore(root: "/b")
#expect(layout.gitVisible)
layout.restore(root: "/a")
#expect(!layout.gitVisible)
}
@Test func dragsSaveOnlyWhenTheyEnd() {
let store = FakeLayouts()
let layout = LayoutStore(session: MemorySession(), persistence: store)
layout.restore(root: "/p")
layout.dragExplorer(by: 10)
#expect(store.saved["/p"] == nil)
layout.endDrag()
#expect(store.saved["/p"]?.fluid == false)
}
@Test func theAgentSplitFollowsTheDragAndStaysClamped() {
let session = FakeSession()
let layout = LayoutStore(session: session)
layout.dragAgentSplit(by: 100, height: 1000)
#expect(abs(layout.agentFraction - 0.62) < 0.0001)
#expect(abs(session.layout.agentFraction - 0.62) < 0.0001)
layout.dragAgentSplit(by: 5000, height: 1000)
#expect(layout.agentFraction == 0.82)
}
@Test func aWindowXMapsToTheColumnUnderIt() {
let layout = LayoutStore(session: MemorySession())
layout.windowResized(width: 1760)
#expect(layout.panel(atX: 10) == .sourceControl)
#expect(layout.panel(atX: 300) == .explorer)
#expect(layout.panel(atX: 900) == .editor)
#expect(layout.panel(atX: 1700) == .terminal)
#expect(layout.panel(atX: 236, splitterMargin: 4) == nil)
layout.toggleGit()
#expect(layout.panel(atX: 10) == .explorer)
}
@Test func neighbourColumnsClampAtTheEdgesAndSkipAHiddenGitColumn() {
let layout = LayoutStore(session: MemorySession())
#expect(layout.neighbour(of: nil, step: 1) == .terminal)
#expect(layout.neighbour(of: .terminal, step: 1) == .terminal)
#expect(layout.neighbour(of: .explorer, step: -1) == .sourceControl)
layout.toggleGit()
#expect(layout.neighbour(of: .explorer, step: -1) == .explorer)
}
}
@@ -0,0 +1,27 @@
@testable import HelderUI
import Testing
@MainActor
@Suite struct OverlayStoreTests {
@Test func overlaysNeverStack() {
let store = OverlayStore()
store.present(.search(seed: "foo"))
store.present(.note)
#expect(store.current == .note)
store.dismiss()
#expect(store.current == .none)
#expect(!store.isPresented)
}
@Test func everyChangeIsReportedWithTheOverlayItReplaced() {
let store = OverlayStore()
var changes: [(Overlay, Overlay)] = []
store.onChange = { changes.append(($0, $1)) }
store.present(.note)
store.present(.note)
store.present(.shortcuts)
store.dismiss()
#expect(changes.map(\.0) == [.none, .note, .shortcuts])
#expect(changes.map(\.1) == [.note, .shortcuts, .none])
}
}
@@ -0,0 +1,38 @@
import HelderUI
import Testing
@MainActor
private final class RecordingTerminal: TerminalSessionHandle {
var sent: [String] = []
func send(_ text: String) { sent.append(text) }
func terminate() {}
}
@MainActor
@Suite struct TerminalStoreTests {
@Test func insertIntoAgentIsABracketedPasteOnItsOwnLine() {
let store = TerminalStore(projectRoot: "/p")
let agent = RecordingTerminal()
store.attach(agent, as: .agent)
store.insertIntoAgent(text: "a.php:1")
store.insertIntoAgent(text: "b.php:2-3")
#expect(agent.sent == ["\u{1b}[200~a.php:1\u{1b}[201~", "\u{1b}[200~\nb.php:2-3\u{1b}[201~"])
}
@Test func enterEmptiesTheComposer() {
let store = TerminalStore()
let agent = RecordingTerminal()
store.attach(agent, as: .agent)
store.agentReceivedInput("x")
#expect(store.agentComposerHasText)
store.agentReceivedInput("\r")
store.insertIntoAgent(text: "ref")
#expect(agent.sent == ["\u{1b}[200~ref\u{1b}[201~"])
}
@Test func withoutAnAgentNothingIsSent() {
let store = TerminalStore()
store.insertIntoAgent(text: "ref")
#expect(!store.agentComposerHasText)
}
}
@@ -0,0 +1,13 @@
@testable import HelderUI
import Testing
@MainActor
@Suite struct ToastStoreTests {
@Test func toastsStackInArrivalOrder() {
let toasts = ToastStore()
toasts.show("Saved", detail: "a.php")
toasts.show("Pushed")
#expect(toasts.toasts.map(\.title) == ["Saved", "Pushed"])
#expect(toasts.toasts.first?.detail == "a.php")
}
}
@@ -0,0 +1,132 @@
import CoreGraphics
import Foundation
import HelderCore
import HelderServices
@testable import HelderUI
import Testing
@MainActor
@Suite struct WorkspaceCloseTests {
private func dirtyHarness() async -> WorkspaceHarness {
let harness = WorkspaceHarness(contents: ["a.php": "<?php"])
await harness.start()
harness.model.open("a.php")
await harness.model.settle()
harness.model.editor?.edit("<?php // unsaved")
return harness
}
@Test func closingAWindowWithUnsavedEditsAsksFirst() async {
let harness = await dirtyHarness()
harness.system.unsavedCloseChoice = .cancel
#expect(await harness.model.prepareToClose() == false)
#expect(harness.system.unsavedCloseQuestions == ["a.php"])
#expect(harness.model.editor?.isDirty("a.php") == true)
}
@Test func savingFromTheCloseQuestionWritesBeforeTheWindowGoes() async {
let harness = await dirtyHarness()
harness.system.unsavedCloseChoice = .save
harness.model.note?.text = "thought"
#expect(await harness.model.prepareToClose())
#expect(harness.files.current("a.php") == "<?php // unsaved")
#expect(harness.notes.writes == ["thought"])
#expect(harness.session.sessions["/fake/project"]?.active == "a.php")
}
@Test func aCancelledProjectSwitchKeepsTheProjectAndItsEdits() async {
let harness = await dirtyHarness()
harness.system.unsavedCloseChoice = .cancel
await harness.model.openProject(URL(fileURLWithPath: "/fake/other"))
#expect(harness.model.root == harness.root)
#expect(harness.model.editor?.text(for: "a.php") == "<?php // unsaved")
#expect(harness.agent.terminations == 0)
}
@Test func aProjectSwitchAsksAboutUnsavedEditsAndSavesThem() async {
let harness = await dirtyHarness()
harness.system.unsavedCloseChoice = .save
await harness.model.openProject(URL(fileURLWithPath: "/fake/other"))
#expect(harness.model.root?.path == "/fake/other")
#expect(harness.files.current("a.php") == "<?php // unsaved")
}
@Test func workStillRunningAtASwitchStaysWithTheOldProject() async {
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false)]), contents: ["a.php": "<?php"])
await harness.start()
harness.model.open("a.php")
await harness.model.settle()
let oldEditor = harness.model.editor
let gate = harness.files.holdNextRead("a.php")
harness.model.perform(.context(.discard("a.php")))
harness.model.perform(.confirmPending)
#expect(await eventually { gate.isWaiting })
harness.model.perform(.openRecentProject("/fake/other"))
gate.open()
await harness.model.settle()
#expect(harness.model.root?.path == "/fake/other")
#expect(harness.model.editor !== oldEditor)
#expect(harness.model.editor?.states["a.php"] == nil)
}
@Test func aFailedNoteSaveSaysSo() async {
let harness = WorkspaceHarness()
await harness.start()
harness.notes.failWrites = true
harness.model.note?.text = "keep me"
harness.model.windowDidResignKey()
await harness.model.settle()
#expect(harness.toastTitles.contains("Save failed"))
}
@Test func anOutsideEditOfTheNoteIsPickedUp() async {
let harness = WorkspaceHarness(note: "before")
await harness.start()
harness.notes.setOnDisk("written by the agent")
await harness.model.handle(.project)
await harness.model.settle()
#expect(harness.model.note?.text == "written by the agent")
}
}
@MainActor
@Suite struct WorkspaceShortcutTests {
@Test func theRowMenuAnchorsToTheReportedRowFrame() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.focus(.explorer))
harness.model.perform(.moveRowCursor(1))
guard let path = harness.model.explorer?.selectedPath else {
Issue.record("no row selected")
return
}
harness.model.rowFrameChanged(.tree(path), CGRect(x: 250, y: 312, width: 200, height: 26))
harness.model.perform(.openRowMenu)
guard case let .contextMenu(menu) = harness.model.overlay.current else {
Issue.record("no menu")
return
}
#expect(menu.anchor.y == 316)
#expect(Double(menu.anchor.x) == harness.model.layout.span(of: .explorer)?.upperBound)
}
@Test func commandASelectsTheOpenFile() async {
let harness = WorkspaceHarness(contents: ["a.php": "<?php"])
await harness.start()
harness.model.open("a.php")
let before = harness.model.editor?.selectAllRequest
harness.model.perform(.selectAllInFile)
#expect(harness.model.editor?.selectAllRequest != before)
}
@Test func zoomStepsAndIsRemembered() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.zoom(.bigger))
harness.model.perform(.zoom(.bigger))
#expect(harness.model.layout.zoomLevel == 1)
#expect(harness.layouts.zoomLevel == 1)
harness.model.perform(.zoom(.reset))
#expect(harness.model.layout.textScale == 1)
}
}
@@ -0,0 +1,588 @@
import CoreGraphics
import Foundation
import HelderCore
import HelderServices
@testable import HelderUI
import Testing
@MainActor
@Suite struct WorkspaceModelLifecycleTests {
@Test func startingAProjectLoadsEverythingOnceAndWatchesIt() async {
let harness = WorkspaceHarness(note: "remember this", git: snapshot([("a.php", .modified, false)]))
await harness.start()
#expect(harness.model.isReady)
#expect(harness.config.resolves == 1)
#expect(harness.git.loads == 1)
#expect(harness.files.treeLoads == 1)
#expect(harness.model.sourceControl?.state.changes.map(\.path) == ["a.php"])
#expect(harness.model.explorer?.tree != nil)
#expect(harness.model.note?.text == "remember this")
#expect(harness.watchers.last?.root == harness.root)
#expect(harness.recents.projects.first?.path == harness.root.path)
#expect(harness.model.sourceControl?.isPolling == true)
}
@Test func startingTwiceDoesNotLoadTwice() async {
let harness = WorkspaceHarness()
await harness.start()
await harness.start()
#expect(harness.git.loads == 1)
}
@Test func theSessionIsRestoredOnlyWhenTheConfigSaysSo() async {
let session = FakeSession()
session.sessions["/fake/project"] = SessionState(active: "README.md")
var config = HelderConfig.defaults
config.session.restoreOnLaunch = false
let off = WorkspaceHarness(config: config, contents: ["README.md": "# hi"], session: session)
await off.start()
#expect(off.model.editor?.activePath == nil)
let on = WorkspaceHarness(contents: ["README.md": "# hi"], session: session)
await on.start()
#expect(on.model.editor?.activePath == "README.md")
#expect(on.model.editor?.text(for: "README.md") == "# hi")
}
@Test func theConfigReachesEveryStore() async {
var config = HelderConfig.defaults
config.git.confirmDiscard = false
config.git.defaultDiffMode = .diff
config.editor.tabSize = 2
let harness = WorkspaceHarness(config: config)
await harness.start()
#expect(harness.model.sourceControl?.config.confirmDiscard == false)
#expect(harness.model.editor?.defaultMode == .diff)
#expect(harness.model.editor?.editorConfig.tabSize == 2)
#expect(harness.model.terminal.isConfigured)
}
@Test func aConfigChangeIsReappliedEverywhere() async {
let harness = WorkspaceHarness()
await harness.start()
var changed = HelderConfig.defaults
changed.ai.command = "other-agent"
changed.git.confirmStage = true
changed.editor.tabSize = 8
harness.config.set(changed)
await harness.model.handle(.config)
#expect(harness.model.config.ai.command == "other-agent")
#expect(harness.model.terminal.config.ai.command == "other-agent")
#expect(harness.model.sourceControl?.config.confirmStage == true)
#expect(harness.model.editor?.editorConfig.tabSize == 8)
}
@Test func withoutAProjectTheWindowIsTheLauncher() async {
let recents = [RecentProject(path: "/code/a", name: "a")]
let harness = WorkspaceHarness(root: nil, recents: recents)
await harness.start()
#expect(harness.model.root == nil)
#expect(harness.model.isReady)
#expect(harness.model.launcher.recents == recents)
#expect(harness.git.loads == 0)
#expect(harness.watchers.made.isEmpty)
}
@Test func openingAProjectFromTheLauncherSwitchesTheWindow() async {
let harness = WorkspaceHarness(root: nil)
await harness.start()
let next = URL(fileURLWithPath: "/fake/other")
await harness.model.openProject(next)
#expect(harness.model.root == next)
#expect(harness.model.name == "other")
#expect(harness.model.editor != nil)
#expect(harness.git.loads == 1)
#expect(harness.recents.projects.map(\.path) == [next.path])
}
@Test func switchingProjectsEndsTheOldProjectCleanly() async {
let harness = WorkspaceHarness(note: "old", contents: ["a.php": "<?php"])
await harness.start()
harness.model.open("a.php")
await harness.model.settle()
harness.model.note?.text = "unsaved thought"
let firstWatcher = harness.watchers.last
await harness.model.openProject(URL(fileURLWithPath: "/fake/other"))
#expect(firstWatcher?.stopped == true)
#expect(harness.watchers.made.count == 2)
#expect(harness.agent.terminations == 1)
#expect(harness.notes.writes == ["unsaved thought"])
#expect(harness.session.sessions["/fake/project"]?.active == "a.php")
}
@Test func closingTheWindowSavesAndEndsTheTerminals() async {
let harness = WorkspaceHarness(contents: ["a.php": "<?php"])
await harness.start()
harness.model.open("a.php")
harness.model.windowWillClose()
await harness.model.settle()
#expect(harness.agent.terminations == 1)
#expect(harness.session.sessions["/fake/project"]?.active == "a.php")
#expect(harness.model.sourceControl?.isPolling == false)
}
@Test func reopeningTheSameProjectOnlyClosesTheLauncher() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.showRecentProjects)
await harness.model.openProject(harness.root)
#expect(harness.model.overlay.current == .none)
#expect(harness.git.loads == 1)
}
@Test func theClassListLoadsAfterLaunch() async {
let harness = WorkspaceHarness()
harness.symbols.declared = ["User"]
await harness.start()
#expect(harness.model.editor?.knownSymbols == ["User"])
}
}
@MainActor
@Suite struct WorkspaceModelRefreshTests {
@Test func aBurstOfFileEventsBecomesOneRefresh() async {
let harness = WorkspaceHarness()
await harness.start()
for _ in 0..<5 { await harness.model.handle(.project) }
await harness.model.handle(.git)
await harness.model.settle()
#expect(harness.git.loads == 2)
#expect(harness.files.treeLoads == 2)
#expect(harness.symbols.invalidations == 1)
}
@Test func aProjectEventRereadsOpenFilesAndTheClassList() async {
let harness = WorkspaceHarness(contents: ["a.php": "one"])
await harness.start()
harness.model.open("a.php")
await harness.model.settle()
harness.files.set("a.php", "two")
harness.symbols.declared = ["Order"]
await harness.model.handle(.project)
await harness.model.settle()
#expect(harness.model.editor?.text(for: "a.php") == "two")
#expect(harness.model.editor?.knownSymbols == ["Order"])
}
@Test func aProjectEventKeepsUnsavedEdits() async {
let harness = WorkspaceHarness(contents: ["a.php": "one"])
await harness.start()
harness.model.open("a.php")
await harness.model.settle()
harness.model.editor?.edit("typing")
harness.files.set("a.php", "agent")
await harness.model.handle(.project)
await harness.model.settle()
#expect(harness.model.editor?.text(for: "a.php") == "typing")
}
@Test func aGitEventRefreshesOnlyGit() async {
let harness = WorkspaceHarness()
await harness.start()
await harness.model.handle(.git)
await harness.model.settle()
#expect(harness.git.loads == 2)
#expect(harness.files.treeLoads == 1)
}
@Test func watcherEventsArriveFromAnyThread() async throws {
let harness = WorkspaceHarness()
await harness.start()
nonisolated(unsafe) let watcher = try #require(harness.watchers.last)
await Task.detached { watcher.emit(.git) }.value
#expect(await eventually { harness.git.loads == 2 })
}
@Test func commandRLetsTheDiskWinAndFlashes() async {
let harness = WorkspaceHarness(contents: ["a.php": "one"])
await harness.start()
harness.model.open("a.php")
await harness.model.settle()
harness.model.editor?.edit("typing")
harness.files.set("a.php", "agent")
await harness.perform(.refresh)
#expect(harness.model.refreshTick == 1)
#expect(harness.model.editor?.text(for: "a.php") == "agent")
#expect(harness.git.loads == 2)
#expect(harness.files.treeLoads == 2)
}
@Test func focusingSourceControlRefreshesGitOnce() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.pointerFocused(.sourceControl)
harness.model.pointerFocused(.sourceControl)
await harness.model.settle()
#expect(harness.git.loads == 2)
}
@Test func savingAFileRefreshesGit() async {
let harness = WorkspaceHarness(contents: ["a.php": "one"])
await harness.start()
harness.model.open("a.php")
await harness.model.settle()
harness.model.editor?.edit("two")
await harness.perform(.save)
#expect(harness.files.writes.map(\.text) == ["two"])
#expect(harness.git.loads == 2)
#expect(harness.toastTitles == ["Saved"])
}
}
@MainActor
@Suite struct WorkspaceModelActionTests {
@Test func openingAFileRevealsItAndWidensTheEditor() async {
let harness = WorkspaceHarness(contents: ["src/Http/Kernel.php": "a\nb\nc\nd"])
await harness.start()
await harness.perform(.open("src/Http/Kernel.php", OpenOptions(line: 4)))
#expect(harness.model.editor?.activePath == "src/Http/Kernel.php")
#expect(harness.model.editor?.cursor?.line == 4)
#expect(harness.model.explorer?.expanded == ["src", "src/Http"])
#expect(harness.model.explorer?.selectedPath == "src/Http/Kernel.php")
#expect(harness.model.layout.focusZone == .editor)
}
@Test func aTooBigFileIsSelectedButNotOpened() async {
let harness = WorkspaceHarness()
await harness.start()
await harness.perform(.open("composer.lock", OpenOptions()))
#expect(harness.model.editor?.activePath == nil)
#expect(harness.model.editor?.tooBig?.path == "composer.lock")
#expect(harness.model.explorer?.selectedPath == "composer.lock")
}
@Test func copyReferenceUsesThePasteboardAndToastsOnce() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.showContextMenu(.file(path: "a/b.php"), anchor: .zero))
await harness.perform(.context(.copyReference("a/b.php")))
#expect(harness.system.copied == ["a/b.php"])
#expect(harness.model.overlay.current == .none)
#expect(harness.toastTitles == ["Copied reference"])
}
@Test func deleteAsksFirstThenForgetsTheFile() async {
let harness = WorkspaceHarness(contents: ["README.md": "# hi"])
await harness.start()
harness.model.open("README.md")
await harness.perform(.context(.delete("README.md", isDirectory: false)))
guard case let .confirm(request) = harness.model.overlay.current else {
Issue.record("expected a confirm overlay")
return
}
#expect(request.title == "Delete file?")
#expect(harness.files.deleted.isEmpty)
await harness.perform(.confirmPending)
#expect(harness.model.overlay.current == .none)
#expect(harness.files.deleted == ["README.md"])
#expect(harness.model.editor?.activePath == nil)
#expect(harness.toastTitles == ["Deleted file"])
}
@Test func discardAsksUnderTheConfigThenReloadsTheFile() async {
let harness = WorkspaceHarness(contents: ["a.php": "edited"])
await harness.start()
harness.model.open("a.php")
await harness.model.settle()
await harness.perform(.context(.discard("a.php")))
guard case let .confirm(request) = harness.model.overlay.current else {
Issue.record("expected a confirm overlay")
return
}
#expect(request.confirmLabel == "Discard")
harness.files.set("a.php", "committed")
await harness.perform(.confirmPending)
#expect(harness.git.discarded == [["a.php"]])
#expect(harness.model.editor?.text(for: "a.php") == "committed")
#expect(harness.toastTitles == ["Discarded changes"])
}
@Test func stagingRunsStraightAwayUnlessTheConfigAsks() async {
let harness = WorkspaceHarness()
await harness.start()
await harness.perform(.context(.stage("a.php")))
#expect(harness.git.staged == [["a.php"]])
var config = HelderConfig.defaults
config.git.confirmStage = true
let asking = WorkspaceHarness(config: config)
await asking.start()
await asking.perform(.context(.stage("a.php")))
#expect(asking.git.staged.isEmpty)
#expect(asking.model.overlay.current != .none)
}
@Test func revealInFinderResolvesAgainstTheProject() async {
let harness = WorkspaceHarness()
await harness.start()
await harness.perform(.context(.revealInFinder("")))
await harness.perform(.context(.revealInFinder("src/app.php")))
#expect(harness.system.revealed.map(\.path) == [harness.root.path, harness.root.appendingPathComponent("src/app.php").path])
}
@Test func aNewFileFromThePromptIsCreatedAndOpened() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.showContextMenu(.directory(path: "src"), anchor: CGPoint(x: 10, y: 20)))
await harness.perform(.context(.newFile(inDirectory: "src")))
guard case let .namePrompt(request) = harness.model.overlay.current else {
Issue.record("expected a name prompt")
return
}
#expect(request.anchor == CGPoint(x: 10, y: 20))
await harness.perform(.submitName("Router.php"))
#expect(harness.files.created == ["src/Router.php"])
#expect(harness.model.editor?.activePath == "src/Router.php")
#expect(harness.toastTitles == ["Created file"])
}
@Test func renamingCarriesTheOpenFileOver() async {
let harness = WorkspaceHarness(contents: ["src/app.php": "<?php"])
await harness.start()
harness.model.open("src/app.php")
await harness.perform(.context(.rename("src/app.php", isDirectory: false)))
guard case let .namePrompt(request) = harness.model.overlay.current else {
Issue.record("expected a name prompt")
return
}
#expect(request.initialName == "app.php")
await harness.perform(.submitName("main.php"))
#expect(harness.model.editor?.activePath == "src/main.php")
#expect(harness.model.explorer?.selectedPath == "src/main.php")
#expect(harness.toastTitles == ["Renamed file"])
}
@Test func commitAndPushToastOnce() async {
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, true)]))
await harness.start()
harness.model.sourceControl?.setCommitMessage("fix it")
await harness.perform(.commit)
#expect(harness.git.commits == ["fix it"])
await harness.perform(.push)
#expect(harness.git.pushes == 1)
#expect(harness.toastTitles == ["Committed 1 file", "Pushing…", "Pushed"])
}
@Test func commitWithoutAMessageDoesNothing() async {
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, true)]))
await harness.start()
await harness.perform(.commit)
#expect(harness.git.commits.isEmpty)
}
@Test func commandPPassesTheWholeNoteAndClosesIt() async {
let harness = WorkspaceHarness(note: " fix the tests ")
await harness.start()
harness.model.perform(.showNote)
await harness.perform(.passNote)
#expect(harness.agent.sent == [BracketedPaste.wrap("fix the tests", composerHasText: false)])
#expect(harness.model.overlay.current == .none)
#expect(harness.git.pushes == 0)
#expect(harness.toastTitles == ["Note passed to agent"])
}
@Test func thePassOnPromptInsertsIntoTheAgent() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.context(.passOnReference("a.php:3", code: nil)))
await harness.perform(.passToAgent(text: "a.php:3", reference: "a.php:3"))
#expect(harness.agent.sent.count == 1)
#expect(harness.model.overlay.current == .none)
#expect(harness.toastTitles == ["Passed to agent"])
}
@Test func aDirtyTabAsksBeforeItCloses() async {
let harness = WorkspaceHarness(contents: ["a.php": "one"])
await harness.start()
harness.model.open("a.php")
await harness.model.settle()
harness.model.editor?.edit("two")
harness.system.unsavedCloseChoice = .cancel
await harness.perform(.closeFileOrWindow)
#expect(harness.system.unsavedCloseQuestions == ["a.php"])
#expect(harness.model.editor?.activePath == "a.php")
harness.system.unsavedCloseChoice = .discard
await harness.perform(.closeFileOrWindow)
#expect(harness.model.editor?.activePath == nil)
}
@Test func commandWWithoutAnOpenFileClosesTheWindow() async {
let harness = WorkspaceHarness()
await harness.start()
var closed = false
harness.model.hooks.closeWindow = { closed = true }
harness.model.perform(.closeFileOrWindow)
#expect(closed)
}
}
@MainActor
@Suite struct WorkspaceModelFocusTests {
@Test func focusCommandsRequestFirstResponder() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.focus(.explorer))
#expect(harness.model.layout.activePanel == .explorer)
#expect(harness.model.focusRequest?.target == .panel(.explorer))
harness.model.perform(.focusNeighbour(step: 1))
#expect(harness.model.focusRequest?.target == .panel(.editor))
}
@Test func commandCShowsAHiddenGitColumnAndFocusesTheCommitBox() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.toggleGit)
harness.model.perform(.focusCommitMessage)
#expect(harness.model.layout.gitVisible)
#expect(harness.model.focusRequest?.target == .commitMessage)
}
@Test func rowCursorKeysDriveTheFocusedList() async {
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false), ("b.php", .added, true)]),
contents: ["a.php": "", "b.php": ""])
await harness.start()
harness.model.perform(.focus(.sourceControl))
harness.model.perform(.moveRowCursor(1))
#expect(harness.model.sourceControl?.selectedRow?.path == "b.php")
harness.model.perform(.moveRowCursor(1))
#expect(harness.model.sourceControl?.selectedRow?.path == "a.php")
await harness.perform(.openSelectedRow)
#expect(harness.model.editor?.activePath == "a.php")
#expect(harness.model.editor?.sides["a.php"] == .unstaged)
}
@Test func commandRightOnARowOpensItsMenuBesideTheColumn() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.focus(.explorer))
harness.model.perform(.moveRowCursor(1))
harness.model.perform(.openRowMenu)
guard case let .contextMenu(menu) = harness.model.overlay.current else {
Issue.record("expected a context menu")
return
}
#expect(menu.target == .directory(path: "src"))
#expect(Double(menu.anchor.x) == harness.model.layout.span(of: .explorer)?.upperBound)
}
@Test func comingBackToTheWindowFlashesBranchAndProjectButLaunchDoesNot() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.windowDidBecomeKey()
#expect(!harness.model.isFocusFlashVisible)
harness.model.windowDidResignKey()
harness.model.windowDidBecomeKey()
#expect(harness.model.isFocusFlashVisible)
#expect(await eventually { !harness.model.isFocusFlashVisible })
}
}
@MainActor
@Suite struct WorkspaceModelOverlayTests {
@Test func escClosesOnlyTheOneOpenOverlay() {
let harness = WorkspaceHarness()
harness.model.perform(.showShortcuts)
harness.model.perform(.showNote)
#expect(harness.model.overlay.current == .note)
harness.model.perform(.dismissOverlay)
#expect(harness.model.overlay.current == .none)
}
@Test func aContextMenuActionReplacesTheMenuWithItsPrompt() {
let harness = WorkspaceHarness()
harness.model.perform(.showContextMenu(.file(path: "src/a.php"), anchor: CGPoint(x: 300, y: 120)))
harness.model.perform(.context(.passOnReference("src/a.php", code: nil)))
#expect(harness.model.overlay.current == .passOn(PassOnRequest(reference: "src/a.php", anchor: CGPoint(x: 300, y: 120))))
}
@Test func closingTheNoteInAnyWaySavesIt() async {
let harness = WorkspaceHarness(note: "old")
await harness.start()
harness.model.note?.text = "new text"
harness.model.perform(.showNote)
await harness.perform(.showShortcuts)
#expect(harness.notes.writes == ["new text"])
}
@Test func theDiffOverlayGivesBackTheModeItCovered() async {
let harness = WorkspaceHarness(git: snapshot([("a.md", .modified, false)]), contents: ["a.md": "b"])
await harness.start()
let editor = harness.model.editor
harness.model.open("a.md")
editor?.setMode(.preview, for: "a.md")
editor?.setMode(.diff, for: "a.md")
#expect(harness.model.overlay.current == .diff(DiffOverlayRequest(path: "a.md", side: nil)))
harness.model.perform(.dismissOverlay)
#expect(editor?.mode(for: "a.md") == .preview)
}
@Test func theRecentProjectListLeavesOutTheOpenProject() async {
let harness = WorkspaceHarness(recents: [RecentProject(path: "/elsewhere", name: "elsewhere")])
await harness.start()
await harness.perform(.showRecentProjects)
#expect(harness.model.overlay.current == .launcher)
#expect(harness.model.otherRecentProjects.map(\.path) == ["/elsewhere"])
}
@Test func activatingTheNewProjectRowAsksForAFolder() async {
let harness = WorkspaceHarness(root: nil)
await harness.start()
let folder = URL(fileURLWithPath: "/fake/chosen")
harness.system.chosenFolder = folder
await harness.perform(.launcherActivate)
#expect(harness.model.root == folder)
}
@Test func searchTakesTheTypedSeed() {
let harness = WorkspaceHarness()
harness.model.perform(.showSearch(seed: "typed"))
#expect(harness.model.overlay.current == .search(seed: "typed"))
}
}
@MainActor
@Suite struct TerminalContextMenuModelTests {
@Test func aRightClickInATerminalOpensTheAppMenuAtThePointer() {
let harness = WorkspaceHarness()
harness.model.terminal.contextMenuRequested?(.agent, true, CGPoint(x: 900, y: 300))
guard case let .contextMenu(menu) = harness.model.overlay.current else {
Issue.record("no context menu")
return
}
#expect(menuLabels(menu) == ["Copy", "Paste"])
#expect(menu.header.isEmpty)
#expect(menu.anchor == CGPoint(x: 900, y: 300))
}
@Test func copyPutsTheSelectionOnThePasteboard() async {
let harness = WorkspaceHarness()
harness.agent.selectedText = "npm test"
await harness.perform(.context(.copyTerminalSelection(.agent)))
#expect(harness.system.copied == ["npm test"])
}
@Test func pasteSendsThePasteboardToThatTerminal() async {
let harness = WorkspaceHarness()
let shell = FakeTerminal()
harness.model.terminal.attach(shell, as: .shell)
harness.system.clipboard = "git status"
await harness.perform(.context(.pasteIntoTerminal(.shell)))
#expect(shell.pasted == ["git status"])
#expect(harness.agent.pasted.isEmpty)
}
@Test func menuIconsUseThePlainTint() {
#expect(ContextMenuOverlay.tint(for: .copyTerminalSelection(.agent)) == .plain)
#expect(ContextMenuOverlay.tint(for: .pasteIntoTerminal(.shell)) == .plain)
#expect(ContextMenuOverlay.symbol(for: .copyTerminalSelection(.agent)) == "doc.on.doc")
#expect(ContextMenuOverlay.symbol(for: .pasteIntoTerminal(.agent)) == "doc.on.clipboard")
}
@Test func aProjectSwitchKeepsTheTerminalMenuWired() async {
let harness = WorkspaceHarness()
await harness.start()
await harness.model.openProject(URL(fileURLWithPath: "/fake/other"))
#expect(harness.model.terminal.contextMenuRequested != nil)
}
}