Compare commits

...
9 Commits
Author SHA1 Message Date
schihei 2a601058f4 feat(capture): translate long selections in parts
The capture gate and the chunk size were the same number, so a selection above one chunk was rejected before the pipeline could split it; the Settings sliders moved both thresholds together. Add maximumPartsPerSelection (1-8, default 1, so existing behaviour is unchanged). The capture limit is now part size x parts and travels on TranslationSessionRequest, so the watcher, CapturePolicy and TranslationSession agree for that capture. TranslationStreaming gained an optional per-part callback; the session emits chunkStarted and the panel shows 'Part 2 of 4' while streaming and '2 parts' when finished. textTooLong now points at Settings and offers an Open Settings button. Lower the dense-script part-size maximum to 4000 because 5000 dense characters plus a 4096-token output can overflow the 8192-token context. Tests cover capture limits, watcher limits, pipeline part callbacks, session events and limits, panel progress, settings clamping and migration. Docs updated: ADR-011, TRANSLATION_OUTPUT, SELECTION_AND_CLIPBOARD, ARCHITECTURE, LANGUAGES and README. Verified: make verify green; live 4355-character German text showed Part 1 of 2, Part 2 of 2 and '2 parts'; with one part the panel showed the too-long message and Open Settings.
2026-11-27 20:21:30 +01:00
schihei 9f89000b0d fix(panel): keep the picked language when overriding the target
The header language picker set the effective target and then re-ran prepare, where TranslationDirectionPolicy only knew a Bool override and returned the mother tongue. Any picked language other than the mother tongue was discarded, so the panel appeared not to change. The policy now takes the override target itself, and PanelViewModel stores it, so a picker choice wins over a rule for that capture; a new capture returns to the rule/mother tongue. Move the shared panel test scaffolding into PanelTestSupport and the routing tests into PanelRoutingTests, and add picker and rule-override tests. Verified: make verify green; live checks with a German -> English rule show the picker switching to French, the next capture back to English with the banner, and the banner override to German.
2026-11-27 10:38:16 +01:00
schihei bd8e3db82d fix(settings): retranslate when language rules change
When Settings saves a changed languageRoutes table, retranslate an open panel so the new rule is visible immediately. Verified with make verify.
2026-11-26 18:32:40 +01:00
schihei 940abcc996 feat(settings): mother-tongue language routing table
Replace the single reverse-direction pair with a general routing table. The saved target is the mother tongue and the default target for every source; languageRoutes is an empty-by-default, source-unique list of source-to-target rules (for example Chinese -> English, Traditional Chinese -> English, German -> English). Rules apply only when the source is confidently detected; otherwise the mother tongue is used. Same-language rules are dropped.\n\nThe panel shows the effective direction and a banner explaining a rule, with a one-capture override back to the mother tongue; the panel picker is now a session-only override. Persistent rules are edited in Settings. The old autoSwitchTarget/fallbackTargetLanguage keys are ignored, so the default after migration is everything -> mother tongue.\n\nAdd LanguageRoute, generalize the direction policy and tests, add the rules UI, and update ADR-022, architecture, translation output, user guide, README and progress. Verified: make verify green; empty rules translate French -> German, a Chinese -> English rule produces Chinese (Simplified) -> English with the banner, and the rules table renders in Settings.
2026-11-26 18:31:45 +01:00
schihei 41f1cea769 feat(panel): optional reverse direction for target-language text
Add opt-in automatic reverse translation for a two-language pair. autoSwitchTarget defaults on with fallbackTargetLanguage English (or German when the target is English); the saved target and the effective request target are separate. Confident source-equals-target text uses the fallback, the header and a panel banner show the effective direction, and the banner can override the direction for one capture without changing the saved target. The language picker still changes the saved target, and changing the target to the fallback swaps the pair. JSON/HTML/code handling is unchanged.\n\nFilter near-zero NLLanguageRecognizer hypotheses so the existing high-confidence same-language rule works for real text. Add resolver, settings, view-model, detector and persistence tests; document ADR-022, the panel, settings and user guide. Verified: make verify green; German text with target German/fallback English renders German → English with the banner, English text stays English → German, a real click on the override shows German → German, and a new German capture switches back to English.
2026-11-26 17:34:11 +01:00
schihei 7c9cece201 docs(readme): present the app instead of the starter kit
Rewrite README.md around the shipped menu-bar app: features, requirements, install from source, usage (Esc, click-outside, Markdown, Replace), privacy, architecture, status and a compact development section. Remove the starter-kit framing, placeholder/stub claims and the kit verification section; update the ADR/module counts and document the transient outside-click monitor.
2026-11-26 17:19:13 +01:00
schihei 39ec191348 feat(panel): dismiss when clicking outside
Close the panel when a mouse-down is sent to another app. The panel observes didResignKey for clicks that make another window key, and installs a transient global mouse-down monitor while visible for clicks outside an open popover or when the panel was not made key. Global monitors ignore events sent to this app, so clicks in the panel and its popover are unaffected; the event is discarded and the monitor is removed on close. Add the dialog guards for recursive close and document the monitor in ADR-009, the architecture, the privacy table and the user guide.\n\nVerified: make verify green; inside clicks keep the panel open; outside clicks close it with closeWithEscape on and off; an outside click while the language popover is open closes both. Replace still works.
2026-11-26 15:34:56 +01:00
schihei a3e544fbe4 feat(panel): close with Esc without a click and render Markdown
Esc: make the panel key when shown (closeWithEscape, default on) without activating the app; the source app stays frontmost and Replace still targets it. Handle Esc with SwiftUI's exit command, which also works from the popover and after clicking controls. Add TranslationPanel.canBecomeKey and amend ADR-009.\n\nMarkdown: add MarkdownPresentation in SprachmittlerText (Foundation inline parser plus a conservative block parser for headings, lists, quotes, fenced code and rules), a SwiftUI MarkdownTranslationView, and a renderMarkdown setting (default on). JSON, HTML and code sources are never rendered; only http/https links open; images become alt text; Copy and Replace keep the raw Markdown (ADR-021).\n\nVerified: make verify green; synthetic Esc closes the panel and closes an open language popover first; a live Markdown translation rendered heading, bold/italic, inline code, list, quote, code block and link; Copy returned the raw Markdown; Replace still changed the TextEdit selection with the panel key.
2026-11-26 15:26:30 +01:00
schihei d126124f97 fix(panel): drag the window manually and make the whole header a drag bar
performDrag did nothing while the app was inactive (verified: mouseDown reached the drag view, performDrag returned, the frame never changed). Move the window from the screen-space mouse delta in mouseDown/mouseDragged instead.

Make the header a full-width 56 pt bar flush with the panel top, with the drag view behind it and the language/gear buttons above, so the whole top area moves the panel.

Verified: make verify green; synthetic drags from the title, top edge, empty header and grip moved the panel by the full delta while Finder was frontmost; body drag does not move it.
2026-11-26 15:03:31 +01:00
52 changed files with 2958 additions and 738 deletions

No files matched your search

