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
4 changes: 2 additions & 2 deletions Sources/SayoCLI/SayoCLI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ struct SayoCLI {
do {
let arguments = Array(CommandLine.arguments.dropFirst())
if arguments.first == "edit" {
guard arguments.count == 2 else { throw CLIError.usage }
let fileURL = try ExternalEditor.draftURL(arguments: Array(arguments.dropFirst()))
let pid = try frontmostApplicationPID()
try await ExternalEditor.edit(fileURL: URL(fileURLWithPath: arguments[1])) { text in
try await ExternalEditor.edit(fileURL: fileURL) { text in
// External editors receive the complete draft, with no caret metadata.
let request = TerminalRequest(text: text,
selection: .init(location: 0, length: text.utf16.count), applicationPID: pid)
Expand Down
3 changes: 3 additions & 0 deletions Sources/SayoCore/DiagnosticAnalysis.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ public struct DiagnosticEvent: Codable, Equatable, Sendable {
case "replacement_failed", "invocation_failed": return Self.errorExplanation(f["error"], language)
case "terminal_shortcut_detected":
let methods = ["focused_title": "聚焦窗口标题与前台进程匹配", "focused_tty": "聚焦 TTY 与前台进程匹配",
"focused_pane_agent": "聚焦 Otty 窗格的代理名称与前台进程匹配",
"focused_pane_unsupported_agent": "聚焦 Otty 窗格运行的是尚未支持的代理",
"focused_pane_agent_unconfirmed": "聚焦 Otty 窗格的代理没有匹配的前台进程",
"focused_text_program": "聚焦终端内容中的 CLI 名称与前台进程匹配", "single_session": "只有一个终端会话",
"no_supported_foreground_cli": "没有受支持的前台 CLI", "ambiguous_sessions": "多个会话无法确定聚焦 CLI",
"process_snapshot_unavailable": "无法读取进程快照"]
Expand Down
58 changes: 58 additions & 0 deletions Sources/SayoPlatform/OttyFocusedPaneDetector.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import AppKit
import Foundation
import SayoCore

enum TerminalFocusedAgent: Equatable {
case supported(CLIEditorProgram)
case unsupported
}

/// Otty's focused-pane metadata survives custom titles and full-screen redraws.
/// Only the agent kind is retained; paths, session IDs and titles are not logged.
enum OttyFocusedPaneDetector {
static func detect(in application: NSRunningApplication) -> TerminalFocusedAgent? {
guard application.bundleIdentifier == "io.appmakes.otty",
let bundleURL = application.bundleURL else { return nil }
let executable = bundleURL.appendingPathComponent("Contents/MacOS/otty-cli")
guard FileManager.default.isExecutableFile(atPath: executable.path) else { return nil }

let process = Process()
let output = Pipe()
process.executableURL = executable
process.arguments = ["pane", "show", "--json", "--timeout", "200"]
var environment = ProcessInfo.processInfo.environment
environment.removeValue(forKey: "OTTY_PANE_ID")
process.environment = environment
process.standardOutput = output
process.standardError = FileHandle.nullDevice
do {
try process.run()
let data = output.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
guard process.terminationStatus == 0 else { return nil }
return parse(data)
} catch {
return nil
}
}

static func parse(_ data: Data) -> TerminalFocusedAgent? {
struct Response: Decodable {
struct Pane: Decodable {
let active: Bool
let agent: String
}
let ok: Bool
let data: Pane
}
guard let response = try? JSONDecoder().decode(Response.self, from: data),
response.ok, response.data.active else { return nil }
switch response.data.agent.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() {
case "claude", "claude code", "claude-code": return .supported(.claude)
case "codex", "codex cli": return .supported(.codex)
case "agy", "antigravity", "antigravity cli": return .supported(.agy)
case "": return nil // No hook evidence: use the ordinary process/AX checks.
default: return .unsupported
}
}
}
28 changes: 24 additions & 4 deletions Sources/SayoPlatform/TerminalForegroundProcessDetector.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ public enum TerminalForegroundProcessDetector {
terminalPID: application.processIdentifier,
focusedTTY: tty(in: context.value),
focusedText: context.value,
focusedTitle: context.title
focusedTitle: context.title,
focusedAgent: OttyFocusedPaneDetector.detect(in: application)
)
}

Expand All @@ -59,18 +60,20 @@ public enum TerminalForegroundProcessDetector {
terminalPID: pid_t,
focusedTTY: String?,
focusedText: String = "",
focusedTitle: String = ""
focusedTitle: String = "",
focusedAgent: TerminalFocusedAgent? = nil
) -> TerminalForegroundRoute {
detectWithDiagnostics(records: records, terminalPID: terminalPID, focusedTTY: focusedTTY,
focusedText: focusedText, focusedTitle: focusedTitle).route
focusedText: focusedText, focusedTitle: focusedTitle, focusedAgent: focusedAgent).route
}

static func detectWithDiagnostics(
records: [TerminalProcessRecord],
terminalPID: pid_t,
focusedTTY: String?,
focusedText: String = "",
focusedTitle: String = ""
focusedTitle: String = "",
focusedAgent: TerminalFocusedAgent? = nil
) -> TerminalForegroundDetection {
var descendants: Set<pid_t> = [terminalPID]
var changed = true
Expand Down Expand Up @@ -107,6 +110,23 @@ public enum TerminalForegroundProcessDetector {
return .init(route: route, fields: fields)
}

// Unlike scrollback or the window title, Otty reports the agent in the
// focused pane. Still require a matching live foreground process: hooks
// can outlast an exited CLI. A program match does not identify its TTY
// when several panes run the same CLI; never pick an arbitrary session.
if let focusedAgent {
guard case .supported(let program) = focusedAgent else {
return result(.unknown, method: "focused_pane_unsupported_agent")
}
let matches = candidates.filter { $0.1 == program }
guard !matches.isEmpty else {
return result(.unknown, method: "focused_pane_agent_unconfirmed")
}
let ttys = Set(matches.map(\.0.tty))
return result(.cli(.init(program: program, tty: ttys.count == 1 ? ttys.first : nil)),
method: "focused_pane_agent")
}

// Ghostty retains scrollback in AXValue, including stale "Last login … on
// ttysNNN" lines. Its focused window title follows the running full-screen
// CLI, so a supported title is stronger evidence than a scrollback TTY.
Expand Down
24 changes: 24 additions & 0 deletions Sources/SayoTerminal/ExternalEditor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,30 @@ import Foundation

/// Adapts an external editor's draft file to the existing rewrite bridge.
public enum ExternalEditor {
/// Claude's VS Code adapter supplies `-g FILE:LINE` (optionally :COLUMN).
/// Existing helpers forward those arguments unchanged to `sayo edit`.
public static func draftURL(arguments: [String]) throws -> URL {
if arguments.count == 1 { return URL(fileURLWithPath: arguments[0]) }
guard arguments.count == 2, ["-g", "--goto"].contains(arguments[0]) else {
throw TerminalBridgeError.invalidRequest("Usage: sayo edit FILE | sayo edit -g FILE:LINE[:COLUMN]")
}
let locator = arguments[1]
let manager = FileManager.default
// A literal filename may itself end in colon-separated numbers.
if manager.fileExists(atPath: locator) { return URL(fileURLWithPath: locator) }
var path = locator
var matches: [String] = []
for _ in 0..<2 {
guard let suffix = path.range(of: #":[0-9]+$"#, options: .regularExpression) else { break }
path = String(path[..<suffix.lowerBound])
if manager.fileExists(atPath: path) { matches.append(path) }
}
guard matches.count == 1, let file = matches.first else {
throw TerminalBridgeError.invalidRequest("The editor draft path is missing or its cursor suffix is ambiguous.")
}
return URL(fileURLWithPath: file)
}

public static func edit(
fileURL: URL,
rewrite: (String) async throws -> String
Expand Down
4 changes: 3 additions & 1 deletion Sources/SayoTerminal/Resources/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ Open a **new zsh terminal tab** and restart the CLI after installation or reset.

Sayo routes its global invoke shortcut according to the foreground process in the focused terminal tab. Codex, Claude and agy receive their configured native external-editor shortcut directly; an ordinary shell receives the installed shell-widget chord. This avoids sending shell editing keys into a full-screen CLI.

Install the corresponding editor integration in Settings → Terminal, then restart your terminal for it to take effect. Continue using your existing Sayo global shortcut, or use the CLI's native external-editor shortcut, normally Ctrl+G. A fixed editor in the CLI's own settings may override environment variables; agy should use its default `auto` editor. Other CLI actions that use the external editor also receive Sayo. Claude's helper name contains `code` to select the GUI-editor waiting branch in Claude Code 2.1.150; this compatibility behavior may change in future versions.
For Otty, Sayo first queries the bundled `otty-cli pane show` read-only metadata and confirms its agent against live foreground processes. This also works with multiple tabs or splits whose titles show task names instead of CLI names. If the focused pane reports an unsupported agent or its agent has no matching foreground process, Sayo does not send a shortcut. When pane metadata is unavailable or no agent is reported, the ordinary process/accessibility checks still apply.

Install the corresponding editor integration in Settings → Terminal, then restart your terminal for it to take effect. Continue using your existing Sayo global shortcut, or use the CLI's native external-editor shortcut, normally Ctrl+G. A fixed editor in the CLI's own settings may override environment variables; agy should use its default `auto` editor. Other CLI actions that use the external editor also receive Sayo. Claude's helper name contains `code` to select its GUI-editor waiting branch. Sayo also accepts the `-g FILE:LINE[:COLUMN]` arguments used by Claude Code 2.1.287; existing helpers work without reinstallation.

`sayo edit FILE` reads a UTF-8 draft (up to 64 KB), opens the existing Sayo rewrite flow, and atomically writes the complete result back only on success. Cancellation, timeout, and invalid input leave the draft untouched; a draft changed during rewriting is not overwritten. Empty files are left unchanged. The complete draft is treated as an explicit selection. Silent mode returns a successful rewrite immediately. The CLI reloads the result without submitting the prompt.

Expand Down
27 changes: 27 additions & 0 deletions Tests/SayoPlatformTests/OttyFocusedPaneDetectorTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import XCTest
@testable import SayoPlatform

final class OttyFocusedPaneDetectorTests: XCTestCase {
func testReadsFocusedAgentWithoutDependingOnTaskTitleOrOtherMetadata() {
let data = Data(#"{"ok":true,"data":{"active":true,"agent":"Claude Code","process":"Custom task","cwd":"/private/project","agent_session_id":"private-session"}}"#.utf8)
XCTAssertEqual(OttyFocusedPaneDetector.parse(data), .supported(.claude))
}

func testRecognizesSupportedAgentNamesAndRejectsOtherAgents() {
for (name, expected) in [("claude", TerminalFocusedAgent.supported(.claude)),
("Codex", .supported(.codex)), ("agy", .supported(.agy)),
("Antigravity CLI", .supported(.agy)), ("omp", .unsupported)] {
let data = Data("{\"ok\":true,\"data\":{\"active\":true,\"agent\":\"\(name)\"}}".utf8)
XCTAssertEqual(OttyFocusedPaneDetector.parse(data), expected)
}
}

func testMissingInvalidInactiveOrEmptyMetadataFallsBack() {
for json in ["not JSON", "{}", #"{"ok":false,"data":{"active":true,"agent":"Claude Code"}}"#,
#"{"ok":true,"data":{"active":false,"agent":"Claude Code"}}"#,
#"{"ok":true,"data":{"active":true}}"#,
#"{"ok":true,"data":{"active":true,"agent":""}}"#] {
XCTAssertNil(OttyFocusedPaneDetector.parse(Data(json.utf8)))
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,53 @@ import SayoCore
@testable import SayoPlatform

final class TerminalForegroundProcessDetectorTests: XCTestCase {
private var ottySessions: [TerminalProcessRecord] {
TerminalForegroundProcessDetector.parseProcessSnapshot("""
100 1 100 0 ?? Otty /Applications/Otty.app/Contents/MacOS/Otty
101 100 101 201 ttys000 zsh -zsh
201 101 201 201 ttys000 claude /usr/local/bin/claude
102 100 102 102 ttys001 zsh -zsh
103 100 103 301 ttys002 zsh -zsh
301 103 301 301 ttys002 codex /usr/local/bin/codex
""")
}

func testOttyFocusedPaneRoutesClaudeWithMultipleSessionsAndCustomTaskTitle() {
// These are the old detector's missing clues after a full-screen redraw.
XCTAssertEqual(TerminalForegroundProcessDetector.detect(records: ottySessions, terminalPID: 100,
focusedTTY: nil, focusedText: "❯ 请整理这个流程", focusedTitle: "◐ 当前任务"), .unknown)
let detection = TerminalForegroundProcessDetector.detectWithDiagnostics(records: ottySessions, terminalPID: 100,
focusedTTY: nil, focusedText: "❯ 请整理这个流程", focusedTitle: "◐ 当前任务", focusedAgent: .supported(.claude))
XCTAssertEqual(detection.route, .cli(.init(program: .claude, tty: "ttys000")))
XCTAssertEqual(detection.fields["detectionMethod"], "focused_pane_agent")
XCTAssertEqual(detection.fields["sessionCount"], "3")
XCTAssertFalse(detection.fields.values.contains { $0.contains("当前任务") || $0.contains("整理") })
}

func testOttyFocusedPaneOverridesOtherCLINamesAndStaleTTYInScrollbackOrTitle() {
XCTAssertEqual(TerminalForegroundProcessDetector.detect(records: ottySessions, terminalPID: 100,
focusedTTY: "ttys002", focusedText: "Last login on ttys002\nCodex output", focusedTitle: "Codex task",
focusedAgent: .supported(.claude)), .cli(.init(program: .claude, tty: "ttys000")))
}

func testMultipleClaudePanesIdentifyProgramWithoutInventingFocusedTTY() {
let records = ottySessions + TerminalForegroundProcessDetector.parseProcessSnapshot("""
104 100 104 401 ttys003 zsh -zsh
401 104 401 401 ttys003 claude /usr/local/bin/claude
""")
XCTAssertEqual(TerminalForegroundProcessDetector.detect(records: records, terminalPID: 100,
focusedTTY: nil, focusedAgent: .supported(.claude)), .cli(.init(program: .claude, tty: nil)))
}

func testOttyUnsupportedOrUnconfirmedAgentNeverFallsThroughToAnotherSession() {
for agent in [TerminalFocusedAgent.unsupported, .supported(.agy)] {
XCTAssertEqual(TerminalForegroundProcessDetector.detect(records: ottySessions, terminalPID: 100,
focusedTTY: "ttys000", focusedText: "Claude Code", focusedTitle: "Claude Code", focusedAgent: agent), .unknown)
}
XCTAssertEqual(TerminalForegroundProcessDetector.detect(records: ottySessions, terminalPID: 999,
focusedTTY: nil, focusedAgent: .supported(.claude)), .unknown)
}

func testDiagnosticEvidenceExplainsTitleTTYAndAmbiguousRoutesWithoutText() {
let records = TerminalForegroundProcessDetector.parseProcessSnapshot("""
100 1 100 100 ?? Otty /Applications/Otty.app/Contents/MacOS/Otty
Expand Down
34 changes: 34 additions & 0 deletions Tests/SayoTerminalTests/ExternalEditorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,40 @@ final class ExternalEditorTests: XCTestCase {
}
}

func testClaudeGotoArgumentsRewriteTheDraftAndPreserveSpaces() async throws {
try await withDraft { file in
for arguments in [[file.path], ["-g", file.path + ":1"], ["--goto", file.path + ":12:3"]] {
XCTAssertEqual(try ExternalEditor.draftURL(arguments: arguments), file)
}
let url = try ExternalEditor.draftURL(arguments: ["-g", file.path + ":1"])
try await ExternalEditor.edit(fileURL: url) { _ in "rewritten" }
XCTAssertEqual(try String(contentsOf: file, encoding: .utf8), "rewritten")
XCTAssertFalse(FileManager.default.fileExists(atPath: file.path + ":1"))
}
}

func testGotoPreservesLiteralNumericFilenameSuffixAndRejectsAmbiguousPaths() async throws {
try await withDraft { file in
let numericFile = URL(fileURLWithPath: file.path + ":12")
try Data("literal filename".utf8).write(to: numericFile)
XCTAssertEqual(try ExternalEditor.draftURL(arguments: [numericFile.path]), numericFile)
XCTAssertEqual(try ExternalEditor.draftURL(arguments: ["-g", numericFile.path]), numericFile)
XCTAssertThrowsError(try ExternalEditor.draftURL(arguments: ["-g", numericFile.path + ":3"]))
XCTAssertEqual(try String(contentsOf: numericFile, encoding: .utf8), "literal filename")
}
}

func testInvalidEditorArgumentsDoNotSelectOrModifyADraft() async throws {
try await withDraft { file in
let original = try Data(contentsOf: file)
for arguments in [[], ["--unknown", file.path], ["-g", file.path + ":bad"],
["-g", file.path + ":1", "another-file"], ["-g", "/missing-draft:1"]] {
XCTAssertThrowsError(try ExternalEditor.draftURL(arguments: arguments))
}
XCTAssertEqual(try Data(contentsOf: file), original)
}
}

func testFailurePreservesOriginal() async throws {
try await withDraft { file in
let original = try Data(contentsOf: file)
Expand Down
5 changes: 5 additions & 0 deletions updates/claude-goto-editor-arguments-20261010.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"bump": "patch",
"en": ["Accept Claude Code's VS Code-style external-editor arguments so newer Claude versions can replace drafts through existing Sayo integrations."],
"zh-CN": ["兼容 Claude Code 的 VS Code 风格外部编辑器参数,让新版 Claude 能通过已有 Sayo 集成替换草稿。"]
}
5 changes: 5 additions & 0 deletions updates/otty-focused-pane-routing-20261010.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"bump": "patch",
"en": ["Fix Claude Code editor routing in Otty with multiple sessions and custom task titles by recognizing the agent in the focused pane."],
"zh-CN": ["修复 Otty 多会话及自定义任务标题下的 Claude Code 编辑器路由,使用当前聚焦窗格的代理信息识别 CLI。"]
}
Loading