diff --git a/Tests/StackNudgePanelCoreTests/EventsListTests.swift b/Tests/StackNudgePanelCoreTests/EventsListTests.swift index 1e3bf2d..a9b8d30 100644 --- a/Tests/StackNudgePanelCoreTests/EventsListTests.swift +++ b/Tests/StackNudgePanelCoreTests/EventsListTests.swift @@ -219,6 +219,46 @@ final class EventsListTests: XCTestCase { XCTAssertEqual(store.events.count, 3) } + // GitHub's approved and changes-requested decisions are keyed review events. + // Folded into the comment row they vanished there and gave it their key, + // so the next decision replaced every comment. + func testAKeyedReviewEventStaysOutOfTheCommentGroup() { + let store = EventStore() + store.append(feed("first", tag: "review", repo: "o/r", pr: 7)) + store.append(feed("second", tag: "review", repo: "o/r", pr: 7)) + store.append(feed("approved", tag: "review", key: "decision:o/r#7", repo: "o/r", pr: 7)) + XCTAssertEqual(store.events.count, 2) + XCTAssertEqual(store.events.first { $0.key == nil }?.members.count, 2) + + store.append(feed("changes requested", tag: "review", key: "decision:o/r#7", repo: "o/r", pr: 7)) + XCTAssertEqual(store.events.count, 2, "the decision replaces only itself") + XCTAssertEqual(store.events.first { $0.key == nil }?.members.count, 2, "the comments survive it") + XCTAssertEqual(store.events.first { $0.key != nil }?.message, "changes requested") + } + + // MARK: Clear all + + // A held C autorepeats, and the first repeat used to be read as the + // confirmation, clearing the feed without ever asking. + func testAHeldCDoesNotConfirmClearAll() { + // KeyCode is private to Panel.swift: C is 8 and ⌫ is 51. + let c: UInt16 = 8 + XCTAssertEqual(PanelController.clearConfirmKeyAction(keyCode: c, shifted: false, isRepeat: true), .ignoreRepeat) + XCTAssertEqual(PanelController.clearConfirmKeyAction(keyCode: c, shifted: false, isRepeat: false), .clear) + XCTAssertEqual(PanelController.clearConfirmKeyAction(keyCode: c, shifted: true, isRepeat: false), .cancel) + XCTAssertEqual(PanelController.clearConfirmKeyAction(keyCode: 51, shifted: false, isRepeat: false), + .cancel) + } + + func testLeavingEventsDisarmsClearAll() { + let nav = PanelNav() + nav.mode = .events + nav.confirmingClear = true + nav.mode = .sessions + nav.mode = .events + XCTAssertFalse(nav.confirmingClear) + } + func testMembersAreBoundedAndExpansionOnlyForGroups() { let store = EventStore() for i in 0..<(EventStore.maxMembers + 10) { diff --git a/Tests/StackNudgePanelCoreTests/GitHubFeedTests.swift b/Tests/StackNudgePanelCoreTests/GitHubFeedTests.swift index 867c441..aaeacd5 100644 --- a/Tests/StackNudgePanelCoreTests/GitHubFeedTests.swift +++ b/Tests/StackNudgePanelCoreTests/GitHubFeedTests.swift @@ -287,13 +287,13 @@ final class GitHubCLITests: XCTestCase { func testNumbersUseTypedFields() { let args = GitHubCLI.graphQLArguments(body: #"{"query":"q","variables":{"n":3}}"#) - XCTAssertEqual(args, ["api", "graphql", "-f", "query=q", "-F", "n=3"]) + XCTAssertEqual(args, ["api", "graphql", "--hostname", "github.com", "-f", "query=q", "-F", "n=3"]) } // A first page sends `after: null`; refusing it failed every paged query. func testNullVariablesAreLeftOut() { let args = GitHubCLI.graphQLArguments(body: #"{"query":"q","variables":{"q":"x","after":null}}"#) - XCTAssertEqual(args, ["api", "graphql", "-f", "query=q", "-f", "q=x"]) + XCTAssertEqual(args, ["api", "graphql", "--hostname", "github.com", "-f", "query=q", "-f", "q=x"]) } func testAnythingElseIsRefused() { diff --git a/Tests/StackNudgePanelCoreTests/IntegrationPageTests.swift b/Tests/StackNudgePanelCoreTests/IntegrationPageTests.swift index fd33f99..57066d9 100644 --- a/Tests/StackNudgePanelCoreTests/IntegrationPageTests.swift +++ b/Tests/StackNudgePanelCoreTests/IntegrationPageTests.swift @@ -135,6 +135,51 @@ final class IntegrationPageTests: XCTestCase { XCTAssertEqual(nav.selectedRow, .githubLinks) } + // MARK: - The gh login + + // `gh auth status` checks its token with github.com. It used to run on main + // at every config load for anyone with gh installed, GitHub on or not. + private func navCheckingGh(_ answer: Bool, asked: @escaping () -> Void) -> PanelNav { + let nav = PanelNav() + nav.checkGitHubCLILogin = { asked(); return answer } + nav.runOffMain = { $0() } + nav.runOnMain = { $0() } + return nav + } + + func testTheGhLoginIsNotAskedWithGitHubOff() { + var asked = 0 + let nav = navCheckingGh(true) { asked += 1 } + var done = false + nav.refreshGitHubCLILogin { done = true } + XCTAssertEqual(asked, 0) + XCTAssertFalse(nav.githubUsesCLILogin) + XCTAssertTrue(done, "the follow-up still runs") + } + + func testTheGhLoginIsAskedOffMainOnceGitHubIsOn() { + var asked = 0 + let nav = navCheckingGh(true) { asked += 1 } + var offMain = 0 + nav.runOffMain = { offMain += 1; $0() } + nav.githubActivityEnabled = true + nav.refreshGitHubCLILogin() + XCTAssertEqual(asked, 1) + XCTAssertEqual(offMain, 1, "gh is asked off main") + XCTAssertTrue(nav.githubUsesCLILogin) + XCTAssertTrue(nav.githubSignedIn) + } + + func testTurningGhOffInTheConfigSkipsTheCheck() { + var asked = 0 + let nav = navCheckingGh(true) { asked += 1 } + nav.githubLinkingEnabled = true + nav.githubUseGH = false + nav.refreshGitHubCLILogin() + XCTAssertEqual(asked, 0) + XCTAssertFalse(nav.githubUsesCLILogin) + } + // MARK: - Status func testSlackStatusSaysWhatsMissingBeforeWhetherItsOn() { diff --git a/Tests/StackNudgePanelCoreTests/SessionLauncherTests.swift b/Tests/StackNudgePanelCoreTests/SessionLauncherTests.swift index c7b7756..8841f15 100644 --- a/Tests/StackNudgePanelCoreTests/SessionLauncherTests.swift +++ b/Tests/StackNudgePanelCoreTests/SessionLauncherTests.swift @@ -51,12 +51,26 @@ final class RecentSessionsTests: XCTestCase { try line(["type": "user", "cwd": cwd, "message": ["content": name]]) .write(toFile: "\(project)/\(name).jsonl", atomically: true, encoding: .utf8) } - try write("keep", cwd: existing) - try write("running", cwd: existing) + let keep = "0a1b2c3d-0000-4000-8000-000000000001" + let running = "0a1b2c3d-0000-4000-8000-000000000002" + try write(keep, cwd: existing) + try write(running, cwd: existing) try write("agent-sub", cwd: existing) - try write("gone", cwd: root + "/deleted") - let ids = RecentSessions.load(root: root, excluding: ["running"]).map(\.id) - XCTAssertEqual(ids, ["keep"]) + try write("0a1b2c3d-0000-4000-8000-000000000004", cwd: root + "/deleted") + let ids = RecentSessions.load(root: root, excluding: [running]).map(\.id) + XCTAssertEqual(ids, [keep]) + } + + // The id is typed into a shell, so a transcript named anything but the + // UUID Claude Code writes is not offered. + func testLoadSkipsATranscriptNotNamedLikeASession() throws { + let root = NSTemporaryDirectory() + "recent-\(UUID().uuidString)" + let project = root + "/-repo" + try FileManager.default.createDirectory(atPath: project, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(atPath: root) } + try line(["type": "user", "cwd": root, "message": ["content": "x"]]) + .write(toFile: "\(project)/x$(touch pwned).jsonl", atomically: true, encoding: .utf8) + XCTAssertEqual(RecentSessions.load(root: root).map(\.id), []) } } @@ -68,6 +82,38 @@ final class SessionLauncherTests: XCTestCase { XCTAssertEqual(SessionLauncher.shellQuoted("it's"), "'it'\\''s'") } + // Terminal and iTerm get `cd ''` typed into the login shell. A + // quote, a backslash or a control character could end the quoting early + // in some shells (fish reads \' inside single quotes as an escape), so + // such a folder is refused there. Ghostty takes the folder as a property. + func testAFolderThatCantBeTypedSafelyIsRefused() { + for folder in ["/r/it's", "/r/back\\slash", "/r/new\nline", "/r/bell\u{07}"] { + XCTAssertNil(SessionLauncher.osascriptArguments(cwd: folder, command: "claude", in: .terminal), folder) + XCTAssertNil(SessionLauncher.osascriptArguments(cwd: folder, command: "claude", in: .iterm), folder) + XCTAssertNotNil(SessionLauncher.osascriptArguments(cwd: folder, command: "claude", in: .ghostty), folder) + } + } + + // The folder and command reach osascript as arguments after `--`, never + // spliced into the script's source. + func testTheFolderAndCommandAreArgumentsNotScript() { + let folder = "/r/a \"b\" $(c)" + let terminal = SessionLauncher.osascriptArguments(cwd: folder, command: "claude", in: .terminal) + XCTAssertEqual(terminal, ["-e", SessionLauncher.terminalScript, "--", "cd '/r/a \"b\" $(c)' && claude"]) + let ghostty = SessionLauncher.osascriptArguments(cwd: folder, command: "claude", in: .ghostty) + XCTAssertEqual(ghostty, ["-e", SessionLauncher.ghosttyScript, "--", folder, "claude"]) + for script in [SessionLauncher.terminalScript, SessionLauncher.itermScript, SessionLauncher.ghosttyScript] { + XCTAssertFalse(script.contains(folder)) + } + } + + func testOnlyAUUIDIsASessionID() { + XCTAssertTrue(SessionLauncher.isSessionID("0a1b2c3d-0000-4000-8000-000000000001")) + for id in ["-c", "-ac", "abc-123", "0a1b2c3d00004000800000000000001", ""] { + XCTAssertFalse(SessionLauncher.isSessionID(id), id) + } + } + func testResumeCommandQuotesTheID() { let session = RecentSession(id: "abc-123", cwd: "/r", title: "t", date: Date()) XCTAssertEqual(SessionLauncher.resumeCommand(session), "claude --resume 'abc-123'") diff --git a/panel/EventStore.swift b/panel/EventStore.swift index 3622ee1..5fe46a4 100644 --- a/panel/EventStore.swift +++ b/panel/EventStore.swift @@ -396,9 +396,14 @@ final class EventStore: ObservableObject { // MARK: - Feed grouping - // Review feedback on the same PR from the same source. + // Review feedback on the same PR from the same source. Keyed events are + // never comments: a key means "this replaces its earlier self" (GitHub's + // approved and changes-requested decisions carry one), and folding one into + // the comment row would hide it there and hand the row its key, so the + // next decision would replace every comment with it. static func groups(_ existing: NudgeEvent, with incoming: NudgeEvent) -> Bool { guard existing.isFeed, incoming.isFeed, + incoming.key == nil, existing.key == nil, incoming.tag == "review", existing.tag == "review", existing.source == incoming.source, let repo = incoming.repo, !repo.isEmpty, existing.repo == repo, @@ -421,7 +426,7 @@ final class EventStore: ObservableObject { ? incoming.severity : previous.severity, title: "\(all.count) new comments on \(name)#\(incoming.pr ?? 0)", message: incoming.message, url: incoming.url ?? previous.url, - repo: incoming.repo, pr: incoming.pr, key: incoming.key ?? previous.key, + repo: incoming.repo, pr: incoming.pr, key: nil, timestamp: incoming.timestamp, members: all, id: incoming.id) } diff --git a/panel/GitHubCLI.swift b/panel/GitHubCLI.swift index 093ddfe..b18a088 100644 --- a/panel/GitHubCLI.swift +++ b/panel/GitHubCLI.swift @@ -35,7 +35,9 @@ enum GitHubCLI { guard let object = try? JSONSerialization.jsonObject(with: Data(body.utf8)) as? [String: Any], let query = object["query"] as? String else { return nil } - var args = ["api", "graphql", "-f", "query=\(query)"] + // github.com always: gh otherwise takes its host from GH_HOST, which + // the app inherits from whatever launched it. + var args = ["api", "graphql", "--hostname", "github.com", "-f", "query=\(query)"] let variables = object["variables"] as? [String: Any] ?? [:] for key in variables.keys.sorted() { switch variables[key] { diff --git a/panel/Panel.swift b/panel/Panel.swift index 31270b2..bfa6fad 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -4643,6 +4643,21 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, isRepeat: event.isARepeat) } + enum ClearConfirmKeyAction: Equatable { + case clear + case cancel + case ignoreRepeat + } + + // The key that answers "Clear all?". A held C autorepeats, and its first + // repeat lands here about half a second after the press that asked, so a + // repeat answers nothing and the question stays up (AGENTS.md: destructive + // keys ignore autorepeat). A fresh C clears; any other key backs out. + static func clearConfirmKeyAction(keyCode: UInt16, shifted: Bool, isRepeat: Bool) -> ClearConfirmKeyAction { + if isRepeat { return .ignoreRepeat } + return keyCode == KeyCode.cKey && !shifted ? .clear : .cancel + } + enum SessionLaunchKeyAction: Equatable { case resume case newSession @@ -5376,8 +5391,12 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, // Clear all asks first. C confirms; anything else backs out, and the // key is swallowed so a stray ⌫ can't also deny a prompt. if nav.confirmingClear { - nav.confirmingClear = false - if event.keyCode == KeyCode.cKey, !shifted { store.clearFeed() } + switch Self.clearConfirmKeyAction(keyCode: event.keyCode, shifted: shifted, + isRepeat: event.isARepeat) { + case .clear: nav.confirmingClear = false; store.clearFeed() + case .cancel: nav.confirmingClear = false + case .ignoreRepeat: break + } return true } @@ -5431,7 +5450,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, case KeyCode.aKey: store.markAllRead() case KeyCode.cKey: - if store.events.contains(where: \.isFeed) { nav.confirmingClear = true } + if !event.isARepeat, store.events.contains(where: \.isFeed) { nav.confirmingClear = true } case KeyCode.upArrow: store.selectPrevious() case KeyCode.downArrow: @@ -5968,8 +5987,10 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, private func launch(cwd: String, command: String) { let terminal = SessionLauncher.terminal(configured: ConfigFile.read()["STACKNUDGE_SESSION_TERMINAL"]) + // Refused (a folder that can't be typed safely in this terminal): the + // panel stays up and beeps rather than vanishing with nothing opened. + guard SessionLauncher.open(cwd: cwd, command: command, in: terminal) else { return NSSound.beep() } hidePanel() - SessionLauncher.open(cwd: cwd, command: command, in: terminal) } private struct SessionMenuItem { diff --git a/panel/PanelNav.swift b/panel/PanelNav.swift index 77f572d..04e80c8 100644 --- a/panel/PanelNav.swift +++ b/panel/PanelNav.swift @@ -329,7 +329,9 @@ final class PanelNav: ObservableObject { // when a tab is picked and when the panel reopens on a different tab. didSet { if mode != .settings, extensionTextEdit != nil { cancelExtensionTextEdit() } - if mode != .events { chipsFocused = false } + // An armed Clear all doesn't survive leaving the page: coming back + // and pressing C must ask again, not clear. + if mode != .events { chipsFocused = false; confirmingClear = false } guard mode != oldValue else { return } modeJustChanged = true dropUpdateConfirmationIfLeft() @@ -634,8 +636,15 @@ final class PanelNav: ObservableObject { // (STACKNUDGE_GITHUB_ACTIVITY). Needs the same GitHub sign-in. @Published var githubActivityEnabled: Bool = false // STACKNUDGE_GITHUB_USE_GH, and whether the gh login is what's in use. + // The second is only ever known once a GitHub feature is on: see + // refreshGitHubCLILogin. @Published var githubUseGH = true @Published var githubUsesCLILogin = false + // `gh auth status` and the queues it runs across, injectable so a test can + // answer it without spawning gh. + var checkGitHubCLILogin: () -> Bool = { GitHubCLI.isLoggedIn() } + var runOffMain: (@escaping () -> Void) -> Void = { DispatchQueue.global(qos: .utility).async(execute: $0) } + var runOnMain: (@escaping () -> Void) -> Void = { DispatchQueue.main.async(execute: $0) } // The PRs tab's data: the latest poll's snapshot and whose it is. @Published var pullRequestSnapshot: GitHubFeed.Snapshot? @Published var pullRequestLogin: String? @@ -1937,8 +1946,8 @@ final class PanelNav: ObservableObject { githubActivityEnabled = ConfigFile.bool(config, "STACKNUDGE_GITHUB_ACTIVITY", default: false) hideShippedTickets = ConfigFile.bool(config, "STACKNUDGE_HIDE_SHIPPED", default: false) githubUseGH = ConfigFile.bool(config, "STACKNUDGE_GITHUB_USE_GH", default: true) - githubUsesCLILogin = githubUseGH && GitHubCLI.isLoggedIn() githubSignedIn = githubUsesCLILogin || GitHubAuth.token() != nil + refreshGitHubCLILogin() quotaTrackingEnabled = ConfigFile.bool(config, "STACKNUDGE_QUOTA_TRACKING", default: true) quotaAlertsEnabled = ConfigFile.bool(config, "STACKNUDGE_QUOTA_ALERTS", default: true) quotaShowRemaining = ConfigFile.bool(config, "STACKNUDGE_QUOTA_SHOW_REMAINING", default: false) @@ -2398,12 +2407,45 @@ final class PanelNav: ObservableObject { // kicks an immediate PR fetch so chips appear without waiting for the next // tab visit, on disable drops cached PR state so chips revert to the local // outcome. + // Whether the gh login is in use. `gh auth status` checks its token with + // github.com, so it runs off main, where a slow network can't freeze the + // panel, and only once PR links or activity is on: nobody who never + // turned GitHub on has it contacted (PRIVACY.md). `then` runs on main + // with the answer applied. + func refreshGitHubCLILogin(then: (() -> Void)? = nil) { + guard githubUseGH, githubLinkingEnabled || githubActivityEnabled else { + applyGitHubCLILogin(false) + then?() + return + } + let check = checkGitHubCLILogin + let toMain = runOnMain + runOffMain { [weak self] in + let loggedIn = check() + toMain { + self?.applyGitHubCLILogin(loggedIn) + then?() + } + } + } + + private func applyGitHubCLILogin(_ loggedIn: Bool) { + if githubUsesCLILogin != loggedIn { githubUsesCLILogin = loggedIn } + let signedIn = loggedIn || GitHubAuth.token() != nil + if githubSignedIn != signedIn { githubSignedIn = signedIn } + } + func toggleGithubLinking() { githubLinkingEnabled.toggle() ConfigFile.write(key: "STACKNUDGE_GITHUB", value: githubLinkingEnabled ? "true" : "false") if githubLinkingEnabled { - if githubSignedIn { refreshPullRequestsNow?() } else { startGithubSignIn?() } + // The gh login isn't known until a GitHub feature is on, so ask + // before deciding whether a sign-in is needed at all. + refreshGitHubCLILogin { [weak self] in + guard let self, self.githubLinkingEnabled else { return } + if self.githubSignedIn { self.refreshPullRequestsNow?() } else { self.startGithubSignIn?() } + } } else { pullRequestByBranch = [:] githubSignIn = .idle @@ -2588,6 +2630,7 @@ final class PanelNav: ObservableObject { case .githubActivity: githubActivityEnabled.toggle() ConfigFile.write(key: "STACKNUDGE_GITHUB_ACTIVITY", value: githubActivityEnabled ? "true" : "false") + refreshGitHubCLILogin() case .hideShipped: toggleHideShipped() case .slackEnabled: diff --git a/panel/SessionLauncher.swift b/panel/SessionLauncher.swift index 0996f0a..8a304ab 100644 --- a/panel/SessionLauncher.swift +++ b/panel/SessionLauncher.swift @@ -83,7 +83,9 @@ enum RecentSessions { where name.hasSuffix(".jsonl") && !name.hasPrefix("agent-") { let path = "\(root)/\(dir)/\(name)" let id = (name as NSString).deletingPathExtension - guard !running.contains(id), + // The id is typed into a shell as `claude --resume `, so + // only the shape Claude Code writes (a UUID) is offered. + guard SessionLauncher.isSessionID(id), !running.contains(id), let modified = (try? fm.attributesOfItem(atPath: path))?[.modificationDate] as? Date else { continue } files.append((path, modified)) @@ -123,6 +125,12 @@ enum SessionLauncher { .sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending } } + // The canonical 8-4-4-4-12 form only, so an id can never start with `-` + // and be read as a flag by `claude --resume`. + static func isSessionID(_ id: String) -> Bool { + UUID(uuidString: id) != nil + } + static func resumeCommand(_ session: RecentSession) -> String { "claude --resume \(shellQuoted(session.id))" } @@ -132,10 +140,6 @@ enum SessionLauncher { "'" + s.replacingOccurrences(of: "'", with: "'\\''") + "'" } - static func appleScriptEscaped(_ s: String) -> String { - s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") - } - enum Terminal: String { case ghostty, terminal, iterm } // STACKNUDGE_SESSION_TERMINAL, else Ghostty when it is installed, else @@ -146,40 +150,73 @@ enum SessionLauncher { return ghostty ? .ghostty : .terminal } - // Opens a new window in `cwd` and types `command` there. - static func open(cwd: String, command: String, in terminal: Terminal) { - let script: String + // A folder Terminal or iTerm can be sent to by typing `cd ''` into + // the login shell. Inside single quotes POSIX shells take everything + // literally, but fish reads `\'` and `\\` as escapes, and a control + // character can end the line early, so a folder holding any of those is + // refused rather than typed. Ghostty takes the folder as a property and + // never types it. + static func isTypable(_ folder: String) -> Bool { + !folder.isEmpty && !folder.unicodeScalars.contains { + $0 == "'" || $0 == "\\" || CharacterSet.controlCharacters.contains($0) + } + } + + // The osascript arguments that open a window in `cwd` and type `command`, + // or nil when that can't be done safely in `terminal`. The folder and the + // command reach the script as arguments, never spliced into its source. + static func osascriptArguments(cwd: String, command: String, in terminal: Terminal) -> [String]? { switch terminal { case .ghostty: - // Ghostty's AppleScript API types the command without the "allow - // Ghostty to execute" prompt that `open --args -e` raises. - script = """ - tell application "Ghostty" - activate - set cfg to new surface configuration from {initial working directory:"\(appleScriptEscaped(cwd))", initial input:"\(appleScriptEscaped(command))" & linefeed} - new window with configuration cfg - end tell - """ - case .iterm: - script = """ - tell application "iTerm2" - activate - set w to (create window with default profile) - tell current session of w to write text "\(appleScriptEscaped("cd \(shellQuoted(cwd)) && \(command)"))" - end tell - """ - case .terminal: - script = """ - tell application "Terminal" - activate - do script "\(appleScriptEscaped("cd \(shellQuoted(cwd)) && \(command)"))" - end tell - """ + return ["-e", ghosttyScript, "--", cwd, command] + case .iterm, .terminal: + guard isTypable(cwd) else { return nil } + let line = "cd \(shellQuoted(cwd)) && \(command)" + return ["-e", terminal == .iterm ? itermScript : terminalScript, "--", line] } + } + + // Ghostty's AppleScript API types the command without the "allow Ghostty + // to execute" prompt that `open --args -e` raises. + static let ghosttyScript = """ + on run argv + tell application "Ghostty" + activate + set cfg to new surface configuration from {initial working directory:(item 1 of argv), initial input:(item 2 of argv) & linefeed} + new window with configuration cfg + end tell + end run + """ + + static let itermScript = """ + on run argv + tell application "iTerm2" + activate + set w to (create window with default profile) + tell current session of w to write text (item 1 of argv) + end tell + end run + """ + + static let terminalScript = """ + on run argv + tell application "Terminal" + activate + do script (item 1 of argv) + end tell + end run + """ + + // Opens a new window in `cwd` and types `command` there. False, having + // opened nothing, when the folder can't be typed safely in that terminal. + @discardableResult + static func open(cwd: String, command: String, in terminal: Terminal) -> Bool { + guard let arguments = osascriptArguments(cwd: cwd, command: command, in: terminal) else { return false } DispatchQueue.global(qos: .userInitiated).async { - let ok = ProcessOutput.run("/usr/bin/osascript", ["-e", script], timeout: 15)?.status == 0 + let ok = ProcessOutput.run("/usr/bin/osascript", arguments, timeout: 15)?.status == 0 // An older Ghostty without the scripting API: fall back once. if !ok, terminal == .ghostty { open(cwd: cwd, command: command, in: .terminal) } } + return true } }