diff --git a/Sources/SayoApp/SayoApp.swift b/Sources/SayoApp/SayoApp.swift index 2f6e6a4..19afec9 100644 --- a/Sources/SayoApp/SayoApp.swift +++ b/Sources/SayoApp/SayoApp.swift @@ -92,6 +92,7 @@ public enum SayoRuntime { private var model: AppViewModel! private var bubble: BubblePanelController! private var bridge: TerminalBridge? + private var terminalRequestDiagnosticFields: [String: String] = [:] private var installer: TerminalInstaller? private var statusItem: NSStatusItem! private var settingsWindow: NSWindow? @@ -179,6 +180,9 @@ public enum SayoRuntime { } fields.merge(invocationApplications[id] ?? [:], uniquingKeysWith: { current, _ in current }) } + if self?.routedInput.terminalContext != nil { + fields.merge(self?.terminalRequestDiagnosticFields ?? [:], uniquingKeysWith: { current, _ in current }) + } if event == "input_captured", self?.routedInput.terminalContext == nil, let evidence = self?.accessibility.lastInputDiagnosticFields, evidence["inputID"] == fields["inputID"] { @@ -554,16 +558,20 @@ public enum SayoRuntime { if routedInput.terminalContext != nil { coordinator.shortcut(destination: destination); return } if let application = NSWorkspace.shared.frontmostApplication, TerminalDetector.isTerminal(application.bundleIdentifier) { - switch TerminalForegroundProcessDetector.detect(in: application) { + let detection = TerminalForegroundProcessDetector.detectWithDiagnostics(in: application) + var routeFields = detection.fields + routeFields.merge([ + "app": application.localizedName ?? "unknown", "bundleID": application.bundleIdentifier ?? "unknown", + "terminalMatch": "known_bundle_id", "attempt": UUID().uuidString, "trigger": "terminal" + ], uniquingKeysWith: { current, _ in current }) + DiagnosticLog.shared.record("terminal_shortcut_detected", fields: routeFields) + switch detection.route { case .cli(let command): - invokeCLIShortcut(command, triggeringShortcut: triggeringShortcut, destination: destination, applicationPID: application.processIdentifier) + invokeCLIShortcut(command, triggeringShortcut: triggeringShortcut, destination: destination, + applicationPID: application.processIdentifier, diagnosticFields: routeFields) return case .unknown: - DiagnosticLog.shared.record("terminal_shortcut_route_unknown", fields: [ - "app": application.localizedName ?? "unknown", - "bundleID": application.bundleIdentifier ?? "unknown", - "attempt": UUID().uuidString - ]) + DiagnosticLog.shared.record("terminal_shortcut_route_unknown", fields: routeFields) model.notice = localized( "Sayo could not identify the CLI in the focused terminal tab. Focus its input and try again.", "Sayo 无法识别当前终端标签页中的 CLI。请聚焦到输入区后重试。" @@ -574,15 +582,19 @@ public enum SayoRuntime { break } guard TerminalShell.allCases.contains(where: { installer?.isInstalled(shell: $0) == true }) else { + routeFields["shellInstalled"] = "false" + routeFields["reason"] = "shell_integration_missing" + DiagnosticLog.shared.record("terminal_shortcut_route_failed", fields: routeFields) model.notice = localized( "Install your shell integration in Terminal settings first.", "请先在终端设置中安装 Shell 集成。" ); model.noticeIsError = true showSettings(); return } - DiagnosticLog.shared.record("terminal_shortcut_route", fields: [ - "route": "shell", "attempt": UUID().uuidString - ]) + routeFields["shellInstalled"] = "true" + routeFields["key"] = "ctrl+x ctrl+r" + DiagnosticLog.shared.record("terminal_shortcut_route", fields: routeFields) + let dispatchFields = routeFields terminalShortcutDispatchTask?.cancel() terminalShortcutDispatchTask = Task { @MainActor [weak self] in guard let self else { return } @@ -590,17 +602,14 @@ public enum SayoRuntime { let routeID = self.terminalTranslationRoute.arm(destination: destination, applicationPID: application.processIdentifier) do { try await self.shortcuts.triggerTerminalWidget(afterReleasing: triggeringShortcut) - DiagnosticLog.shared.record("terminal_shortcut_posted", fields: [ - "route": "shell", "key": "ctrl+x ctrl+r" - ]) + DiagnosticLog.shared.record("terminal_shortcut_posted", fields: dispatchFields) } catch is CancellationError { self.terminalTranslationRoute.clear(id: routeID) return } catch { self.terminalTranslationRoute.clear(id: routeID) - DiagnosticLog.shared.record("terminal_shortcut_route_failed", fields: [ - "route": "shell", "error": error.localizedDescription - ]) + DiagnosticLog.shared.record("terminal_shortcut_route_failed", fields: + dispatchFields.merging(["error": error.localizedDescription], uniquingKeysWith: { _, new in new })) self.model.notice = error.localizedDescription self.model.noticeIsError = true } @@ -608,10 +617,16 @@ public enum SayoRuntime { } else { invokeTextShortcutPressed(destination: destination) } } - private func invokeCLIShortcut(_ command: TerminalForegroundCommand, triggeringShortcut: Shortcut, destination: TranslationDestination, applicationPID: Int32) { + private func invokeCLIShortcut(_ command: TerminalForegroundCommand, triggeringShortcut: Shortcut, + destination: TranslationDestination, applicationPID: Int32, + diagnosticFields: [String: String]) { let program = command.program + var routeFields = diagnosticFields do { guard try CLIEditorInstaller().isInstalled(program) else { + routeFields["editorInstalled"] = "false" + routeFields["reason"] = "cli_editor_integration_missing" + DiagnosticLog.shared.record("terminal_shortcut_route_failed", fields: routeFields) model.notice = localized( "Install the \(program.name) editor integration in Terminal settings first.", "请先在终端设置中安装 \(program.name) 编辑器集成。" @@ -620,8 +635,12 @@ public enum SayoRuntime { showSettings() return } + routeFields["editorInstalled"] = "true" let state = try CLIShortcutSettings().status(program) + routeFields["key"] = state.value guard let shortcut = CLIShortcut.shortcut(for: state.value) else { + routeFields["reason"] = "cli_editor_shortcut_unbound" + DiagnosticLog.shared.record("terminal_shortcut_route_failed", fields: routeFields) model.notice = localized( "The \(program.name) external-editor shortcut is unbound.", "\(program.name) 的外部编辑器快捷键尚未绑定。" @@ -630,14 +649,9 @@ public enum SayoRuntime { showSettings() return } - DiagnosticLog.shared.record("terminal_shortcut_route", fields: [ - "route": "cli", - "program": program.rawValue, - "key": state.value, - "tty": command.tty ?? "unknown", - "matchesGlobal": String(coordinator.settings.activeGlobalShortcuts.contains(shortcut)), - "attempt": UUID().uuidString - ]) + routeFields["matchesGlobal"] = String(coordinator.settings.activeGlobalShortcuts.contains(shortcut)) + DiagnosticLog.shared.record("terminal_shortcut_route", fields: routeFields) + let dispatchFields = routeFields terminalShortcutDispatchTask?.cancel() terminalShortcutDispatchTask = Task { @MainActor [weak self] in guard let self else { return } @@ -648,31 +662,22 @@ public enum SayoRuntime { shortcut, afterReleasing: triggeringShortcut ) - DiagnosticLog.shared.record("terminal_shortcut_posted", fields: [ - "program": program.rawValue, - "key": state.value, - "relayed": String(relayed) - ]) + DiagnosticLog.shared.record("terminal_shortcut_posted", fields: + dispatchFields.merging(["relayed": String(relayed)], uniquingKeysWith: { _, new in new })) } catch is CancellationError { self.terminalTranslationRoute.clear(id: routeID) return } catch { self.terminalTranslationRoute.clear(id: routeID) - DiagnosticLog.shared.record("terminal_shortcut_route_failed", fields: [ - "route": "cli", - "program": program.rawValue, - "error": error.localizedDescription - ]) + DiagnosticLog.shared.record("terminal_shortcut_route_failed", fields: + dispatchFields.merging(["error": error.localizedDescription], uniquingKeysWith: { _, new in new })) self.model.notice = error.localizedDescription self.model.noticeIsError = true } } } catch { - DiagnosticLog.shared.record("terminal_shortcut_route_failed", fields: [ - "route": "cli", - "program": program.rawValue, - "error": error.localizedDescription - ]) + DiagnosticLog.shared.record("terminal_shortcut_route_failed", fields: + routeFields.merging(["error": error.localizedDescription], uniquingKeysWith: { _, new in new })) model.notice = error.localizedDescription model.noticeIsError = true showSettings() @@ -745,6 +750,9 @@ public enum SayoRuntime { return .init(error: localized("Sayo is disabled in this app.", "Sayo 已在此应用中停用。")) } let destination = terminalTranslationRoute.consume(for: request) + terminalRequestDiagnosticFields = TerminalForegroundProcessDetector.detectWithDiagnostics(in: application).fields + terminalRequestDiagnosticFields["terminalMatch"] = TerminalDetector.isTerminal(application.bundleIdentifier) ? "known_bundle_id" : "bridge_request" + terminalRequestDiagnosticFields["method"] = "terminal_bridge" coordinator.dismiss() let timeoutMessage = localized( "Rewrite timed out. Your original buffer was kept.", diff --git a/Sources/SayoApplication/RewriteCoordinator.swift b/Sources/SayoApplication/RewriteCoordinator.swift index 4298043..3961cf2 100644 --- a/Sources/SayoApplication/RewriteCoordinator.swift +++ b/Sources/SayoApplication/RewriteCoordinator.swift @@ -195,7 +195,7 @@ public struct BubbleState: Equatable, Sendable { } let outcome: TextReplacementOutcome // The animated replacer falls back to an instant write when Reduce Motion is on. - if captured.context.selection.length == 0, + if self.settings.inputAnimationEnabled, captured.context.selection.length == 0, let animatedReplacer = self.replacer as? any AnimatedTextReplacer { outcome = try await animatedReplacer.replaceAnimated(text, in: captured) } else { diff --git a/Sources/SayoCore/DiagnosticAnalysis.swift b/Sources/SayoCore/DiagnosticAnalysis.swift index b499689..913c66e 100644 --- a/Sources/SayoCore/DiagnosticAnalysis.swift +++ b/Sources/SayoCore/DiagnosticAnalysis.swift @@ -60,6 +60,27 @@ public struct DiagnosticEvent: Codable, Equatable, Sendable { case "replacement_finished", "invocation_completed": return f["outcome"] == "inserted_at_caret" ? t("Inserted at the original caret; original text was kept.", "已追加到原光标位置,原文保留。") : t("Replacement completed.", "已完成替换。") case "replacement_failed", "invocation_failed": return Self.errorExplanation(f["error"], language) + case "terminal_shortcut_detected": + let methods = ["focused_title": "聚焦窗口标题与前台进程匹配", "focused_tty": "聚焦 TTY 与前台进程匹配", + "focused_text_program": "聚焦终端内容中的 CLI 名称与前台进程匹配", "single_session": "只有一个终端会话", + "no_supported_foreground_cli": "没有受支持的前台 CLI", "ambiguous_sessions": "多个会话无法确定聚焦 CLI", + "process_snapshot_unavailable": "无法读取进程快照"] + let method = f["detectionMethod"] ?? "unknown" + return t("Recognized \(f["app"] ?? "app") as a terminal by bundle ID; route \(f["route"] ?? "unknown"), CLI \(f["program"] ?? "none"), evidence \(method).", + "按应用标识识别 \(f["app"] ?? "当前应用") 为终端;路由:\(f["route"] ?? "unknown"),CLI:\(f["program"] ?? "无");依据:\(methods[method] ?? method)。") + case "terminal_shortcut_route": + return t("Using \(f["route"] ?? "unknown") integration with key \(f["key"] ?? "unknown").", + "使用 \(f["route"] ?? "unknown") 集成,转发快捷键 \(f["key"] ?? "未知")。") + case "terminal_shortcut_posted": + return t("Terminal shortcut \(f["key"] ?? "unknown") dispatched; this alone does not confirm an editor opened or text was replaced.", + "已发送终端快捷键 \(f["key"] ?? "未知");仅此记录还不能确认编辑器已打开或正文已替换。") + case "terminal_shortcut_route_unknown": + return t("Could not identify the CLI in the focused terminal tab; no shortcut was sent.", "无法确定聚焦终端标签页中的 CLI,未发送快捷键。") + case "terminal_shortcut_route_failed": + let reasons = ["shell_integration_missing": "尚未安装 Shell 集成", "cli_editor_integration_missing": "尚未安装 CLI 外部编辑器集成", + "cli_editor_shortcut_unbound": "CLI 外部编辑器快捷键未绑定"] + return t("Terminal handoff stopped: \(f["reason"] ?? f["error"] ?? "unknown").", + "终端转发停止:\(reasons[f["reason"] ?? ""] ?? f["error"] ?? "未知原因")。") case "input": switch f["reason"] { case "placeholder_containment_length": return t("Filtered placeholder: the value contains it and is no longer than twice its length (\(f["rawLength"] ?? "?") → 0).", "文案包含 placeholder,且长度不超过其两倍,已按空内容处理(\(f["rawLength"] ?? "?") → 0)。") @@ -68,6 +89,9 @@ public struct DiagnosticEvent: Codable, Equatable, Sendable { case "empty_value": return t("The focused input is empty.", "当前输入框为空。") case "secure_input_skipped": return t("Skipped a secure input without reading its text.", "当前为密码等安全输入框,未读取正文。") case "terminal_or_excluded_app", "sayo_settings": return t("This application is excluded or uses terminal integration.", "当前应用被排除,或需要走终端集成。") + case "terminal_detected": return t("Recognized this terminal by its application bundle ID. Use Shell or CLI external-editor integration; terminal screen text is not a normal editable input.", + "按应用标识识别为终端,应走 Shell 或 CLI 外部编辑器集成;终端屏幕内容不作为普通输入框读取。") + case "excluded_app": return t("Sayo is disabled for this app by the application filter.", "应用范围设置已在此应用中停用 Sayo。") case "no_focused_element": return t("No focused input was exposed by the app.", "应用没有提供当前聚焦的输入控件。") case "unsupported_role": return t("Focused control \(f["role"] ?? "?") is not a supported text input.", "当前聚焦的 \(f["role"] ?? "?") 控件不是支持的文本输入框。") default: return t("Input read was unavailable: \(f["reason"] ?? "unknown").", "未能读取输入,原因:\(f["reason"] ?? "未知")。") @@ -135,13 +159,15 @@ public struct DiagnosticGroup: Identifiable, Equatable, Sendable { public var applicationKey: String { events.compactMap { $0.fields["bundleID"] }.first ?? application } public var startedAt: Date? { events.first?.date } public var lastEventAt: Date? { events.last?.date } - public var trigger: String? { events.first(where: { $0.event == "invocation_started" })?.fields["trigger"] } + public var trigger: String? { events.first(where: { $0.event == "invocation_started" || $0.event == "terminal_shortcut_detected" })?.fields["trigger"] } public var ordinal: String? { events.first(where: { $0.event == "invocation_started" })?.fields["ordinal"] } - public var incomplete: Bool { category == .invocation && !events.contains(where: { $0.event == "invocation_started" }) } + public var incomplete: Bool { category == .invocation && !events.contains(where: { $0.event == "invocation_started" || $0.event == "terminal_shortcut_detected" }) } public var outcome: String? { - events.last(where: { ["invocation_completed", "replacement_finished", "invocation_failed", "replacement_failed", "invocation_cancelled", "invocation_ignored", "rewrite_ready", "rewrite_requested"].contains($0.event) }).map { + events.last(where: { ["invocation_completed", "replacement_finished", "invocation_failed", "replacement_failed", "invocation_cancelled", "invocation_ignored", "rewrite_ready", "rewrite_requested", "terminal_shortcut_route_failed", "terminal_shortcut_route_unknown", "terminal_shortcut_posted"].contains($0.event) }).map { switch $0.event { case "invocation_failed", "replacement_failed": return "failed" + case "terminal_shortcut_route_failed", "terminal_shortcut_route_unknown": return "failed" + case "terminal_shortcut_posted": return "dispatched" case "invocation_cancelled": return "cancelled" case "invocation_ignored": return "ignored" case "rewrite_ready": return "ready" @@ -160,6 +186,7 @@ public struct DiagnosticGroup: Identifiable, Equatable, Sendable { case "ignored": return language.text("Skipped", "未触发改写") case "ready": return language.text("Result ready; not yet applied", "结果已就绪,尚未应用") case "loading": return language.text("Request started; no completion recorded", "已发起请求,尚无完成记录") + case "dispatched": return language.text("Shortcut sent; replacement not confirmed here", "快捷键已发送,此记录尚未确认替换") default: return category == .invocation ? language.text("No outcome recorded", "暂无结果记录") : language.text("\(events.count) events", "\(events.count) 条事件") } } @@ -180,6 +207,8 @@ public struct DiagnosticAnalysis: Equatable, Sendable { let key: String if let invocation = event.fields["invocationID"], !invocation.isEmpty { category = .invocation; key = "invocation:\(invocation)" + } else if event.event.hasPrefix("terminal_shortcut_"), let attempt = event.fields["attempt"], !attempt.isEmpty { + category = .invocation; key = "terminal:\(attempt)" } else if event.event == "input" { category = .input; key = "input:\(event.fields["bundleID"] ?? event.fields["app"] ?? "unknown"):\(event.fields["inputID"] ?? "unavailable")" } else if event.event == "bubble" { @@ -232,7 +261,9 @@ public struct AIDiagnosticEvidence: Codable, Equatable, Sendable { "placeholderMatchesValue", "placeholderSource", "prefersPaste", "range", "rawLength", "reason", "replacementLength", "resolvedLength", "resultLength", "revertedAfterResult", "role", "samples", "scope", "selection", "sequence", "sourceLength", "stableSamples", - "status", "step", "targetRange", "textSnippets", "tree", "trigger", "webInput" + "status", "step", "targetRange", "textSnippets", "tree", "trigger", "webInput", + "terminalMatch", "detectionMethod", "route", "program", "key", "tty", "focusedTTY", + "titleProgram", "candidateCount", "sessionCount", "editorInstalled", "shellInstalled", "matchesGlobal", "relayed" ] public init( @@ -246,7 +277,7 @@ public struct AIDiagnosticEvidence: Codable, Equatable, Sendable { let candidates = analysis.groups.compactMap { group -> (DiagnosticGroup, Date)? in guard group.category == .invocation, group.outcome == "failed", let failedAt = group.events.last(where: { - $0.event == "invocation_failed" || $0.event == "replacement_failed" + ["invocation_failed", "replacement_failed", "terminal_shortcut_route_failed", "terminal_shortcut_route_unknown"].contains($0.event) })?.date, failedAt >= cutoff, failedAt <= now else { return nil } diff --git a/Sources/SayoCore/Settings.swift b/Sources/SayoCore/Settings.swift index 0257705..cda8e53 100644 --- a/Sources/SayoCore/Settings.swift +++ b/Sources/SayoCore/Settings.swift @@ -357,6 +357,8 @@ public struct AppSettings: Codable, Equatable, Sendable { /// Explicit opt-in for apps that do not expose a readable Accessibility text input. /// Shortcut invocations may capture the current selection with Copy and apply with Paste. public var copyPasteCompatibilityEnabled = false + /// Animate whole-input replacements when the input supports verified animated writes. + public var inputAnimationEnabled = true public var developerMode = false public var retainDiagnosticLogs = true public var launchAtLogin = false @@ -477,7 +479,7 @@ public struct AppSettings: Codable, Equatable, Sendable { case mode, llm, prompt, interfaceLanguage, targetLanguage case secondaryTargetLanguage, secondaryPrompt, secondaryShortcut case invokeShortcut, copyShortcut, replaceShortcut - case copyPasteCompatibilityEnabled + case copyPasteCompatibilityEnabled, inputAnimationEnabled case automaticallyChecksForUpdates, automaticallyDownloadsUpdates case shortcut case developerMode, retainDiagnosticLogs, launchAtLogin, statusBarIconStyle, onboardingCompleted, applicationFilterMode, applicationBundleIDs @@ -526,6 +528,7 @@ public struct AppSettings: Codable, Equatable, Sendable { replaceShortcut = legacyShortcut ?? .controlG } copyPasteCompatibilityEnabled = try container.decodeIfPresent(Bool.self, forKey: .copyPasteCompatibilityEnabled) ?? false + inputAnimationEnabled = try container.decodeIfPresent(Bool.self, forKey: .inputAnimationEnabled) ?? true launchAtLogin = try container.decodeIfPresent(Bool.self, forKey: .launchAtLogin) ?? false automaticallyChecksForUpdates = try container.decodeIfPresent(Bool.self, forKey: .automaticallyChecksForUpdates) ?? true automaticallyDownloadsUpdates = try container.decodeIfPresent(Bool.self, forKey: .automaticallyDownloadsUpdates) ?? true @@ -557,6 +560,7 @@ public struct AppSettings: Codable, Equatable, Sendable { try container.encodeIfPresent(copyShortcut, forKey: .copyShortcut) try container.encode(replaceShortcut, forKey: .replaceShortcut) try container.encode(copyPasteCompatibilityEnabled, forKey: .copyPasteCompatibilityEnabled) + try container.encode(inputAnimationEnabled, forKey: .inputAnimationEnabled) try container.encode(developerMode, forKey: .developerMode) try container.encode(retainDiagnosticLogs, forKey: .retainDiagnosticLogs) try container.encode(launchAtLogin, forKey: .launchAtLogin) diff --git a/Sources/SayoPlatform/AccessibilityTextAdapter.swift b/Sources/SayoPlatform/AccessibilityTextAdapter.swift index 767fef7..51c42a0 100644 --- a/Sources/SayoPlatform/AccessibilityTextAdapter.swift +++ b/Sources/SayoPlatform/AccessibilityTextAdapter.swift @@ -301,6 +301,12 @@ public final class AccessibilityTextAdapter: TextInputSource, AnimatedTextReplac "bundleID": foreground?.bundleIdentifier ?? "unknown", "reason": "permission_required"] defer { lastInputDiagnosticFields = diagnostics; DiagnosticLog.shared.record("input", fields: diagnostics) } guard Self.isTrusted else { throw SayoError.permissionRequired } + if let foreground, TerminalDetector.isTerminal(foreground.bundleIdentifier) { + diagnostics["reason"] = "terminal_detected" + diagnostics["terminalMatch"] = "known_bundle_id" + diagnostics["route"] = "terminal_integration" + return nil + } // Chromium/Electron expose text markers only after an assistive client // requests their full accessibility tree. Do this on activation, before @@ -329,8 +335,8 @@ public final class AccessibilityTextAdapter: TextInputSource, AnimatedTextReplac diagnostics["app"] = application.localizedName ?? "unknown" diagnostics["bundleID"] = bundleID ?? "unknown" diagnostics["pid"] = String(pid) - if TerminalDetector.isTerminal(bundleID) || !isApplicationAllowed(bundleID) { - diagnostics["reason"] = "terminal_or_excluded_app" + if !isApplicationAllowed(bundleID) { + diagnostics["reason"] = "excluded_app" return nil } if pid == ProcessInfo.processInfo.processIdentifier && isOwnSettings(focused) { @@ -1164,6 +1170,7 @@ public enum TerminalDetector { "com.apple.Terminal", "com.googlecode.iterm2", "com.mitchellh.ghostty", + "io.appmakes.otty", "dev.warp.Warp", "dev.warp.Warp-Stable", "com.github.wez.wezterm", diff --git a/Sources/SayoPlatform/TerminalForegroundProcessDetector.swift b/Sources/SayoPlatform/TerminalForegroundProcessDetector.swift index fa5470a..8dcec82 100644 --- a/Sources/SayoPlatform/TerminalForegroundProcessDetector.swift +++ b/Sources/SayoPlatform/TerminalForegroundProcessDetector.swift @@ -19,6 +19,12 @@ public enum TerminalForegroundRoute: Equatable, Sendable { case unknown } +/// Structural evidence only: no window titles, terminal contents or process arguments. +public struct TerminalForegroundDetection: Equatable, Sendable { + public let route: TerminalForegroundRoute + public let fields: [String: String] +} + struct TerminalProcessRecord: Equatable { let pid: pid_t let parentPID: pid_t @@ -31,9 +37,15 @@ struct TerminalProcessRecord: Equatable { public enum TerminalForegroundProcessDetector { public static func detect(in application: NSRunningApplication) -> TerminalForegroundRoute { - guard let records = processSnapshot() else { return .unknown } + detectWithDiagnostics(in: application).route + } + + public static func detectWithDiagnostics(in application: NSRunningApplication) -> TerminalForegroundDetection { + guard let records = processSnapshot() else { + return .init(route: .unknown, fields: ["detectionMethod": "process_snapshot_unavailable", "route": "unknown"]) + } let context = accessibilityContext(for: application.processIdentifier) - return detect( + return detectWithDiagnostics( records: records, terminalPID: application.processIdentifier, focusedTTY: tty(in: context.value), @@ -49,6 +61,17 @@ public enum TerminalForegroundProcessDetector { focusedText: String = "", focusedTitle: String = "" ) -> TerminalForegroundRoute { + detectWithDiagnostics(records: records, terminalPID: terminalPID, focusedTTY: focusedTTY, + focusedText: focusedText, focusedTitle: focusedTitle).route + } + + static func detectWithDiagnostics( + records: [TerminalProcessRecord], + terminalPID: pid_t, + focusedTTY: String?, + focusedText: String = "", + focusedTitle: String = "" + ) -> TerminalForegroundDetection { var descendants: Set = [terminalPID] var changed = true while changed { @@ -68,6 +91,21 @@ public enum TerminalForegroundProcessDetector { guard let program = program(for: record) else { return nil } return (record, program) } + let sessionTTYs = Set(terminalRecords.map(\.tty).filter { $0 != "??" && $0 != "-" }) + func result(_ route: TerminalForegroundRoute, method: String) -> TerminalForegroundDetection { + var fields = ["detectionMethod": method, "candidateCount": String(candidates.count), + "sessionCount": String(sessionTTYs.count)] + if let focusedTTY { fields["focusedTTY"] = focusedTTY } + if let program = program(inTitle: focusedTitle) { fields["titleProgram"] = program.rawValue } + switch route { + case .cli(let command): + fields["route"] = "cli"; fields["program"] = command.program.rawValue + fields["tty"] = command.tty ?? "unknown" + case .shell: fields["route"] = "shell" + case .unknown: fields["route"] = "unknown" + } + return .init(route: route, fields: fields) + } // Ghostty retains scrollback in AXValue, including stale "Last login … on // ttysNNN" lines. Its focused window title follows the running full-screen @@ -76,12 +114,12 @@ public enum TerminalForegroundProcessDetector { let matches = candidates.filter { $0.1 == titledProgram } let ttys = Set(matches.map(\.0.tty)) if !matches.isEmpty { - return .cli(.init(program: titledProgram, tty: ttys.count == 1 ? ttys.first : nil)) + return result(.cli(.init(program: titledProgram, tty: ttys.count == 1 ? ttys.first : nil)), method: "focused_title") } } if let focusedTTY { - return route(for: candidates.filter { $0.0.tty == focusedTTY }, tty: focusedTTY) + return result(route(for: candidates.filter { $0.0.tty == focusedTTY }, tty: focusedTTY), method: "focused_tty") } let mentionedPrograms = Set(candidates.map(\.1).filter { program in @@ -95,17 +133,17 @@ public enum TerminalForegroundProcessDetector { }) if mentionedPrograms.count == 1, let program = mentionedPrograms.first, let tty = candidates.first(where: { $0.1 == program })?.0.tty { - return .cli(.init(program: program, tty: tty)) + return result(.cli(.init(program: program, tty: tty)), method: "focused_text_program") } - let sessionTTYs = Set(terminalRecords.map(\.tty).filter { $0 != "??" && $0 != "-" }) if sessionTTYs.count == 1, let tty = sessionTTYs.first { - return route(for: candidates.filter { $0.0.tty == tty }, tty: tty) + return result(route(for: candidates.filter { $0.0.tty == tty }, tty: tty), method: "single_session") } // No supported foreground CLI exists in any of this terminal application's // sessions, so the focused session can safely use the shell widget route. - return candidates.isEmpty ? .shell : .unknown + return result(candidates.isEmpty ? .shell : .unknown, + method: candidates.isEmpty ? "no_supported_foreground_cli" : "ambiguous_sessions") } private static func route( diff --git a/Sources/SayoUI/SettingsView.swift b/Sources/SayoUI/SettingsView.swift index 2b23d44..b042d23 100644 --- a/Sources/SayoUI/SettingsView.swift +++ b/Sources/SayoUI/SettingsView.swift @@ -303,6 +303,11 @@ public struct SettingsView: View { if model.supportsFocusedInput { SayoCard { sectionLabel(t("REPLACEMENT", "替换方式")) + toggleRow(t("Character-by-character replacement", "逐字替换动画"), isOn: $model.settings.inputAnimationEnabled, detail: t( + "Reveal whole-input replacements gradually in supported apps. Selected text and terminal drafts are replaced instantly. Respects macOS Reduce Motion.", + "在支持的应用中逐字显示整段替换结果。选区和终端草稿仍一次性回填,并遵循 macOS 的“减少动态效果”设置。" + )) + Divider() toggleRow(t("Copy/Paste compatibility fallback", "复制/粘贴兼容模式"), isOn: $model.settings.copyPasteCompatibilityEnabled, detail: t( "For apps whose input cannot be read normally. An explicit shortcut copies the current selection, then pastes the rewrite back after checking the app and window.", "用于无法正常读取输入框的应用。快捷键会复制当前选区,并在核对应用和窗口后粘贴改写结果。" diff --git a/Tests/SayoApplicationTests/RewriteCoordinatorTests.swift b/Tests/SayoApplicationTests/RewriteCoordinatorTests.swift index fe70424..afda2e7 100644 --- a/Tests/SayoApplicationTests/RewriteCoordinatorTests.swift +++ b/Tests/SayoApplicationTests/RewriteCoordinatorTests.swift @@ -251,8 +251,9 @@ private actor ControlledProvider: RewriteProvider { await eventually { await clock.count == 1 }; await clock.advance() await eventually { sut.state.phase == .hidden } } - func testExperimentalInputAnimationUsesAnimatedReplacer() async { + func testEnabledInputAnimationUsesAnimatedReplacer() async { var settings = AppSettings() + settings.inputAnimationEnabled = true settings.mode = .silent let input = MemoryInput(), provider = ControlledProvider(), clock = ControlledClock() let sut = RewriteCoordinator(settings: settings, source: input, replacer: input, provider: provider, clock: clock) @@ -267,6 +268,23 @@ private actor ControlledProvider: RewriteProvider { await eventually { await clock.count == 1 } await clock.advance() } + func testDisabledInputAnimationUsesInstantReplacer() async { + var settings = AppSettings() + settings.mode = .silent + settings.inputAnimationEnabled = false + let input = MemoryInput(), provider = ControlledProvider(), clock = ControlledClock() + let sut = RewriteCoordinator(settings: settings, source: input, replacer: input, provider: provider, clock: clock) + + sut.shortcut() + await eventually { await provider.count == 1 } + await provider.complete("I like this product.") + await eventually { sut.state.phase == .replaced } + + XCTAssertEqual(input.animatedReplacementCount, 0) + XCTAssertEqual(input.replacements, ["I like this product."]) + await eventually { await clock.count == 1 } + await clock.advance() + } func testSelectedTextSkipsInputAnimationEvenIfSelectionCollapsesBeforeApply() async { var settings = AppSettings() settings.mode = .manual diff --git a/Tests/SayoCoreTests/DiagnosticAnalysisTests.swift b/Tests/SayoCoreTests/DiagnosticAnalysisTests.swift index 73dc7dd..391d014 100644 --- a/Tests/SayoCoreTests/DiagnosticAnalysisTests.swift +++ b/Tests/SayoCoreTests/DiagnosticAnalysisTests.swift @@ -59,6 +59,58 @@ final class DiagnosticAnalysisTests: XCTestCase { XCTAssertEqual(DiagnosticEvent.errorCode(SayoError.network("secret response")), "network") } + func testTerminalRecognitionHasDistinctExplanationFromExcludedApplications() { + let terminal = DiagnosticEvent(timestamp: "", event: "input", fields: ["reason": "terminal_detected"]) + XCTAssertTrue(terminal.explanation(.simplifiedChinese).contains("按应用标识识别为终端")) + XCTAssertTrue(terminal.explanation(.english).contains("Shell or CLI")) + let excluded = DiagnosticEvent(timestamp: "", event: "input", fields: ["reason": "excluded_app"]) + XCTAssertTrue(excluded.explanation(.simplifiedChinese).contains("应用范围设置")) + XCTAssertFalse(excluded.explanation(.english).contains("terminal")) + } + + func testTerminalRoutingFailuresAreGroupedAndIncludedInRedactedAIEvidence() throws { + let lines = try [ + line("terminal_shortcut_detected", ["attempt": "missing", "app": "Otty", "bundleID": "io.appmakes.otty", + "trigger": "terminal", "terminalMatch": "known_bundle_id", "route": "cli", "program": "claude", + "detectionMethod": "focused_title", "candidateCount": "1", "sessionCount": "2", + "focusedTitle": "private document", "arguments": "private command", "pid": "42"]), + line("terminal_shortcut_route_failed", ["attempt": "missing", "reason": "cli_editor_integration_missing", "editorInstalled": "false"]), + line("terminal_shortcut_detected", ["attempt": "unknown", "app": "Other Terminal", "route": "unknown", "detectionMethod": "ambiguous_sessions"]), + line("terminal_shortcut_route_unknown", ["attempt": "unknown"]), + line("terminal_shortcut_detected", ["attempt": "posted", "app": "Working Terminal"]), + line("terminal_shortcut_posted", ["attempt": "posted", "key": "ctrl+g"]) + ] + let analysis = DiagnosticAnalysis(jsonLines: lines.joined(separator: "\n")) + let failed = try XCTUnwrap(analysis.groups.first { $0.id == "terminal:missing" }) + XCTAssertEqual(failed.outcome, "failed") + XCTAssertEqual(failed.trigger, "terminal") + XCTAssertFalse(failed.incomplete) + XCTAssertEqual(failed.applicationKey, "io.appmakes.otty") + XCTAssertEqual(analysis.groups.first { $0.id == "terminal:posted" }?.outcome, "dispatched") + let evidence = AIDiagnosticEvidence(jsonLines: lines.joined(separator: "\n"), + now: try XCTUnwrap(ISO8601DateFormatter().date(from: "2026-09-07T15:00:00Z"))) + XCTAssertEqual(evidence.failures.count, 2) + let otty = try XCTUnwrap(evidence.failures.first { $0.application == "Otty" }) + XCTAssertEqual(otty.events.map(\.event), ["terminal_shortcut_detected", "terminal_shortcut_route_failed"]) + XCTAssertEqual(otty.events.first?.fields["detectionMethod"], "focused_title") + XCTAssertEqual(otty.events.first?.fields["program"], "claude") + XCTAssertEqual(otty.events.last?.fields["editorInstalled"], "false") + let exported = try evidence.jsonText() + for secret in ["private document", "private command", "attempt", "pid"] { XCTAssertFalse(exported.contains(secret)) } + } + + func testBridgeFailurePreservesTerminalEvidenceForAI() throws { + let lines = try [ + line("invocation_started", ["invocationID": "bridge", "app": "Otty", "terminalMatch": "known_bundle_id", + "trigger": "terminal", "program": "claude", "method": "terminal_bridge", "detectionMethod": "focused_title"]), + line("invocation_failed", ["invocationID": "bridge", "error": "network"]) + ] + let evidence = AIDiagnosticEvidence(jsonLines: lines.joined(separator: "\n"), + now: try XCTUnwrap(ISO8601DateFormatter().date(from: "2026-09-07T15:00:00Z"))) + XCTAssertEqual(evidence.failures.first?.events.first?.fields["method"], "terminal_bridge") + XCTAssertEqual(evidence.failures.first?.events.first?.fields["program"], "claude") + } + func testAIDiagnosticEvidenceIncludesAllRecentFailuresAndTheirFullTimelines() throws { let lines = try [ line("invocation_started", ["invocationID": "a", "app": "Editor", "bundleID": "com.example.editor"], timestamp: "2026-09-07T14:29:30.000Z"), diff --git a/Tests/SayoCoreTests/SettingsLanguageTests.swift b/Tests/SayoCoreTests/SettingsLanguageTests.swift index 3b6a5ea..77c33ed 100644 --- a/Tests/SayoCoreTests/SettingsLanguageTests.swift +++ b/Tests/SayoCoreTests/SettingsLanguageTests.swift @@ -200,6 +200,17 @@ final class SettingsLanguageTests: XCTestCase { XCTAssertEqual(decoded.llm.model, "example-model") } + func testInputAnimationPreferenceRoundTripsAndPreservesExistingDefault() throws { + XCTAssertTrue(AppSettings().inputAnimationEnabled) + XCTAssertTrue(try JSONDecoder().decode(AppSettings.self, from: Data("{}".utf8)).inputAnimationEnabled) + for enabled in [false, true] { + var settings = AppSettings() + settings.inputAnimationEnabled = enabled + let decoded = try JSONDecoder().decode(AppSettings.self, from: JSONEncoder().encode(settings)) + XCTAssertEqual(decoded.inputAnimationEnabled, enabled) + } + } + func testVersionTwoModelSelectionMigratesToAProfileIdentifier() throws { let data = Data(#"{"schemaVersion":2,"llm":{"provider":"deepSeek","baseURL":"https://api.deepseek.com/v1","model":"deepseek-chat"}}"#.utf8) diff --git a/Tests/SayoPlatformTests/PasteboardLeaseTests.swift b/Tests/SayoPlatformTests/PasteboardLeaseTests.swift index fb20056..71ddac6 100644 --- a/Tests/SayoPlatformTests/PasteboardLeaseTests.swift +++ b/Tests/SayoPlatformTests/PasteboardLeaseTests.swift @@ -70,7 +70,7 @@ final class PasteboardLeaseTests: XCTestCase { "value_or_selection_unavailable", "input_not_writable"] { XCTAssertTrue(CopyPasteCompatibilityAdapter.shouldAttemptFallback(after: ["reason": reason])) } - for reason in ["secure_input_skipped", "terminal_or_excluded_app", "sayo_settings", + for reason in ["secure_input_skipped", "terminal_or_excluded_app", "terminal_detected", "excluded_app", "sayo_settings", "permission_required", "value_preserved"] { XCTAssertFalse(CopyPasteCompatibilityAdapter.shouldAttemptFallback(after: ["reason": reason])) } diff --git a/Tests/SayoPlatformTests/SettingsPersistenceTests.swift b/Tests/SayoPlatformTests/SettingsPersistenceTests.swift index 6162f8c..e7b1965 100644 --- a/Tests/SayoPlatformTests/SettingsPersistenceTests.swift +++ b/Tests/SayoPlatformTests/SettingsPersistenceTests.swift @@ -36,6 +36,7 @@ import SayoCore settings.copyShortcut = Shortcut(keyCode: 8, command: true) settings.replaceShortcut = nil settings.copyPasteCompatibilityEnabled = true + settings.inputAnimationEnabled = false settings.developerMode = true settings.retainDiagnosticLogs = false settings.launchAtLogin = true diff --git a/Tests/SayoPlatformTests/TerminalDetectorTests.swift b/Tests/SayoPlatformTests/TerminalDetectorTests.swift new file mode 100644 index 0000000..dfa93ee --- /dev/null +++ b/Tests/SayoPlatformTests/TerminalDetectorTests.swift @@ -0,0 +1,13 @@ +import XCTest +@testable import SayoPlatform + +final class TerminalDetectorTests: XCTestCase { + func testOttyUsesTerminalRouting() { + XCTAssertTrue(TerminalDetector.isTerminal("io.appmakes.otty")) + } + + func testOrdinaryEditorsDoNotUseTerminalRouting() { + XCTAssertFalse(TerminalDetector.isTerminal("com.apple.TextEdit")) + XCTAssertFalse(TerminalDetector.isTerminal(nil)) + } +} diff --git a/Tests/SayoPlatformTests/TerminalForegroundProcessDetectorTests.swift b/Tests/SayoPlatformTests/TerminalForegroundProcessDetectorTests.swift index eab0e0f..32f93b0 100644 --- a/Tests/SayoPlatformTests/TerminalForegroundProcessDetectorTests.swift +++ b/Tests/SayoPlatformTests/TerminalForegroundProcessDetectorTests.swift @@ -3,6 +3,29 @@ import SayoCore @testable import SayoPlatform final class TerminalForegroundProcessDetectorTests: XCTestCase { + func testDiagnosticEvidenceExplainsTitleTTYAndAmbiguousRoutesWithoutText() { + let records = TerminalForegroundProcessDetector.parseProcessSnapshot(""" + 100 1 100 100 ?? Otty /Applications/Otty.app/Contents/MacOS/Otty + 101 100 101 201 ttys000 zsh -zsh + 201 101 201 201 ttys000 claude /usr/local/bin/claude private-argument + 102 100 102 301 ttys001 zsh -zsh + 301 102 301 301 ttys001 codex /usr/local/bin/codex + """) + let titled = TerminalForegroundProcessDetector.detectWithDiagnostics(records: records, terminalPID: 100, + focusedTTY: nil, focusedText: "private text", focusedTitle: "Claude Code private-title") + XCTAssertEqual(titled.route, .cli(.init(program: .claude, tty: "ttys000"))) + XCTAssertEqual(titled.fields["detectionMethod"], "focused_title") + XCTAssertEqual(titled.fields["program"], "claude") + XCTAssertEqual(titled.fields["candidateCount"], "2") + XCTAssertEqual(titled.fields["sessionCount"], "2") + XCTAssertFalse(titled.fields.values.contains { $0.contains("private") }) + let tty = TerminalForegroundProcessDetector.detectWithDiagnostics(records: records, terminalPID: 100, focusedTTY: "ttys001") + XCTAssertEqual(tty.fields["detectionMethod"], "focused_tty") + XCTAssertEqual(tty.fields["program"], "codex") + let ambiguous = TerminalForegroundProcessDetector.detectWithDiagnostics(records: records, terminalPID: 100, focusedTTY: nil) + XCTAssertEqual(ambiguous.route, .unknown) + XCTAssertEqual(ambiguous.fields["detectionMethod"], "ambiguous_sessions") + } func testRoutesFocusedGhosttyTTYToCodexWhileClaudeRunsInAnotherTab() { let records = TerminalForegroundProcessDetector.parseProcessSnapshot(""" 100 1 100 100 ?? Ghostty /Applications/Ghostty.app/Contents/MacOS/ghostty diff --git a/updates/otty-cli-editor-routing-20261003.json b/updates/otty-cli-editor-routing-20261003.json new file mode 100644 index 0000000..59400ea --- /dev/null +++ b/updates/otty-cli-editor-routing-20261003.json @@ -0,0 +1,5 @@ +{ + "bump": "patch", + "en": ["Recognize Otty as a terminal so Sayo shortcuts open the active CLI's external editor instead of replacing terminal screen text."], + "zh-CN": ["识别 Otty 终端,让 Sayo 快捷键调用当前 CLI 的外部编辑器,避免按普通输入框处理终端屏幕文本。"] +} diff --git a/updates/restore-input-animation-setting-20261003.json b/updates/restore-input-animation-setting-20261003.json new file mode 100644 index 0000000..dfd35e1 --- /dev/null +++ b/updates/restore-input-animation-setting-20261003.json @@ -0,0 +1,5 @@ +{ + "bump": "patch", + "en": ["Restore the character-by-character replacement switch in Rewriting settings, preserving the current enabled default and allowing instant replacement when turned off."], + "zh-CN": ["在改写设置中恢复逐字替换动画开关,保留当前默认启用行为,关闭后立即回填替换结果。"] +} diff --git a/updates/terminal-routing-diagnostics-20261003.json b/updates/terminal-routing-diagnostics-20261003.json new file mode 100644 index 0000000..cdcbc4d --- /dev/null +++ b/updates/terminal-routing-diagnostics-20261003.json @@ -0,0 +1,5 @@ +{ + "bump": "patch", + "en": ["Explain terminal recognition and Shell/CLI routing in application logs, including detection evidence, integration status and dispatched shortcuts; include terminal routing failures in AI self-diagnosis."], + "zh-CN": ["应用日志说明终端识别与 Shell/CLI 路由依据,记录集成状态和转发快捷键,并将终端路由失败纳入 AI 自诊断。"] +}