+15 -6
View File
@@ -88,7 +88,8 @@ final class AppEnvironment {
pasteboard: pasteboard,
configuration: DoubleCopyDetector.Configuration(
window: Double(windowMs) / 1000
)
),
limits: store.current().captureLimits
)
let factoryStore = store
@@ -215,20 +216,27 @@ final class AppEnvironment {
sampling: settings.samplingOptions,
showSourcePreview: settings.showSourcePreview,
translationFontSize: settings.translationFontSize,
recentTargets: settings.recentTargets
renderMarkdown: settings.renderMarkdown,
closeWithEscape: settings.closeWithEscape,
languageRoutes: settings.languageRoutes,
recentTargets: settings.recentTargets,
captureLimits: settings.captureLimits
)
}
private func applySettings() {
let settings = settingsStore.current()
let previousTarget = panelViewModel.configuration.target.code
let previousRoutes = panelViewModel.configuration.languageRoutes
panelViewModel.updateConfiguration(configuration(for: settings))
watcher.limits = settings.captureLimits
if settings.doubleCopyWindowMs != watcherWindowMs {
watcherWindowMs = settings.doubleCopyWindowMs
restartWatcher()
}
let targetChanged = previousTarget != settings.targetLanguage && panelViewModel.source != nil
if targetChanged {
let routesChanged = previousRoutes != settings.languageRoutes && panelViewModel.source != nil
if targetChanged || routesChanged {
Task { await panelViewModel.retranslate() }
}
onStateChange?()
@@ -245,7 +253,8 @@ final class AppEnvironment {
pasteboard: pasteboard,
configuration: DoubleCopyDetector.Configuration(
window: Double(watcherWindowMs) / 1000
)
),
limits: settingsStore.current().captureLimits
)
if let sink = watcherEventSink {
watcher.start(onEvent: sink)
@@ -274,7 +283,7 @@ final class AppEnvironment {
lastWarnings = []
onStateChange?()
switch CapturePolicy.validate(captured.text) {
switch CapturePolicy.validate(captured.text, limits: settingsStore.current().captureLimits) {
case .valid:
lastCaptureFailure = nil
case .empty:
@@ -399,7 +408,7 @@ extension AppEnvironment {
await diagnostics.record(kind: "error", detail: error.diagnosticCode)
}
onStateChange?()
case .started, .delta, .cancelled:
case .started, .chunkStarted, .delta, .cancelled:
break
}
}
+7 -2
View File
@@ -5,6 +5,7 @@ import SwiftUI
struct LanguagePickerView: View {
@Binding var selection: ModelLanguage
var recent: [ModelLanguage] = []
var excluding: String?
@Environment(\.dismiss) private var dismiss
@State private var query = ""
@@ -45,8 +46,12 @@ struct LanguagePickerView: View {
let all = LanguageCatalogue.all.sorted {
$0.localizedDisplayName.localizedCaseInsensitiveCompare($1.localizedDisplayName) == .orderedAscending
}
guard !query.trimmingCharacters(in: .whitespaces).isEmpty else { return all }
return all.filter {
let available = all.filter { language in
guard let excluding else { return true }
return language.code.caseInsensitiveCompare(excluding) != .orderedSame
}
guard !query.trimmingCharacters(in: .whitespaces).isEmpty else { return available }
return available.filter {
$0.localizedDisplayName.localizedCaseInsensitiveContains(query)
|| $0.modelName.localizedCaseInsensitiveContains(query)
|| $0.code.localizedCaseInsensitiveContains(query)
+136
View File
@@ -0,0 +1,136 @@
import AppKit
import SprachmittlerText
import SwiftUI
/// Renders a translation as formatted Markdown. Copy and Replace still use the raw translation.
struct MarkdownTranslationView: View {
let markdown: String
let fontSize: Int
let isRTL: Bool
private let blocks: [MarkdownBlock]
init(markdown: String, fontSize: Int, isRTL: Bool) {
self.markdown = markdown
self.fontSize = fontSize
self.isRTL = isRTL
blocks = MarkdownPresentation.blocks(in: markdown)
}
var body: some View {
VStack(alignment: .leading, spacing: 8) {
ForEach(blocks.indices, id: \.self) { index in
block(blocks[index])
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.environment(\.layoutDirection, isRTL ? .rightToLeft : .leftToRight)
.environment(\.openURL, OpenURLAction { url in
guard MarkdownPresentation.isAllowedLink(url) else { return .discarded }
NSWorkspace.shared.open(url)
return .handled
})
.accessibilityElement(children: .contain)
.accessibilityLabel(String(localized: "Translation"))
}
private var baseSize: CGFloat {
CGFloat(fontSize)
}
@ViewBuilder private func block(_ block: MarkdownBlock) -> some View {
switch block {
case let .paragraph(text):
inlineText(text, size: baseSize)
case let .heading(level, text):
inlineText(text, size: baseSize * headingScale(level), weight: .bold)
.accessibilityAddTraits(.isHeader)
case let .listItem(ordered, number, indent, text):
HStack(alignment: .firstTextBaseline, spacing: 6) {
Text(ordered ? "\(number)." : "•")
.font(.system(size: baseSize, weight: ordered ? .regular : .bold))
.foregroundStyle(.secondary)
.frame(minWidth: ordered ? 18 : 12, alignment: .trailing)
.accessibilityHidden(true)
inlineText(text, size: baseSize)
}
.padding(.leading, CGFloat(indent) * 14)
case let .quote(text):
HStack(alignment: .top, spacing: 8) {
Rectangle()
.fill(.secondary.opacity(0.35))
.frame(width: 3)
.accessibilityHidden(true)
inlineText(text, size: baseSize)
.foregroundStyle(.secondary)
}
case let .codeBlock(_, text):
ScrollView(.horizontal, showsIndicators: false) {
Text(verbatim: text)
.font(.system(size: baseSize * 0.95, design: .monospaced))
.textSelection(.enabled)
.fixedSize(horizontal: true, vertical: false)
.padding(10)
}
.frame(maxWidth: .infinity, alignment: .leading)
.background(.primary.opacity(0.06), in: RoundedRectangle(cornerRadius: 8))
.environment(\.layoutDirection, .leftToRight)
case .rule:
Divider()
.padding(.vertical, 2)
}
}
private func inlineText(_ text: String, size: CGFloat, weight: Font.Weight = .regular) -> some View {
Text(styled(text, size: size))
.font(.system(size: size, weight: weight))
.textSelection(.enabled)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
}
private func styled(_ text: String, size: CGFloat) -> AttributedString {
var attributed = MarkdownPresentation.inline(text)
let runs = attributed.runs.compactMap { run -> (Range<AttributedString.Index>, InlinePresentationIntent)? in
guard let intent = run.inlinePresentationIntent else { return nil }
let relevant = intent.contains(.stronglyEmphasized)
|| intent.contains(.emphasized)
|| intent.contains(.code)
return relevant ? (run.range, intent) : nil
}
for (range, intent) in runs {
if intent.contains(.code) {
var font = Font.system(size: size * 0.95, design: .monospaced)
if intent.contains(.stronglyEmphasized) {
font = font.bold()
}
if intent.contains(.emphasized) {
font = font.italic()
}
attributed[range].font = font
} else {
var font = Font.system(
size: size,
weight: intent.contains(.stronglyEmphasized) ? .bold : .regular
)
if intent.contains(.emphasized) {
font = font.italic()
}
attributed[range].font = font
}
}
return attributed
}
private func headingScale(_ level: Int) -> CGFloat {
switch level {
case 1: 1.6
case 2: 1.45
case 3: 1.3
case 4: 1.2
case 5: 1.12
default: 1.06
}
}
}
+58 -4
View File
@@ -2,16 +2,19 @@ import AppKit
import SprachmittlerCore
import SwiftUI
/// The non-activating floating panel. It never activates the app or steals focus.
/// The non-activating floating panel. It never activates the app. While visible it can be the key
/// window so Esc and the keyboard shortcuts work without a click.
@MainActor
final class PanelController: NSObject, NSWindowDelegate {
private let panel: NSPanel
private let panel: TranslationPanel
private let viewModel: PanelViewModel
private var isClosing = false
private var outsideClickMonitor: Any?
/// Creates the panel and its SwiftUI content.
init(viewModel: PanelViewModel) {
self.viewModel = viewModel
panel = NSPanel(
panel = TranslationPanel(
contentRect: NSRect(x: 0, y: 0, width: 540, height: 520),
styleMask: [.titled, .fullSizeContentView, .nonactivatingPanel],
backing: .buffered,
@@ -19,9 +22,15 @@ final class PanelController: NSObject, NSWindowDelegate {
)
super.init()
panel.delegate = self
NotificationCenter.default.addObserver(
self,
selector: #selector(panelDidResignKey(_:)),
name: NSWindow.didResignKeyNotification,
object: panel
)
panel.isFloatingPanel = true
panel.isMovable = true
panel.becomesKeyOnlyIfNeeded = true
panel.becomesKeyOnlyIfNeeded = false
panel.level = .floating
panel.hidesOnDeactivate = false
panel.isMovableByWindowBackground = true
@@ -50,15 +59,60 @@ final class PanelController: NSObject, NSWindowDelegate {
positionNearMouse()
}
panel.orderFrontRegardless()
if viewModel.configuration.closeWithEscape {
panel.makeKey()
}
installOutsideClickMonitor()
}
/// Hides the panel and cancels/releases its content.
func close() {
guard !isClosing else { return }
isClosing = true
defer { isClosing = false }
removeOutsideClickMonitor()
panel.orderOut(nil)
Task { await viewModel.close() }
}
/// A click outside the panel makes another window key. Treat that as a dismissal, but not
/// while the language popover (a child window) is open.
@objc private func panelDidResignKey(_ notification: Notification) {
guard panel.isVisible, !isClosing else { return }
if panel.childWindows?.contains(where: \.isVisible) == true {
return
}
close()
}
/// While the panel is visible, a click sent to another app dismisses it. Global monitors do not
/// receive events sent to this app, so clicks in the panel and its popover are ignored. The
/// event itself is never read.
private func installOutsideClickMonitor() {
guard outsideClickMonitor == nil else { return }
outsideClickMonitor = NSEvent.addGlobalMonitorForEvents(
matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]
) { [weak self] _ in
Task { @MainActor [weak self] in
guard let self, panel.isVisible else { return }
close()
}
}
}
private func removeOutsideClickMonitor() {
if let outsideClickMonitor {
NSEvent.removeMonitor(outsideClickMonitor)
self.outsideClickMonitor = nil
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func windowWillClose(_ notification: Notification) {
removeOutsideClickMonitor()
Task { await viewModel.close() }
}
+257
View File
@@ -0,0 +1,257 @@
import AppKit
import SprachmittlerCore
import SprachmittlerText
import SwiftUI
extension PanelView {
private var rendersMarkdown: Bool {
!model.translation.isEmpty
&& model.configuration.renderMarkdown
&& MarkdownPresentation.shouldRender(
source: model.source?.text ?? "",
translation: model.translation
)
}
var translationArea: some View {
ScrollView {
translationContent
.frame(maxWidth: .infinity, alignment: .leading)
}
.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"))
}
}
}
@ViewBuilder var translationContent: some View {
if rendersMarkdown {
MarkdownTranslationView(
markdown: model.translation,
fontSize: model.configuration.translationFontSize,
isRTL: model.effectiveTarget.isRTL
)
} else {
Text(translationText)
.font(.system(size: CGFloat(model.configuration.translationFontSize)))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.foregroundStyle(model.translation.isEmpty ? .secondary : .primary)
.environment(
\.layoutDirection,
model.effectiveTarget.isRTL ? .rightToLeft : .leftToRight
)
.accessibilityLabel(String(localized: "Translation"))
}
}
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.")
}
}
private func routedMessage(from routedSource: ModelLanguage) -> String {
let source = routedSource.localizedDisplayName
let target = model.effectiveTarget.localizedDisplayName
return String(localized: "Detected \(source). Translating to \(target).")
}
@ViewBuilder var warningArea: some View {
if let routedSource = model.routedSource {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "arrow.left.arrow.right.circle.fill")
.foregroundStyle(.blue)
.accessibilityHidden(true)
Text(routedMessage(from: routedSource))
.font(.callout)
Spacer()
Button(String(localized: "Translate to \(model.configuration.target.localizedDisplayName)")) {
Task { await model.overrideTarget(model.configuration.target) }
}
.controlSize(.small)
}
.padding(8)
.background(.blue.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
}
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.effectiveTarget.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)
}
}
var visibleWarnings: [TranslationWarning] {
model.warnings.filter { warning in
if case .sameLanguage = warning {
return false
}
return true
}
}
@ViewBuilder 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 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()
}
}
var accessibilitySettingsURL: URL? {
URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
}
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"))
if let current = model.currentChunk, let total = model.totalChunks, total > 1 {
Text(String(localized: "Part \(current) of \(total)"))
.font(.caption)
.foregroundStyle(.secondary)
.accessibilityLabel(String(localized: "Part \(current) of \(total)"))
} else if model.chunkCount > 1 {
Text(String(localized: "\(model.chunkCount) parts"))
.font(.caption)
.foregroundStyle(.secondary)
.accessibilityLabel(String(localized: "Translated in \(model.chunkCount) parts"))
}
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"))
}
}
}
+51 -236
View File
@@ -1,5 +1,6 @@
import AppKit
import SprachmittlerCore
import SprachmittlerText
import SwiftUI
/// The translation panel view. It never activates the app.
@@ -7,22 +8,26 @@ struct PanelView: View {
@Bindable var model: PanelViewModel
let onClose: @MainActor () -> Void
@Environment(\.openSettings) private var openSettings
@Environment(\.openSettings) var openSettings
@State private var showLanguagePicker = false
@State private var showSource = true
var body: some View {
VStack(alignment: .leading, spacing: 10) {
VStack(alignment: .leading, spacing: 0) {
header
if model.configuration.showSourcePreview, let source = model.source {
sourcePreview(source)
VStack(alignment: .leading, spacing: 10) {
if model.configuration.showSourcePreview, let source = model.source {
sourcePreview(source)
}
translationArea
warningArea
errorArea
footer
}
translationArea
warningArea
errorArea
footer
.padding(.horizontal, 16)
.padding(.top, 10)
.padding(.bottom, 16)
}
.padding(16)
.frame(width: 540)
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 14, style: .continuous))
.clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
@@ -30,6 +35,7 @@ struct PanelView: View {
RoundedRectangle(cornerRadius: 14, style: .continuous)
.strokeBorder(.separator, lineWidth: 1)
)
.ignoresSafeArea(.container, edges: .top)
.onAppear { showSource = model.configuration.showSourcePreview }
.onChange(of: model.configuration.showSourcePreview) { _, newValue in
showSource = newValue
@@ -40,9 +46,10 @@ struct PanelView: View {
}
private var header: some View {
HStack(spacing: 10) {
ZStack(alignment: .leading) {
WindowDragArea()
ZStack {
WindowDragArea()
Color.primary.opacity(0.04).allowsHitTesting(false)
HStack(spacing: 10) {
HStack(spacing: 10) {
Image(systemName: "line.3.horizontal")
.font(.system(size: 12, weight: .semibold))
@@ -55,44 +62,46 @@ struct PanelView: View {
VStack(alignment: .leading, spacing: 1) {
Text(String(localized: "Translate"))
.font(.headline)
Text("\(sourceLanguageLabel) → \(model.configuration.target.localizedDisplayName)")
Text("\(sourceLanguageLabel) → \(model.effectiveTarget.localizedDisplayName)")
.font(.caption)
.foregroundStyle(.secondary)
}
}
.allowsHitTesting(false)
}
.frame(height: 44)
.contentShape(Rectangle())
.help(String(localized: "Drag to move panel"))
.accessibilityLabel(String(localized: "Move panel"))
.accessibilityElement(children: .combine)
.accessibilityLabel(String(localized: "Move panel"))
Spacer()
Button {
showLanguagePicker.toggle()
} label: {
Label(model.configuration.target.localizedDisplayName, systemImage: "globe")
.labelStyle(.titleAndIcon)
Spacer().allowsHitTesting(false)
Button {
showLanguagePicker.toggle()
} label: {
Label(model.effectiveTarget.localizedDisplayName, systemImage: "globe")
.labelStyle(.titleAndIcon)
}
.accessibilityLabel(String(localized: "Target language"))
.popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) {
LanguagePickerView(
selection: Binding(
get: { model.effectiveTarget },
set: { language in
Task { await model.overrideTarget(language) }
}
),
recent: model.configuration.recentTargets
)
}
Button {
openSettings()
} label: {
Image(systemName: "gearshape")
}
.accessibilityLabel(String(localized: "Settings"))
}
.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"))
.padding(.horizontal, 16)
}
.frame(height: 56)
.frame(maxWidth: .infinity)
.help(String(localized: "Drag to move panel"))
}
private var sourceLanguageLabel: String {
@@ -119,198 +128,4 @@ struct PanelView: View {
.help(showSource ? String(localized: "Hide source") : String(localized: "Show source"))
.accessibilityLabel(String(localized: "Source text"))
}
private var translationArea: some View {
ScrollView {
Text(translationText)
.font(.system(size: CGFloat(model.configuration.translationFontSize)))
.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"))
}
}
}
+13
View File
@@ -0,0 +1,13 @@
import AppKit
/// The translation panel. It can become the key window without activating the app, so Esc and the
/// keyboard shortcuts work as soon as it is shown.
final class TranslationPanel: NSPanel {
override var canBecomeKey: Bool {
true
}
override var canBecomeMain: Bool {
false
}
}
+25 -3
View File
@@ -2,7 +2,8 @@ import AppKit
import SwiftUI
/// An AppKit drag surface for the non-activating panel. SwiftUI's hosting view consumes mouse
/// events, so this view starts a native window drag on the first click.
/// events, and `performDrag` is unreliable while the app is inactive, so the view moves the
/// window itself from the screen-space mouse delta.
struct WindowDragArea: NSViewRepresentable {
func makeNSView(context: Context) -> NSView {
DragView()
@@ -12,8 +13,11 @@ struct WindowDragArea: NSViewRepresentable {
}
private final class DragView: NSView {
private var startMouse = NSPoint.zero
private var startOrigin = NSPoint.zero
override var mouseDownCanMoveWindow: Bool {
true
false
}
override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
@@ -21,7 +25,25 @@ private final class DragView: NSView {
}
override func mouseDown(with event: NSEvent) {
window?.performDrag(with: event)
guard let window else { return }
startMouse = NSEvent.mouseLocation
startOrigin = window.frame.origin
NSCursor.closedHand.push()
}
override func mouseDragged(with event: NSEvent) {
guard let window else { return }
let mouse = NSEvent.mouseLocation
window.setFrameOrigin(
NSPoint(
x: startOrigin.x + mouse.x - startMouse.x,
y: startOrigin.y + mouse.y - startMouse.y
)
)
}
override func mouseUp(with event: NSEvent) {
NSCursor.pop()
}
override func resetCursorRects() {
@@ -100,3 +100,18 @@
"Copy report" = "Bericht kopieren";
"Clear" = "Leeren";
"Open Diagnostics…" = "Diagnose öffnen…";
"Render Markdown formatting" = "Markdown-Formatierung anzeigen";
"Render bold, italic, headings, lists, code and links when the source is Markdown." = "Fett, kursiv, Überschriften, Listen, Code und Links anzeigen, wenn die Quelle Markdown ist.";
"Close with Esc without clicking" = "Mit Esc schließen, ohne zu klicken";
"The panel takes keyboard focus while it is visible. The source app stays frontmost." = "Das Panel übernimmt die Tastatureingabe, solange es sichtbar ist. Die Quell-App bleibt im Vordergrund.";
"Detected %@. Translating to %@." = "%@ erkannt. Übersetzung nach %@.";
"Translate to %@" = "Nach %@ übersetzen";
"This text already appears to be in %@ (detected %@)." = "Dieser Text scheint bereits auf %@ zu sein (erkannt: %@).";
"Mother tongue" = "Muttersprache";
"The default target for every language unless a rule matches." = "Das Standardziel für jede Sprache, wenn keine Regel passt.";
"Language rules" = "Sprachregeln";
"Add rule" = "Regel hinzufügen";
"No rules. Every language translates to your mother tongue." = "Keine Regeln. Jede Sprache wird in Ihre Muttersprache übersetzt.";
"Source language" = "Ausgangssprache";
"Remove rule" = "Regel entfernen";
"Rules apply only to confidently detected sources; otherwise the mother tongue is used." = "Regeln gelten nur für sicher erkannte Ausgangssprachen; sonst wird die Muttersprache verwendet.";
@@ -100,3 +100,18 @@
"Copy report" = "Copy report";
"Clear" = "Clear";
"Open Diagnostics…" = "Open Diagnostics…";
"Render Markdown formatting" = "Render Markdown formatting";
"Render bold, italic, headings, lists, code and links when the source is Markdown." = "Render bold, italic, headings, lists, code and links when the source is Markdown.";
"Close with Esc without clicking" = "Close with Esc without clicking";
"The panel takes keyboard focus while it is visible. The source app stays frontmost." = "The panel takes keyboard focus while it is visible. The source app stays frontmost.";
"Detected %@. Translating to %@." = "Detected %@. Translating to %@.";
"Translate to %@" = "Translate to %@";
"This text already appears to be in %@ (detected %@)." = "This text already appears to be in %@ (detected %@).";
"Mother tongue" = "Mother tongue";
"The default target for every language unless a rule matches." = "The default target for every language unless a rule matches.";
"Language rules" = "Language rules";
"Add rule" = "Add rule";
"No rules. Every language translates to your mother tongue." = "No rules. Every language translates to your mother tongue.";
"Source language" = "Source language";
"Remove rule" = "Remove rule";
"Rules apply only to confidently detected sources; otherwise the mother tongue is used." = "Rules apply only to confidently detected sources; otherwise the mother tongue is used.";
+93
View File
@@ -0,0 +1,93 @@
import SprachmittlerCore
import SprachmittlerEngines
import SwiftUI
/// The source-to-target rules in Settings ▸ General. An empty table means everything goes to the
/// mother tongue.
struct LanguageRulesSettings: View {
@Binding var routes: [LanguageRoute]
let motherTongue: ModelLanguage
private var languages: [ModelLanguage] {
LanguageCatalogue.all.sorted {
$0.localizedDisplayName.localizedCaseInsensitiveCompare($1.localizedDisplayName) == .orderedAscending
}
}
var body: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
Text(String(localized: "Language rules"))
Spacer()
Button(String(localized: "Add rule")) {
addRule()
}
.controlSize(.small)
}
if routes.isEmpty {
Text(String(localized: "No rules. Every language translates to your mother tongue."))
.font(.caption)
.foregroundStyle(.secondary)
}
ForEach($routes) { $route in
HStack(spacing: 8) {
Picker(String(localized: "Source language"), selection: $route.source) {
ForEach(sourceOptions(for: route.source)) { language in
Text(language.localizedDisplayName).tag(language.code)
}
}
.labelsHidden()
.accessibilityLabel(String(localized: "Source language"))
Image(systemName: "arrow.right")
.foregroundStyle(.secondary)
.accessibilityHidden(true)
Picker(String(localized: "Target language"), selection: $route.target) {
ForEach(targetOptions(for: route.source)) { language in
Text(language.localizedDisplayName).tag(language.code)
}
}
.labelsHidden()
.accessibilityLabel(String(localized: "Target language"))
Button {
routes.removeAll { $0.id == route.id }
} label: {
Image(systemName: "trash")
}
.buttonStyle(.borderless)
.accessibilityLabel(String(localized: "Remove rule"))
}
}
Text(
String(
localized: "Rules apply only to confidently detected sources; otherwise the mother tongue is used."
)
)
.font(.caption)
.foregroundStyle(.secondary)
}
}
private func sourceOptions(for current: String) -> [ModelLanguage] {
let used = Set(routes.map(\.source))
return languages.filter { $0.code == current || !used.contains($0.code) }
}
private func targetOptions(for source: String) -> [ModelLanguage] {
languages.filter { $0.code.caseInsensitiveCompare(source) != .orderedSame }
}
private func addRule() {
let used = Set(routes.map(\.source))
let source = languages.first {
!used.contains($0.code) && $0.code.caseInsensitiveCompare(motherTongue.code) != .orderedSame
} ?? languages.first { !used.contains($0.code) }
guard let source else { return }
routes.append(LanguageRoute(source: source, target: motherTongue))
}
}
+39
View File
@@ -0,0 +1,39 @@
import SprachmittlerCore
import SwiftUI
/// The long-selection settings: part size and the number of parts one capture may use.
struct LongSelectionsSettings: View {
@Binding var draft: AppSettings
var body: some View {
Section(String(localized: "Long selections")) {
Stepper(
String(localized: "Latin part size: \(draft.maxCharactersLatin)"),
value: $draft.maxCharactersLatin,
in: 1000 ... 10000,
step: 500
)
Stepper(
String(localized: "Dense-script part size: \(draft.maxCharactersCJK)"),
value: $draft.maxCharactersCJK,
in: 500 ... 4000,
step: 250
)
Stepper(
String(localized: "Maximum parts per selection: \(draft.maximumPartsPerSelection)"),
value: $draft.maximumPartsPerSelection,
in: 1 ... 8
)
Text(
String(
localized: """
One part rejects text longer than a single part. Higher values translate \
long selections one part at a time, which takes longer.
"""
)
)
.font(.caption)
.foregroundStyle(.secondary)
}
}
}
+27 -16
View File
@@ -74,7 +74,7 @@ struct SettingsView: View {
private var generalTab: some View {
Form {
Section(String(localized: "Translation")) {
LabeledContent(String(localized: "Target language")) {
LabeledContent(String(localized: "Mother tongue")) {
Button {
showLanguagePicker.toggle()
} label: {
@@ -93,8 +93,11 @@ struct SettingsView: View {
recent: draft.recentTargets
)
}
.accessibilityLabel(String(localized: "Target language"))
.accessibilityLabel(String(localized: "Mother tongue"))
}
Text(String(localized: "The default target for every language unless a rule matches."))
.font(.caption)
.foregroundStyle(.secondary)
Toggle(String(localized: "Show source preview"), isOn: $draft.showSourcePreview)
Stepper(value: $draft.translationFontSize, in: 12 ... 28) {
LabeledContent(
@@ -103,6 +106,27 @@ struct SettingsView: View {
)
}
.accessibilityLabel(String(localized: "Translation text size"))
Toggle(String(localized: "Render Markdown formatting"), isOn: $draft.renderMarkdown)
.accessibilityLabel(String(localized: "Render Markdown formatting"))
Text(
String(
localized: """
Render bold, italic, headings, lists, code and links when the source is Markdown.
"""
)
)
.font(.caption)
.foregroundStyle(.secondary)
Toggle(String(localized: "Close with Esc without clicking"), isOn: $draft.closeWithEscape)
.accessibilityLabel(String(localized: "Close with Esc without clicking"))
Text(
String(
localized: "The panel takes keyboard focus while it is visible. The source app stays frontmost."
)
)
.font(.caption)
.foregroundStyle(.secondary)
LanguageRulesSettings(routes: $draft.languageRoutes, motherTongue: draft.targetLanguageModel)
}
Section(String(localized: "Double copy")) {
@@ -215,20 +239,7 @@ struct SettingsView: View {
}
}
Section(String(localized: "Chunking")) {
Stepper(
String(localized: "Latin limit: \(draft.maxCharactersLatin)"),
value: $draft.maxCharactersLatin,
in: 1000 ... 10000,
step: 500
)
Stepper(
String(localized: "Dense-script limit: \(draft.maxCharactersCJK)"),
value: $draft.maxCharactersCJK,
in: 500 ... 5000,
step: 250
)
}
LongSelectionsSettings(draft: $draft)
Section(String(localized: "Prompt policy")) {
Text(String(localized: "Default translation is fixed for v1."))
+245 -38
View File
@@ -1,4 +1,4 @@
f6951b1dfd3273d8b320f489125b01f6cdbac708f6e6a6a1af1c35fd43f224ce ./.gitignore
ac3b5df584dabe8c38d8dde42e1871198e11c0512e1ed57b45b8cbcdfc5e35f6 ./.gitignore
b6f32f48809b596fa90c724e986bc78f220cac1928039eb57b8f7c13ea9a3081 ./.opencode/agents/architect.md
a58c2194b2a853d0e418ea68b6816e8cde60a007b5fab596819a5cdf77dc4140 ./.opencode/agents/swift-reviewer.md
f58fbb98fbe250169d903f3f3233564ebab9ec73db96418adf0a5d9db26ed389 ./.opencode/agents/test-engineer.md
@@ -17,76 +17,283 @@ c989a2513d0b926f3a202b0616426c7443594ce72896ee91c29c4e83451d433c ./.opencode/sk
57f91677056a59e48748c63557672361cdb24bfa39264560df0209bcff0fd919 ./.swiftformat
2c0c375f3f6704a43e1042b250e0b633ba740aa7bc2fbf5518891a7b5464507e ./.swiftlint.yml
3222c8553505401c967cc302e2d46a99db95f98d92650f6b245e2a1dc901bea9 ./AGENTS.md
52b02a06a5fa40eb610a19c4e83564fb6c5b3592e25a63f271bc42eb75a25924 ./App/AppDelegate.swift
c36aade859ae4432a04f5fb050322e1c78a6e535c206a18b61971809c0fef4dd ./App/Info.plist
593745fab27436e91148de34b7e0e530cef5137e2c566cb479caed033602b949 ./App/AppDelegate.swift
1461fb881c44cee037051e78a4ea1e36ad459abbab1fc7d530ad993687520d11 ./App/AppEnvironment.swift
dc41f554a88b5b499840f72ef676b31530e6ebfcc5da636155001c52ca48d8a1 ./App/Diagnostics/DiagnosticsView.swift
69f0c24937507ed7a9137abfa95fdcd2798cd909dd74642d4b5e6a859da94253 ./App/Info.plist
36aec6e936e6ffff104908b370a7231b9283e178df8d0a453639dca9c573460d ./App/LaunchAtLoginController.swift
553ade6c51a4532be13593e95684c0cc3403e7222f1208bb36200f96915d5e83 ./App/MenuBar/README.md
3099e4feba33120e9ce41e3b8701d8fb8f305b4fdd965336950c3bb7e0e38c50 ./App/MenuBar/StatusMenuState.swift
3b001166f13cac42136917cfde0277c6cd8cfa922280832a4065081b822b3f9d ./App/MenuBar/StatusMenuView.swift
c4a25b6c1207197109d12ea740dc15ad8aa75b6304d901110aa3e10570cd65a0 ./App/Onboarding/OnboardingView.swift
ba9467153908c81fbb2497d5679642ae15c7b9fa23a10ca9b9ab678042aab222 ./App/Onboarding/README.md
382661bb55524acd7a686f215f8dd1cfdd4127dc19629dd637204c5b1e0734e9 ./App/Panel/LanguagePickerView.swift
76dcf59e01ae8319d4f0aabc5e600c549adaf56b6db802794804c3215be9377c ./App/Panel/MarkdownTranslationView.swift
0d8e9dd5c361987e717e5425cb3a4bef2849a3ba5f40d302a4074f4847abf45b ./App/Panel/PanelController.swift
6b84571bda2bd12e4990430d098d081871c6e239782f5c2e07650e3f7cde6dbc ./App/Panel/PanelView+Content.swift
5a76a652c8f5b03421f475211a4beff98037092004dfbfb54fcaab18fab67b36 ./App/Panel/PanelView.swift
bd37b327672595d55c263f109005b816406cce5928ac58c66286cee0f5d16531 ./App/Panel/README.md
9e09591204b9ca4518a031fc856b0cd01245fe8c4e14aa7238e75a83ab05d4c3 ./App/Panel/TranslationPanel.swift
9e8223452ecc9eb20a4e0395d225b93871c4fd2cccbdfe58880620c30d3bb047 ./App/Panel/WindowDragArea.swift
718f35bba5763975e162109095348661d4edfa1d8f167da04376fbdc71cfc7ad ./App/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json
183606ef4431a2099a26983fac8261ab4d8fbf5fb6ff0204367d3a51e11212ce ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_128x128.png
5e90d81c2decbf8a5c4fd5624e976cd4591f4f53c4c4a40e146d8bb1872d2353 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_128x128@2x.png
968a49a8667ed72ccb608b39fe28afc3f95cd4ee8689d567983ae0dafd6978aa ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_16x16.png
f7fb7b04d7936a965befe202545fdaccb69d7c0c95a99449a27c9119d0326991 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_16x16@2x.png
5e90d81c2decbf8a5c4fd5624e976cd4591f4f53c4c4a40e146d8bb1872d2353 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_256x256.png
182c8e94854779aefc2f19115d04abb2c66493537bd68f7c5448ae9b9161e38f ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_256x256@2x.png
f7fb7b04d7936a965befe202545fdaccb69d7c0c95a99449a27c9119d0326991 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_32x32.png
77e828091f2a32d6e233182320842921ae6770c33db8b1dd25800c2e88bfb835 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_32x32@2x.png
182c8e94854779aefc2f19115d04abb2c66493537bd68f7c5448ae9b9161e38f ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_512x512.png
2c8e82d99378ff2fe0ca98754a3ef29861f0130c54008634106532d0754760d6 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_512x512@2x.png
f23266b9672263c92ced1d26fe4dafa75a14d530eb9bc5fc1f599034d597ab48 ./App/Resources/Assets.xcassets/Contents.json
ce0c088300a0a739ecc0a73892aad6b9538397d637760962a810dbf65692f62b ./App/Resources/de.lproj/Localizable.strings
ac67edd346d0828cd0e86cae4e3da719a9e574d22217f0f15a6d30558bd76e14 ./App/Resources/en.lproj/Localizable.strings
5c2e5222430e1822c3e13cdfed202f54cabc32beefb7651af78475b29494dcf2 ./App/Settings/LanguageRulesSettings.swift
0be6586ef0653cd8e5dd12a1b195c236d54fd1aeaf09bbef48da43195e78b6c7 ./App/Settings/LongSelectionsSettings.swift
dcdaf8761f3b195e8c8d8889b2b792aa3dabbaa47b0c641fb4db4cdc09436026 ./App/Settings/README.md
3066bb45d7b90e3ad07931f56dc234b4b3481c40459842e00430b6a66ef28308 ./App/Settings/SettingsView.swift
d3dcb4365c3d9ec39fa379b8e5cc0813745acc68dc851a85b4ab277896a2a5b1 ./App/Sprachmittler.entitlements
3a384017b5b54049c946a674f8263be61f445b8f1ff6f48cdefd70a4bfbe2b00 ./App/SprachmittlerApp.swift
8bad14fa182903bd8f17cca19edceb0b779246f9ce858ede63cd6b575c2b2265 ./Makefile
ddda3377a2e130e25195da349dd0964cfca8a401464b7b0cd8fcec6bfb575fa3 ./App/SprachmittlerApp.swift
c3d0de679f6d151f46cfdd11577eba65e1cff1f82be669be32e42a99fba302ba ./Makefile
0608007aa6ef1a3533d5e5b4d021e753efe89d24dea881d5ed443429a43a9de2 ./Packages/SprachmittlerKit/Package.resolved
8222951112a60723d1d9a65aa00a152f9138d10c4c8b3dc6e7c47bf2b5c46bf5 ./Packages/SprachmittlerKit/Package.swift
44627d4034cde7e11afff37e9b7b99b8384b2291db657f9914a5312ff8f5eac8 ./Packages/SprachmittlerKit/Package.swift
a6b0221a7c806cfbcb6007c960772ee1c063c0b85727a1d1fc42097baf6dcd70 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AXTextEditor.swift
9c7c19d9ea7d8369244447772a3fa0c3fac21cec0ec22b9df700555f4113a22f ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AccessibilityPermission.swift
348b56aa312a253c6a4de1e1af51ca6b9b5c4e49b86aaf7525f43c180ed17937 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/ClipboardSnapshot.swift
2386c6d9f5637e4be701eec1296240dad71211509c971bc7dcc334c975f4b9cf ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/DoubleCopyDetector.swift
ec2f66d1a2d8ebb308427802f54cc70c6bdead8c31a57ed87648446d6bda9ce1 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/FrontmostTargetProvider.swift
85abecf8ca1b15fe1a9d5dbaa0caee16a38a4408e932f6115975d9823a2ac47c ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/InsertionCoordinator.swift
0b8a8223e67d0c94551c1dd68609858602069d0ecd4eda736f988880d1e04464 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardAccessing.swift
4ca88b4f08515057738a45c9ae475260e3a840c1d5bb3d4622a57ce04f5b8cb1 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardTicking.swift
dc5f5b08ec537ac917c96b7ba4c1881bfdfb7c21e166a4f9ee1f6d9e1289b351 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardWatcher.swift
26aeb81883b8216f364215602b804a2d6e6994a221f9c910c0ed52cc70d4c3aa ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/ServicesProvider.swift
dada1b00037d12da0df03a24d1140e428beb9488fde7e0a9d99d0cca58d1a4ca ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/SprachmittlerCapture.swift
728ab857854f1f2bb46f032a13f6d47edd491ee0d6ca0aa8bf2b98f91ccb3c23 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/SystemPasteboard.swift
7c580669d76ca3154889a2f3045a1e2689c8984398163496e0ce4cdcad9ae880 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppOllama.swift
9030a1f039515cd92b2178f90649cb028d248a941f16e2d1fc9d52663d7239d9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift
e2ced0cedfdbea4621ba9d01907a56e80001770af0e7e41b31712a042d0c451e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift
a150f68cc08fddc17c09dea5bdb4d85b1b4c3035fa4a9f8a24c48efd1fc0f313 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureLimits.swift
d711719fa15d25c28c7e29c1a8773da9da61ff0372917ecf684fe27538e1decf ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturePolicy.swift
02421321864ecf0540a96b55a692e91eacb9364d579735d20b9ca94ebcf99a80 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureText.swift
3ce80227fe4f6cfb9efc00d83cb4bff28e870fd72aa29d8cc03a723e8694a34e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturedText.swift
2a8c7b261b3c955547fd88520a9582c5c31a1e86a4c13d8bebfbe1d4b8f752bc ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsStore.swift
3275711919331a617e9db199e89d6ba5a9c28d518eea4a590fd9dac74c7bd876 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsViewModel.swift
d81ffb9aedc1feef70af050f55f3d0bfd85a828bda80d54d32e5a0667e05bef9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/InsertionTarget.swift
56037f9dc0096e9e5e0a44365fb29ecd3185e8c39bb7ee156f31ec08e1326ff5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageAliases.swift
5d78b5e2aafd267d0e6eba66ae7257dabfc1dfb4b913e78754f7ae128bddfd4d ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageCatalogue.swift
c2fcbae9e59d203f90c7f21a92d3c46ffa9c04d916a1565d16b90e4fa1b361fb ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/LogCategory.swift
cc89553a898735a1288bdd1c67a04fbcd282f99ee812a83c8b18eff9627ab65d ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/LogRedaction.swift
39cec81db2748fd5e01c5d6ade00bae5babf4a68d7d472a69e98b20884585c5f ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/Loggers.swift
83b6c93fc950df1fa8e4942521187a0ee3ecb319b5ffec6deef6047ef8d2b171 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/OllamaErrorMapping.swift
b7dfab9b2c613071b97bc329378eae47b97305cae758221fba787c8be4eb52f5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/OnboardingViewModel.swift
0e08aac528b2a8da63f2b2cccbc2a4a134c1dbc49927f3d78115b3faaa2944ef ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift
c52e182fdc6806a06f7b516806140ef26aad8c44e72f9e5beb9135acbe28b878 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelWarningMessages.swift
563d79ceae06a20e8a5b78e155bfe8489bac8f5267a8c3d064fd5c50ecc66cf5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PermissionProtocols.swift
761c20b4a1c063ac39648c3d24d8864a0329ff348eaf45db4fb27c573f15e44a ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsStore.swift
afd0db8a53c0afb37bafc8647e2da0a8f741e0b7396c018f95c63a80484ea80e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsViewModel.swift
b126a8164e50da9c4f276efbc2f591fb94a587b9855a5c9379485ab7d334864e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SignpostInterval.swift
e33ebfeeeb27b88029c20f212769852c5c0a697abaeb1bc249d350e7ad649273 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SignpostName.swift
20e3977534de6e1c1af8bcc3049318007213a034aa2e8d2d24032b22e1bacba0 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/Signposts.swift
b6580ae5a0f5e18b6b527766cb5acd5de4d828df3badac44ae294dd72acfc436 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerCore.swift
fa4aeb76903a93335817a71e80829c6a950288c3575deddc0dd3f89d7a59ce79 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/SprachmittlerEngines.swift
2864b92feb24a0616fa546ea2683fbdc9f73352ca64ab84da110e19fd7c6a926 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerError.swift
359faa0524007bb58a504b073c854c04736482b893e9509e56843a6850d9e7ac ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift
f75ae67b262e18b53721d070acc0e8d7bdfca94698f10c1a5780ef948ef72912 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TextInserting.swift
98de162fc7be182a5832e81f12b2bf72c336abf1a65a6a2c94821b4bf51b39d9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift
d3511504a464cb986ffad56ef31f5723cf6451fdef04b1e2bf6c58d2be21a6be ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift
480503eea4bc64f3125560c91d47e56cd9905e957af189a54cdf8b816a380ec2 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationWarning.swift
5a721207611b9aa6228bc288f5f5e0c57dd26c593ab3aec9bd38c91f9a9e0fd2 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Adapter.swift
06bf6da9127b3a010cb33b3db091e4301b32aca44f8cc7181ed1c34b00ece7b5 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Languages.swift
0b5e6571d378577091f8ce3b86020545b45ca2c3400afe88ebeed7b4aa8b68f8 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3ModelPreset.swift
dfbbd5cfa397340a38b844307621c26e28708eb36aa91095739e492838124c9f ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Options.swift
021919b8ff8e27bde4f02b4ada08e2b70463225afdc749d4604db6f84efa85cc ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Prompt.swift
fd9c98abd3fccbb77154a5ec7822e3eac3624134b377719078f5549f2081eeaa ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/LanguageMatching.swift
90c3ab7c90331c97ff18cd8a00fe2fcf5101b1915c45d5217a7edab95e612ac7 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/LanguageRoute.swift
1ad2760062b723e41d46c38fe7b1b4cbe959af417f9657aa12c6f3a6c08f406f ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/ModelLanguage.swift
ab9d4fcd37731131646decc9bb9a25b1e2338613ee6b093427c89287a2e9b762 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/NumericTokenNormalizer.swift
f00f88c07fc06f2abbf5a17554cb3cb7915f4e60fd32cdf98cdeeb810875add6 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/OutputValidator.swift
c473fa0f2c89d4a4f75307e81a6a5d28f1f21f3bffcc8911bb30487d27f64486 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/PreambleDetector.swift
50394e1fd104b4fd85cd2b206b146addca15fa21d7cadc5e3cef4ea7f88436a9 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/PromptPolicy.swift
5c5b1bfa5f10e2be6ce52f13e7c13143cbcbd7ab3e2af53edd3b13badc228f5a ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/PromptVariant.swift
dfe9d284e76ae67a42418c69dae4f84810b9ac7e6d3af675ded1625dd083282b ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/RepetitionDetector.swift
5ddee40aab9a5e099ffdb3c7844ae9d19ea44c885a89a774335c66b6927de62d ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/SamplingOptions.swift
1a0d4d9149432f7771a84060377eda2589d14b9041d9f296b871dc4ae3e92718 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationAdapter.swift
edf6c7617410a9ef2f6f0ea4cdf22e12842543d77f88f268075baad0749b74ba ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationDirection.swift
8969928cf7b9a71d9aeb2ee36fd6a70cec1c7ba9fdd5f42c23d4bf28e49a43b6 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationWarning.swift
418b1f3737fcf926815055c4f4f3409b292e6afcf0d6b81f37d1160b9f65ac35 ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationManifest.swift
43d7f19f92767fb2109dadf939ec4e829a58bd738f81c8abe7b8f3c92e58f9bd ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationMetrics.swift
dde82951a4e969628d80b224771124fa70caaa2ba0b447366343d5a99dc0361e ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationReportWriter.swift
dd445421272beed0c28e0c2f853d267fb6c8832a313cf836f6c2e47cf024b574 ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationRunner.swift
83f6c78029abb6c43c78039773f601752411f0f8f23ec3a9891e8008b70387b6 ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/SprachmittlerEval.swift
887b767c70d1c765fc73553439980c4216bdc278d4b27f923bde04378cd6d6e9 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/SprachmittlerOllama.swift
a517bee61c90ae280f6d8893e998aeff3ea4ccdcfca08a006287e1b4750275fd ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/SprachmittlerTestSupport.swift
c5a26fded64056855f876a6a2c0c466afbc3f5fce1de2323eb073da9ec09f256 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/AsyncSleeper.swift
58160c8c41ba81d72aa96dee583fa0ffc5fc64654da3a56f608c67c62aa49352 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatEvent.swift
0817f2102a866ce7c0bfc06fa8504a73294e75a6fca70ee0578ce78216b42147 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatMessage.swift
363bb249519c2b2d67a6a0c516bb5b113298545cad1a575593b5212702418acd ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatMetrics.swift
38a5c0272aff387a1ba70a073559a97d2b31b4b9c4550c0540a7ddbcd8a93705 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatOptions.swift
7ecf5e465e8cb14182396e850ba8640c74d1a0d1fec3f8c39d288d0ff89cf750 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatRequest.swift
f22c1caae9a722373605504cf9a3a268497f3d8683548e0b75b417042d3af9ed ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatStreamContext.swift
9944f8e250c2b334a9129a82281fef45663043a5b0a3bf01acdb114b68c565bc ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatTimeoutController.swift
4f850d29de8d81ff85e0a3602cc72029f675ea37d56481e75aea7d5b5e0d087d ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatTimeouts.swift
f158a61553f38138d6e8a08e02c15de949b882898273d9c13b857401a01df7a5 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/EndpointPolicy.swift
eb3bdca89e3e15d2c9300e0f92ddd36dfde28d6105e87ee3c4ca29171ca2152d ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/EndpointRejection.swift
157abae634245d3646f16e2742ecaeae72adead8c10f6d1ab3dcaa02b5766ff6 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/InstalledModel.swift
312b3919d01d0128b57db111a579b0add5b89d7e8010ec270aecdd9a3ef38dac ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/LoadedModel.swift
88ea1a3e0617aef24ddcff51073fc30b27974b9bf8454ab8288e9f003240cc11 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ModelDetails.swift
ab586304f68d4e46146577438db1560107eb8f713cd0f4244fb0ae3344496742 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaCatalog.swift
68491c3709467eb22a9d9c21ea72d7ef3a37ab04b6acde496a714e772fd3c3f8 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaCatalogClient.swift
1ff7419acc3a2401faa719eb0e8955a318ebade41b8718a8bf7c52abc5be2c7b ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaChatClient.swift
ba536c52aa94cf7e48dd98b741a41234b3f8709a38503ab264998da281d44dbe ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaChatting.swift
5f4ee95364526a59e0776207a1e93ce6cea5eed3473bd5686a8674a425824401 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaError.swift
711780019b33a02bf048968196f04b04a4f996ea9d0e1128140b153524a0ddf9 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaErrorBody.swift
0020db5fc620a8a188ec0e6feb8d903bd4d849c87808efb8b85449c4056e4bf7 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaHTTPClient.swift
d76d67d55efc70289aeed9626265c3f6d183b001c4d36047f4e8962180a18ce1 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaHTTPRequest.swift
c32d05b70ba04d525064a2ed71f5ea67d1655d72c56f9d185aefe4250840321b ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaHTTPResponse.swift
232e1e3d1eb070a353e72f301c82a4f3ce56c874f8754fddb98bf71a5a816798 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaHTTPTransport.swift
92753142b6151ff867de64d1ce93ef1e975c3b0e7cf15f36b23828f3346e0275 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaSessionFactory.swift
15038cb5553980b00888fb763a8950da29e9c976fdc5288c0421053e84aefe4d ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaVersion.swift
58d527fdb66f62fb6b7009bf454b94ba0f6ebd19c3686d91c5f598154533c830 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaWarmUpPolicy.swift
443eefc6de2a8196735ba2deb207bfc36f46b1217e7873db9115c69f6db26921 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaWarmUpRunner.swift
314982eecd8a75575e2c25fc776ac785c8d9e99d035a645480e68b946d007a43 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/RedirectRefusingDelegate.swift
2c4ec4c3422d65987661842420f313b48c17bb5785b6b8be28ea07cd8f95d02f ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/StreamLineAction.swift
54c856650277c61b2e6dde34120eaae59a7b354d0ed621f5ac8634684211b030 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/TimeoutPhase.swift
9a8d1d437e08462d0f063ac0784812b0f8183dce5b4251b28c5c064e4a47d3fe ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeOllamaCatalog.swift
54076808b76b6efd5ecb174403210c331d1b674b15120400323c0623e9e3ac85 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeOllamaChat.swift
1cd84966052430f540220cd7bd22203b8a77574540a66700288e588e9b8efb52 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeOllamaHTTPTransport.swift
524e816552afe34f8844a1c01bb56b6bc81fc5a83cc96889a25bd044e73dc0c0 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakePasteboard.swift
03d570bc4022f205abb52da509bd68444879308b14f46bad497cadf9f80f3845 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeSettingsAndPermissions.swift
16e6ae7d693df1ee6532affec1fa687aeed1e709595b929f2a4e1f00e1b9d88a ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/ManualPasteboardTicker.swift
c0f87a5320fe715f5dbc7c9bbc7c0fb19a5b64d1c145c45b26f060c151eccada ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/ManualSleeper.swift
0ea5a0c60c2185262e52f71c78538f9b1bb308c9835dc2362f70929da9bc42cd ./Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift
b639d452d78dcda9e9f3b5ac3298e8499a7837a955839ae5203b508944df2c63 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ContentClass.swift
b768d43f50bd4fcede0f3c654787771a605b6ea2648cac722d0e78dd913b4fa5 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ContentClassifier.swift
9eebbc1339104d8a0b0f9f579d0c9f0bf69b05b5ad1a4550cf645ca3197686dd ./Packages/SprachmittlerKit/Sources/SprachmittlerText/LanguageDetector.swift
41aeff6d807caa027f9496a4bd6048bdde55d6eeb4a11b2acdf445dff39735bc ./Packages/SprachmittlerKit/Sources/SprachmittlerText/MarkdownPresentation.swift
c7591458a2fcf4813a166cf4f15aaca69688a85e319cf71ebd5c2dcffba756b8 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ProtectedToken.swift
2ec31538fe5a2ed98fcce6b815c1844cfd30a53073f4987eda8043bcd222d58d ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ProtectedTokenScanner.swift
6ea915648616c12b9b2ae3bbb97838a512c6c3a91b2bccfc13e144d950d4bb6e ./Packages/SprachmittlerKit/Sources/SprachmittlerText/SprachmittlerText.swift
8a349b1fdbd3755bec2f6ef45ebec31af96be8857923e3d0f79696f5c98eeffb ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/SprachmittlerCLI.swift
4e05396e9e2f915d450af13f57dde523b961d1ba204bffdb5c94db4ba0d82941 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/TextChunk.swift
f528068c473ed46c7daec43a1306b7bd50aec76bf3fc353bfd86fd5e18388854 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/TextNormalization.swift
383da4ec8485cf7457d9e336978ec8b4a6d9f49cbfab8db70db45dc833decb56 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/TextScript.swift
b2f837437ba28548e74d43a2a88bdc3f2e79d3d1e6ec16b381af04256909174d ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/CLIEnvironment.swift
d775cfc21b88687a443118fc0d12f6c4837f712ab674b12286f87470a33bee8f ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/CLIError.swift
7475168734bec7883f4f911af91e4a7184da55849b853eaf7429ae20171d3db9 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/CLIOutput.swift
9c0e6beeffe1ac02e5f32d24f2fe78159183719414978a5c9bb9752313805777 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/DetectCommand.swift
d4ea1f2538934b1c2ffa69fd905c42194760a535a54ac4d241daa616530f976e ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/EndpointOptions.swift
57a104206b2e662d3fd8e5040b422242744752a90133f2f902771d1d73e6d62e ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/EvalCommand.swift
48a9061c6c40d9bd32a55635873e64f5ed7f97edc97827f78979c7b74eb55a85 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/LanguagesCommand.swift
aa686ae5d4b40d290b7963a2ba97dab4e3ae8c2054c0df09e9093448408dbcfc ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ModelSummary.swift
97d119e9c05d62a527bb255ac67dff9049d76a7c11ac292b7ed0ce11b63c1cbe ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ModelsCommand.swift
b8645b487845964dbc060c2a99081d7f89ca5026fb6ab5be82433bf1aa0c1b18 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ModelsRunner.swift
b0125112472bc642661bf0233f0b7cf1bce3ef7f511c333f73364152b0527213 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ShowCommand.swift
a2e96139102375e8586a1568f22d44317cb0034e62c977ae45fc691126c4114c ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ShowRunner.swift
1c9b3e180e4ce78c5cf10bba99edd6c36fa9fbac85e4062dce84d396693e1776 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/SprachmittlerCLI.swift
78d1933ed58d565c2cc5b5463e8c99b3dbcc379f77ec956c645085912441282c ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/TranslateCommand.swift
d0e8bf434a42ce93fba7e611b26797dd5b7d20cd0c9468524fc14ef84b3abcc1 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/TranslateOutcome.swift
e7ec098ecc2e0c3f62ba53cd44afc0659b77b7baf2d5ab307cb4238c1f6efa5c ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/TranslateRunner.swift
3466e030b39a884371d10ba4a2b9ea1a05b7b053af1bd0cb88aa046ba1af2067 ./Packages/SprachmittlerKit/Tests/SprachmittlerCLITests/CLITests.swift
57fbb191c4bf3a9325d5fdab1cdc950bc6e2579f12ea64442c8b2dbd56b79cf4 ./Packages/SprachmittlerKit/Tests/SprachmittlerCLITests/SmokeTests.swift
d4e110c510cac46c1acecc68f28ef8b30daaf1f9b623f0533ad359a6a13680aa ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/ClipboardSnapshotTests.swift
23e0c52e3f5f9b5848ff9118bfe3baf474a21c830560be382b978328e794218e ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/DoubleCopyDetectorTests.swift
efac77b258ef29cca1cc61311ef8d167e45ad5680a73396a1b4bc6d99d9a3f45 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/InsertionCoordinatorTests.swift
c23c58fa553049241f4c40193d41aba4fed8261f1ece4f32bcdf65af25abf099 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PasteboardWatcherTests.swift
87e92d608b14675873a6554a3bcce951fb62b45b95ce32972df978cada697a43 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PlaceholderTests.swift
d2d3507f437c7126bf15ebcba7be6d03794a73a637089c511c99096bc564cc5a ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/ServicesProviderTests.swift
f7375e2cd08709d7b590ae4f6d70be3edb88f122f9fb3aeaac37c826ff637d12 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/SystemPasteboardTests.swift
8eb9ab1b8b15568295aff0b90640afad7f1a38ceaf3dfa2145a0a338f7071d57 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift
2ea18f23e2328110fa6d61e51ecf4607eea7bb82d1c8eeac5dfd844f07c3a6e0 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/CapturePolicyTests.swift
2d5742a1fbbb65044455cea92b9f95b9d39f5236e92e4f152b141bcf964c639e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMappingTests.swift
c584df764e9fa0a029ed9f17c1a3b27cb4e3b91005f27171d5553aaf51edb48a ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMessageTests.swift
95ca20f1c4cf0fd68f29a488770a1d6d7911c534913a0f88515ea1fe4f4cdb9e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/LogRedactionTests.swift
6610797e6dd77401d1bce624d65e84db9bdda95820b1f56add1d24cea1f5df91 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/LoggingContractTests.swift
8c0462d50ff3796aba6024349083d8b1ede654b495790d7610f95aecc8870001 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/OnboardingAndSettingsTests.swift
fa5572b8825c7cff4c21f45e5381cb746606c270a45dee75e304be684b64ce1d ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelChunkingTests.swift
f8f1ecfe58f003a0713ee2948c06a7b0ea18272319336025a31f87618bd56f0d ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelRoutingTests.swift
f2071269097a49ddd38a23a213920d09a7786201ef7eb68199a8eb90a4bee303 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelTestSupport.swift
667624e7bc610bbecf323d4401787082bec3e3a2397bd1de86d1dca897e1082b ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift
e9fe1b63792e610bac81153c6bc79d4c836c36c4c9538b26887daf62e9684d80 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PlaceholderTests.swift
5671265556115fe93adb7ee3ccd39a9f31786c7da2e022fe9914db06e5555e24 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift
641482d5c4e8540861775d67d007d6820e1849f6e7b3d2b0456ef462434ada79 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift
988eb93a5d1483a6db061c1a11d5b06d7632157c076352c435418152f47910a5 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/README.md
86bae20b590f03748a5b498a0ae402d7bb10fb0b7ba7bbccc821fcbbcba8ab37 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/default-prompt.txt
86fafc88be2c581fb3eeaaace4320c9e6eb8bda2d89b757cfcb3ce1b4540fe74 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PlaceholderTests.swift
615de4459d2d77dac87809bb33af42d32ab624cb5367d1b3b9de6841d4935bc3 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/delimiters-prompt.txt
4cb7a5de7d493e2b21826322dc38b4d31415352c609f3b68b4786bd12bbdac42 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/structured-data-1-prompt.txt
cb657108c3f9b6f1b3a743313d2b6622ecf7b039ce80b8b2a1da3bce78451751 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/HyMT3AdapterTests.swift
ada2bbfcf0213001077d55b475c3c2ec764623ddf6bd70e62d73d3dc08c99dad ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/LanguageCatalogueTests.swift
e56dc9de2741d731b02ff3bb39ee74532ac4350d232eb66fac86ffb770cb7a86 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/OutputValidatorTests.swift
7d1c6fd3193bcd169be2421a56e42fca82e7e44a5a288dd6482957ab6c50af21 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PromptFixtureTests.swift
8bb2e2310a40e5923fa77014ac5209cf09cc8a52056a22cae9544f3468e1d2cc ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PromptGoldenTests.swift
d93aa1ae54f4a6f49aba4f2badb065a86d29c335afb6efd0890684759718a3c3 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PromptPolicyTests.swift
1824f05ed6f704263fbfb70cdbe07fec85812745b1b71133be2781c380963db7 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/TranslationDirectionTests.swift
b921811eb2bad2cde5a5c199b9c5e4fac710740193789d324d73580d2b8c7abf ./Packages/SprachmittlerKit/Tests/SprachmittlerEvalTests/PlaceholderTests.swift
78fd25235b625f82115f3d14c6a9863949055fbead95c9ef83668866bf255d10 ./Packages/SprachmittlerKit/Tests/SprachmittlerEvalTests/SprachmittlerEvalTests.swift
e9fe1b63792e610bac81153c6bc79d4c836c36c4c9538b26887daf62e9684d80 ./Packages/SprachmittlerKit/Tests/SprachmittlerLiveTests/PlaceholderTests.swift
bf9501d4defd98c8249b5524c2113f00e27e05a279548a8cae4fd441b370d256 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/EndpointPolicyTests.swift
1581a9133daf1294fb224820af9c8c265a03b73eac959ff921b213107881940b ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/EphemeralSessionTests.swift
3552c16d0da451db9b8d9cad3375d9dc4d716003dfb6afb89b6ca92c99d4fa2d ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/FixtureContractTests.swift
c48ac2946761e46da0d2eed81204e97a7fd96361b55b44a289ccb56587f6a83b ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/README.md
0c2d6cdb4ea5255e9266dee670a8a1d84ad4a27549c6e8a4f8d99eccf6677eab ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/capture-meta.json
4157b4206f99f974ce4a6d54f1816f8912f409368f63206d7cc65abf6426d50d ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-de-en.ndjson
944d0baa3a932e0bc42ed0eff59a055f2cf01e1a1e2cc66a051ba3a82e8e1f84 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-en-de.ndjson
398ae470bf8bc88df8a2d1c1f15289e62cc941f162774d3a5469dd6e3b907378 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-markdown.ndjson
e5a38a0283dad14969131052bd8daf60132c783af10945b6d03aff71b89e4b58 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-truncated.ndjson
4bafec6db42fb16e1901cb8f4de666c52d9a270c8fadb5e3359b10be7ebec80d ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/capture-meta.json
b735e23f9edd09a19969869fe5db53b9924214eabd57932a3a371f8cbafc30de ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-de-en.ndjson
7f6f9589c6ce4f4bc542d940f1eb72210acdab4ae39c93e79df40df1b87a2270 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-en-de.ndjson
568503e59cf16924996dbfb2ee50a944eed20768fa637d595caa358a91a4ce88 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-markdown.ndjson
1a9c3e41b0fc5dbd6d97f1b9bdff0d3db365ccb2621785b8ad34454381cafc99 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-truncated.ndjson
2f0cfe6365fe218b3c9ecb2f2a712bb53ebfea811982a5a0d9e4f32076ef3bfe ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/error-missing-model.json
a8f7899f295520b026b56e103486fe3ff8e66eb35db9c457f44e36c8a45d8fc2 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/ps.json
f1410d0bb4a28d89c049fd9f9cd7df5cef24780f246225de6f1a7c38db5f41d5 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/show-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M.json
4e7e6b8cc3ec35a6e3e69d96335ae12fff289374e9cbdedfe0563ec3db8941eb ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/tags.json
fbb02594028ba766fe5f93bf8a5b62236841fb9d051277e0dc633f87e2c2d396 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/ps.json
e3844615abca9419b448745038c8fe2f9813ea0a56eccb1e34c57be879071a1c ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/show-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M.json
dec441bad497eeb245c9b28d2a231a4859762b82b8a4b0b07ab0211f5595ea24 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/tags.json
672856105eb7e7811ecbae8fcd189743b8fd44aece7baad3a1a781b5a41c43eb ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/version.json
a32b7bdc7476fc1521d3161560ee83a3c7c2ceb83c0ac7c2c0ee22d8c869240e ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/PlaceholderTests.swift
a4a387099e42bc0bf9ebc1ffb43e3a0aab843d70ef3d5a09590b72ec9d53fe15 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaCatalogTests.swift
da75e1c796f1889f594e9cd8bb4d32b1a11d7d4977647cae7e97d352b1545b55 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaChatClientTests.swift
6ed315b6389a479f0bc25865182e76ebe32a6bbca5c3be63c847a0ecac91ca90 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaErrorBodyTests.swift
ec4e2973a3933903563b1955da6213f2931b4e961fdc2bd8d40ab1d5577cff48 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaTransportTests.swift
4f388b8c70fb6b890d4b2fb86c338b837a7991a3592c3995038946c2df8e2e40 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaWarmUpPolicyTests.swift
4442060cc5810f0a0332a0abd05b1b9b54a73bf0045fe0fdc94b543a56238106 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaWarmUpRunnerTests.swift
deb3801d380aaa32228732c60b70ac576ebc2563f1dee8854215f2ee1a1004d7 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Support/ChatStubURLProtocol.swift
ecedbb779b022a8d87a385903040d49aa9d1ee144c2ffb58dc50ea58d297f630 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Support/StubURLProtocol.swift
766a76be19e12928f2cc39cb1e905de6da07eea86a68f19247464af6a163708c ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ChunkerTests.swift
a90dc29af451dac1557a88081a53defcffa8d21fdc0029d7fc19bc3a34d81598 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ContentClassifierTests.swift
74e7640a50e5cdc77207700b4a76b608abc88de48464ee76e40c07d9db8c4bf1 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/de-sample.txt
f9ede3201de7a3d092b2f114dd7f131dafd3b2d6614c0ba91d6181e326ab005b ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/en-sample.txt
b0a7d3451d8830654fe79476b8d32d95709d956817a4436f58c0f73bbd8d3194 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/markdown-sample.md
6ceff5d7b34dc4f4099c1ac8415f89b680f64608c3b9e140c4dee1737cf2477b ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/placeholders.txt
436ed18c9c1cd8bf15df11e2c2f9ca974f9a6f17ca8b894e5ffef999458653fa ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/LanguageDetectorTests.swift
80d28cb607b67a35cda89d86e2819e29e71b38e8234557683cb7c96f611037d1 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/MarkdownPresentationTests.swift
8c5c21634d749ad05da8b6a0fc1d8e132a494177a697ba0a1338a7a6b5dba50c ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/PlaceholderTests.swift
dc45614d3b3268dd5081f8678f1bd4231dd73b067b49b088271b29362563bb8c ./README.md
de21f0e9556ed2d25289c10041a913d1ea55470a4951d05880921cc1e809d964 ./docs/ARCHITECTURE.md
67c0f9ba9e818267e99c1756b82643f7e59effa6783325675386aba0a1002cb3 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ProtectedTokenScannerTests.swift
c3294d486cfe44a6f0a69a1ec05cff33a8eccf090fce04fadffa96b6b2563d6f ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/TextNormalizationTests.swift
2d902ce53c14b6d64a578bdcc99845b6375a69ced37f503423c9df6cbf3c15f0 ./README.md
f1dbc2fb876d909b8486239e9b75b09ed68516c341d586e96d8626715c86a88c ./dist/Sprachmittler-0.1.0-local.dmg
b100978fe55c5afbf6b3c987b34e17f3413329d3fd580a2cfcd616f71a564aa9 ./docs/ARCHITECTURE.md
018c5faf1a5d2e8d851ab209d45e64993cbd6b7976c4aa90c571359c83e83264 ./docs/CODING_STANDARDS.md
c17e0eee0e06c0ee1e3e073545b80eef55142cd1859cfc541e195447b00f68f1 ./docs/DECISIONS.md
0186c9d6ccd86c745b0d78068283c7dd786b4329185ef9022f4169e2d4ec1a60 ./docs/HYMT3_MODEL.md
7da97c74eb82432130e4cf91b3175504bd2c0fc3b1227be0efb872df922feaa6 ./docs/IMPLEMENTATION_PLAN.md
0eddd31ac7f4ad295720b9081896200d622f28ed3a17bdab30f57f557d980bdd ./docs/DECISIONS.md
5b80ea8994519f2be34aa10abb345ac3029d3d3a29705dcfa0a1cb344f4b95d2 ./docs/HYMT3_MODEL.md
d87fc9df926f6ba77ce67b2731b83f48f2b49848c637f12d0fdfb5f27f3c6775 ./docs/IMPLEMENTATION_PLAN.md
c3a1838fb0a06acf6b7826f6ff278e15065af198dab22ffb1435dacdc064ad69 ./docs/KICKOFF.md
20a87dc7cf8cb593445c89d334e123f6275232524598ac71a21ca32766cedfb7 ./docs/LANGUAGES.md
96c63103091dc9c53c4629e5bc830b2ce92eae04e74096ac1ab15d6c3615528b ./docs/MODEL_EVALUATION.md
1abe88261cb0c46df94b195db3307ac2eff8ad0c610c1f3683b306eda67ae243 ./docs/OLLAMA_TRANSLATION_API.md
b1d9fcfffd9d0e6b3a9792633ad71acdef29a344eea0dea778e132a7c0330322 ./docs/LANGUAGES.md
a28161210fbabe27d1348f3552851fe7b30c9dccc658272f2cc79af5e085ec40 ./docs/MODEL_EVALUATION.md
6f94dfe4f2146ce0b9e066198c9e05ce659faf4318513ce586c966989fd3d1c0 ./docs/OLLAMA_TRANSLATION_API.md
e6dbccc3cb4c7a169a6daaa563066a6764a76b6b7649738b839dcbd9b2400ee5 ./docs/OPENCODE_V2.md
1251f24645cbe526b015c5b683e55073cd61a7ee9a34a1a613167b5d1fdba925 ./docs/PERFORMANCE.md
e2b785807ecb56eb1e7c02aaa6a487ce7c1be421865685bed4be2e973269bdce ./docs/PERFORMANCE.md
4a37cf1815071b3afdd10443ec9e05a5a78411d615c42f51117c5873922531c4 ./docs/PRD.md
8f73b8056f62e3310adaa0252dcab035888772f163e03792f88171e4039da5d4 ./docs/PROGRESS.md
d69d08cd64f6ae6c6779692c7e2e04dca6ede7729f53790c0e3e71b6fc8aa367 ./docs/SECURITY_PRIVACY.md
8707e5bd7db8f5981c49bdfe739be3ca2da9370efd39e8f3450db29b95ffcbb6 ./docs/SELECTION_AND_CLIPBOARD.md
c7609798be659d3d96c0b4e1226bbfd66cc0c0b0d583eaba47df37c3ddb70ddc ./docs/TESTING.md
381bf8425054d8b4eb6722ecbff4f6d4a4b0ec868bad8793441ed1246b5153e4 ./docs/TRANSLATION_OUTPUT.md
6ea3e3881a9f6a7de968128e660a897c648d8e01af77b3e831228b809d0d94e2 ./docs/PROGRESS.md
c72f39e7e5e1fb9c45c32f0741a379564debca4b408e702615d162f360d47ecf ./docs/SECURITY_PRIVACY.md
f140344de55d11eb450961639ba85a1ff479cf2e0cfb3c8bd3c4cdb2220a11ea ./docs/SELECTION_AND_CLIPBOARD.md
8720e8bf79ba7ab051bb8bd09f55b7766f98941904f354cbe3ab7b88c941e860 ./docs/TESTING.md
14677683317de607406997825d4ee239ec042c9872f0b44c29ebdf00f6540aa5 ./docs/TRANSLATION_OUTPUT.md
5c4d63f01581cdbc21d7ff9da8604adf8230e280b42512e3375cd0a72a225f5a ./docs/USER_GUIDE.md
373b20746a6ed145ee598786458a97cead5cacd97a339db14b3e2341645c6c8d ./evaluation/README.md
a60f1917c64ac8c3df0d01dd55818652ae100a6d750c34be24675b33226cad45 ./evaluation/corpus.example.json
a5c4b95257aa02eca20ae98acf68dee329acb870f16fb3ac549038627327da71 ./evaluation/corpus.schema.json
6a54dadd3426cfc011c8b02b9c9b935f6ba4bbbdc5db38ee59377d71a8919833 ./opencode.json
2b065f1791c31305ba1e9c018ffd439a04f82110e96a55f05e67311926cfd6e0 ./project.yml
e0628748753d6c8952f05c7da78a632632c2fedd6c9632bc8d9c7bba42127e51 ./project.yml
749bfb269c22aed25e67b73abfda7055aee645b68a9907f292ef5c1c38366eae ./scripts/bootstrap.sh
443548848c9ce9edb9ce54efac6158e6cc63e69b40259dab4edb6ead89972373 ./scripts/capture-fixtures.sh
aa9531690d41071e34dfcb33241bb576f7349092d52c36242cedf55af7ca9c46 ./scripts/capture-fixtures.sh
495f78822630ac48a91e21a06c5d96f4ffbb4a38b8b7ee5b591faeaeb1fdbbd0 ./scripts/check-signature.sh
fb00d11b43730fd5a22a2b9c9d2bb19dda9933507972071d5cf68fe19f09d60f ./scripts/generate-app-icon.swift
ff66487399a93eb08890b8b85027df2db6572c85a183baec823b1f697014a7a7 ./scripts/make-dmg.sh
85eef8a97a24d834b7119788f11559c3fc5ab40be87ca2a244abae85801d8cac ./scripts/manifest.sh
d8f5a7fd6907772e961e129920af66290257b3299beae867639abcf956d71fb8 ./scripts/opencode-check.sh
50d0a6b4f78eca45363a7dded4efd1e6332628127e5f634b0bbba1215a499830 ./scripts/privacy-check.sh
480dee8c4969ed231f5d58e8c66999940aae2fa707ac964fd19b4671ce1ad83a ./scripts/privacy-check.sh
eba6aa14e31e41da73792503e946251691d635a45124d7150433227a218dc330 ./scripts/privacy-self-test.sh
52a752481678227da453b0487043f2d0950862791ef75dab71f695f78950a514 ./scripts/release.sh
0cf1aee371a3a98429906be86de2832c5649e8212f2eb35a5433990a0b15ad5d ./scripts/smoke-ollama.sh
dca61cd7f7833ecb5c72347c526a69bafab7499fe05c21c67f0b8dee71d50245 ./scripts/verify.sh
1a17309daafb04fc4880d74df39ab711c33694b6405cc375681d4fdfd9af9f9c ./scripts/verify.sh
+1
View File
@@ -14,6 +14,7 @@ let package = Package(
products: [
.library(name: "SprachmittlerCore", targets: ["SprachmittlerCore"]),
.library(name: "SprachmittlerCapture", targets: ["SprachmittlerCapture"]),
.library(name: "SprachmittlerText", targets: ["SprachmittlerText"]),
.executable(name: "sprachmittler-cli", targets: ["sprachmittler-cli"]),
],
dependencies: [
@@ -30,6 +30,9 @@ public final class PasteboardWatcher {
private var suppressUntil = Date.distantPast
private var task: Task<Void, Never>?
/// The capture limits used by the next poll.
public var limits: CaptureLimits
/// True while the poll task is running.
public private(set) var isRunning = false
@@ -38,11 +41,13 @@ public final class PasteboardWatcher {
pasteboard: any PasteboardAccessing,
configuration: DoubleCopyDetector.Configuration = DoubleCopyDetector.Configuration(),
ticker: any PasteboardTicking = TimerPasteboardTicker(),
limits: CaptureLimits = CaptureLimits(),
now: @escaping @MainActor () -> Date = { Date() }
) {
self.pasteboard = pasteboard
detector = DoubleCopyDetector(configuration: configuration)
self.ticker = ticker
self.limits = limits
self.now = now
lastChangeCount = pasteboard.changeCount
}
@@ -102,7 +107,7 @@ public final class PasteboardWatcher {
case .empty:
return .noText
case let .captured(text):
let limit = CaptureLimits.characters(for: text)
let limit = limits.captureLimit(for: text)
guard text.count <= limit else {
detector.reset()
return .textTooLong(characters: text.count, limit: limit)
@@ -0,0 +1,102 @@
import Foundation
import SprachmittlerEngines
public extension AppSettings {
init(from decoder: any Decoder) throws {
let defaults = AppSettings()
let container = try decoder.container(keyedBy: CodingKeys.self)
endpoint = try container.decodeIfPresent(URL.self, forKey: .endpoint) ?? defaults.endpoint
allowRemoteEndpoint = try container.decodeIfPresent(Bool.self, forKey: .allowRemoteEndpoint)
?? defaults.allowRemoteEndpoint
model = try container.decodeIfPresent(String.self, forKey: .model) ?? defaults.model
fastModel = container.contains(.fastModel)
? try container.decodeIfPresent(String.self, forKey: .fastModel)
: defaults.fastModel
let decodedTarget = try container.decodeIfPresent(String.self, forKey: .targetLanguage)
?? defaults.targetLanguage
targetLanguage = HyMT3Languages.resolve(decodedTarget)?.code ?? defaults.targetLanguage
languageRoutes = try AppSettings.normalizedRoutes(
container.decodeIfPresent([LanguageRoute].self, forKey: .languageRoutes) ?? []
)
recentTargetLanguages = try Self.decodeRecentTargets(from: container)
let limits = try Self.decodeLimits(from: container, defaults: defaults)
doubleCopyWindowMs = limits.window
maxCharactersLatin = limits.latin
maxCharactersCJK = limits.cjk
maximumPartsPerSelection = limits.parts
numCtx = limits.numCtx
numPredict = limits.numPredict
translationFontSize = limits.fontSize
let sampling = try Self.decodeSampling(from: container, defaults: defaults)
temperature = sampling.temperature
topP = sampling.topP
topK = sampling.topK
repeatPenalty = sampling.repeatPenalty
let keep = try container.decodeIfPresent(String.self, forKey: .keepModelLoaded)
?? defaults.keepModelLoaded
keepModelLoaded = ["5m", "30m", "1h", "0"].contains(keep) ? keep : defaults.keepModelLoaded
warmUpOnLaunch = try container.decodeIfPresent(Bool.self, forKey: .warmUpOnLaunch) ?? defaults.warmUpOnLaunch
let policy = try container.decodeIfPresent(PromptVariantPolicy.self, forKey: .promptVariantPolicy)
?? defaults.promptVariantPolicy
promptVariantPolicy = policy
// Auto-copy is a hard invariant: decoding cannot turn it on.
autoCopy = false
showSourcePreview = try container.decodeIfPresent(Bool.self, forKey: .showSourcePreview)
?? defaults.showSourcePreview
renderMarkdown = try container.decodeIfPresent(Bool.self, forKey: .renderMarkdown) ?? defaults.renderMarkdown
closeWithEscape = try container.decodeIfPresent(Bool.self, forKey: .closeWithEscape) ?? defaults.closeWithEscape
launchAtLogin = try container.decodeIfPresent(Bool.self, forKey: .launchAtLogin) ?? defaults.launchAtLogin
keepRecentTranslationInMemory = try container.decodeIfPresent(
Bool.self,
forKey: .keepRecentTranslationInMemory
) ?? defaults.keepRecentTranslationInMemory
hasCompletedOnboarding = try container.decodeIfPresent(Bool.self, forKey: .hasCompletedOnboarding)
?? defaults.hasCompletedOnboarding
settingsVersion = Self.currentVersion
}
func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(endpoint, forKey: .endpoint)
try container.encode(allowRemoteEndpoint, forKey: .allowRemoteEndpoint)
try container.encode(model, forKey: .model)
try container.encode(fastModel, forKey: .fastModel)
try container.encode(targetLanguage, forKey: .targetLanguage)
try container.encode(languageRoutes, forKey: .languageRoutes)
try container.encode(recentTargetLanguages, forKey: .recentTargetLanguages)
try container.encode(doubleCopyWindowMs, forKey: .doubleCopyWindowMs)
try container.encode(maxCharactersLatin, forKey: .maxCharactersLatin)
try container.encode(maxCharactersCJK, forKey: .maxCharactersCJK)
try container.encode(maximumPartsPerSelection, forKey: .maximumPartsPerSelection)
try container.encode(numCtx, forKey: .numCtx)
try container.encode(numPredict, forKey: .numPredict)
try container.encode(temperature, forKey: .temperature)
try container.encode(topP, forKey: .topP)
try container.encode(topK, forKey: .topK)
try container.encode(repeatPenalty, forKey: .repeatPenalty)
try container.encode(keepModelLoaded, forKey: .keepModelLoaded)
try container.encode(warmUpOnLaunch, forKey: .warmUpOnLaunch)
try container.encode(promptVariantPolicy, forKey: .promptVariantPolicy)
try container.encode(autoCopy, forKey: .autoCopy)
try container.encode(showSourcePreview, forKey: .showSourcePreview)
try container.encode(translationFontSize, forKey: .translationFontSize)
try container.encode(renderMarkdown, forKey: .renderMarkdown)
try container.encode(closeWithEscape, forKey: .closeWithEscape)
try container.encode(launchAtLogin, forKey: .launchAtLogin)
try container.encode(keepRecentTranslationInMemory, forKey: .keepRecentTranslationInMemory)
try container.encode(hasCompletedOnboarding, forKey: .hasCompletedOnboarding)
try container.encode(settingsVersion, forKey: .settingsVersion)
}
private static func decodeRecentTargets(
from container: KeyedDecodingContainer<CodingKeys>
) throws -> [String] {
let recents = try container.decodeIfPresent([String].self, forKey: .recentTargetLanguages) ?? []
var seen = Set<String>()
return recents.compactMap { HyMT3Languages.resolve($0)?.code }
.filter { seen.insert($0).inserted }
.prefix(3)
.map(\.self)
}
}
@@ -27,8 +27,10 @@ public struct AppSettings: Codable, Sendable, Equatable {
public var model: String
/// The optional Fast model tag.
public var fastModel: String?
/// The selected target BCP-47 code.
/// The mother tongue BCP-47 code; the default target when no rule matches.
public var targetLanguage: String
/// Source-language to target-language rules. Empty means everything goes to the mother tongue.
public var languageRoutes: [LanguageRoute]
/// Up to three recent target codes, most recent first.
public var recentTargetLanguages: [String]
/// The double-copy window in milliseconds (300–1000).
@@ -37,6 +39,8 @@ public struct AppSettings: Codable, Sendable, Equatable {
public var maxCharactersLatin: Int
/// The dense-script chunk limit.
public var maxCharactersCJK: Int
/// How many chunks one capture may contain (1–8). `1` rejects text longer than one chunk.
public var maximumPartsPerSelection: Int
/// `num_ctx`.
public var numCtx: Int
/// `num_predict`.
@@ -61,6 +65,10 @@ public struct AppSettings: Codable, Sendable, Equatable {
public var showSourcePreview: Bool
/// Translation text size in points (12–28).
public var translationFontSize: Int
/// Render Markdown formatting in the translation panel.
public var renderMarkdown: Bool
/// Make the panel key when shown so Esc and the shortcuts work without a click.
public var closeWithEscape: Bool
/// Reflect the login-item setting.
public var launchAtLogin: Bool
/// Keep the last translation in memory for the panel.
@@ -78,10 +86,12 @@ public struct AppSettings: Codable, Sendable, Equatable {
model = HyMT3ModelPreset.defaultModel
fastModel = HyMT3ModelPreset.fastModel
targetLanguage = systemCode ?? HyMT3Languages.english.code
languageRoutes = []
recentTargetLanguages = []
doubleCopyWindowMs = 500
maxCharactersLatin = 4000
maxCharactersCJK = 2000
maximumPartsPerSelection = 1
numCtx = 8192
numPredict = 4096
temperature = 0.7
@@ -94,6 +104,8 @@ public struct AppSettings: Codable, Sendable, Equatable {
autoCopy = false
showSourcePreview = true
translationFontSize = 17
renderMarkdown = true
closeWithEscape = true
launchAtLogin = false
keepRecentTranslationInMemory = true
hasCompletedOnboarding = false
@@ -126,9 +138,11 @@ public struct AppSettings: Codable, Sendable, Equatable {
/// Clamps values edited outside the decoder (Settings UI) to the safe ranges.
public mutating func sanitize() {
targetLanguage = HyMT3Languages.resolve(targetLanguage)?.code ?? HyMT3Languages.english.code
languageRoutes = Self.normalizedRoutes(languageRoutes)
doubleCopyWindowMs = Self.clamp(doubleCopyWindowMs, to: 300 ... 1000)
maxCharactersLatin = Self.clamp(maxCharactersLatin, to: 500 ... 10000)
maxCharactersCJK = Self.clamp(maxCharactersCJK, to: 500 ... 5000)
maxCharactersCJK = Self.clamp(maxCharactersCJK, to: 500 ... 4000)
maximumPartsPerSelection = Self.clamp(maximumPartsPerSelection, to: 1 ... 8)
numCtx = Self.clamp(numCtx, to: 1024 ... 32768)
numPredict = Self.clamp(numPredict, to: 1 ... 8192)
temperature = min(max(temperature, 0), 2)
@@ -159,23 +173,29 @@ public struct AppSettings: Codable, Sendable, Equatable {
Chunker(latinLimit: maxCharactersLatin, denseLimit: maxCharactersCJK)
}
private struct DecodedLimits {
/// The chunk and capture limits derived from the settings.
public var captureLimits: CaptureLimits {
CaptureLimits(chunker: chunker, maximumParts: maximumPartsPerSelection)
}
struct DecodedLimits {
let window: Int
let latin: Int
let cjk: Int
let parts: Int
let numCtx: Int
let numPredict: Int
let fontSize: Int
}
private struct DecodedSampling {
struct DecodedSampling {
let temperature: Double
let topP: Double
let topK: Int
let repeatPenalty: Double
}
private static func decodeLimits(
static func decodeLimits(
from container: KeyedDecodingContainer<CodingKeys>,
defaults: AppSettings
) throws -> DecodedLimits {
@@ -193,7 +213,12 @@ public struct AppSettings: Codable, Sendable, Equatable {
cjk: clamp(
container.decodeIfPresent(Int.self, forKey: .maxCharactersCJK)
?? defaults.maxCharactersCJK,
to: 500 ... 5000
to: 500 ... 4000
),
parts: clamp(
container.decodeIfPresent(Int.self, forKey: .maximumPartsPerSelection)
?? defaults.maximumPartsPerSelection,
to: 1 ... 8
),
numCtx: clamp(
container.decodeIfPresent(Int.self, forKey: .numCtx) ?? defaults.numCtx,
@@ -211,7 +236,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
)
}
private static func decodeSampling(
static func decodeSampling(
from container: KeyedDecodingContainer<CodingKeys>,
defaults: AppSettings
) throws -> DecodedSampling {
@@ -231,101 +256,32 @@ public struct AppSettings: Codable, Sendable, Equatable {
)
}
private enum CodingKeys: String, CodingKey {
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, recentTargetLanguages
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, numCtx, numPredict
enum CodingKeys: String, CodingKey {
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, languageRoutes
case recentTargetLanguages
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, maximumPartsPerSelection
case numCtx, numPredict
case temperature, topP, topK, repeatPenalty, keepModelLoaded, warmUpOnLaunch
case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, launchAtLogin
case keepRecentTranslationInMemory, hasCompletedOnboarding, settingsVersion
case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, renderMarkdown
case closeWithEscape, launchAtLogin, keepRecentTranslationInMemory, hasCompletedOnboarding
case settingsVersion
}
/// Decodes with v0 migration: missing or unknown fields fall back to defaults, and an old
/// `settingsVersion` is upgraded to the current one. Unknown keys are ignored by Codable.
public init(from decoder: any Decoder) throws {
let defaults = AppSettings()
let container = try decoder.container(keyedBy: CodingKeys.self)
endpoint = try container.decodeIfPresent(URL.self, forKey: .endpoint) ?? defaults.endpoint
allowRemoteEndpoint = try container.decodeIfPresent(Bool.self, forKey: .allowRemoteEndpoint)
?? defaults.allowRemoteEndpoint
model = try container.decodeIfPresent(String.self, forKey: .model) ?? defaults.model
fastModel = container.contains(.fastModel)
? try container.decodeIfPresent(String.self, forKey: .fastModel)
: defaults.fastModel
let decodedTarget = try container.decodeIfPresent(String.self, forKey: .targetLanguage)
?? defaults.targetLanguage
targetLanguage = HyMT3Languages.resolve(decodedTarget)?.code ?? defaults.targetLanguage
let recents = try container.decodeIfPresent([String].self, forKey: .recentTargetLanguages) ?? []
static func normalizedRoutes(_ routes: [LanguageRoute]) -> [LanguageRoute] {
var seen = Set<String>()
recentTargetLanguages = recents.compactMap { HyMT3Languages.resolve($0)?.code }
.filter { seen.insert($0).inserted }
.prefix(3)
.map(\.self)
let limits = try Self.decodeLimits(from: container, defaults: defaults)
doubleCopyWindowMs = limits.window
maxCharactersLatin = limits.latin
maxCharactersCJK = limits.cjk
numCtx = limits.numCtx
numPredict = limits.numPredict
translationFontSize = limits.fontSize
let sampling = try Self.decodeSampling(from: container, defaults: defaults)
temperature = sampling.temperature
topP = sampling.topP
topK = sampling.topK
repeatPenalty = sampling.repeatPenalty
let keep = try container.decodeIfPresent(String.self, forKey: .keepModelLoaded)
?? defaults.keepModelLoaded
keepModelLoaded = ["5m", "30m", "1h", "0"].contains(keep) ? keep : defaults.keepModelLoaded
warmUpOnLaunch = try container.decodeIfPresent(Bool.self, forKey: .warmUpOnLaunch)
?? defaults.warmUpOnLaunch
let policy = try container.decodeIfPresent(PromptVariantPolicy.self, forKey: .promptVariantPolicy)
?? defaults.promptVariantPolicy
promptVariantPolicy = policy
// Auto-copy is a hard invariant: decoding cannot turn it on.
autoCopy = false
showSourcePreview = try container.decodeIfPresent(Bool.self, forKey: .showSourcePreview)
?? defaults.showSourcePreview
launchAtLogin = try container.decodeIfPresent(Bool.self, forKey: .launchAtLogin)
?? defaults.launchAtLogin
keepRecentTranslationInMemory = try container.decodeIfPresent(
Bool.self,
forKey: .keepRecentTranslationInMemory
) ?? defaults.keepRecentTranslationInMemory
hasCompletedOnboarding = try container.decodeIfPresent(Bool.self, forKey: .hasCompletedOnboarding)
?? defaults.hasCompletedOnboarding
settingsVersion = Self.currentVersion
return routes.compactMap { route in
guard let source = HyMT3Languages.resolve(route.source)?.code,
let target = HyMT3Languages.resolve(route.target)?.code,
source.caseInsensitiveCompare(target) != .orderedSame,
seen.insert(source.lowercased()).inserted
else {
return nil
}
return LanguageRoute(source: source, target: target)
}
}
public func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(endpoint, forKey: .endpoint)
try container.encode(allowRemoteEndpoint, forKey: .allowRemoteEndpoint)
try container.encode(model, forKey: .model)
try container.encode(fastModel, forKey: .fastModel)
try container.encode(targetLanguage, forKey: .targetLanguage)
try container.encode(recentTargetLanguages, forKey: .recentTargetLanguages)
try container.encode(doubleCopyWindowMs, forKey: .doubleCopyWindowMs)
try container.encode(maxCharactersLatin, forKey: .maxCharactersLatin)
try container.encode(maxCharactersCJK, forKey: .maxCharactersCJK)
try container.encode(numCtx, forKey: .numCtx)
try container.encode(numPredict, forKey: .numPredict)
try container.encode(temperature, forKey: .temperature)
try container.encode(topP, forKey: .topP)
try container.encode(topK, forKey: .topK)
try container.encode(repeatPenalty, forKey: .repeatPenalty)
try container.encode(keepModelLoaded, forKey: .keepModelLoaded)
try container.encode(warmUpOnLaunch, forKey: .warmUpOnLaunch)
try container.encode(promptVariantPolicy, forKey: .promptVariantPolicy)
try container.encode(autoCopy, forKey: .autoCopy)
try container.encode(showSourcePreview, forKey: .showSourcePreview)
try container.encode(translationFontSize, forKey: .translationFontSize)
try container.encode(launchAtLogin, forKey: .launchAtLogin)
try container.encode(keepRecentTranslationInMemory, forKey: .keepRecentTranslationInMemory)
try container.encode(hasCompletedOnboarding, forKey: .hasCompletedOnboarding)
try container.encode(settingsVersion, forKey: .settingsVersion)
}
private static func clamp(_ value: Int, to range: ClosedRange<Int>) -> Int {
static func clamp(_ value: Int, to range: ClosedRange<Int>) -> Int {
min(max(value, range.lowerBound), range.upperBound)
}
}
@@ -1,9 +1,28 @@
import SprachmittlerText
/// The capture character limit for a text, based on its script (`docs/TRANSLATION_OUTPUT.md` §3).
public enum CaptureLimits {
/// 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts.
public static func characters(for text: String) -> Int {
Chunker().limit(for: text)
/// The per-request chunk size and the total size one capture may have.
///
/// `maximumParts == 1` rejects anything longer than one chunk. Higher values accept up to
/// `maximumParts` chunks and translate them sequentially (`docs/TRANSLATION_OUTPUT.md` §3).
public struct CaptureLimits: Sendable, Equatable {
/// The per-request chunk size.
public let chunker: Chunker
/// How many chunks one capture may contain (at least 1).
public let maximumParts: Int
/// Creates limits.
public init(chunker: Chunker = Chunker(), maximumParts: Int = 1) {
self.chunker = chunker
self.maximumParts = max(1, maximumParts)
}
/// The per-chunk character limit for `text`.
public func chunkLimit(for text: String) -> Int {
chunker.limit(for: text)
}
/// The total character limit for one capture.
public func captureLimit(for text: String) -> Int {
chunkLimit(for: text) * maximumParts
}
}
@@ -12,10 +12,10 @@ public enum CaptureValidation: Sendable, Equatable {
/// Applies the capture rules shared by double copy, the menu and Services.
public enum CapturePolicy {
/// Validates non-emptiness and the 4000/2000 script-aware limit.
public static func validate(_ text: String) -> CaptureValidation {
/// Validates non-emptiness and the capture limit (`chunk size × maximum parts`).
public static func validate(_ text: String, limits: CaptureLimits = CaptureLimits()) -> CaptureValidation {
guard text.contains(where: { !$0.isWhitespace }) else { return .empty }
let limit = CaptureLimits.characters(for: text)
let limit = limits.captureLimit(for: text)
let characters = text.count
guard characters <= limit else {
return .textTooLong(characters: characters, limit: limit)
@@ -1,6 +1,7 @@
import Foundation
import Observation
import SprachmittlerEngines
import SprachmittlerText
/// The panel phase from `docs/ARCHITECTURE.md` §10.
public enum PanelPhase: Sendable, Equatable {
@@ -20,6 +21,8 @@ public enum PanelPhase: Sendable, Equatable {
public struct PanelConfiguration: Sendable, Equatable {
/// The selected target language.
public var target: ModelLanguage
/// Source-to-target rules. Empty means everything goes to `target` (the mother tongue).
public var languageRoutes: [LanguageRoute]
/// The selected model tag.
public var model: String
/// The Ollama keep-alive value.
@@ -30,8 +33,14 @@ public struct PanelConfiguration: Sendable, Equatable {
public var showSourcePreview: Bool
/// Translation text size in points.
public var translationFontSize: Int
/// Render Markdown formatting for Markdown sources.
public var renderMarkdown: Bool
/// Make the panel key when shown so Esc works without a click.
public var closeWithEscape: Bool
/// Recent targets, most recent first.
public var recentTargets: [ModelLanguage]
/// The chunk and capture limits accepted for this capture.
public var captureLimits: CaptureLimits
/// Creates a configuration.
public init(
@@ -41,7 +50,11 @@ public struct PanelConfiguration: Sendable, Equatable {
sampling: SamplingOptions = .publisherDefault,
showSourcePreview: Bool = true,
translationFontSize: Int = 17,
recentTargets: [ModelLanguage] = []
renderMarkdown: Bool = true,
closeWithEscape: Bool = true,
languageRoutes: [LanguageRoute] = [],
recentTargets: [ModelLanguage] = [],
captureLimits: CaptureLimits = CaptureLimits()
) {
self.target = target
self.model = model
@@ -49,7 +62,11 @@ public struct PanelConfiguration: Sendable, Equatable {
self.sampling = sampling
self.showSourcePreview = showSourcePreview
self.translationFontSize = translationFontSize
self.renderMarkdown = renderMarkdown
self.closeWithEscape = closeWithEscape
self.languageRoutes = languageRoutes
self.recentTargets = recentTargets
self.captureLimits = captureLimits
}
}
@@ -75,10 +92,20 @@ public final class PanelViewModel {
public private(set) var didCopy = false
/// True while a Replace action is running.
public private(set) var isReplacing = false
/// The current target, model and prompt settings.
/// The current target, model and prompt settings. `target` is the user's saved preference.
public private(set) var configuration: PanelConfiguration
/// The target used by the current request, after a language rule or an explicit picker choice.
public private(set) var effectiveTarget: ModelLanguage
/// The matched rule source when `effectiveTarget` differs from the mother tongue, or nil.
public private(set) var routedSource: ModelLanguage?
/// True after the user dismisses the same-language advisory.
public private(set) var sameLanguageDismissed = false
/// The number of parts in the last finished translation.
public private(set) var chunkCount = 1
/// The current part while a multi-part request runs.
public private(set) var currentChunk: Int?
/// The total parts of the current multi-part request.
public private(set) var totalChunks: Int?
/// The copy action. The composition root writes with own-write markers.
public let copy: @MainActor (String) -> Void
@@ -92,9 +119,11 @@ public final class PanelViewModel {
public let onTargetChanged: @MainActor (ModelLanguage) -> Void
private let session: TranslationSession
private let detector: any LanguageDetecting
private var eventTask: Task<Void, Never>?
private var currentEpoch: UInt64 = 0
private var lastCaptured: CapturedText?
private var targetOverride: ModelLanguage?
/// Creates a panel model.
public init(
@@ -104,10 +133,13 @@ public final class PanelViewModel {
replace: (@MainActor () async -> InsertionOutcome)? = nil,
onCloseRequest: @escaping @MainActor () -> Void = {},
eventObserver: (@MainActor (TranslationSessionEvent) -> Void)? = nil,
onTargetChanged: @escaping @MainActor (ModelLanguage) -> Void = { _ in }
onTargetChanged: @escaping @MainActor (ModelLanguage) -> Void = { _ in },
detector: any LanguageDetecting = NaturalLanguageDetector()
) {
self.session = session
self.configuration = configuration
effectiveTarget = configuration.target
self.detector = detector
self.copy = copy
self.replace = replace
self.onCloseRequest = onCloseRequest
@@ -172,8 +204,8 @@ public final class PanelViewModel {
error?.recoveryAction
}
/// Synchronously resets the visible state before the panel is shown.
public func prepare(_ captured: CapturedText) {
/// Synchronously resets the visible state before the panel is shown and resolves the direction.
public func prepare(_ captured: CapturedText, resetDirectionOverride: Bool = true) {
currentEpoch = 0
lastCaptured = captured
source = captured
@@ -181,29 +213,49 @@ public final class PanelViewModel {
warnings = []
error = nil
timing = nil
sourceLanguage = nil
didCopy = false
isReplacing = false
sameLanguageDismissed = false
chunkCount = 1
currentChunk = nil
totalChunks = nil
if resetDirectionOverride {
targetOverride = nil
}
let normalized = TextNormalization.normalizeInput(captured.text)
let detection = detector.detect(normalized)
sourceLanguage = detection?.code
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: configuration.target,
routes: configuration.languageRoutes,
detection: detection,
override: targetOverride
)
effectiveTarget = direction.target
routedSource = direction.didRoute ? direction.source : nil
sameLanguageDismissed = targetOverride != nil
phase = .translating
}
/// Starts a translation for a captured text.
public func begin(_ captured: CapturedText) async {
prepare(captured)
await begin(captured, resetDirectionOverride: true)
}
private func begin(_ captured: CapturedText, resetDirectionOverride: Bool) async {
prepare(captured, resetDirectionOverride: resetDirectionOverride)
_ = await session.start(request(for: captured))
}
/// Retries the last captured text.
/// Retries the last captured text without discarding a manual direction choice.
public func retry() async {
guard let lastCaptured else { return }
await begin(lastCaptured)
await begin(lastCaptured, resetDirectionOverride: false)
}
/// Retranslates after an external target change.
/// Retranslates after an external target change and re-evaluates the direction.
public func retranslate() async {
guard let lastCaptured else { return }
await begin(lastCaptured)
await begin(lastCaptured, resetDirectionOverride: true)
}
/// Shows a capture-time error such as a too-long selection.
@@ -217,15 +269,36 @@ public final class PanelViewModel {
warnings = []
timing = nil
sourceLanguage = nil
chunkCount = 1
currentChunk = nil
totalChunks = nil
effectiveTarget = configuration.target
routedSource = nil
targetOverride = nil
}
/// Changes the target and retranslates the current selection.
/// Changes the saved target from the panel and retranslates the current selection.
public func setTarget(_ language: ModelLanguage) async {
guard language.code != configuration.target.code else { return }
guard language.code != effectiveTarget.code else { return }
configuration.target = language
effectiveTarget = language
routedSource = nil
targetOverride = language
onTargetChanged(language)
if let lastCaptured {
await begin(lastCaptured)
await begin(lastCaptured, resetDirectionOverride: false)
}
}
/// Uses another language for this capture only. It does not change the saved target.
public func overrideTarget(_ language: ModelLanguage) async {
guard language.code != effectiveTarget.code else { return }
effectiveTarget = language
routedSource = nil
targetOverride = language
sameLanguageDismissed = true
if let lastCaptured {
await begin(lastCaptured, resetDirectionOverride: false)
}
}
@@ -260,7 +333,13 @@ public final class PanelViewModel {
/// Updates the settings snapshot without restarting the current request.
public func updateConfiguration(_ configuration: PanelConfiguration) {
let targetChanged = configuration.target.code != self.configuration.target.code
self.configuration = configuration
if targetChanged || source == nil {
effectiveTarget = configuration.target
routedSource = nil
targetOverride = nil
}
}
/// Resets the panel and cancels the active request. The event stream stays open.
@@ -276,6 +355,12 @@ public final class PanelViewModel {
didCopy = false
isReplacing = false
sameLanguageDismissed = false
chunkCount = 1
currentChunk = nil
totalChunks = nil
effectiveTarget = configuration.target
routedSource = nil
targetOverride = nil
lastCaptured = nil
}
@@ -288,48 +373,86 @@ public final class PanelViewModel {
private func request(for captured: CapturedText) -> TranslationSessionRequest {
TranslationSessionRequest(
captured: captured,
target: configuration.target,
target: effectiveTarget,
model: configuration.model,
keepAlive: configuration.keepAlive,
sampling: configuration.sampling
sampling: configuration.sampling,
captureLimits: configuration.captureLimits
)
}
}
private extension PanelViewModel {
private func handle(_ event: TranslationSessionEvent) {
switch event {
case let .started(epoch, request):
currentEpoch = epoch
source = request.captured
configuration.target = request.target
translation = ""
warnings = []
error = nil
phase = .translating
handleStarted(epoch: epoch, request: request)
case let .chunkStarted(epoch, index, total):
handleChunkStarted(epoch: epoch, index: index, total: total)
case let .delta(epoch, text):
guard epoch == currentEpoch else { return }
translation += text
phase = .streaming
handleDelta(epoch: epoch, text: text)
case let .finished(epoch, result):
guard epoch == currentEpoch else { return }
translation = result.translation
warnings = result.warnings
timing = result.timing
sourceLanguage = result.sourceLanguage
if result.warnings.contains(.emptyOutput) {
error = .emptyOutput
phase = .failed
} else {
phase = .ready
}
case let .failed(epoch, failure):
guard epoch == currentEpoch else { return }
error = failure
phase = .failed
handleFinished(epoch: epoch, result: result)
case let .failed(epoch, error):
handleFailed(epoch: epoch, error: error)
case let .cancelled(epoch):
guard epoch == currentEpoch else { return }
phase = .idle
error = nil
handleCancelled(epoch: epoch)
}
eventObserver?(event)
}
private func handleStarted(epoch: UInt64, request: TranslationSessionRequest) {
currentEpoch = epoch
source = request.captured
effectiveTarget = request.target
translation = ""
warnings = []
error = nil
chunkCount = 1
currentChunk = nil
totalChunks = nil
phase = .translating
}
private func handleChunkStarted(epoch: UInt64, index: Int, total: Int) {
guard epoch == currentEpoch else { return }
currentChunk = index
totalChunks = total
}
private func handleDelta(epoch: UInt64, text: String) {
guard epoch == currentEpoch else { return }
translation += text
phase = .streaming
}
private func handleFinished(epoch: UInt64, result: PipelineResult) {
guard epoch == currentEpoch else { return }
translation = result.translation
warnings = result.warnings
timing = result.timing
sourceLanguage = result.sourceLanguage
chunkCount = result.chunkCount
currentChunk = nil
totalChunks = nil
if result.warnings.contains(.emptyOutput) {
error = .emptyOutput
phase = .failed
} else {
phase = .ready
}
}
private func handleFailed(epoch: UInt64, error: SprachmittlerError) {
guard epoch == currentEpoch else { return }
self.error = error
currentChunk = nil
phase = .failed
}
private func handleCancelled(epoch: UInt64) {
guard epoch == currentEpoch else { return }
phase = .idle
error = nil
}
}
@@ -28,7 +28,7 @@ public extension SprachmittlerError {
case .emptyText:
"No text was copied."
case let .textTooLong(_, limit):
"This selection is too long (limit \(limit) characters)."
"This selection is too long (limit \(limit) characters). You can raise the limit in Settings."
case .pasteboardUnavailable:
"The clipboard is unavailable."
case .ollamaUnreachable:
@@ -108,7 +108,7 @@ public extension SprachmittlerError {
case .ollamaTooOld, .endpointRejected:
.openSettings
case .textTooLong:
.shortenText
.openSettings
case .accessibilityNotTrusted:
.openSettings
case .accessibilityUnsupported, .insertionTargetChanged, .pasteboardRestoreFailed:
@@ -94,7 +94,8 @@ public struct TranslationPipeline: Sendable {
model: String,
keepAlive: String,
sampling: SamplingOptions = .publisherDefault,
onDelta: (@Sendable (String) async -> Void)? = nil
onDelta: (@Sendable (String) async -> Void)? = nil,
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)? = nil
) async throws -> PipelineResult {
let normalized = TextNormalization.normalizeInput(text)
guard !normalized.isEmpty else {
@@ -118,7 +119,7 @@ public struct TranslationPipeline: Sendable {
tokens: tokens,
onDelta: onDelta
)
let accumulator = try await translateAll(chunks, context: context)
let accumulator = try await translateAll(chunks, context: context, onChunk: onChunk)
let final = TextNormalization.normalizeOutput(accumulator.joined)
let validation = validator.validate(
@@ -168,11 +169,16 @@ public struct TranslationPipeline: Sendable {
var sawLength = false
}
private func translateAll(_ chunks: [TextChunk], context: TranslationContext) async throws -> Accumulator {
private func translateAll(
_ chunks: [TextChunk],
context: TranslationContext,
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)?
) async throws -> Accumulator {
var accumulator = Accumulator()
do {
for chunk in chunks {
for (offset, chunk) in chunks.enumerated() {
try Task.checkCancellation()
await onChunk?(offset + 1, chunks.count)
let result = try await translateChunk(chunk, context: context)
if accumulator.firstTokenAt == nil {
accumulator.firstTokenAt = result.firstTokenAt
@@ -10,6 +10,24 @@ public protocol TranslationStreaming: Sendable {
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult
/// Translates one captured selection, forwarding deltas and the start of each chunk.
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?,
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)?
) async throws -> PipelineResult
}
public extension TranslationStreaming {
/// Fakes that do not report chunk progress use this fallback.
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?,
onChunk: (@Sendable (Int, Int) async -> Void)?
) async throws -> PipelineResult {
try await translate(request, onDelta: onDelta)
}
}
extension TranslationPipeline: TranslationStreaming {}
@@ -28,6 +46,22 @@ public extension TranslationPipeline {
onDelta: onDelta
)
}
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?,
onChunk: (@Sendable (Int, Int) async -> Void)?
) async throws -> PipelineResult {
try await translate(
text: request.captured.text,
target: request.target,
model: request.model,
keepAlive: request.keepAlive,
sampling: request.sampling,
onDelta: onDelta,
onChunk: onChunk
)
}
}
/// One translation request, including the settings snapshot it was built from.
@@ -42,6 +76,8 @@ public struct TranslationSessionRequest: Sendable, Equatable {
public let keepAlive: String
/// The sampling values.
public let sampling: SamplingOptions
/// The chunk and capture limits accepted for this capture.
public let captureLimits: CaptureLimits
/// Creates a request.
public init(
@@ -49,13 +85,15 @@ public struct TranslationSessionRequest: Sendable, Equatable {
target: ModelLanguage,
model: String,
keepAlive: String,
sampling: SamplingOptions = .publisherDefault
sampling: SamplingOptions = .publisherDefault,
captureLimits: CaptureLimits = CaptureLimits()
) {
self.captured = captured
self.target = target
self.model = model
self.keepAlive = keepAlive
self.sampling = sampling
self.captureLimits = captureLimits
}
}
@@ -63,6 +101,8 @@ public struct TranslationSessionRequest: Sendable, Equatable {
public enum TranslationSessionEvent: Sendable, Equatable {
/// A request started.
case started(epoch: UInt64, request: TranslationSessionRequest)
/// One chunk of a multi-part request started (`index` is 1-based).
case chunkStarted(epoch: UInt64, index: Int, total: Int)
/// One streamed delta.
case delta(epoch: UInt64, text: String)
/// The final validated result.
@@ -102,16 +142,7 @@ public actor TranslationSession {
let currentEpoch = epoch
continuation.yield(.started(epoch: currentEpoch, request: request))
switch CapturePolicy.validate(request.captured.text) {
case .valid:
break
case .empty:
continuation.yield(.failed(epoch: currentEpoch, error: .emptyText))
return currentEpoch
case let .textTooLong(characters, limit):
continuation.yield(
.failed(epoch: currentEpoch, error: .textTooLong(characters: characters, limit: limit))
)
guard validate(request, epoch: currentEpoch) else {
return currentEpoch
}
@@ -122,6 +153,9 @@ public actor TranslationSession {
request,
onDelta: { delta in
await self.forwardDelta(epoch: currentEpoch, text: delta)
},
onChunk: { index, total in
await self.forwardChunk(epoch: currentEpoch, index: index, total: total)
}
)
self.finish(epoch: currentEpoch, result: result)
@@ -166,11 +200,31 @@ public actor TranslationSession {
task = nil
}
private func validate(_ request: TranslationSessionRequest, epoch eventEpoch: UInt64) -> Bool {
switch CapturePolicy.validate(request.captured.text, limits: request.captureLimits) {
case .valid:
return true
case .empty:
continuation.yield(.failed(epoch: eventEpoch, error: .emptyText))
return false
case let .textTooLong(characters, limit):
continuation.yield(
.failed(epoch: eventEpoch, error: .textTooLong(characters: characters, limit: limit))
)
return false
}
}
private func forwardDelta(epoch eventEpoch: UInt64, text: String) {
guard eventEpoch == epoch else { return }
continuation.yield(.delta(epoch: eventEpoch, text: text))
}
private func forwardChunk(epoch eventEpoch: UInt64, index: Int, total: Int) {
guard eventEpoch == epoch else { return }
continuation.yield(.chunkStarted(epoch: eventEpoch, index: index, total: total))
}
private func finish(epoch eventEpoch: UInt64, result: PipelineResult) {
guard eventEpoch == epoch else { return }
task = nil
@@ -3,14 +3,14 @@ import SprachmittlerText
/// Family-neutral same-language check used by the pipeline. The canonical-code mapping stays in
/// Engines, next to the catalogue that defines it.
public enum LanguageMatching {
/// True when detection is confident and every alternative resolves to the target language.
public static func isSameLanguage(_ detection: LanguageDetection, target: ModelLanguage) -> Bool {
/// True when detection is confident and every meaningful alternative resolves to `language`.
public static func isLanguage(_ detection: LanguageDetection, _ language: ModelLanguage) -> Bool {
guard detection.confidence >= 0.5, !detection.alternatives.isEmpty else { return false }
let targetCode = HyMT3Languages.resolve(target.code)?.code ?? target.code
let targetCode = HyMT3Languages.resolve(language.code)?.code ?? language.code
var agreed = false
for code in detection.alternatives {
guard let language = HyMT3Languages.resolve(code),
language.code.caseInsensitiveCompare(targetCode) == .orderedSame
guard let resolved = HyMT3Languages.resolve(code),
resolved.code.caseInsensitiveCompare(targetCode) == .orderedSame
else {
return false
}
@@ -18,4 +18,9 @@ public enum LanguageMatching {
}
return agreed
}
/// True when detection is confident and every meaningful alternative is the target language.
public static func isSameLanguage(_ detection: LanguageDetection, target: ModelLanguage) -> Bool {
isLanguage(detection, target)
}
}
@@ -0,0 +1,35 @@
import Foundation
/// A source-language to target-language rule. The mother tongue is the default when no rule matches.
public struct LanguageRoute: Codable, Sendable, Equatable, Hashable, Identifiable {
/// The canonical BCP-47 source code.
public var source: String
/// The canonical BCP-47 target code.
public var target: String
/// The source code is unique in the rule table.
public var id: String {
source
}
/// Creates a route from canonical codes.
public init(source: String, target: String) {
self.source = source
self.target = target
}
/// Creates a route from catalogue entries.
public init(source: ModelLanguage, target: ModelLanguage) {
self.init(source: source.code, target: target.code)
}
/// The catalogue entry for the source, or nil when the code is unknown.
public var sourceLanguage: ModelLanguage? {
HyMT3Languages.resolve(source)
}
/// The catalogue entry for the target, or nil when the code is unknown.
public var targetLanguage: ModelLanguage? {
HyMT3Languages.resolve(target)
}
}
@@ -0,0 +1,55 @@
import SprachmittlerText
/// The effective target for one translation, after a language rule or an explicit override.
public struct TranslationDirection: Sendable, Equatable {
/// The language the request will translate into.
public let target: ModelLanguage
/// True when a language rule changed the target.
public let didRoute: Bool
/// The rule source when `didRoute` is true.
public let source: ModelLanguage?
/// Creates a direction.
public init(target: ModelLanguage, didRoute: Bool, source: ModelLanguage?) {
self.target = target
self.didRoute = didRoute
self.source = source
}
}
/// Chooses the direction for a capture. Detection stays advisory: a switch needs the same
/// high-confidence agreement as the same-language advisory.
public enum TranslationDirectionPolicy {
/// Resolves the target.
///
/// - Parameters:
/// - configuredTarget: The user's mother tongue, used when no rule matches.
/// - routes: The source-to-target rules.
/// - detection: The advisory source-language detection.
/// - override: An explicit target choice for the current capture, or nil to use the routes.
public static func resolve(
configuredTarget: ModelLanguage,
routes: [LanguageRoute],
detection: LanguageDetection?,
override: ModelLanguage?
) -> TranslationDirection {
if let override {
return TranslationDirection(target: override, didRoute: false, source: nil)
}
guard let detection else {
return TranslationDirection(target: configuredTarget, didRoute: false, source: nil)
}
for route in routes {
guard let source = route.sourceLanguage,
let target = route.targetLanguage,
target.code.caseInsensitiveCompare(source.code) != .orderedSame,
target.code.caseInsensitiveCompare(configuredTarget.code) != .orderedSame,
LanguageMatching.isLanguage(detection, source)
else {
continue
}
return TranslationDirection(target: target, didRoute: true, source: source)
}
return TranslationDirection(target: configuredTarget, didRoute: false, source: nil)
}
}
@@ -4,7 +4,7 @@ import Foundation
///
/// Joining `chunks(for:)` with `reassemble(_:)` always returns the input exactly. The chunker does
/// not trim, normalise or invent separators; call `TextNormalization.normalizeInput` first.
public struct Chunker: Sendable {
public struct Chunker: Sendable, Equatable {
/// The limit for Latin, Cyrillic and Greek text.
public let latinLimit: Int
/// The limit for CJK, Arabic, Thai, Indic and other dense scripts.
@@ -37,10 +37,16 @@ public struct NaturalLanguageDetector: LanguageDetecting {
let recognizer = NLLanguageRecognizer()
recognizer.processString(trimmed)
guard let dominant = recognizer.dominantLanguage else { return nil }
let hypotheses = recognizer.languageHypotheses(withMaximum: 3)
let ordered = hypotheses.sorted { lhs, rhs in
lhs.value == rhs.value ? lhs.key.rawValue < rhs.key.rawValue : lhs.value > rhs.value
}.map(\.key.rawValue)
let hypotheses = recognizer.languageHypotheses(withMaximum: 5)
// NLLanguageRecognizer returns many near-zero hypotheses. Keep only candidates that
// carry meaningful evidence, so a confident single-language text is not treated as mixed.
let minimumAlternativeConfidence = 0.05
let ordered = hypotheses
.filter { $0.value >= minimumAlternativeConfidence }
.sorted { lhs, rhs in
lhs.value == rhs.value ? lhs.key.rawValue < rhs.key.rawValue : lhs.value > rhs.value
}
.map(\.key.rawValue)
let alternatives = ordered.isEmpty ? [dominant.rawValue] : ordered
return LanguageDetection(
code: dominant.rawValue,
@@ -0,0 +1,269 @@
import Foundation
/// A block-level element produced by the conservative Markdown presentation parser.
///
/// The cases carry raw inline Markdown; the app parses that with
/// ``MarkdownPresentation/inline(_:)``. The parser is presentation-only: it never changes the
/// translation that is validated, copied or inserted.
public enum MarkdownBlock: Equatable, Sendable {
/// A paragraph, with soft line breaks preserved.
case paragraph(String)
/// An ATX heading (`#`…`######`).
case heading(level: Int, text: String)
/// One list item. `indent` is a display indentation in steps, `number` is the ordinal for ordered lists.
case listItem(ordered: Bool, number: Int, indent: Int, text: String)
/// A block quote, with one level of `>` removed.
case quote(String)
/// A fenced code block.
case codeBlock(language: String?, text: String)
/// A thematic break (`---`, `***`, `___`).
case rule
}
/// Presentation-only Markdown parsing for the translation panel.
///
/// Inline formatting comes from Foundation's Markdown parser. Block structure is parsed here with a
/// deliberately small set of rules: anything that is not recognised stays visible as plain text
/// rather than being silently dropped.
public enum MarkdownPresentation {
private static let classifier = ContentClassifier()
private static let inlineDetectionPatterns = [
#"\*\*[^*\n]+\*\*"#,
#"(?<![\w*])\*[^*\s][^*\n]*\*(?![\w*])"#,
#"(?<![\w_])__[^_\n]+__(?![\w_])"#,
#"~~[^~\n]+~~"#,
#"`[^`\n]+`"#,
#"\[[^\]\n]+\]\([^)\s]+\)"#,
]
/// Whether the panel should render this source/translation pair as Markdown.
///
/// JSON, HTML and code are never rendered as Markdown, so their text is not mangled. Plain or
/// delimiter-heavy text is rendered only when it contains Markdown inline markers.
public static func shouldRender(source: String, translation: String) -> Bool {
let trimmed = source.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return false }
switch classifier.classify(trimmed) {
case .json, .html, .code:
return false
case .markdown:
return true
case .plain, .delimited:
break
}
return hasInlineMarkdown(trimmed) || hasInlineMarkdown(translation)
}
/// Splits `markdown` into display blocks. Unknown constructs stay in a paragraph.
public static func blocks(in markdown: String) -> [MarkdownBlock] {
let normalized = markdown
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
let lines = normalized.components(separatedBy: "\n")
var blocks: [MarkdownBlock] = []
var paragraph: [String] = []
var index = 0
func flushParagraph() {
guard !paragraph.isEmpty else { return }
let text = paragraph.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
if !text.isEmpty {
blocks.append(.paragraph(text))
}
paragraph.removeAll()
}
while index < lines.count {
let raw = lines[index]
let line = raw.trimmingCharacters(in: .whitespaces)
if line.isEmpty {
flushParagraph()
index += 1
} else if let fence = fenceMarker(line) {
flushParagraph()
blocks.append(fencedBlock(lines, index: &index, opening: line, fence: fence))
} else if let heading = heading(in: raw) {
flushParagraph()
blocks.append(heading)
index += 1
} else if isRule(line) {
flushParagraph()
blocks.append(.rule)
index += 1
} else if line.hasPrefix(">") {
flushParagraph()
blocks.append(quoteBlock(lines, index: &index))
} else if let item = listItem(in: raw) {
flushParagraph()
blocks.append(item)
index += 1
} else {
paragraph.append(line)
index += 1
}
}
flushParagraph()
return blocks
}
private static func fencedBlock(
_ lines: [String],
index: inout Int,
opening: String,
fence: (marker: Character, count: Int)
) -> MarkdownBlock {
var code: [String] = []
var closed = false
index += 1
while index < lines.count, !isClosingFence(lines[index], marker: fence.marker) {
code.append(lines[index])
index += 1
}
if index < lines.count {
index += 1
closed = true
}
let info = opening.dropFirst(fence.count).trimmingCharacters(in: .whitespaces)
let language = info.split(separator: " ").first.map(String.init)
var text = code.joined(separator: "\n")
if !closed {
text = text.trimmingCharacters(in: .newlines)
}
return .codeBlock(language: language, text: text)
}
private static func quoteBlock(_ lines: [String], index: inout Int) -> MarkdownBlock {
var quote: [String] = []
while index < lines.count {
let line = lines[index].trimmingCharacters(in: .whitespaces)
guard line.hasPrefix(">") else { break }
var content = String(line.dropFirst())
if content.hasPrefix(" ") {
content.removeFirst()
}
quote.append(content)
index += 1
}
return .quote(quote.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines))
}
/// Parses one inline Markdown fragment. Images are reduced to their alt text so no attachment
/// or remote resource can be requested; malformed input falls back to plain text.
public static func inline(_ text: String) -> AttributedString {
let cleaned = strippingImages(text)
let options = AttributedString.MarkdownParsingOptions(
interpretedSyntax: .inlineOnlyPreservingWhitespace,
failurePolicy: .returnPartiallyParsedIfPossible
)
if let attributed = try? AttributedString(markdown: cleaned, options: options) {
return attributed
}
return AttributedString(cleaned)
}
/// Only explicit web links may be opened. `file:`, `javascript:`, `data:` and app schemes stay inert.
public static func isAllowedLink(_ url: URL) -> Bool {
guard let scheme = url.scheme?.lowercased(), let host = url.host, !host.isEmpty else {
return false
}
return scheme == "http" || scheme == "https"
}
private static func hasInlineMarkdown(_ text: String) -> Bool {
inlineDetectionPatterns.contains { pattern in
text.range(of: pattern, options: .regularExpression) != nil
}
}
private static func strippingImages(_ text: String) -> String {
var result = text.replacingOccurrences(
of: #"!\[([^\]]*)\]\([^)]*\)"#,
with: "$1",
options: .regularExpression
)
result = result.replacingOccurrences(
of: #"<img\b[^>]*>"#,
with: "",
options: [.regularExpression, .caseInsensitive]
)
return result
}
private static func fenceMarker(_ line: String) -> (marker: Character, count: Int)? {
let stripped = line.drop(while: { $0 == " " })
guard let first = stripped.first, first == "`" || first == "~" else { return nil }
let count = stripped.prefix(while: { $0 == first }).count
guard count >= 3 else { return nil }
return (first, count)
}
private static func isClosingFence(_ line: String, marker: Character) -> Bool {
let stripped = line.trimmingCharacters(in: .whitespaces)
guard stripped.count >= 3 else { return false }
return stripped.allSatisfy { $0 == marker }
}
private static func heading(in raw: String) -> MarkdownBlock? {
let leading = raw.prefix(while: { $0 == " " }).count
guard leading <= 3 else { return nil }
let trimmed = raw.dropFirst(leading)
let hashes = trimmed.prefix(while: { $0 == "#" }).count
guard (1 ... 6).contains(hashes) else { return nil }
let rest = trimmed.dropFirst(hashes)
guard rest.isEmpty || rest.first == " " || rest.first == "\t" else { return nil }
var text = rest.trimmingCharacters(in: .whitespaces)
if text.hasSuffix("#") {
text = String(text.reversed().drop(while: { $0 == "#" }).reversed())
.trimmingCharacters(in: .whitespaces)
}
return .heading(level: hashes, text: text)
}
private static func isRule(_ line: String) -> Bool {
let compact = line.replacingOccurrences(of: " ", with: "")
guard compact.count >= 3, let first = compact.first, "-*_".contains(first) else {
return false
}
return compact.allSatisfy { $0 == first }
}
private static func listItem(in raw: String) -> MarkdownBlock? {
var columns = 0
for character in raw {
if character == " " {
columns += 1
} else if character == "\t" {
columns += 4
} else {
break
}
}
let indent = min(columns / 2, 8)
let trimmed = raw.trimmingCharacters(in: .whitespaces)
if let first = trimmed.first, "-*+".contains(first) {
let rest = trimmed.dropFirst()
guard rest.first == " " || rest.first == "\t" else { return nil }
let text = rest.trimmingCharacters(in: .whitespaces)
guard !text.isEmpty else { return nil }
return .listItem(ordered: false, number: 0, indent: indent, text: text)
}
let digits = trimmed.prefix(while: { $0.isNumber })
guard !digits.isEmpty, digits.count <= 9 else { return nil }
let afterDigits = trimmed.dropFirst(digits.count)
guard let delimiter = afterDigits.first, delimiter == "." || delimiter == ")" else {
return nil
}
let rest = afterDigits.dropFirst()
guard rest.first == " " || rest.first == "\t", let number = Int(digits) else { return nil }
let text = rest.trimmingCharacters(in: .whitespaces)
guard !text.isEmpty else { return nil }
return .listItem(ordered: true, number: number, indent: indent, text: text)
}
}
@@ -67,6 +67,31 @@ struct PasteboardWatcherTests {
)
}
@Test func configuredPartsAcceptLongerText() {
let pasteboard = FakePasteboard()
let watcher = PasteboardWatcher(pasteboard: pasteboard, limits: CaptureLimits(maximumParts: 3))
let accepted = String(repeating: "a", count: 12000)
pasteboard.simulateCopy(accepted)
_ = watcher.poll(at: start)
pasteboard.simulateCopy(accepted)
guard case let .captured(captured) = watcher.poll(at: start.addingTimeInterval(0.1)) else {
Issue.record("expected a capture")
return
}
#expect(captured.text.count == 12000)
let tooLong = String(repeating: "a", count: 12001)
watcher.clear()
pasteboard.simulateCopy(tooLong)
_ = watcher.poll(at: start.addingTimeInterval(0.2))
pasteboard.simulateCopy(tooLong)
#expect(
watcher.poll(at: start.addingTimeInterval(0.3))
== .textTooLong(characters: 12001, limit: 12000)
)
}
@Test func ownWritesAreSuppressedFor750Milliseconds() {
let pasteboard = FakePasteboard()
let watcher = PasteboardWatcher(pasteboard: pasteboard)
@@ -16,12 +16,28 @@ struct AppSettingsTests {
#expect(settings.doubleCopyWindowMs == 500)
#expect(settings.maxCharactersLatin == 4000)
#expect(settings.maxCharactersCJK == 2000)
#expect(settings.maximumPartsPerSelection == 1)
#expect(settings.numCtx == 8192)
#expect(settings.translationFontSize == 17)
#expect(settings.languageRoutes.isEmpty)
#expect(settings.renderMarkdown)
#expect(settings.closeWithEscape)
#expect(!settings.autoCopy)
#expect(!settings.hasCompletedOnboarding)
}
@Test func captureLimitsFollowPartsAndScript() {
var settings = AppSettings()
#expect(settings.captureLimits.chunkLimit(for: "a") == 4000)
#expect(settings.captureLimits.captureLimit(for: "a") == 4000)
#expect(settings.captureLimits.captureLimit(for: "你") == 2000)
settings.maximumPartsPerSelection = 4
#expect(settings.captureLimits.captureLimit(for: "a") == 16000)
#expect(settings.captureLimits.captureLimit(for: "你") == 8000)
#expect(settings.captureLimits.maximumParts == 4)
}
@Test func codableRoundTripPreservesValues() throws {
var settings = AppSettings()
settings.endpoint = try #require(URL(string: "https://example.com:11434"))
@@ -30,8 +46,12 @@ struct AppSettingsTests {
settings.noteTarget(HyMT3Languages.german)
settings.temperature = 0.2
settings.translationFontSize = 22
settings.languageRoutes = [LanguageRoute(source: "zh", target: "en")]
settings.renderMarkdown = false
settings.closeWithEscape = false
settings.launchAtLogin = true
settings.hasCompletedOnboarding = true
settings.maximumPartsPerSelection = 4
let data = try JSONEncoder().encode(settings)
let decoded = try JSONDecoder().decode(AppSettings.self, from: data)
@@ -45,6 +65,8 @@ struct AppSettingsTests {
"settingsVersion": 0,
"endpoint": "http://127.0.0.1:11434",
"targetLanguage": "de",
"autoSwitchTarget": true,
"fallbackTargetLanguage": "en",
"autoCopy": true,
"unknownFutureKey": "ignored"
}
@@ -53,7 +75,11 @@ struct AppSettingsTests {
#expect(decoded.settingsVersion == AppSettings.currentVersion)
#expect(decoded.targetLanguage == "de")
#expect(decoded.model == HyMT3ModelPreset.defaultModel)
#expect(decoded.languageRoutes.isEmpty)
#expect(decoded.renderMarkdown)
#expect(decoded.closeWithEscape)
#expect(!decoded.autoCopy)
#expect(decoded.maximumPartsPerSelection == 1)
}
@Test func fastModelCanBeClearedExplicitly() throws {
@@ -91,7 +117,8 @@ struct AppSettingsTests {
let decoded = try JSONDecoder().decode(AppSettings.self, from: Data(json.utf8))
#expect(decoded.doubleCopyWindowMs == 300)
#expect(decoded.maxCharactersLatin == 500)
#expect(decoded.maxCharactersCJK == 5000)
#expect(decoded.maxCharactersCJK == 4000)
#expect(decoded.maximumPartsPerSelection == 1)
#expect(decoded.numCtx == 1024)
#expect(decoded.numPredict == 8192)
#expect(decoded.temperature == 2)
@@ -100,6 +127,7 @@ struct AppSettingsTests {
#expect(decoded.repeatPenalty == 2)
#expect(decoded.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive)
#expect(decoded.translationFontSize == 28)
#expect(decoded.languageRoutes.isEmpty)
#expect(HyMT3Languages.resolve(decoded.targetLanguage) != nil)
}
@@ -111,8 +139,16 @@ struct AppSettingsTests {
settings.topK = 0
settings.keepModelLoaded = "forever"
settings.translationFontSize = 99
settings.languageRoutes = [
LanguageRoute(source: "xx", target: "en"),
LanguageRoute(source: "de", target: "de"),
LanguageRoute(source: "de", target: "en"),
LanguageRoute(source: "zh-Hans", target: "en"),
]
settings.autoCopy = true
settings.targetLanguage = "xx"
settings.targetLanguage = "de"
settings.maxCharactersCJK = 9999
settings.maximumPartsPerSelection = 99
settings.sanitize()
#expect(settings.doubleCopyWindowMs == 300)
@@ -121,6 +157,12 @@ struct AppSettingsTests {
#expect(settings.topK == 1)
#expect(settings.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive)
#expect(settings.translationFontSize == 28)
#expect(settings.maxCharactersCJK == 4000)
#expect(settings.maximumPartsPerSelection == 8)
#expect(settings.languageRoutes == [
LanguageRoute(source: "de", target: "en"),
LanguageRoute(source: "zh", target: "en"),
])
#expect(!settings.autoCopy)
#expect(HyMT3Languages.resolve(settings.targetLanguage) != nil)
}
@@ -1,4 +1,5 @@
import SprachmittlerCore
import SprachmittlerText
import Testing
@Suite("Capture policy")
@@ -25,4 +26,29 @@ struct CapturePolicyTests {
== .textTooLong(characters: 2001, limit: 2000)
)
}
@Test func partsRaiseTheCaptureLimit() {
let limits = CaptureLimits(maximumParts: 3)
#expect(CapturePolicy.validate(String(repeating: "a", count: 12000), limits: limits) == .valid)
#expect(
CapturePolicy.validate(String(repeating: "a", count: 12001), limits: limits)
== .textTooLong(characters: 12001, limit: 12000)
)
#expect(CapturePolicy.validate(String(repeating: "你", count: 6000), limits: limits) == .valid)
#expect(
CapturePolicy.validate(String(repeating: "你", count: 6001), limits: limits)
== .textTooLong(characters: 6001, limit: 6000)
)
}
@Test func maximumPartsIsAtLeastOne() {
#expect(CaptureLimits(maximumParts: 0).maximumParts == 1)
#expect(CaptureLimits(maximumParts: 0).captureLimit(for: "a") == 4000)
}
@Test func chunkerStillSplitsTheAcceptedText() {
let limits = CaptureLimits(maximumParts: 3)
let text = String(repeating: "a", count: 12000)
#expect(limits.chunker.chunks(for: text).count == 3)
}
}
@@ -0,0 +1,51 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerText
import Testing
@testable import SprachmittlerCore
@Suite("Panel chunk progress")
@MainActor
struct PanelChunkingTests {
private let longCaptured = CapturedText(
text: String(repeating: "a", count: 9000),
capturedAt: Date(timeIntervalSince1970: 0),
source: .doubleCopy
)
@Test func reportsPartsAndProgress() async {
let limits = CaptureLimits(maximumParts: 3)
let streaming = GatedMultiPartStreaming()
let (panel, _, _) = makePanel(streaming: streaming, captureLimits: limits)
await panel.begin(longCaptured)
await waitFor { panel.currentChunk == 1 && panel.totalChunks == 3 && !panel.translation.isEmpty }
#expect(panel.phase == .streaming)
#expect(panel.chunkCount == 1)
await streaming.release()
await waitFor { panel.phase == .ready }
#expect(panel.translation == "part1 part2 part3")
#expect(panel.chunkCount == 3)
#expect(panel.currentChunk == nil)
#expect(panel.totalChunks == nil)
#expect(await streaming.requests.first?.captureLimits == limits)
}
@Test func aSinglePartHasNoProgress() async {
let captured = CapturedText(
text: "Hallo.",
capturedAt: Date(timeIntervalSince1970: 0),
source: .doubleCopy
)
let (panel, _, _) = makePanel(streaming: EchoStreaming())
await panel.begin(captured)
await waitFor { panel.phase == .ready }
#expect(panel.chunkCount == 1)
#expect(panel.currentChunk == nil)
#expect(panel.totalChunks == nil)
}
}
@@ -0,0 +1,191 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerText
import Testing
@testable import SprachmittlerCore
@Suite("Panel language routing")
@MainActor
struct PanelRoutingTests {
private let germanCaptured = CapturedText(
text: "Hallo.",
capturedAt: Date(timeIntervalSince1970: 0),
source: .doubleCopy
)
@Test func appliesAMatchingLanguageRule() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, _) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
#expect(panel.effectiveTarget == HyMT3Languages.english)
#expect(panel.routedSource == HyMT3Languages.german)
#expect(panel.configuration.target == HyMT3Languages.german)
#expect(panel.translation == "en")
}
@Test func noRuleKeepsTheMotherTongue() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, _) = makePanel(streaming: EchoStreaming(), detector: detector)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
#expect(panel.effectiveTarget == HyMT3Languages.german)
#expect(panel.routedSource == nil)
#expect(panel.translation == "de")
}
@Test func routesAnArbitrarySourceLanguage() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "fr", confidence: 0.9, alternatives: ["fr"])
)
let (panel, _, _) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "fr", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
#expect(panel.effectiveTarget == HyMT3Languages.english)
#expect(panel.routedSource == HyMT3Languages.resolve("fr"))
#expect(panel.translation == "en")
}
@Test func routeOverrideIsSessionOnly() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, targets) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
await panel.overrideTarget(HyMT3Languages.german)
await waitFor { panel.phase == .ready && panel.translation == "de" }
#expect(panel.effectiveTarget == HyMT3Languages.german)
#expect(panel.routedSource == nil)
#expect(panel.configuration.target == HyMT3Languages.german)
#expect(targets.codes.isEmpty)
}
@Test func pickerChoosesANonMotherTongueTarget() async {
let (panel, _, targets) = makePanel(streaming: EchoStreaming())
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
await panel.overrideTarget(HyMT3Languages.english)
await waitFor { panel.phase == .ready && panel.translation == "en" }
#expect(panel.effectiveTarget == HyMT3Languages.english)
#expect(panel.routedSource == nil)
#expect(panel.configuration.target == HyMT3Languages.german)
#expect(targets.codes.isEmpty)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready && panel.translation == "de" }
#expect(panel.effectiveTarget == HyMT3Languages.german)
}
@Test func pickerOverridesAMatchingRule() async throws {
let french = try #require(HyMT3Languages.resolve("fr"))
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, _) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
#expect(panel.effectiveTarget == HyMT3Languages.english)
await panel.overrideTarget(french)
await waitFor { panel.phase == .ready && panel.translation == "fr" }
#expect(panel.effectiveTarget == french)
#expect(panel.routedSource == nil)
}
@Test func explicitTargetPersistsAndDisablesTheRule() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, targets) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
await panel.setTarget(HyMT3Languages.german)
await waitFor { panel.phase == .ready && panel.translation == "de" }
#expect(targets.codes == ["de"])
#expect(panel.effectiveTarget == HyMT3Languages.german)
#expect(panel.routedSource == nil)
}
@Test func retryKeepsTheManualTarget() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let streaming = EchoStreaming()
let (panel, _, _) = makePanel(
streaming: streaming,
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
await panel.setTarget(HyMT3Languages.german)
await waitFor { panel.phase == .ready && panel.translation == "de" }
await panel.retry()
await waitFor { panel.phase == .ready && panel.translation == "de" }
#expect(panel.effectiveTarget == HyMT3Languages.german)
#expect(await streaming.callCount == 3)
}
@Test func newCaptureReevaluatesTheDirection() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, _) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
await panel.overrideTarget(HyMT3Languages.german)
await waitFor { panel.phase == .ready && panel.translation == "de" }
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready && panel.translation == "en" }
#expect(panel.effectiveTarget == HyMT3Languages.english)
#expect(panel.routedSource == HyMT3Languages.german)
}
}
@@ -0,0 +1,198 @@
import Foundation
import SprachmittlerCore
import SprachmittlerEngines
import SprachmittlerText
import Testing
// Shared scaffolding for the panel test suites. The fakes are small and local to the tests.
// The helper returns the panel plus two small test boxes; a struct would add noise here.
// swiftlint:disable large_tuple
@MainActor
func makePanel(
streaming: any TranslationStreaming,
replacement: (@MainActor () async -> InsertionOutcome)? = nil,
onClose: @escaping @MainActor () -> Void = {},
detector: any LanguageDetecting = FixedLanguageDetector(detection: nil),
target: ModelLanguage = HyMT3Languages.german,
routes: [LanguageRoute] = [],
captureLimits: CaptureLimits = CaptureLimits()
) -> (PanelViewModel, CopiedTextBox, TargetBox) {
let session = TranslationSession(pipelineFactory: { streaming })
let copies = CopiedTextBox()
let targets = TargetBox()
let panel = PanelViewModel(
session: session,
configuration: PanelConfiguration(
target: target,
model: "test-hy-mt3",
keepAlive: "30m",
languageRoutes: routes,
captureLimits: captureLimits
),
copy: { copies.text = $0 },
replace: replacement,
onCloseRequest: onClose,
onTargetChanged: { targets.codes.append($0.code) },
detector: detector
)
panel.startObserving()
return (panel, copies, targets)
}
// swiftlint:enable large_tuple
@MainActor
func waitFor(_ condition: @MainActor () -> Bool) async {
for _ in 0 ..< 10000 {
if condition() {
return
}
await Task.yield()
}
Issue.record("panel condition was not reached")
}
func makeResult(
_ translation: String,
warnings: [TranslationWarning] = []
) -> PipelineResult {
PipelineResult(
translation: translation,
warnings: warnings,
sourceLanguage: "en",
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
chunkCount: 1
)
}
struct ImmediateStreaming: TranslationStreaming {
let deltas: [String]
let result: PipelineResult
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
for delta in deltas {
await onDelta?(delta)
}
return result
}
}
struct FailingStreaming: TranslationStreaming {
let error: SprachmittlerError
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
throw error
}
}
actor EchoStreaming: TranslationStreaming {
private(set) var callCount = 0
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
callCount += 1
let result = PipelineResult(
translation: request.target.code,
warnings: [],
sourceLanguage: "en",
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
chunkCount: 1
)
await onDelta?(result.translation)
return result
}
}
actor CountingStreaming: TranslationStreaming {
private(set) var callCount = 0
let result: PipelineResult
init(result: PipelineResult) {
self.result = result
}
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
callCount += 1
await onDelta?(result.translation)
return result
}
}
final class CopiedTextBox: @unchecked Sendable {
var text: String?
}
final class TargetBox: @unchecked Sendable {
var codes: [String] = []
}
final class ReplaceBox: @unchecked Sendable {
var called = false
}
final class CloseBox: @unchecked Sendable {
var closed = false
}
struct FixedLanguageDetector: LanguageDetecting {
let detection: LanguageDetection?
func detect(_ text: String) -> LanguageDetection? {
detection
}
}
/// A fake that reports three parts and waits after the first until the test releases it.
actor GatedMultiPartStreaming: TranslationStreaming {
private(set) var requests: [TranslationSessionRequest] = []
private var releaseContinuation: CheckedContinuation<Void, Never>?
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
try await translate(request, onDelta: onDelta, onChunk: nil)
}
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?,
onChunk: (@Sendable (Int, Int) async -> Void)?
) async throws -> PipelineResult {
requests.append(request)
await onChunk?(1, 3)
await onDelta?("part1 ")
await withCheckedContinuation { releaseContinuation = $0 }
await onChunk?(2, 3)
await onDelta?("part2 ")
await onChunk?(3, 3)
await onDelta?("part3")
return PipelineResult(
translation: "part1 part2 part3",
warnings: [],
sourceLanguage: "en",
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
chunkCount: 3
)
}
func release() async {
while releaseContinuation == nil {
await Task.yield()
}
releaseContinuation?.resume()
releaseContinuation = nil
}
}
@@ -1,5 +1,6 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerText
import Testing
@testable import SprachmittlerCore
@@ -139,135 +140,4 @@ struct PanelViewModelTests {
#expect(panel.translation.isEmpty)
#expect(panel.warnings.isEmpty)
}
// The helper returns the panel and two small test captures; a struct would add noise here.
// swiftlint:disable large_tuple
private func makePanel(
streaming: any TranslationStreaming,
replacement: (@MainActor () async -> InsertionOutcome)? = nil,
onClose: @escaping @MainActor () -> Void = {}
) -> (PanelViewModel, CopiedTextBox, TargetBox) {
let session = TranslationSession(pipelineFactory: { streaming })
let copies = CopiedTextBox()
let targets = TargetBox()
let panel = PanelViewModel(
session: session,
configuration: PanelConfiguration(
target: HyMT3Languages.german,
model: "test-hy-mt3",
keepAlive: "30m"
),
copy: { copies.text = $0 },
replace: replacement,
onCloseRequest: onClose,
onTargetChanged: { targets.codes.append($0.code) }
)
panel.startObserving()
return (panel, copies, targets)
}
// swiftlint:enable large_tuple
private func waitFor(_ condition: @MainActor () -> Bool) async {
for _ in 0 ..< 10000 {
if condition() {
return
}
await Task.yield()
}
Issue.record("panel condition was not reached")
}
private func makeResult(
_ translation: String,
warnings: [TranslationWarning] = []
) -> PipelineResult {
PipelineResult(
translation: translation,
warnings: warnings,
sourceLanguage: "en",
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
chunkCount: 1
)
}
}
private struct ImmediateStreaming: TranslationStreaming {
let deltas: [String]
let result: PipelineResult
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
for delta in deltas {
await onDelta?(delta)
}
return result
}
}
private struct FailingStreaming: TranslationStreaming {
let error: SprachmittlerError
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
throw error
}
}
private actor EchoStreaming: TranslationStreaming {
private(set) var callCount = 0
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
callCount += 1
let result = PipelineResult(
translation: request.target.code,
warnings: [],
sourceLanguage: "en",
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
chunkCount: 1
)
await onDelta?(result.translation)
return result
}
}
private actor CountingStreaming: TranslationStreaming {
private(set) var callCount = 0
let result: PipelineResult
init(result: PipelineResult) {
self.result = result
}
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
callCount += 1
await onDelta?(result.translation)
return result
}
}
private final class CopiedTextBox: @unchecked Sendable {
var text: String?
}
private final class TargetBox: @unchecked Sendable {
var codes: [String] = []
}
private final class ReplaceBox: @unchecked Sendable {
var called = false
}
private final class CloseBox: @unchecked Sendable {
var closed = false
}
@@ -50,6 +50,28 @@ struct TranslationPipelineTests {
#expect(chat.recorded[1].messages.first?.content.contains("Second paragraph.") == true)
}
@Test func reportsEachChunkBeforeItStarts() async throws {
let chat = SequencedChat(responses: [
[.delta("Erster Absatz."), .done(reason: "stop", metrics: .empty)],
[.delta("Zweiter Absatz."), .done(reason: "stop", metrics: .empty)],
])
let collector = DeltaCollector()
let pipeline = makePipeline(
chat: chat,
chunker: Chunker(latinLimit: 20, denseLimit: 20),
detector: FixedDetector(code: "en", confidence: 0.9)
)
_ = try await pipeline.translate(
text: "First paragraph.\n\nSecond paragraph.",
target: german,
model: model,
keepAlive: "30m",
onChunk: { index, total in await collector.append("\(index)/\(total) ") }
)
#expect(await collector.text == "1/2 2/2 ")
}
@Test func streamedTextIncludesChunkSeparators() async throws {
let chat = SequencedChat(responses: [
[.delta("Erster Absatz."), .done(reason: "stop", metrics: .empty)],
@@ -165,6 +165,67 @@ struct TranslationSessionTests {
#expect(event == .failed(epoch: epoch, error: .ollamaUnreachable(url: url)))
}
@Test func chunkProgressAndRequestLimitsAreForwarded() async {
let streaming = ChunkReportingStreaming()
let session = TranslationSession(pipelineFactory: { streaming })
var iterator = await session.events().makeAsyncIterator()
let longRequest = TranslationSessionRequest(
captured: CapturedText(
text: String(repeating: "a", count: 9000),
capturedAt: Date(),
source: .doubleCopy
),
target: HyMT3Languages.german,
model: "test-hy-mt3",
keepAlive: "30m",
captureLimits: CaptureLimits(maximumParts: 3)
)
let epoch = await session.start(longRequest)
var chunks: [String] = []
var finished = false
while let event = await iterator.next() {
switch event {
case let .chunkStarted(eventEpoch, index, total) where eventEpoch == epoch:
chunks.append("\(index)/\(total)")
case let .finished(eventEpoch, result) where eventEpoch == epoch:
#expect(result.chunkCount == 3)
finished = true
default:
break
}
if finished {
break
}
}
#expect(chunks == ["1/3", "2/3", "3/3"])
#expect(finished)
}
@Test func textAboveTheRequestCaptureLimitFailsBeforeTheFactory() async {
let streaming = ScriptedStreaming()
let session = TranslationSession(pipelineFactory: { streaming })
var iterator = await session.events().makeAsyncIterator()
let tooLong = TranslationSessionRequest(
captured: CapturedText(
text: String(repeating: "a", count: 8001),
capturedAt: Date(),
source: .doubleCopy
),
target: HyMT3Languages.german,
model: "test-hy-mt3",
keepAlive: "30m",
captureLimits: CaptureLimits(maximumParts: 2)
)
let epoch = await session.start(tooLong)
_ = await iterator.next()
let event = await iterator.next()
#expect(event == .failed(epoch: epoch, error: .textTooLong(characters: 8001, limit: 8000)))
#expect(await streaming.callCount == 0)
}
private func result(_ translation: String, warnings: [TranslationWarning] = []) -> PipelineResult {
PipelineResult(
translation: translation,
@@ -176,6 +237,34 @@ struct TranslationSessionTests {
}
}
/// A fake that reports three chunks and a matching result.
private actor ChunkReportingStreaming: TranslationStreaming {
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
try await translate(request, onDelta: onDelta, onChunk: nil)
}
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?,
onChunk: (@Sendable (Int, Int) async -> Void)?
) async throws -> PipelineResult {
for index in 1 ... 3 {
await onChunk?(index, 3)
await onDelta?("part\(index)")
}
return PipelineResult(
translation: "done",
warnings: [],
sourceLanguage: "en",
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
chunkCount: 3
)
}
}
/// A controlled streaming fake. Each call waits until the test releases its outcome.
private actor ScriptedStreaming: TranslationStreaming {
enum Outcome: Sendable {
@@ -0,0 +1,126 @@
import SprachmittlerEngines
import SprachmittlerText
import Testing
@Suite("Translation direction")
struct TranslationDirectionTests {
private let german = HyMT3Languages.german
private let english = HyMT3Languages.english
private func detection(
_ code: String,
confidence: Double = 0.9,
alternatives: [String]? = nil
) -> LanguageDetection {
LanguageDetection(code: code, confidence: confidence, alternatives: alternatives ?? [code])
}
@Test func usesTheMotherTongueWithoutRules() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [],
detection: detection("en"),
override: nil
)
#expect(direction == TranslationDirection(target: german, didRoute: false, source: nil))
}
@Test func appliesAMatchingRule() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "en")],
detection: detection("de"),
override: nil
)
#expect(direction == TranslationDirection(target: english, didRoute: true, source: german))
}
@Test func appliesAnArbitrarySourceRule() throws {
let french = try #require(HyMT3Languages.resolve("fr"))
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "fr", target: "en")],
detection: detection("fr"),
override: nil
)
#expect(direction.target == english)
#expect(direction.didRoute)
#expect(direction.source == french)
}
@Test func supportsChineseToEnglish() throws {
let chinese = try #require(HyMT3Languages.resolve("zh"))
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "zh", target: "en")],
detection: detection("zh-Hans"),
override: nil
)
#expect(direction.target == english)
#expect(direction.source == chinese)
}
@Test func keepsTheMotherTongueWhenTheRuleTargetIsTheMotherTongue() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "en", target: "de")],
detection: detection("en"),
override: nil
)
#expect(direction.target == german)
#expect(!direction.didRoute)
}
@Test func ignoresARuleWhoseTargetEqualsItsSource() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "de")],
detection: detection("de"),
override: nil
)
#expect(direction.target == german)
#expect(!direction.didRoute)
}
@Test func ignoresRulesOnLowConfidence() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "en")],
detection: detection("de", confidence: 0.49),
override: nil
)
#expect(direction.target == german)
}
@Test func ignoresRulesWhenTheAlternativesDisagree() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "en")],
detection: detection("de", alternatives: ["de", "en"]),
override: nil
)
#expect(direction.target == german)
}
@Test func manualOverrideCarriesTheChosenLanguage() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "en")],
detection: detection("de"),
override: english
)
#expect(direction.target == english)
#expect(!direction.didRoute)
#expect(direction.source == nil)
}
@Test func noDetectionUsesTheMotherTongue() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "en")],
detection: nil,
override: nil
)
#expect(direction.target == german)
}
}
@@ -13,6 +13,8 @@ struct LanguageDetectorTests {
)
#expect(detection.code == "de")
#expect(detection.confidence > 0.5)
#expect(detection.alternatives.contains("de"))
#expect(detection.alternatives.count == 1)
}
@Test func detectsEnglish() throws {
@@ -0,0 +1,106 @@
import Foundation
import Testing
@testable import SprachmittlerText
@Suite("Markdown presentation")
struct MarkdownPresentationTests {
@Test func parsesHeadingsParagraphsAndRules() {
let blocks = MarkdownPresentation.blocks(in: """
# Title
First paragraph.
Second line.
---
""")
#expect(blocks == [
.heading(level: 1, text: "Title"),
.paragraph("First paragraph.\nSecond line."),
.rule,
])
}
@Test func parsesOrderedAndUnorderedLists() {
let blocks = MarkdownPresentation.blocks(in: """
- one
* two
3. three
4) four
""")
#expect(blocks == [
.listItem(ordered: false, number: 0, indent: 0, text: "one"),
.listItem(ordered: false, number: 0, indent: 0, text: "two"),
.listItem(ordered: true, number: 3, indent: 0, text: "three"),
.listItem(ordered: true, number: 4, indent: 0, text: "four"),
])
}
@Test func parsesQuotesAndFencedCode() {
let blocks = MarkdownPresentation.blocks(in: """
> quoted **text**
> second
```swift
let value = 1
```
""")
#expect(blocks == [
.quote("quoted **text**\nsecond"),
.codeBlock(language: "swift", text: "let value = 1"),
])
}
@Test func keepsUnclosedFenceAsCode() {
let blocks = MarkdownPresentation.blocks(in: "```\nstill code\n")
#expect(blocks == [.codeBlock(language: nil, text: "still code")])
}
@Test func recognisesInlineFormatting() {
let attributed = MarkdownPresentation.inline("**bold** and *italic* and `code`")
let intents = attributed.runs.compactMap(\.inlinePresentationIntent)
#expect(intents.contains { $0.contains(.stronglyEmphasized) })
#expect(intents.contains { $0.contains(.emphasized) })
#expect(intents.contains { $0.contains(.code) })
}
@Test func parsesLinksButNeverImages() throws {
let attributed = MarkdownPresentation
.inline("See [docs](https://example.com) and ![alt](https://example.com/x.png)")
let links = attributed.runs.compactMap(\.link)
#expect(try links == [#require(URL(string: "https://example.com"))])
#expect(String(attributed.characters).contains("alt"))
#expect(!String(attributed.characters).contains("x.png"))
}
@Test func malformedMarkdownFallsBackToText() {
let attributed = MarkdownPresentation.inline("**unclosed and <unterminated")
#expect(String(attributed.characters).contains("unclosed"))
}
@Test func onlyHTTPLinksAreAllowed() throws {
#expect(try MarkdownPresentation.isAllowedLink(#require(URL(string: "https://example.com"))))
#expect(try MarkdownPresentation.isAllowedLink(#require(URL(string: "http://example.com"))))
#expect(try !MarkdownPresentation.isAllowedLink(#require(URL(string: "file:///etc/passwd"))))
#expect(try !MarkdownPresentation.isAllowedLink(#require(URL(string: "javascript:alert(1)"))))
#expect(try !MarkdownPresentation.isAllowedLink(#require(URL(string: "sprachmittler://open"))))
}
@Test func rendersMarkdownSourcesButNotStructuredData() {
#expect(MarkdownPresentation.shouldRender(source: "# Title\n\n- item", translation: "x"))
#expect(MarkdownPresentation.shouldRender(source: "A **bold** sentence.", translation: "x"))
#expect(MarkdownPresentation.shouldRender(source: "plain", translation: "translated **bold**"))
#expect(!MarkdownPresentation.shouldRender(source: #"{"key": "value"}"#, translation: "x"))
#expect(!MarkdownPresentation.shouldRender(source: "<div><p>Hello</p></div>", translation: "x"))
#expect(!MarkdownPresentation.shouldRender(source: "```\nlet x = 1\n```", translation: "x"))
#expect(!MarkdownPresentation.shouldRender(source: "Just prose, no markers.", translation: "Nur Prosa."))
#expect(!MarkdownPresentation.shouldRender(source: "", translation: "**bold**"))
}
@Test func headingsWithDifferentLevelsAndClosingHashes() {
let blocks = MarkdownPresentation.blocks(in: "### Sub heading ###\n\n####### not a heading")
#expect(blocks == [
.heading(level: 3, text: "Sub heading"),
.paragraph("####### not a heading"),
])
}
}
+183 -100
View File
@@ -1,134 +1,217 @@
# Sprachmittler: OpenCode 2.x starter kit
# Sprachmittler
Sprachmittler is a native macOS menu-bar app for Apple Silicon. Select text in any app, press **⌘C twice**, and a small floating panel shows a translation produced by Tencent's **Hy-MT3-7B** translation model running locally through **Ollama**. The panel has **Copy** and an explicit **Replace** button in the lower right corner; nothing is ever replaced automatically.
Sprachmittler is a native macOS menu-bar app for Apple Silicon. Select text in any app, press **⌘C twice**, and a floating panel shows a translation from Tencent's **Hy-MT3** model running locally through **Ollama**. Copy it, or click **Replace** to put it over the selection. Nothing is replaced automatically, and nothing leaves your Mac by default.
This repository is the development kit for building the app with **OpenCode 2.x**. It contains the architecture, specifications, a task plan, an evaluation design, OpenCode agents, commands and skills in native V2 format, and a compilable scaffold.
Sprachmittler is the companion to Schriftleser and Vorleser: Vorleser reads text aloud, Schriftleser reads documents into text, Sprachmittler translates the text you select.
It is the companion to **Schriftleser** and **Vorleser**: Vorleser reads text aloud, Schriftleser turns documents into text, and Sprachmittler translates the text you select.
A user-facing installation, permission and troubleshooting guide is in [docs/USER_GUIDE.md](docs/USER_GUIDE.md).
## How it works
## Features
1. Select text in Safari, Mail, Word, Notes, an editor or any other app.
2. Press **⌘C** twice quickly (the DeepL-style double copy).
3. A non-activating panel appears; the source app keeps the keyboard focus.
4. The translation streams in while the local Hy-MT3 model works.
5. **Copy** puts the translation on the clipboard. **Replace** replaces the selected text with the translation — only when you click it.
6. **Esc** closes the panel. **⌘Z** in the source app undoes a Replace in apps that support undo.
**Translate**
Nothing is sent anywhere except the configured Ollama endpoint, which is `http://127.0.0.1:11434` by default. There is no history, no telemetry and no account.
- Double-copy trigger in any app: select, **⌘C**, **⌘C**.
- Streaming translations from a local Hy-MT3 model; no cloud API.
- 102 supported languages with a language picker and recent targets.
- Language routing: a mother tongue default (e.g. everything to German) plus optional source-to-target rules (e.g. Chinese → English).
- Markdown rendering for headings, bold, italic, lists, quotes, code and links.
- Configurable translation text size, source-preview toggle and an optional Fast model preset.
## Prerequisites
**The panel**
| Requirement | Version |
- Non-activating floating panel: the source app stays frontmost and keeps the menu bar.
- Draggable full-width header; the panel keeps its position while open and appears near the cursor when shown again.
- **Esc** closes it without clicking first; a click outside closes it too.
- Copy, Retry and explicit **Replace**, with validation warnings that disable Replace when the output is unsafe.
**System integration**
- Menu-bar actions: Translate Clipboard Text, target language, Copy Last Translation, Replace Last Translation, Settings, onboarding, diagnostics and Quit.
- macOS **Services** item: "Translate with Sprachmittler".
- First-run onboarding checks Ollama, the model and the optional Accessibility permission.
- Accessibility is used only for Replace and is never required for translation or Copy.
**Privacy**
- Local Ollama endpoint by default; a remote endpoint needs an explicit toggle and HTTPS.
- No history, telemetry or account. Source text and translations are never written to disk.
- No global key taps and no Input Monitoring.
## Requirements
| Requirement | Details |
|---|---|
| Apple Silicon Mac | macOS 14 Sonoma or later; 16 GB unified memory recommended for the 7B model |
| Xcode | 16 or later (Swift 6) |
| Ollama | current release; this kit was verified with 0.40.18 |
| Translation model | `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` (about 5.15 GB); optional fast model `hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M` (about 1.35 GB) |
| Homebrew | for `xcodegen`, `swiftformat`, `swiftlint`, `xcbeautify`, `ripgrep`, `jq` |
| OpenCode | **2.x** (check with `opencode --version`) |
| Mac | Apple Silicon, macOS 14 Sonoma or later |
| Ollama | Current release; verified with 0.40.18 |
| Translation model | `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` (about 5.15 GB, 16 GB unified memory recommended) |
| Fast preset (optional) | `hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M` (about 1.35 GB) |
| Accessibility | Optional; needed only for Replace |
| Build tools | Xcode 16 or later, Homebrew, XcodeGen, SwiftFormat and SwiftLint (`make bootstrap`) |
| OpenCode | Optional; **2.x** only when using the repository's agent workflow |
## Getting started
## Install from source
```bash
git init && git add -A && git commit -m "chore: Sprachmittler OpenCode kit"
make bootstrap # installs xcodegen, swiftformat, swiftlint, jq, ripgrep
ollama pull hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M # about 5.15 GB
make smoke # translates one fixed synthetic sentence
make doctor # checks OpenCode 2.x and the resolved V2 config
make verify # format, lint, privacy, tests, Debug + Release builds
make app # builds and launches the Debug app
make install # builds Release, installs in /Applications and launches
make dmg # local unnotarised DMG from the Release build
make icon # regenerate the app icon assets
opencode # start OpenCode in the repo root
git clone <repository-url>
cd Sprachmittler
make bootstrap
```
Then paste the prompt from `docs/KICKOFF.md` into OpenCode, or simply run:
Start Ollama and download the model once:
```text
/next
```bash
ollama serve
ollama pull hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M
```
The **Replace** button needs the macOS Accessibility permission. The app asks for it only when you use Replace; double-copy, translation and Copy work without any permission.
Then build, install and launch the Release app:
## What's inside
```bash
make install
```
| Path | Purpose |
`make install` builds the Release configuration, replaces `/Applications/Sprachmittler.app` and opens it. For a local disk image instead:
```bash
make dmg
```
The DMG is ad-hoc signed for local use, not notarised. The app runs from the menu bar and has no Dock icon; open it and follow the first-run onboarding.
For a Debug build during development:
```bash
make app
```
## Usage
1. Select text in Safari, Mail, Notes, an editor or any other app.
2. Press **⌘C** twice quickly. The double-copy window is 500 ms by default and configurable.
3. The panel appears near the cursor and the translation streams in.
4. **Copy** puts the translation on the clipboard. **Replace** overwrites the selection only when you click it.
5. **Esc** or a click outside closes the panel.
The panel takes keyboard focus while it is visible by default, so Esc and the shortcuts work immediately. The app itself is not activated: the source app stays frontmost, and clicking it returns keyboard focus. The **Close with Esc without clicking** setting turns the focus-taking behaviour off.
| Action | Shortcut |
|---|---|
| `AGENTS.md` | Project rules OpenCode loads automatically: commands, workflow, non-negotiables, doc map |
| `opencode.json` | Native OpenCode 2.x config: loads `docs/CODING_STANDARDS.md` and defines an ordered `permissions` list |
| `.opencode/agents/` | `architect` (plans, read-only), `swift-reviewer` (reviews, read-only), `test-engineer` (tests and fakes only), `translation-evaluator` (runs evaluations) |
| `.opencode/commands/` | `/next`, `/task T2.2`, `/plan …`, `/verify`, `/review`, `/adr …`, `/status`, `/manual-test …`, `/evaluate …` |
| `.opencode/skills/` | `translation-quality` (prompt fidelity, validation, judging output), `selection-capture` (double copy, pasteboard, insertion, permissions) |
| `docs/ARCHITECTURE.md` | Authoritative design: modules, capture/insertion flow, session state machine, budgets, risks |
| `docs/PRD.md` | User stories, requirements R001–R050, acceptance criteria |
| `docs/IMPLEMENTATION_PLAN.md` | 9 milestones (M0–M8), about 50 tasks, each with acceptance criteria and traceability |
| `docs/KICKOFF.md` | Ready-to-paste prompts for the first session and checkpoints |
| `docs/PROGRESS.md` | Checklist the agent updates after each task |
| `docs/HYMT3_MODEL.md` | Model tags, licence, all documented prompt templates, sampling, performance |
| `docs/OLLAMA_TRANSLATION_API.md` | HTTP contract for `/api/chat`, options mapping, error mapping, fixtures |
| `docs/SELECTION_AND_CLIPBOARD.md` | Double-copy algorithm, pasteboard restoration, Accessibility replacement, compatibility matrix |
| `docs/TRANSLATION_OUTPUT.md` | Prompt selection, chunking, protective token validation, output rules T1–T4 |
| `docs/LANGUAGES.md` | The 102 supported languages and their exact model names |
| `docs/SECURITY_PRIVACY.md` | Privacy invariants SP-1…SP-15, checked by `scripts/privacy-check.sh` |
| `docs/MODEL_EVALUATION.md` | Corpus, metrics, report format and the default-model gate |
| `docs/TESTING.md` | Test layers, required cases, manual release checklist |
| `docs/DECISIONS.md` | ADR-001…ADR-015 |
| `docs/CODING_STANDARDS.md` | Swift 6 concurrency, structure, logging, UI, style |
| `docs/OPENCODE_V2.md` | Why the OpenCode files look the way they do, and how to check them |
| `docs/PERFORMANCE.md` | Reference measurements and budgets |
| `evaluation/` | Corpus manifest schema and example; the corpus itself stays out of git |
| `project.yml` | XcodeGen spec for the app target |
| `Packages/SprachmittlerKit/` | SwiftPM package with module placeholders, test targets and synthetic fixtures |
| `App/` | Menu-bar app stubs, `Info.plist` (Services, ATS), non-sandboxed entitlements |
| `scripts/` | `bootstrap`, `verify`, `privacy-check`, `opencode-check`, `smoke-ollama`, `capture-fixtures`, `manifest` |
| Translate the selection | **⌘C** twice |
| Close the panel | **Esc**, or click outside |
| Copy the translation | **⌘C** |
| Retry | **⌘R** |
| Replace the selection | **⌘↩** |
| Settings | **⌘,** |
## The canonical prompt
### Mother tongue and language rules
All translation prompts live in `SprachmittlerEngines`. The default is Tencent's documented English template, byte for byte:
The **mother tongue** is the default target for every source. In **Settings ▸ General ▸ Translation** you can add **language rules** that override it for a specific source language, for example:
```text
Translate the following text into {target_lang}. Note that you should **only output the translated result without any additional explanation**:
{source_text}
Mother tongue: German
Chinese (Simplified) → English
Traditional Chinese → English
German → English
```
`{target_lang}` is the full English language name from the model card (for example `German`, `Chinese`, `Traditional Chinese`). The prefix is kept stable so Ollama can reuse its prompt cache; only the target language and the source text change. The model has no default system prompt, and the app sends none.
With no rules, every language goes to the mother tongue. Rules apply only when the source is confidently detected; otherwise the mother tongue is used. The panel header shows the effective direction, a banner explains a rule and offers a one-capture override, and the panel language picker is a session-only override. Persistent rules live in Settings.
## Recommended way to work with OpenCode
### Markdown
1. **One task per session.** `/task T2.2` keeps context small and focused.
2. **Headless first.** M1–M2 build the Ollama client, the Hy-MT3 adapter, the language catalogue, chunking and validation. `sprachmittler-cli translate` gives you a working translation engine before any UI exists.
3. **Capture real fixtures early (T1.1).** The exact `/api/show` output, streaming shapes and prompt-cache behaviour are recorded from your Ollama. Recorded fixtures stop the agent from guessing.
4. **Measure before choosing.** The 7B is the provisional default; T7.4 is the evaluation gate. The 1.8B may be the better everyday choice on smaller Macs.
5. **You are the test rig for macOS-only behaviour.** Double copy, panel focus, Accessibility replacement, clipboard restoration, Services and VoiceOver need a human. Use `/manual-test <feature>` and report results back.
6. **Review gate.** `/next` already calls `@swift-reviewer`. Run `/review` yourself before committing larger changes.
7. **Record decisions.** When you deviate from the architecture, run `/adr <title>` so the docs stay true.
When the source looks like Markdown and **Settings ▸ General ▸ Translation ▸ Render Markdown formatting** is on (the default), the translation is rendered with headings, bold, italic, lists, quotes, fenced code and links. JSON, HTML and code sources are never Markdown-rendered. **Copy** and **Replace** always use the raw Markdown translation, not the rendered text. Only `http` and `https` links open, and only on an explicit click.
## Placeholders to change
### Replace
- Bundle ID prefix `de.schihei` in `project.yml`.
- App name "Sprachmittler" if you prefer another. Search the repo for `Sprachmittler`.
- The default model tag in `docs/HYMT3_MODEL.md` and `docs/PROGRESS.md` once T7.4 is decided.
- Model tags for the fast preset once the 1.8B conversion has been verified on your Ollama.
Replace verifies the source app and, when available, the selected text before touching it. It prefers a direct Accessibility write and falls back to a clipboard snapshot plus synthetic paste. Blocking validation warnings — a likely preamble, truncation, a repetition loop or a lost protected token — disable Replace by default. The previous clipboard is restored after the fallback paste when it is still safe to do so.
## Licensing note
### Settings
- **General** — mother tongue, language rules, source preview, Markdown rendering, translation text size, Esc behaviour, double-copy window and startup.
- **Model** — model and Fast preset, Ollama endpoint, sampling and context settings.
- **Translation** — part size, maximum parts per selection and prompt policy. One part (the default) rejects longer text; higher values translate long selections sequentially and the panel shows the part progress.
- **Privacy** — local/remote endpoint policy and permissions.
- **Diagnostics** — server version, model digests, the last 50 timings and error kinds. No text or translations.
## Privacy
- The default endpoint is `http://127.0.0.1:11434`. A non-loopback endpoint requires an explicit setting and HTTPS.
- Source text, translations and pasteboard contents are never written to disk and are not kept as history.
- The clipboard snapshot for a Replace fallback lives in memory for that one replacement and is restored.
- Logs contain counts, timings, short hashes and error kinds, never the selected text or the translation.
- Markdown links are restricted to `http`/`https`; remote images are never fetched.
- The app does not install a key tap and never requests Input Monitoring. While the panel is visible, a transient mouse-down monitor dismisses it when a click goes to another app; the event is discarded and the monitor is removed when the panel closes.
The hard requirements are listed in [docs/SECURITY_PRIVACY.md](docs/SECURITY_PRIVACY.md).
## How it works
```text
select text → ⌘C twice → pasteboard capture → validate → chunk
→ documented Hy-MT3 prompt → Ollama /api/chat (streaming)
→ validate → floating panel
```
The app is a menu-bar agent (`LSUIElement`) with a non-activating `NSPanel`. Replace re-verifies the frontmost app and the selected text before inserting. The translation pipeline, capture/insertion seams and UI state models are separate modules so they can be tested without the UI.
| Module | Responsibility |
|---|---|
| `App/` | Menu-bar app, panel, settings, onboarding, diagnostics and composition root |
| `Packages/SprachmittlerKit/` | Translation pipeline, prompt adapters, Ollama client, capture/insertion, text utilities and tests |
| `docs/` | Architecture, product requirements, model/API contracts, privacy, testing and decisions |
| `scripts/` | Build, verification, privacy, fixture, icon and release helpers |
| `evaluation/` | Corpus manifest schema, metrics and report format; the corpus itself stays out of git |
See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for the full design.
## Status
Sprachmittler is at **0.1.0**. M0–M8 are implemented, `make verify` is green, and local install and DMG builds are verified.
The 7B model is the provisional default; the default model and prompt policy are decided by the evaluation gate in [docs/MODEL_EVALUATION.md](docs/MODEL_EVALUATION.md). Manual macOS-only checks remain for the double-copy and insertion matrices, VoiceOver, and the 10-app compatibility matrix. Current task state is in [docs/PROGRESS.md](docs/PROGRESS.md).
Local builds are ad-hoc signed. `make release` is the Developer ID and notarisation path and needs the corresponding credentials.
## Development
```bash
make bootstrap # install xcodegen, swiftformat, swiftlint, jq and ripgrep if missing
make doctor # check OpenCode 2.x and the resolved V2 configuration
make generate # regenerate Sprachmittler.xcodeproj from project.yml
make build # swift build plus the Debug app target
make test # package unit, contract and component tests
make app # build and launch the Debug app
make verify # format, lint, privacy, tests, Debug + Release builds
make install # build Release, install in /Applications and launch
make dmg # local unnotarised DMG from the Release build
make smoke # translate one fixed synthetic sentence
make live-test # tests against a real local Ollama
make fixtures # capture Ollama fixtures
make manifest # regenerate MANIFEST.sha256
make release # signed/notarised release dry-run; needs credentials
```
The package builds and tests without Xcode UI:
```bash
swift build --package-path Packages/SprachmittlerKit
swift test --package-path Packages/SprachmittlerKit
```
`swift run --package-path Packages/SprachmittlerKit sprachmittler-cli --help` exposes the language catalogue, model inspection, translation and evaluation commands.
### Working with OpenCode
The repository is set up for the **OpenCode 2.x** development workflow. `AGENTS.md` contains the rules the agent loads, `opencode.json` is the native V2 config, and `.opencode/` contains the agents, commands and skills. Use `/next` for the next open task, `/task T4.2` for a named task, and `/verify` before calling work done. [docs/OPENCODE_V2.md](docs/OPENCODE_V2.md) explains the configuration and how to check it.
OpenCode is a development tool. The app builds and runs without it.
### Forking
- Set your bundle identifier in `project.yml` (the default `de.schihei.sprachmittler` is a placeholder).
- Change model tags in `docs/HYMT3_MODEL.md` and the preset definitions in `SprachmittlerEngines`.
- Use your own Developer ID and notarisation credentials for `make release`.
- Do not commit `Sprachmittler.xcodeproj`, build products, `evaluation/corpus/` or evaluation results.
## Licensing
Sprachmittler bundles no models. Hy-MT3 is published by Tencent under **Apache-2.0**; the GGUF conversions used here are published by Tencent on Hugging Face. Settings shows the licence and the model digest. Re-check the model card before commercial distribution. The 30B-A3B model is not a preset: it needs far more memory than a 16 GB Mac has.
## Kit verification status (2026-11-26)
What was checked when the kit was assembled:
- `swift build` and `swift test --skip SprachmittlerLiveTests` pass for `Packages/SprachmittlerKit` with Swift 6.4.2 on macOS 27.2.1 (arm64).
- `xcodegen generate` and the Debug app build pass with Xcode 27.2.
- `scripts/privacy-check.sh` and `scripts/opencode-check.sh` (static part) pass; all scripts pass `bash -n`.
- `opencode.json`, the evaluation schema and the example parse as JSON; `plutil` accepts the Info.plist and entitlements.
- `make smoke` translated the fixed synthetic sentence into German with `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` on Ollama 0.40.18: 34 output tokens in 2.89 s, 45.81 tokens/s, cold load 2.05 s.
- The canonical prompt on the longer Hy-MT3 figure caption: 246 output tokens in 6.52 s, 44.6 tokens/s; 6.49 GB resident with `num_ctx` 8192.
- The owner's reference run with the same model: 255 output tokens, 43.07 tokens/s, 5.97 s warm, 177/178 prompt tokens cached.
Not yet checked: the double-copy gesture, panel focus, Accessibility replacement, clipboard restoration, Services, VoiceOver and real-world translation quality. Those are manual tasks in `docs/TESTING.md` and the compatibility matrices.
+12 -6
View File
@@ -359,7 +359,7 @@ public struct DoubleCopyDetector { /* pure state machine */ }
- Poll `NSPasteboard.general.changeCount` every **120 ms** on the main actor through `PasteboardTicking`.
- A candidate trigger is two changes within **500 ms** (range 300–1000 ms, setting) whose `.string` values are identical and non-empty after trimming.
- Require at least one non-whitespace character and at most `maxCharacters` (4000 Latin / 2000 CJK by default).
- Require at least one non-whitespace character and at most the capture limit (`maxCharacters` per part × `maximumPartsPerSelection`: 4000/2000 Latin/dense by default, one part).
- Ignore changes whose pasteboard contains the app's own marker (`com.schihei.sprachmittler.own`) or `org.nspasteboard.TransientType`, and ignore all changes for 750 ms after our own write.
- Keep only the last two strings and their hashes in memory; clear them after the window or after the session starts.
- Do not log the text. Log only `changeCount` deltas and a short hash at `privacy: .private`.
@@ -483,7 +483,7 @@ Full detail: `docs/TRANSLATION_OUTPUT.md`.
2. Detect the source language with `NLLanguageRecognizer` for display only. The prompt does not need it.
3. Classify content: `.plain`, `.markdown`, `.json`, `.html`, `.code`, `.delimited` (many URLs/placeholders).
4. Scan protected tokens: URLs, e-mail addresses, `{{var}}`, `${var}`, `%s`, `%d`, `%1$@`, Markdown code spans, fenced code blocks, HTML tags, JSON keys.
5. Plan chunks: paragraph boundaries first, then sentence, then word; script-aware limits (4000 characters for Latin/Cyrillic/Greek, 2000 for CJK/Arabic/Hebrew/Devanagari etc.). Never split a grapheme cluster.
5. Plan parts: paragraph boundaries first, then sentence, then word; script-aware part sizes (4000 characters for Latin/Cyrillic/Greek, 2000 for CJK/Arabic/Hebrew/Devanagari etc.). Never split a grapheme cluster. The capture gate accepts up to `maximumPartsPerSelection` parts.
### 9.2 Prompt selection (`SprachmittlerEngines`)
@@ -549,12 +549,14 @@ stateDiagram-v2
| Surface | Implementation | Contents |
|---|---|---|
| Status item | `MenuBarExtra` | Translate clipboard text, Target language submenu, Copy last translation, Replace last translation (if safe), Settings, Set up Sprachmittler, Diagnostics, Quit |
| Panel | `NSPanel` with `.nonactivatingPanel`, `becomesKeyOnlyIfNeeded = true` | Header (source → target, language picker, gear), collapsible source preview, streaming translation, warnings, Copy (left) and **Replace** (right, primary) |
| Panel | `NSPanel` with `.nonactivatingPanel`, `becomesKeyOnlyIfNeeded = false` | Header (source → target, language picker, gear), collapsible source preview, streaming translation (Markdown rendered when detected), warnings, Copy (left) and **Replace** (right, primary) |
| Settings | SwiftUI `Settings` scene | General, Model, Translation, Privacy, Diagnostics |
| Onboarding | `NSWindow` (not a SwiftUI `Window` scene) | Ollama reachable + version, Hy-MT3 installed, target language, optional Accessibility for Replace; each with a fix button |
| Diagnostics | Window from the menu | Server version, model digests, last 50 timings and error kinds; copy as text; no text or translations |
Panel keyboard: **Esc** close, **⌘C** copy translation, **⌘↩** Replace, **⌘R** retry, **⌘,** Settings. The panel becomes key only when clicked; the source app keeps focus until then. The left header block and its drag grip move the panel; moving it keeps its position while it stays open, and a newly shown panel is placed near the cursor (DeepL-like transient position). The translation text size is a Settings value.
The saved target is the **mother tongue** and the default target for every source. Optional source-language to target-language rules override it when the source is confidently detected; otherwise the mother tongue is used. The mother tongue and the effective target are separate: the header and language picker show the effective target, a banner explains a rule-driven direction and offers a one-capture override back to the mother tongue, and the panel picker is a session-only override. Persistent rules live in Settings. Detection remains advisory and uses the same high-confidence rule as the same-language advisory.
Panel keyboard: **Esc** close, **⌘C** copy translation, **⌘↩** Replace, **⌘R** retry, **⌘,** Settings. The panel is made key when shown (unless the setting is off) so Esc and the shortcuts work without a click; the app is still not activated, the source app remains frontmost and owns the menu bar, and clicking the source app takes keyboard focus back. A click sent to another app dismisses the panel; while the panel is visible a transient mouse-down monitor observes only that the click went to another app, discards the event and is removed on close. While the panel is key it receives keystrokes, so a user who types immediately after triggering should disable the Esc-on-show setting. The whole header bar (full width, flush with the top edge) moves the panel; the drag view moves the window itself from the screen-space mouse delta because `performDrag` does nothing while the app is inactive; moving it keeps its position while it stays open, and a newly shown panel is placed near the cursor (DeepL-like transient position). The translation text size is a Settings value.
Accessibility: every control has an `accessibilityLabel`; the panel exposes source and translation as read-only text elements; full keyboard navigation; respects Reduce Motion and Increase Contrast.
@@ -573,8 +575,9 @@ Accessibility: every control has an `accessibilityLabel`; the panel exposes sour
| `targetLanguage` | LanguageCode | system language if supported, else `en` |
| `recentTargetLanguages` | [String] | last three targets, most recent first |
| `doubleCopyWindowMs` | Int | 500 (300–1000) |
| `maxCharactersLatin` | Int | 4000 |
| `maxCharactersCJK` | Int | 2000 |
| `maxCharactersLatin` | Int | 4000 (500–10000) |
| `maxCharactersCJK` | Int | 2000 (500–4000) |
| `maximumPartsPerSelection` | Int | 1 (1–8); 1 rejects text longer than one part |
| `numCtx` | Int | 8192 |
| `numPredict` | Int | 4096 |
| `temperature` | Double | 0.7 |
@@ -587,6 +590,9 @@ Accessibility: every control has an `accessibilityLabel`; the panel exposes sour
| `autoCopy` | Bool | **false** (never copy automatically) |
| `showSourcePreview` | Bool | true |
| `translationFontSize` | Int | 17 pt (12–28) |
| `languageRoutes` | [LanguageRoute] | `[]` (everything translates into the mother tongue unless a rule matches) |
| `renderMarkdown` | Bool | true (presentation only; raw text is copied and replaced) |
| `closeWithEscape` | Bool | true (make the panel key on show; no app activation) |
| `launchAtLogin` | Bool | false |
| `keepRecentTranslationInMemory` | Bool | true (cleared on quit; no disk) |
| `hasCompletedOnboarding` | Bool | false |
+21 -7
View File
@@ -61,11 +61,11 @@ Decision: Ship with `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` as the provisional def
Consequences: Until the gate, the 7B is labelled provisional in Settings. The decision is re-run when a model, Ollama or the prompt policy changes.
## ADR-009 — Menu-bar agent with a non-activating panel
Status: Accepted
Status: Accepted (amended 2026-11-26: Esc without a click)
Context: The app must be available over any app and must not take focus from the selection. A regular Dock app with a window would interrupt the workflow.
Decision: Use `LSUIElement = YES`, a `MenuBarExtra`, and a floating `NSPanel` with `.nonactivatingPanel` and `becomesKeyOnlyIfNeeded = true`. Never call `NSApp.activate` or `makeKeyAndOrderFront` for the translation panel. Onboarding and Settings are the only surfaces that activate the app.
Consequences: The source app keeps focus, so Replace can target it. Keyboard shortcuts inside the panel require a click first; every action also has a button.
Context: The app must be available over any app and must not activate itself or take application focus from the selection. A regular Dock app with a window would interrupt the workflow. Users also expect Esc to dismiss a transient panel immediately, which requires the panel to be the key window.
Decision: Use `LSUIElement = YES`, a `MenuBarExtra`, and a floating `NSPanel` with `.nonactivatingPanel` and `becomesKeyOnlyIfNeeded = false`. Never call `NSApp.activate` or `makeKeyAndOrderFront` for the translation panel. Onboarding and Settings are the only surfaces that activate the app. By default the panel calls `makeKey()` when shown, so Esc and the keyboard shortcuts work immediately; the setting `closeWithEscape` can restore click-first behaviour. The panel's SwiftUI exit command handles Esc and calls the same close path that cancels an in-flight request.
Consequences: The app stays unactivated: `NSWorkspace.frontmostApplication` and the menu bar stay with the source app, and Replace still re-verifies that app. While the panel is visible it holds keyboard focus, so keystrokes and shortcuts go to the panel until the user clicks back into the source app; the setting turns this off. A click outside the panel dismisses it: the panel observes `didResignKey` and, while visible, a transient global mouse-down monitor. Global monitors do not receive events sent to this app, so clicks in the panel and its popover are ignored; the event is discarded and the monitor is removed on close. The monitor is not a key tap and needs no Input Monitoring. Every action still has a button.
## ADR-010 — Native OpenCode 2.x configuration
Status: Accepted
@@ -77,9 +77,9 @@ Consequences: No mixed V1/V2 files. Sampling settings for agents, if wanted, go
## ADR-011 — Chunk at paragraph boundaries with script-aware limits
Status: Accepted
Context: Hy-MT3's documented translation context is 8192 tokens. A long selection can exceed it; splitting mid-sentence harms quality; splitting mid-grapheme corrupts text.
Decision: Chunk at blank-line paragraph boundaries first, then sentence, then word. Use 4000 characters for Latin/Cyrillic/Greek and 2000 for CJK and other dense scripts. Never split a grapheme cluster. Reassemble with the original separators. Translate chunks sequentially with one request in flight.
Consequences: Most selections are one chunk. Very long selections lose some cross-paragraph context; the panel shows a chunk count and any failed chunk. `done_reason: "length"` is always a warning.
Context: Hy-MT3's documented translation context is 8192 tokens. A long selection can exceed it; splitting mid-sentence harms quality; splitting mid-grapheme corrupts text. The capture gate and the chunk size were the same number, so selections over one chunk were rejected before the pipeline could split them.
Decision: Chunk at blank-line paragraph boundaries first, then sentence, then word. Use 4000 characters per part for Latin/Cyrillic/Greek and 2000 for CJK and other dense scripts. Never split a grapheme cluster. Reassemble with the original separators. Translate parts sequentially with one request in flight. The capture limit is the part size multiplied by `maximumPartsPerSelection` (1–8, default 1); `1` rejects anything over one part, and higher values accept the selection and translate it in parts. The dense-script part size is capped at 4000 because 5000 dense characters plus a 4096-token output can overflow the context.
Consequences: Default behaviour is unchanged (one part). Users who opt into parts trade latency for reach: every extra part is another sequential request, and the panel shows “Part 2 of 4” while streaming and “3 parts” when finished. Very long selections lose some cross-paragraph context; the panel keeps the streamed partial text and disables Replace when a part fails. `done_reason: "length"` is always a warning.
## ADR-012 — Only documented prompt variants; no free-form prompts
Status: Accepted
@@ -143,3 +143,17 @@ Status: Accepted
Context: Panel, Settings, Onboarding and Diagnostics contain branching worth testing, but their windows are AppKit/SwiftUI. The app target must stay thin.
Decision: `PanelViewModel`, `SettingsViewModel`, `OnboardingViewModel` and `DiagnosticsViewModel` are `@MainActor @Observable` types in `SprachmittlerCore`; `SettingsStore` uses a `SettingsDataStoring` seam. `App` owns only `NSPanel`/`NSWindow` controllers, SwiftUI views, the composition root (`AppEnvironment`) and lifecycle glue. `TranslationSession` uses an injected pipeline factory so endpoint/settings changes apply on the next request without rebuilding the UI.
Consequences: Logic is covered by package tests; AppKit remains untested by `make verify` and requires the manual checklist.
## ADR-021 — Markdown is rendered as presentation only
Status: Accepted
Context: Hy-MT3 preserves Markdown structure, but a plain `Text` showed `**bold**`, headings and lists literally. Users translating Markdown want the formatting rendered, while Copy and Replace must keep the Markdown that the model produced and the validator checked.
Decision: Parse presentation Markdown in `SprachmittlerText` with Foundation's inline Markdown parser plus a small, conservative block parser (headings, lists, quotes, fenced code, rules, paragraphs). `MarkdownPresentation.shouldRender` rejects JSON, HTML and code sources and otherwise requires block or inline Markdown markers. The panel renders only when the setting `renderMarkdown` is on (default). Copy and Replace use the raw translation unchanged. Only `http` and `https` links open, on an explicit click; image syntax is reduced to alt text and no remote resource is fetched. Tables, raw HTML and nested lists/quotes remain plain text in this pass.
Consequences: Rendering never rewrites the translation or weakens validation. Literal markers can be interpreted as formatting, so the setting is the escape hatch; Copy always returns the raw Markdown. The block layout makes text selection per block, while Copy remains the whole-translation path. No new dependency is added.
## ADR-022 — Language routing: mother tongue plus source-to-target rules
Status: Accepted
Context: A single target language is a good default, but users who work in several languages need different targets for different sources: German text to English, Chinese text to English, French text to German, and everything else to the mother tongue. The earlier single fallback only covered source-equals-target.
Decision: Keep the saved target as the **mother tongue** and the default target for every source. Add `languageRoutes`, an ordered, source-unique list of `source → target` rules; the default list is empty. Before a request, detect the source and apply the first rule whose source is confidently detected; otherwise use the mother tongue. The saved and effective targets are separate: the header and language picker show the effective target, a banner explains a rule-driven direction and offers a one-capture override back to the mother tongue, and the panel picker is a session-only override. Persistent rules are edited in Settings. Same-language rules are dropped and sources are deduplicated. The source detector ignores near-zero hypotheses so the high-confidence rule is meaningful.
Consequences: The default is "every language → mother tongue". Rules are explicit, arbitrary and can be added later (for example Chinese → English or Traditional Chinese → English) without code changes. Confident detections route automatically; short, mixed or uncertain text stays on the mother tongue. The mother tongue is unchanged by routing, and the panel override never rewrites the rules. Detection is advisory, so a wrong dominant language can select the wrong rule; the banner and picker make it visible and recoverable. No key tap, permission, network access or new dependency is added.
+1 -1
View File
@@ -138,7 +138,7 @@ Hy-MT3 supports **102 languages**. The exact English name matters: it is inserte
4. **Unknown codes are not silently mapped.** The UI shows only the 102 supported languages; an incoming detection result outside the list is displayed as "Unknown" and translation still proceeds (the prompt only needs the target).
5. **Source detection is advisory.** `NLLanguageRecognizer` supports fewer languages than Hy-MT3. A low-confidence or unsupported detection never blocks translation.
6. **RTL languages:** `ar`, `he`, `fa`, `ur`, `ps`, `sd`, `ug`, `ckb`, `yi`, and `kk` (Arabic Kazakh). The panel must render them right-to-left; the source and translation directions can differ.
7. **Dense-script chunk limit:** CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts use the 2000-character chunk limit; Latin/Cyrillic/Greek use 4000. The chunker uses Unicode script ranges, not the language code.
7. **Dense-script part size:** CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts use the 2000-character part size; Latin/Cyrillic/Greek use 4000. The chunker uses Unicode script ranges, not the language code.
## 5. UI ordering
+8
View File
@@ -152,3 +152,11 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
2026-11-26 · T8.5 · Added a sibling-family app icon (`make icon`), `CFBundleIconName`/asset catalog wiring, `make install` from the Release build, and `make dmg`/`scripts/make-dmg.sh` with a mounted-image signature check. Dry-run release and local DMG/install were verified.
2026-11-26 · M4 polish · Enlarged the drag surface to the whole left header block, with a visible grip backed by an AppKit `performDrag` area; the panel keeps a moved position while visible and only recenters near the cursor when shown again. Added a persisted `translationFontSize` setting (default 17 pt, 12–28) with a Settings stepper and applied it to the translation text.
2026-11-26 · Panel · The source section now stays available as a collapsed “Show source” disclosure row after the user collapses it, instead of disappearing.
2026-11-26 · Panel · Fixed dragging: `performDrag` was a no-op while the non-activating panel's app is inactive, so `WindowDragArea` now moves the window from the screen-space mouse delta. The drag surface is a full-width 56 pt header bar flush with the panel top; buttons stay clickable above it. Verified with synthetic drags from the title, top edge, empty header and grip while Finder was frontmost.
2026-11-26 · Panel · Esc now closes the panel without a click: `TranslationPanel` becomes key on show without activating the app (`frontmostApplication` and the menu bar stay with the source app), and `keyDown` handles keyCode 53. Added the `closeWithEscape` setting (default on) and amended ADR-009.
2026-11-26 · Panel · Markdown translations render with headings, bold/italic, inline code, lists, quotes, fenced code, rules and http/https links. `MarkdownPresentation` rejects JSON/HTML/code and only renders with the `renderMarkdown` setting (default on); Copy/Replace stay raw. Added ADR-021 and tests.
2026-11-26 · Panel · A click outside the panel now closes it. The panel observes `didResignKey` and installs a transient global mouse-down monitor while visible; global monitors ignore events sent to this app, so panel/popover clicks are unaffected, and the monitor is removed on close. Verified: inside click keeps it open, outside click closes it with and without `closeWithEscape`, and an outside click while the language popover is open closes both.
2026-11-26 · Panel · Added an optional reverse direction: with the saved target German and fallback English, confidently German text is translated to English automatically, and vice versa. The saved target and effective target are separate; a banner offers a one-capture override, and the language picker still changes the saved target. `autoSwitchTarget` defaults on and `fallbackTargetLanguage` defaults to English/the opposite language. Filtered near-zero detector hypotheses so the high-confidence same-language rule works. Added resolver, settings, view-model and detector tests. (Superseded by the routing entry below.)
2026-11-26 · Settings · Replaced the single reverse-direction pair with language routing: the saved target is the mother tongue and the default for every source; an empty `languageRoutes` table means everything goes to the mother tongue. Optional source→target rules (for example Chinese → English) apply only to confidently detected sources. The panel shows the effective direction, offers a one-capture override, and keeps the picker session-only; persistent rules live in Settings. Removed the old fallback settings.
2026-11-27 · Panel · Fixed the header language picker: an override now carries the chosen language instead of only disabling routing. `TranslationDirectionPolicy.resolve` takes `override: ModelLanguage?`, and `PanelViewModel` stores the override target, so picking a language other than the mother tongue retranslates into it; a new capture still returns to the rule/mother tongue. Added picker and rule-override tests.
2026-11-27 · T3.2/T4.1/Settings · Long selections can now be translated in parts. The capture gate and the chunk size were the same number, so text over one chunk was rejected before the pipeline could split it. Added `maximumPartsPerSelection` (1–8, default 1, so existing behaviour is unchanged); the capture limit is now part size × parts, carried on `TranslationSessionRequest` and applied by the watcher, `CapturePolicy` and the session. `TranslationStreaming` can report each part, the session emits `chunkStarted`, and the panel shows “Part 2 of 4” while streaming and “3 parts” when finished. `textTooLong` now points at Settings and offers the Settings button. Lowered the dense-script part size maximum to 4000 (5000 dense characters plus a 4096-token output can overflow the 8192 context). Tests: capture limits, watcher limits, pipeline part callbacks, session events, panel progress and settings clamping. Docs: ADR-011, TRANSLATION_OUTPUT, SELECTION_AND_CLIPBOARD, ARCHITECTURE, LANGUAGES, README.
+1
View File
@@ -40,6 +40,7 @@ These are hard requirements. The `swift-reviewer` agent checks every change agai
| Screen Recording | Nothing | Never requested. No screenshots, no `CGWindowListCreateImage`, no `SCStream`. |
| Camera / Microphone | Nothing | Never requested. No `AVCaptureDevice`. |
| Apple Events | Nothing | Never requested. No `NSAppleScript` / `AEDeterminePermissionToAutomateTarget`. |
| Global mouse-down monitor | Dismiss the translation panel when the click goes to another app | Installed only while the panel is visible and removed on close. The event is discarded; no key events, location, text or app identity are read. Not a key tap and needs no Input Monitoring. |
## Clipboard rules
+2 -2
View File
@@ -33,7 +33,7 @@ Rules:
- Window: **500 ms** default, configurable 300–1000 ms.
- Identical text: compare normalized line endings and trimming only; do not collapse internal whitespace.
- Non-empty: at least one non-whitespace character.
- Length: 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts; above the limit, show `textTooLong` with the limit and no request.
- Length: part size 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts, multiplied by `maximumPartsPerSelection` (1–8, default 1); above that capture limit, show `textTooLong` with the limit, offer Settings and make no request.
- A new trigger during an active translation cancels the old one (ADR-015).
- Copying two different things quickly does not trigger; this is deliberate.
- Copying the same text twice slowly does not trigger; increase the window if needed.
@@ -160,7 +160,7 @@ Info.plist:
**This table is filled in by a person, on a real Mac.** Double copy, Accessibility replacement and clipboard restoration differ in every app and cannot be tested headlessly. Until a row is tested its cells stay ☐; an untested cell is not a claim.
Implementation status (2026-11-26): T3.1–T3.4 and T5.1–T5.4 are implemented and covered by component tests (`DoubleCopyDetector`, `PasteboardWatcher`, `ClipboardSnapshot`, `ServicesProvider`, `InsertionCoordinator`). The 4000/2000 limit and own-marker check apply to double copy, the menu item and Services (`CapturePolicy`). Replace captures the target at trigger time, re-verifies it, prefers AX and falls back to a snapshot/⌘V/restore path. The 10-app double-copy and insertion matrices remain untested; they are the T3.5/T5.5 manual tasks.
Implementation status (2026-11-26): T3.1–T3.4 and T5.1–T5.4 are implemented and covered by component tests (`DoubleCopyDetector`, `PasteboardWatcher`, `ClipboardSnapshot`, `ServicesProvider`, `InsertionCoordinator`). The script-aware part size × `maximumPartsPerSelection` capture limit and own-marker check apply to double copy, the menu item and Services (`CapturePolicy`). Replace captures the target at trigger time, re-verifies it, prefers AX and falls back to a snapshot/⌘V/restore path. The 10-app double-copy and insertion matrices remain untested; they are the T3.5/T5.5 manual tasks.
For each app test:
+14 -6
View File
@@ -24,10 +24,12 @@ The prompt prefix depends only on the target language. Append the source last. D
- Paragraph boundaries (blank lines) first.
- Then sentence boundaries (`.`, `!`, `?`, `。`, `!`, `?`, `…` followed by whitespace/end).
- Then word boundaries; never split a grapheme cluster.
- Limits: **4000 characters** for Latin/Cyrillic/Greek; **2000** for CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts. The limit is script-based, not language-based.
- Part size: **4000 characters** for Latin/Cyrillic/Greek; **2000** for CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts. The limit is script-based, not language-based.
- Capture limit: part size × `maximumPartsPerSelection` (1–8, default **1**). `1` rejects a selection longer than one part; higher values accept it and translate it part by part. The dense part size is configurable up to 4000.
- Reassemble with the original separators (usually `\n\n`). Do not collapse or invent paragraph breaks.
- Translate chunks sequentially; one request in flight.
- A chunk failure stops the sequence and is shown as `chunkFailed(index:)`; the panel keeps the partial translation and disables Replace.
- Translate parts sequentially; one request in flight.
- Show “Part i of n” while a multi-part request streams and “n parts” when it finishes.
- A part failure stops the sequence and is shown as `chunkFailed(index:)`; the panel keeps the partial translation and disables Replace.
## 4. Protected tokens
@@ -62,7 +64,7 @@ Do not substitute tokens with sentinels in v1: sentinels can leak into the outpu
| T3 | No spelling, grammar, style, terminology or punctuation edits. No de-duplication. No "cleanup" of model wording. | always |
| T4 | Do not strip a preamble or explanation. Detect it, warn, keep the raw text, disable Replace by default. | always |
The panel shows the T1 output. There is no hidden rewrite. If the model returns a preamble, the user sees it.
The panel shows the T1 output. There is no hidden rewrite. If the model returns a preamble, the user sees it. Markdown rendering in the panel is presentation only: validation, Copy and Replace all use the raw T1 string, including its Markdown markers. See ADR-021.
## 6. Preamble detection
@@ -81,9 +83,15 @@ If detected: warning `preambleDetected(firstLine:)`; the panel shows a banner; R
- Repetition: the same normalised line (≥ 8 chars) repeated ≥ 6 times consecutively, or a 64-character window repeated ≥ 8 times in the last 2048 characters. Cancel the stream early and warn `repetitionLoop`.
- Empty output after T1 → `emptyOutput`; no Copy/Replace of an empty string.
## 8. Same-language input
## 8. Same-language input and language routing
If `NLLanguageRecognizer` reports the target language with confidence ≥ 0.5 and all detected candidates agree, show "This text already appears to be in {language}" and offer "Translate anyway". Do not block: short text, names and mixed text are often misdetected.
`NLLanguageRecognizer` reports the dominant language with a confidence and several candidates. Hypotheses below 0.05 are ignored, so a confident single-language text is not treated as mixed. The source is considered to be language `X` only when the confidence is at least 0.5 and every meaningful candidate resolves to `X`.
The saved target is the **mother tongue**. Every source language without a rule is translated into the mother tongue. Optional `languageRoutes` map a source language to a target language; a rule is used only when its source is confidently detected. Rules with source equal to target are ignored, and routes are deduplicated by source.
When a rule applies, the prompt, chunking and validation use its target. The panel shows the effective direction (for example "French → English"), a banner explains the rule, and "Translate to German" (the mother tongue) overrides the direction for that capture only. The panel's language picker is a session-only override; persistent rules are managed in Settings. When no rule applies, the same-language advisory appears if the source is the mother tongue.
Detection is advisory: short, mixed or uncertain text keeps the mother tongue, and the user can change the target for that result.
## 9. Numbers and units
+24 -1
View File
@@ -35,7 +35,7 @@ the Hy-MT3 model and the target language. You can reopen setup from the menu bar
1. Select text in any app.
2. Press **⌘C** twice quickly (within 500 ms).
3. The floating panel appears near the mouse. The source app keeps focus.
3. The floating panel appears near the mouse. The source app stays frontmost; the panel takes keyboard focus while it is visible so Esc and the shortcuts work immediately. Clicking the source app takes focus back. Clicking anywhere outside the panel closes it; Esc also closes it.
4. The translation streams in. Use the language picker to change the target.
5. Click **Copy** to put the translation on the clipboard, or **Replace** to replace the selection.
6. **Esc** closes the panel. **⌘C** copies, **⌘↩** replaces, **⌘R** retries and **⌘,** opens Settings.
@@ -43,6 +43,29 @@ the Hy-MT3 model and the target language. You can reopen setup from the menu bar
Replace is explicit; nothing is inserted automatically. Replace needs the macOS Accessibility
permission. Double copy, translation, Copy and the Services menu work without it.
### Mother tongue and language rules
The **mother tongue** is the default target for every source language. In
**Settings ▸ General ▸ Translation**, you can add **language rules** that override the default for
specific source languages:
```text
Mother tongue: German
Language rules:
Chinese (Simplified) → English
Traditional Chinese → English
German → English
```
With the table above, Chinese and German text go to English, and every other language goes to
German. An empty table means everything goes to the mother tongue.
Rules run in the order shown; a source language appears at most once. Rules apply only when the
source is confidently detected; short or mixed text keeps the mother tongue. When a rule applies,
the panel header shows the effective direction and a banner offers a one-capture override back to
the mother tongue. Choosing a language from the panel picker also overrides the current result only;
manage persistent rules in Settings.
## 4. Services and the menu bar
- **Services ▸ Translate with Sprachmittler** translates the current selection without polling
+2
View File
@@ -59,6 +59,8 @@ targets:
product: SprachmittlerCore
- package: SprachmittlerKit
product: SprachmittlerCapture
- package: SprachmittlerKit
product: SprachmittlerText
schemes:
Sprachmittler: