feat(m4-m6): session, panel, Replace, settings and onboarding

M4: TranslationSession actor with epochs/one-in-flight streaming, PanelViewModel, non-activating NSPanel, streaming panel UI, searchable/recent target languages, warnings/errors and Copy/Retry/Replace actions.

M5: InsertionCoordinator with target capture, AX direct replacement, secure-field/own-PID refusal, frontmost and selected-text verification, snapshot/⌘V/restore fallback, cancellation-safe restore and blocking-warning gate.

M6: versioned AppSettings/SettingsStore, onboarding for Ollama/model/target/Accessibility, General/Model/Translation/Privacy/Diagnostics settings, launch-at-login via SMAppService, status menu (target, copy/replace last, setup, diagnostics, about), text-free diagnostics and first-run setup.

Docs: PROGRESS M4–M6, ARCHITECTURE §10–§12, ADR-019/020, SELECTION_AND_CLIPBOARD and TESTING. Manual 10-app matrices, real AX/paste delivery, VoiceOver and focus checks remain open.

Verified: make verify green (format, strict lint, scripts, privacy, Debug+Release signatures, 217 package tests); app launches and a two-copy clipboard smoke test opens the panel.
This commit is contained in:
schihei committed 2026-11-26 14:03:16 +01:00
1 parent 64078e2f04
commit a78572adc3
47 files changed
+4963 -79

No files matched your search

