Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 58 additions & 7 deletions .github/workflows/macos.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,26 @@ jobs:
for script in script/*.sh; do bash -n "$script"; done
python3 script/version.py

- name: Install popular terminals for signed release acceptance
if: inputs.sign-release
run: brew install --cask iterm2 ghostty

- name: Verify first launch of downloaded test terminals
if: inputs.sign-release
run: |
mkdir -p artifacts
defaults write com.googlecode.iterm2 NoSyncConfirmRunOpenFile -bool true
defaults write com.googlecode.iterm2 NoSyncConfirmRunOpenFile_selection -int 0
swiftc script/accept-ci-terminal-first-open.swift -o "$RUNNER_TEMP/accept-terminal-first-open"
failed=0
for app in iTerm Ghostty; do
if ! "$RUNNER_TEMP/accept-terminal-first-open" "/Applications/$app.app"; then
screencapture -x "artifacts/terminal-failure-first-open-$app.png" || true
failed=1
fi
done
exit "$failed"

- name: Build release
run: |
swift --version
Expand Down Expand Up @@ -158,6 +178,42 @@ jobs:
- name: Verify packaged launcher
run: python3 script/test-macos-launcher.py "dist/darwin-universal/Y CONNECT.app/Contents/MacOS/YConnect"

- name: Verify native Terminal launch and missing-terminal fallback
run: |
BIN="dist/darwin-universal/Y CONNECT.app/Contents/MacOS/YConnect"
"$BIN" --smoke-terminal-launch com.apple.Terminal
"$BIN" --smoke-terminal-launch fixture.missing-terminal

- name: Verify signed app launches popular terminals
if: inputs.sign-release
timeout-minutes: 5
run: |
set -euo pipefail
BIN="dist/darwin-universal/Y CONNECT.app/Contents/MacOS/YConnect"
# Simulate a user who acknowledged iTerm's open-file confirmation in
# this disposable test account. Production never changes this setting.
defaults write com.googlecode.iterm2 NoSyncConfirmRunOpenFile -bool true
defaults write com.googlecode.iterm2 NoSyncConfirmRunOpenFile_selection -int 0
trap 'defaults delete com.googlecode.iterm2 NoSyncConfirmRunOpenFile; defaults delete com.googlecode.iterm2 NoSyncConfirmRunOpenFile_selection' EXIT
failed=0
for terminal in com.googlecode.iterm2 com.mitchellh.ghostty; do
echo "Testing native terminal: $terminal"
if ! "$BIN" --smoke-terminal-launch "$terminal"; then
failed=1
screencapture -x "artifacts/terminal-failure-$terminal.png" || true
fi
done
exit "$failed"

- name: Upload terminal acceptance diagnostics
if: always() && inputs.sign-release
uses: actions/upload-artifact@v4
with:
name: terminal-acceptance-diagnostics
path: artifacts/terminal-*
if-no-files-found: ignore
retention-days: 14

- name: Create production DMG
run: |
version="$(tr -d '[:space:]' < VERSION)"
Expand Down Expand Up @@ -230,13 +286,8 @@ jobs:
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- name: Select OpenSSL 3
run: echo "$(brew --prefix openssl@3)/bin" >> "$GITHUB_PATH"
- name: Build and test against Tahoe SDK
run: |
sw_vers
swift build --package-path darwin --configuration release -Xswiftc -warnings-as-errors
swift test --package-path darwin -Xswiftc -warnings-as-errors
- name: Check Tahoe host
run: sw_vers
- uses: actions/download-artifact@v4
with:
name: release-macos
Expand Down
19 changes: 19 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Project agent memory

This file is the project's committed home for project-intrinsic agent knowledge: build, test, release, architecture, and sharp-edge notes that should travel with the code.

- Add durable project-specific notes here as they are discovered through real work.

## Maintaining this file

Keep this file for knowledge useful to almost every future agent session in this project.
Do not repeat what the codebase already shows; point to the authoritative file or command instead.
Prefer rewriting or pruning existing entries over appending new ones.

## Build environment sharp edges (this workstation)

- SwiftPM dependency fetch dies with `Failed to find credentials for 'https://github.com' in keychain: status -128` because the login keychain holds an inaccessible `github.com` internet password. Always pass `--disable-keychain` to `swift build` / `swift test` (SwiftPM still downloads public artifacts anonymously).
- `swift test` cannot run locally: CLT 15.1 ships no macOS XCTest (`xcrun --sdk macosx --find XCTest` fails, no Xcode installed). Local gate is `swift build --disable-keychain` plus the binary's render/smoke flags; the full `swift test --package-path darwin` suite is the PR CI's job (`.github/workflows/macos.yml`).
- Local toolchain 5.9.2 + `-Xswiftc -warnings-as-errors` fails on a pre-existing actor-isolation conversion at `YConnectStore.swift` (`models.map(Self.clientModelOption)`); CI's newer Xcode toolchains accept it. Don't "fix" that line just to satisfy a local strict build.

When updating this file, preserve this bar for all agents and keep entries concise.
2 changes: 2 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<!-- Points Claude at AGENTS.md via import; edit AGENTS.md, not this file. -->
@AGENTS.md
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@

| 平台 | 要求 | 安装包 |
| --- | --- | --- |
| macOS | macOS 14+,Apple Silicon / Intel | [通用 DMG](https://aliyun-oss.yaklang.com/yconnect/0.5.3/YConnect-0.5.3-darwin-universal.dmg) |
| Windows | Windows 10/11 x64,.NET Framework 4.8 | [安装程序](https://aliyun-oss.yaklang.com/yconnect/0.5.3/YConnect-0.5.3-windows-x64-setup.exe) · [便携 ZIP](https://aliyun-oss.yaklang.com/yconnect/0.5.3/YConnect-0.5.3-windows-x64.zip) |
| macOS | macOS 14+,Apple Silicon / Intel | [通用 DMG](https://aliyun-oss.yaklang.com/yconnect/0.5.4/YConnect-0.5.4-darwin-universal.dmg) |
| Windows | Windows 10/11 x64,.NET Framework 4.8 | [安装程序](https://aliyun-oss.yaklang.com/yconnect/0.5.4/YConnect-0.5.4-windows-x64-setup.exe) · [便携 ZIP](https://aliyun-oss.yaklang.com/yconnect/0.5.4/YConnect-0.5.4-windows-x64.zip) |

[GitHub Releases / 更新说明](https://github.com/yaklang/yconnect/releases) · [最新版本](https://aliyun-oss.yaklang.com/yconnect/version.txt) · [SHA-256 校验](https://aliyun-oss.yaklang.com/yconnect/0.5.3/SHA256SUMS.txt)
[GitHub Releases / 更新说明](https://github.com/yaklang/yconnect/releases) · [最新版本](https://aliyun-oss.yaklang.com/yconnect/version.txt) · [SHA-256 校验](https://aliyun-oss.yaklang.com/yconnect/0.5.4/SHA256SUMS.txt)

正式发行的 macOS 应用经过 Developer ID 签名与 Apple 公证,Windows 程序和安装包经过 Authenticode 签名。macOS 将应用拖入 Applications;Windows 运行安装程序或解压便携包。Windows 扫码登录需要系统 WebView2。

Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.5.3
0.5.4
2 changes: 1 addition & 1 deletion darwin/Resources/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>0.5.3</string>
<string>0.5.4</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
Expand Down
5 changes: 5 additions & 0 deletions darwin/Sources/YConnect/AppEnvironment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,11 @@ enum YConnectPreferences {
set { UserDefaults.standard.set(newValue, forKey: prefix + "launch-directory") }
}

static var defaultTerminalBundleID: String {
get { UserDefaults.standard.string(forKey: prefix + "default-terminal") ?? TerminalBundleID.terminalApp }
set { UserDefaults.standard.set(newValue, forKey: prefix + "default-terminal") }
}

static var selectedClientID: ClientID {
get {
guard let value = UserDefaults.standard.string(forKey: prefix + "selected-client-id"), !value.isEmpty else {
Expand Down
2 changes: 1 addition & 1 deletion darwin/Sources/YConnect/BuildInfo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ import Foundation

enum BuildInfo {
// Kept in sync with VERSION by script/version.py.
static let version = "0.5.3"
static let version = "0.5.4"
}
178 changes: 165 additions & 13 deletions darwin/Sources/YConnect/ClientLauncher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,23 @@ struct AgentLaunchPlan {
var exitURL: URL { root.appendingPathComponent("exit-status") }
}

/// A terminal emulator Y CONNECT can hand a launch session to.
struct TerminalOption: Identifiable, Equatable {
let bundleID: String
let name: String
var id: String { bundleID }
}

/// Bundle identifiers of the terminals with a supported launch strategy.
enum TerminalBundleID {
static let terminalApp = "com.apple.Terminal"
static let iTerm2 = "com.googlecode.iterm2"
static let ghostty = "com.mitchellh.ghostty"
static let kitty = "net.kovidgoyal.kitty"
static let wezTerm = "com.github.wez.wezterm"
static let alacritty = "org.alacritty"
}

enum ClientLauncher {
static func supports(_ id: ClientID) -> Bool {
[.openCode, .codex, .claudeCode, .pi, .grokBuild, .hermes, .openClaw].contains(id)
Expand All @@ -32,6 +49,78 @@ enum ClientLauncher {

static func shellQuote(_ text: String) -> String { "'" + text.replacingOccurrences(of: "'", with: "'\\''") + "'" }

/// Selectable launch terminals. macOS Terminal stays first: default and fallback.
static let terminals: [TerminalOption] = [
TerminalOption(bundleID: TerminalBundleID.terminalApp, name: "macOS Terminal"),
TerminalOption(bundleID: TerminalBundleID.iTerm2, name: "iTerm2"),
TerminalOption(bundleID: TerminalBundleID.ghostty, name: "Ghostty"),
TerminalOption(bundleID: TerminalBundleID.kitty, name: "kitty"),
TerminalOption(bundleID: TerminalBundleID.wezTerm, name: "WezTerm"),
TerminalOption(bundleID: TerminalBundleID.alacritty, name: "Alacritty"),
]

static func terminal(withBundleID bundleID: String) -> TerminalOption? {
terminals.first { $0.bundleID == bundleID }
}

/// App URLs of the installed supported terminals, keyed by bundle identifier.
@MainActor
static func terminalApplications() -> [String: URL] {
var applications: [String: URL] = [:]
for terminal in terminals {
if let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: terminal.bundleID) {
applications[terminal.bundleID] = url
}
}
return applications
}

/// Picks the launch terminal: the preferred one when it is a known, installed
/// choice; macOS Terminal otherwise. Pure so tests cover the fallback rules.
static func resolveTerminal(preferredBundleID: String, installedBundleIDs: Set<String>)
-> (terminal: TerminalOption, fellBackToTerminalApp: Bool) {
if let preferred = terminal(withBundleID: preferredBundleID),
installedBundleIDs.contains(preferred.bundleID) {
return (preferred, false)
}
return (terminals[0], true)
}

/// How a terminal receives the session `.command` file.
enum TerminalLaunchKind: Equatable {
/// Terminal.app and iTerm2 open the same executable session file natively.
case openCommandFile
/// Ghostty / kitty / WezTerm / Alacritty run a process with explicit argv.
case process(URL, [String])
}

/// Launch instructions per terminal, pure so tests can assert exact argv and script text.
static func launchKind(for terminal: TerminalOption, application: URL, plan: AgentLaunchPlan) -> TerminalLaunchKind {
switch terminal.bundleID {
case TerminalBundleID.terminalApp, TerminalBundleID.iTerm2:
return .openCommandFile
case TerminalBundleID.kitty:
// macOS app bundles are not on PATH; resolve the bundled binary from the app.
return .process(application.appendingPathComponent("Contents/MacOS/kitty"),
["--directory", plan.root.path, "/bin/zsh", "-f", plan.commandURL.path])
case TerminalBundleID.wezTerm:
// Keep the session independent of an already-running GUI/mux.
return .process(URL(fileURLWithPath: "/usr/bin/open"),
["-na", application.path, "--args", "start", "--always-new-process", "--", "/bin/zsh", "-f", plan.commandURL.path])
case TerminalBundleID.ghostty, TerminalBundleID.alacritty:
return .process(URL(fileURLWithPath: "/usr/bin/open"),
["-na", application.path, "--args", "-e", "/bin/zsh", "-f", plan.commandURL.path])
default:
return .openCommandFile
}
}

static func launchReadyMessage(autoStart: Bool, model: String, fellBackToTerminalApp: Bool) -> String {
var message = autoStart ? "Agent 进程已在新终端启动 · \(model)" : "专用终端已就绪 · 输入 yconnect-agent 启动"
if fellBackToTerminalApp { message += " · 未检测到所选终端,已改用 macOS Terminal" }
return message
}

static func prepare(environment: AppEnvironment, clientID: ClientID, model: ClientModelOption,
apiKey: String, directory: String, autoStart: Bool,
executable: URL, runner: URL, contextWindow: Int? = nil) throws -> AgentLaunchPlan {
Expand Down Expand Up @@ -141,31 +230,78 @@ enum ClientLauncher {
}

@MainActor
static func start(_ plan: AgentLaunchPlan) async throws -> String {
guard let terminal = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Terminal") else {
static func start(_ plan: AgentLaunchPlan,
preferredTerminalBundleID: String = YConnectPreferences.defaultTerminalBundleID,
applications: [String: URL]? = nil) async throws -> String {
var acknowledged = false
defer { if !acknowledged { cancelPendingLaunch(plan) } }
let applications = applications ?? terminalApplications()
let resolved = resolveTerminal(preferredBundleID: preferredTerminalBundleID,
installedBundleIDs: Set(applications.keys))
guard let application = applications[resolved.terminal.bundleID] else {
throw YConnectError.unsupported("未找到 macOS 终端")
}
let configuration = NSWorkspace.OpenConfiguration()
configuration.activates = true
// The macOS 14 SDK's async overlay moves non-Sendable AppKit objects
// across actors. Keep the request on the main actor and bridge only
// its completion, without transferring NSRunningApplication.
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
NSWorkspace.shared.open([plan.commandURL], withApplicationAt: terminal, configuration: configuration) { _, error in
if let error { continuation.resume(throwing: error) }
else { continuation.resume(returning: ()) }
switch launchKind(for: resolved.terminal, application: application, plan: plan) {
case .openCommandFile:
let configuration = NSWorkspace.OpenConfiguration()
configuration.activates = true
// The macOS 14 SDK's async overlay moves non-Sendable AppKit objects
// across actors. Keep the request on the main actor and bridge only
// its completion, without transferring NSRunningApplication.
try await waitForTerminalOpen { completion in
NSWorkspace.shared.open([plan.commandURL], withApplicationAt: application, configuration: configuration) { _, error in
completion(error)
}
}
case .process(let executable, let arguments):
guard FileManager.default.isExecutableFile(atPath: executable.path) else {
throw YConnectError.unsupported("未找到 \(resolved.terminal.name) 的启动程序")
}
let process = Process()
process.executableURL = executable
process.arguments = arguments
process.standardInput = FileHandle.nullDevice
process.standardOutput = FileHandle.nullDevice
process.standardError = FileHandle.nullDevice
try process.run()
}
for _ in 0..<150 {
try await Task.sleep(for: .milliseconds(200))
if let status = try? String(contentsOf: plan.exitURL), let code = Int32(status.trimmingCharacters(in: .whitespacesAndNewlines)), code != 0 {
throw YConnectError.unsupported("Agent 启动后退出(状态 \(code)),请查看终端中的提示")
}
if FileManager.default.fileExists(atPath: plan.readyURL.path) {
return plan.manifest.autoStart ? "Agent 进程已在新终端启动 · \(plan.manifest.model)" : "专用终端已就绪 · 输入 yconnect-agent 启动"
acknowledged = true
return launchReadyMessage(autoStart: plan.manifest.autoStart, model: plan.manifest.model,
fellBackToTerminalApp: resolved.fellBackToTerminalApp)
}
}
throw YConnectError.unsupported("终端尚未确认启动,未使用的启动请求已取消。请查看终端窗口后重试")
}

/// Launch Services can wait indefinitely while the terminal shows its own
/// confirmation dialog. Bound that wait and ignore a later completion.
@MainActor
static func waitForTerminalOpen(timeout: TimeInterval = 30,
request: (@escaping (Error?) -> Void) -> Void) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
let completion = TerminalOpenCompletion(continuation)
DispatchQueue.main.asyncAfter(deadline: .now() + timeout) {
completion.finish(YConnectError.unsupported("等待终端确认超时,启动请求已取消。请处理终端中的运行确认提示,然后返回重试"))
}
request { completion.finish($0) }
}
}

/// Claim an unconsumed manifest atomically before revoking its credential.
/// A runner that already consumed it owns cleanup; never disrupt that session.
static func cancelPendingLaunch(_ plan: AgentLaunchPlan) {
let cancelled = plan.root.appendingPathComponent("cancelled.json")
guard (try? FileManager.default.moveItem(at: plan.manifestURL, to: cancelled)) != nil else { return }
let secret = URL(fileURLWithPath: plan.manifest.secretPath).resolvingSymlinksInPath()
if secret.path.hasPrefix(plan.root.resolvingSymlinksInPath().path + "/") {
try? FileManager.default.removeItem(at: secret)
}
throw YConnectError.unsupported("终端尚未确认启动,请查看终端窗口。启动请求两分钟后失效")
}

static func write(_ data: Data, to url: URL, permissions: Int = 0o600) throws {
Expand All @@ -191,6 +327,22 @@ enum ClientLauncher {
}
}

private final class TerminalOpenCompletion: @unchecked Sendable {
private let lock = NSLock()
private var continuation: CheckedContinuation<Void, Error>?

init(_ continuation: CheckedContinuation<Void, Error>) { self.continuation = continuation }

func finish(_ error: Error?) {
lock.lock()
let pending = continuation
continuation = nil
lock.unlock()
if let error { pending?.resume(throwing: error) }
else { pending?.resume(returning: ()) }
}
}

/// Runs before AppKit starts. Credentials travel in the child environment, never argv or shell history.
enum AgentSessionRunner {
static func run(manifestURL: URL) -> Int32 {
Expand Down
Loading
Loading