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

+55
View File
@@ -0,0 +1,55 @@
import SprachmittlerCore
import SwiftUI
/// A searchable language list used by the panel and Settings.
struct LanguagePickerView: View {
@Binding var selection: ModelLanguage
var recent: [ModelLanguage] = []
@Environment(\.dismiss) private var dismiss
@State private var query = ""
var body: some View {
VStack(alignment: .leading, spacing: 8) {
TextField(String(localized: "Search languages"), text: $query)
.textFieldStyle(.roundedBorder)
.accessibilityLabel(String(localized: "Search languages"))
ScrollView {
LazyVStack(alignment: .leading, spacing: 2) {
ForEach(filtered) { language in
Button {
selection = language
dismiss()
} label: {
HStack {
Text(language.localizedDisplayName)
Spacer()
if language.code == selection.code {
Image(systemName: "checkmark")
}
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.padding(.vertical, 4)
.padding(.horizontal, 6)
}
}
}
}
.padding(12)
.frame(width: 320, height: 380)
}
private var filtered: [ModelLanguage] {
let all = LanguageCatalogue.all.sorted {
$0.localizedDisplayName.localizedCaseInsensitiveCompare($1.localizedDisplayName) == .orderedAscending
}
guard !query.trimmingCharacters(in: .whitespaces).isEmpty else { return all }
return all.filter {
$0.localizedDisplayName.localizedCaseInsensitiveContains(query)
|| $0.modelName.localizedCaseInsensitiveContains(query)
|| $0.code.localizedCaseInsensitiveContains(query)
}
}
}
+75
View File
@@ -0,0 +1,75 @@
import AppKit
import SprachmittlerCore
import SwiftUI
/// The non-activating floating panel. It never activates the app or steals focus.
@MainActor
final class PanelController: NSObject, NSWindowDelegate {
private let panel: NSPanel
private let viewModel: PanelViewModel
/// Creates the panel and its SwiftUI content.
init(viewModel: PanelViewModel) {
self.viewModel = viewModel
panel = NSPanel(
contentRect: NSRect(x: 0, y: 0, width: 540, height: 520),
styleMask: [.titled, .fullSizeContentView, .nonactivatingPanel],
backing: .buffered,
defer: false
)
super.init()
panel.delegate = self
panel.isFloatingPanel = true
panel.becomesKeyOnlyIfNeeded = true
panel.level = .floating
panel.hidesOnDeactivate = false
panel.isMovableByWindowBackground = true
panel.isReleasedWhenClosed = false
panel.titleVisibility = .hidden
panel.titlebarAppearsTransparent = true
panel.backgroundColor = .clear
panel.isOpaque = false
panel.hasShadow = true
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
panel.standardWindowButton(.closeButton)?.isHidden = true
panel.standardWindowButton(.miniaturizeButton)?.isHidden = true
panel.standardWindowButton(.zoomButton)?.isHidden = true
panel.contentView = NSHostingView(
rootView: PanelView(
model: viewModel,
onClose: { [weak self] in self?.close() }
)
)
panel.setContentSize(NSSize(width: 540, height: 520))
}
/// Shows the panel near the mouse without activating the app.
func show() {
positionNearMouse()
panel.orderFrontRegardless()
}
/// Hides the panel and cancels/releases its content.
func close() {
panel.orderOut(nil)
Task { await viewModel.close() }
}
func windowWillClose(_ notification: Notification) {
Task { await viewModel.close() }
}
private func positionNearMouse() {
let mouse = NSEvent.mouseLocation
let screen = NSScreen.screens.first { $0.frame.contains(mouse) } ?? NSScreen.main
guard let visible = screen?.visibleFrame else {
panel.setFrameOrigin(mouse)
return
}
let size = panel.frame.size
var origin = NSPoint(x: mouse.x - size.width / 2, y: mouse.y + 16)
origin.x = max(visible.minX + 12, min(origin.x, visible.maxX - size.width - 12))
origin.y = max(visible.minY + 12, min(origin.y, visible.maxY - size.height - 12))
panel.setFrameOrigin(origin)
}
}
+300
View File
@@ -0,0 +1,300 @@
import AppKit
import SprachmittlerCore
import SwiftUI
/// The translation panel view. It never activates the app.
struct PanelView: View {
@Bindable var model: PanelViewModel
let onClose: @MainActor () -> Void
@Environment(\.openSettings) private var openSettings
@State private var showLanguagePicker = false
@State private var showSource = true
var body: some View {
VStack(alignment: .leading, spacing: 10) {
header
if showSource, let source = model.source {
sourcePreview(source)
}
translationArea
warningArea
errorArea
footer
}
.padding(16)
.frame(width: 540)
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 14, style: .continuous))
.clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: 14, style: .continuous)
.strokeBorder(.separator, lineWidth: 1)
)
.onAppear { showSource = model.configuration.showSourcePreview }
.onChange(of: model.configuration.showSourcePreview) { _, newValue in
showSource = newValue
}
.onExitCommand(perform: onClose)
.accessibilityElement(children: .contain)
.accessibilityLabel(String(localized: "Translation panel"))
}
private var header: some View {
HStack(spacing: 10) {
Image(systemName: "character.bubble")
.font(.title2)
.foregroundStyle(.tint)
.accessibilityHidden(true)
VStack(alignment: .leading, spacing: 1) {
Text(String(localized: "Translate"))
.font(.headline)
Text("\(sourceLanguageLabel) → \(model.configuration.target.localizedDisplayName)")
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
Button {
showLanguagePicker.toggle()
} label: {
Label(model.configuration.target.localizedDisplayName, systemImage: "globe")
.labelStyle(.titleAndIcon)
}
.accessibilityLabel(String(localized: "Target language"))
.popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) {
LanguagePickerView(
selection: Binding(
get: { model.configuration.target },
set: { language in
Task { await model.setTarget(language) }
}
),
recent: model.configuration.recentTargets
)
}
Button {
openSettings()
} label: {
Image(systemName: "gearshape")
}
.accessibilityLabel(String(localized: "Settings"))
}
}
private var sourceLanguageLabel: String {
guard let code = model.sourceLanguage, let language = LanguageCatalogue.resolve(code) else {
return String(localized: "Detected language")
}
return language.localizedDisplayName
}
private func sourcePreview(_ source: CapturedText) -> some View {
DisclosureGroup(isExpanded: $showSource) {
ScrollView {
Text(source.text)
.font(.callout)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(maxHeight: 100)
} label: {
Text(String(localized: "Source"))
.font(.caption.weight(.semibold))
.foregroundStyle(.secondary)
}
.accessibilityLabel(String(localized: "Source text"))
}
private var translationArea: some View {
ScrollView {
Text(translationText)
.font(.body)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.foregroundStyle(model.translation.isEmpty ? .secondary : .primary)
.environment(
\.layoutDirection,
model.configuration.target.isRTL ? .rightToLeft : .leftToRight
)
.accessibilityLabel(String(localized: "Translation"))
}
.frame(minHeight: 120, maxHeight: 260)
.padding(10)
.background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8))
.overlay(alignment: .topTrailing) {
if model.phase == .translating || model.phase == .streaming {
ProgressView()
.controlSize(.small)
.padding(8)
.accessibilityLabel(String(localized: "Translating"))
}
}
}
private var translationText: String {
if !model.translation.isEmpty {
return model.translation
}
switch model.phase {
case .translating, .streaming:
return String(localized: "Translating…")
case .failed:
return String(localized: "No translation.")
case .idle, .ready:
return String(localized: "No translation yet.")
}
}
@ViewBuilder private var warningArea: some View {
if model.sameLanguageWarning != nil {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "info.circle.fill").foregroundStyle(.blue)
Text("This text already appears to be in \(model.configuration.target.localizedDisplayName).")
.font(.callout)
Spacer()
Button(String(localized: "Translate anyway")) {
model.dismissSameLanguageWarning()
}
.controlSize(.small)
}
.padding(8)
.background(.blue.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
}
ForEach(Array(visibleWarnings.enumerated()), id: \.offset) { _, warning in
HStack(alignment: .top, spacing: 8) {
Image(systemName: warning.isBlocking ? "exclamationmark.triangle.fill" : "exclamationmark.circle")
.foregroundStyle(warning.isBlocking ? .orange : .secondary)
Text(warning.panelMessage)
.font(.callout)
Spacer()
}
.padding(8)
.background(
(warning.isBlocking ? Color.orange : Color.secondary)
.opacity(0.08),
in: RoundedRectangle(cornerRadius: 8)
)
.accessibilityLabel(warning.panelMessage)
}
}
private var visibleWarnings: [TranslationWarning] {
model.warnings.filter { warning in
if case .sameLanguage = warning {
return false
}
return true
}
}
@ViewBuilder private var errorArea: some View {
if let message = model.errorMessage, model.phase == .failed {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "exclamationmark.octagon.fill")
.foregroundStyle(.red)
VStack(alignment: .leading, spacing: 6) {
Text(message)
.font(.callout)
if let action = model.recoveryAction {
recoveryButton(action)
}
}
Spacer()
}
.padding(8)
.background(.red.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
.accessibilityLabel(message)
}
}
@ViewBuilder private func recoveryButton(_ action: RecoveryAction) -> some View {
switch action {
case .startOllama:
if let url = URL(string: "https://ollama.com/download") {
Link(String(localized: "Download Ollama"), destination: url)
.controlSize(.small)
}
case let .pullModel(modelName):
Button(String(localized: "Copy pull command")) {
model.copy("ollama pull \(modelName)")
}
.controlSize(.small)
case .openSettings:
if model.error == .accessibilityNotTrusted, let url = accessibilitySettingsURL {
Button(String(localized: "Open Accessibility Settings")) {
NSWorkspace.shared.open(url)
}
.controlSize(.small)
} else {
Button(String(localized: "Open Settings")) {
openSettings()
}
.controlSize(.small)
}
case .copyInstead:
Button(String(localized: "Copy instead")) {
model.copyTranslation()
}
.controlSize(.small)
case .shortenText:
EmptyView()
case .retry:
Button(String(localized: "Retry")) {
Task { await model.retry() }
}
.controlSize(.small)
case .none:
EmptyView()
}
}
private var accessibilitySettingsURL: URL? {
URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
}
private var footer: some View {
HStack(spacing: 10) {
Button {
model.copyTranslation()
} label: {
Label(
model.didCopy ? String(localized: "Copied") : String(localized: "Copy"),
systemImage: "doc.on.doc"
)
}
.keyboardShortcut("c", modifiers: .command)
.disabled(!model.canCopy)
.accessibilityLabel(String(localized: "Copy translation"))
Button {
Task { await model.retry() }
} label: {
Label(String(localized: "Retry"), systemImage: "arrow.clockwise")
}
.keyboardShortcut("r", modifiers: .command)
.disabled(model.source == nil)
.accessibilityLabel(String(localized: "Retry translation"))
Spacer()
Button {
onClose()
} label: {
Text(String(localized: "Close"))
}
.keyboardShortcut(.cancelAction)
.accessibilityLabel(String(localized: "Close panel"))
Button {
Task { await model.replaceSelection() }
} label: {
Text(String(localized: "Replace"))
}
.keyboardShortcut(.return, modifiers: .command)
.buttonStyle(.borderedProminent)
.disabled(!model.canReplace)
.help(model.replaceUnavailableReason ?? String(localized: "Replace the selection"))
.accessibilityLabel(String(localized: "Replace selection"))
}
}
}