@@ -0,0 +1,99 @@
import ApplicationServices
import CoreGraphics
import Foundation
/// The Accessibility operations Replace needs, behind a seam for tests.
public protocol AccessibilityTextEditing: Sendable {
/// Whether the app is trusted for Accessibility.
func isTrusted() async -> Bool
/// The focused element's selected text, or nil when unsupported.
func selectedText(pid: pid_t) async -> String?
/// True for a secure/password field.
func isSecureField(pid: pid_t) async -> Bool
/// Sets the focused selection. Returns false when the app does not accept it.
func setSelectedText(pid: pid_t, to text: String) async -> Bool
}
/// Posts the synthetic paste. Tests replace it with a fake.
public protocol EventPosting: Sendable {
/// Posts ⌘V to a PID. Returns false when events cannot be created.
func postPaste(to pid: pid_t) -> Bool
}
/// The production Accessibility editor. AX calls run on this actor, never on the main actor.
public actor AXTextEditor: AccessibilityTextEditing {
/// Creates the editor.
public init() {}
public func isTrusted() -> Bool {
AXIsProcessTrusted()
}
public func selectedText(pid: pid_t) -> String? {
guard let focused = focusedElement(pid: pid) else { return nil }
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(
focused,
kAXSelectedTextAttribute as CFString,
&value
) == .success else {
return nil
}
return value as? String
}
public func isSecureField(pid: pid_t) -> Bool {
guard let focused = focusedElement(pid: pid) else { return false }
if attribute(focused, kAXSubroleAttribute) == "AXSecureTextField" {
return true
}
return attribute(focused, kAXRoleAttribute) == "AXSecureTextField"
}
private func attribute(_ element: AXUIElement, _ name: String) -> String? {
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success else {
return nil
}
return value as? String
}
public func setSelectedText(pid: pid_t, to text: String) async -> Bool {
guard let focused = focusedElement(pid: pid) else { return false }
return AXUIElementSetAttributeValue(
focused,
kAXSelectedTextAttribute as CFString,
text as CFTypeRef
) == .success
}
private func focusedElement(pid: pid_t) -> AXUIElement? {
let application = AXUIElementCreateApplication(pid)
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(
application,
kAXFocusedUIElementAttribute as CFString,
&value
) == .success, let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil }
return unsafeDowncast(value, to: AXUIElement.self)
}
}
/// The production ⌘V poster.
public struct CGEventPoster: EventPosting {
/// Creates a poster.
public init() {}
public func postPaste(to pid: pid_t) -> Bool {
guard let keyDown = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: true),
let keyUp = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: false)
else {
return false
}
keyDown.flags = .maskCommand
keyUp.flags = .maskCommand
keyDown.postToPid(pid)
keyUp.postToPid(pid)
return true
}
}
@@ -0,0 +1,27 @@
import AppKit
import ApplicationServices
import SprachmittlerCore
/// The production Accessibility permission gate. It is never called on the capture path.
@MainActor
public final class AccessibilityPermission: AccessibilityPermissionChecking {
/// Creates the gate.
public init() {}
public var isTrusted: Bool {
AXIsProcessTrusted()
}
public func requestTrust() {
// Use the public option key literal: the ApplicationServices global is not
// concurrency-safe under Swift 6, and this is the same documented key.
let options = ["AXTrustedCheckOptionPrompt": true] as CFDictionary
_ = AXIsProcessTrustedWithOptions(options)
}
public func openSettings() {
let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
?? URL(fileURLWithPath: "/System/Applications/System Settings.app")
NSWorkspace.shared.open(url)
}
}
@@ -0,0 +1,20 @@
import AppKit
import Foundation
import SprachmittlerCore
/// Captures the frontmost app at trigger time. It never reads a full document value.
@MainActor
public final class FrontmostTargetProvider: InsertionTargetProviding {
/// Creates a provider.
public init() {}
public func captureTarget() -> InsertionTarget? {
guard let application = NSWorkspace.shared.frontmostApplication else { return nil }
return InsertionTarget(
pid: application.processIdentifier,
bundleID: application.bundleIdentifier,
selectedText: nil,
capturedAt: Date()
)
}
}
@@ -0,0 +1,110 @@
import Darwin
import Foundation
import SprachmittlerCore
/// Replaces the selection with Accessibility first and a clipboard paste as fallback.
public actor InsertionCoordinator: TextInserting {
private let pasteboard: any PasteboardAccessing
private let accessibility: any AccessibilityTextEditing
private let poster: any EventPosting
private let delay: @Sendable (Duration) async throws -> Void
private let ownWrite: @MainActor @Sendable () -> Void
private let frontmostPID: @MainActor @Sendable () -> pid_t
/// Creates the coordinator.
public init(
pasteboard: any PasteboardAccessing,
accessibility: any AccessibilityTextEditing,
poster: any EventPosting = CGEventPoster(),
delay: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) },
ownWrite: @escaping @MainActor @Sendable () -> Void,
frontmostPID: @escaping @MainActor @Sendable () -> pid_t
) {
self.pasteboard = pasteboard
self.accessibility = accessibility
self.poster = poster
self.delay = delay
self.ownWrite = ownWrite
self.frontmostPID = frontmostPID
}
public func replace(
selection: CapturedText,
with translation: String,
target: InsertionTarget
) async throws -> InsertionOutcome {
guard target.pid != getpid() else {
throw SprachmittlerError.insertionTargetChanged
}
let pid = await frontmostPID()
try InsertionPolicy.verify(
frontmostPID: pid,
target: target,
selectedText: nil,
source: selection.text
)
guard await accessibility.isTrusted() else {
throw SprachmittlerError.accessibilityNotTrusted
}
if await accessibility.isSecureField(pid: target.pid) {
throw SprachmittlerError.accessibilityUnsupported(app: target.bundleID)
}
if let selected = await accessibility.selectedText(pid: target.pid) {
try InsertionPolicy.verify(
frontmostPID: pid,
target: target,
selectedText: selected,
source: selection.text
)
if await accessibility.setSelectedText(pid: target.pid, to: translation) {
return .replaced(using: .accessibility)
}
}
return try await pasteFallback(selection: selection, translation: translation, target: target, pid: pid)
}
private func pasteFallback(
selection: CapturedText,
translation: String,
target: InsertionTarget,
pid: pid_t
) async throws -> InsertionOutcome {
// Re-check the selection after a failed AX set before mutating the clipboard.
if let selected = await accessibility.selectedText(pid: target.pid) {
try InsertionPolicy.verify(
frontmostPID: pid,
target: target,
selectedText: selected,
source: selection.text
)
}
guard let snapshot = await pasteboard.snapshot() else {
throw SprachmittlerError.pasteboardUnavailable
}
let written = await pasteboard.write(translation)
await ownWrite()
do {
guard poster.postPaste(to: target.pid) else {
throw SprachmittlerError.accessibilityUnsupported(app: target.bundleID)
}
try await delay(.milliseconds(300))
guard await pasteboard.restore(snapshot, onlyIfChangeCountMatches: written) else {
throw SprachmittlerError.pasteboardRestoreFailed
}
} catch {
// SP-9: restore even when the paste or the settle delay is cancelled/fails.
_ = await pasteboard.restore(snapshot, onlyIfChangeCountMatches: written)
throw error
}
return .replaced(using: .paste)
}
/// Whether Accessibility is currently available; the panel uses this for hints.
public func isAccessibilityTrusted() async -> Bool {
await accessibility.isTrusted()
}
}
@@ -3,7 +3,7 @@ import Foundation
/// The pasteboard operations `SprachmittlerCapture` needs. Tests use a fake; the app uses
/// `SystemPasteboard`. Every member is main-actor isolated because `NSPasteboard` is.
@MainActor
public protocol PasteboardAccessing: AnyObject {
public protocol PasteboardAccessing: AnyObject, Sendable {
/// The current pasteboard change count.
var changeCount: Int { get }