M4: TranslationSession actor with epochs/one-in-flight streaming, PanelViewModel, non-activating NSPanel, streaming panel UI, searchable/recent target languages, warnings/errors and Copy/Retry/Replace actions. M5: InsertionCoordinator with target capture, AX direct replacement, secure-field/own-PID refusal, frontmost and selected-text verification, snapshot/⌘V/restore fallback, cancellation-safe restore and blocking-warning gate. M6: versioned AppSettings/SettingsStore, onboarding for Ollama/model/target/Accessibility, General/Model/Translation/Privacy/Diagnostics settings, launch-at-login via SMAppService, status menu (target, copy/replace last, setup, diagnostics, about), text-free diagnostics and first-run setup. Docs: PROGRESS M4–M6, ARCHITECTURE §10–§12, ADR-019/020, SELECTION_AND_CLIPBOARD and TESTING. Manual 10-app matrices, real AX/paste delivery, VoiceOver and focus checks remain open. Verified: make verify green (format, strict lint, scripts, privacy, Debug+Release signatures, 217 package tests); app launches and a two-copy clipboard smoke test opens the panel.
347 lines
12 KiB
Swift
347 lines
12 KiB
Swift
import Foundation
|
|
import SprachmittlerEngines
|
|
import SprachmittlerOllama
|
|
import SprachmittlerText
|
|
|
|
/// Timing for one completed translation (`docs/ARCHITECTURE.md` §5).
|
|
public struct TranslationTiming: Sendable, Equatable {
|
|
/// Time to the first delta, when one arrived.
|
|
public let firstTokenMs: Int?
|
|
/// Total time.
|
|
public let totalMs: Int
|
|
/// Prompt tokens reported by Ollama, summed over attempts.
|
|
public let promptTokens: Int?
|
|
/// Output tokens reported by Ollama, summed over attempts.
|
|
public let outputTokens: Int?
|
|
|
|
/// Creates a timing value.
|
|
public init(firstTokenMs: Int?, totalMs: Int, promptTokens: Int?, outputTokens: Int?) {
|
|
self.firstTokenMs = firstTokenMs
|
|
self.totalMs = totalMs
|
|
self.promptTokens = promptTokens
|
|
self.outputTokens = outputTokens
|
|
}
|
|
}
|
|
|
|
/// The result of the documented translation pipeline.
|
|
public struct PipelineResult: Sendable, Equatable {
|
|
/// The translation after T1 only.
|
|
public let translation: String
|
|
/// Validation warnings and guard findings from the output validator.
|
|
public let warnings: [TranslationWarning]
|
|
/// The advisory source language, when detection succeeded.
|
|
public let sourceLanguage: String?
|
|
/// Timing counters.
|
|
public let timing: TranslationTiming
|
|
/// How many chunks were translated.
|
|
public let chunkCount: Int
|
|
|
|
/// Creates a result.
|
|
public init(
|
|
translation: String,
|
|
warnings: [TranslationWarning],
|
|
sourceLanguage: String?,
|
|
timing: TranslationTiming,
|
|
chunkCount: Int
|
|
) {
|
|
self.translation = translation
|
|
self.warnings = warnings
|
|
self.sourceLanguage = sourceLanguage
|
|
self.timing = timing
|
|
self.chunkCount = chunkCount
|
|
}
|
|
}
|
|
|
|
/// Translates text with the documented prompt, chunking and validation.
|
|
///
|
|
/// This type is shared by the CLI and the M4 session. It never edits the model output beyond T1
|
|
/// and it retries only once, only when a protected token was lost.
|
|
public struct TranslationPipeline: Sendable {
|
|
private let chat: any OllamaChatting
|
|
private let registry: AdapterRegistry
|
|
private let detector: any LanguageDetecting
|
|
private let chunker: Chunker
|
|
private let scanner: ProtectedTokenScanner
|
|
private let validator: OutputValidator
|
|
private let policy: PromptPolicy
|
|
private let clock: @Sendable () -> Date
|
|
|
|
/// Creates a pipeline. Concrete clients come from the composition root.
|
|
public init(
|
|
chat: any OllamaChatting,
|
|
registry: AdapterRegistry,
|
|
detector: any LanguageDetecting = NaturalLanguageDetector(),
|
|
chunker: Chunker = Chunker(),
|
|
scanner: ProtectedTokenScanner = ProtectedTokenScanner(),
|
|
validator: OutputValidator = OutputValidator(),
|
|
policy: PromptPolicy = PromptPolicy(),
|
|
clock: @escaping @Sendable () -> Date = { Date() }
|
|
) {
|
|
self.chat = chat
|
|
self.registry = registry
|
|
self.detector = detector
|
|
self.chunker = chunker
|
|
self.scanner = scanner
|
|
self.validator = validator
|
|
self.policy = policy
|
|
self.clock = clock
|
|
}
|
|
|
|
/// Translates `text` into `target` with `model`.
|
|
public func translate(
|
|
text: String,
|
|
target: ModelLanguage,
|
|
model: String,
|
|
keepAlive: String,
|
|
sampling: SamplingOptions = .publisherDefault,
|
|
onDelta: (@Sendable (String) async -> Void)? = nil
|
|
) async throws -> PipelineResult {
|
|
let normalized = TextNormalization.normalizeInput(text)
|
|
guard !normalized.isEmpty else {
|
|
throw SprachmittlerError.emptyText
|
|
}
|
|
guard registry.adapter(for: model) != nil else {
|
|
throw SprachmittlerError.noAdapter(model: model)
|
|
}
|
|
|
|
let started = clock()
|
|
let detection = detector.detect(normalized)
|
|
let content = ContentClassifier(scanner: scanner).classify(normalized)
|
|
let tokens = scanner.scan(normalized)
|
|
let chunks = chunker.chunks(for: normalized)
|
|
let context = TranslationContext(
|
|
content: content,
|
|
target: target,
|
|
model: model,
|
|
keepAlive: keepAlive,
|
|
sampling: sampling,
|
|
tokens: tokens,
|
|
onDelta: onDelta
|
|
)
|
|
let accumulator = try await translateAll(chunks, context: context)
|
|
|
|
let final = TextNormalization.normalizeOutput(accumulator.joined)
|
|
let validation = validator.validate(
|
|
source: normalized,
|
|
translation: final,
|
|
doneReason: accumulator.sawLength ? "length" : nil,
|
|
tokens: tokens
|
|
)
|
|
var warnings = accumulator.warnings
|
|
warnings.append(contentsOf: validation.warnings)
|
|
if let detection, LanguageMatching.isSameLanguage(detection, target: target) {
|
|
warnings.append(.sameLanguage(source: detection.code, target: target.code))
|
|
}
|
|
|
|
let elapsed = max(0, Int(clock().timeIntervalSince(started) * 1000))
|
|
let firstTokenMs = accumulator.firstTokenAt.map { max(0, Int($0.timeIntervalSince(started) * 1000)) }
|
|
return PipelineResult(
|
|
translation: final,
|
|
warnings: deduplicated(warnings),
|
|
sourceLanguage: detection?.code,
|
|
timing: TranslationTiming(
|
|
firstTokenMs: firstTokenMs,
|
|
totalMs: elapsed,
|
|
promptTokens: accumulator.promptTokens,
|
|
outputTokens: accumulator.outputTokens
|
|
),
|
|
chunkCount: chunks.count
|
|
)
|
|
}
|
|
|
|
private struct TranslationContext {
|
|
let content: ContentClass
|
|
let target: ModelLanguage
|
|
let model: String
|
|
let keepAlive: String
|
|
let sampling: SamplingOptions
|
|
let tokens: [ProtectedToken]
|
|
let onDelta: (@Sendable (String) async -> Void)?
|
|
}
|
|
|
|
private struct Accumulator {
|
|
var firstTokenAt: Date?
|
|
var promptTokens: Int?
|
|
var outputTokens: Int?
|
|
var joined = ""
|
|
var warnings: [TranslationWarning] = []
|
|
var sawLength = false
|
|
}
|
|
|
|
private func translateAll(_ chunks: [TextChunk], context: TranslationContext) async throws -> Accumulator {
|
|
var accumulator = Accumulator()
|
|
do {
|
|
for chunk in chunks {
|
|
try Task.checkCancellation()
|
|
let result = try await translateChunk(chunk, context: context)
|
|
if accumulator.firstTokenAt == nil {
|
|
accumulator.firstTokenAt = result.firstTokenAt
|
|
}
|
|
accumulator.promptTokens = sum(accumulator.promptTokens, result.promptTokens)
|
|
accumulator.outputTokens = sum(accumulator.outputTokens, result.outputTokens)
|
|
if result.looped {
|
|
accumulator.warnings.append(.repetitionLoop)
|
|
}
|
|
if result.doneReason == "length" {
|
|
accumulator.sawLength = true
|
|
}
|
|
accumulator.joined += result.text + chunk.separatorAfter
|
|
if !chunk.separatorAfter.isEmpty {
|
|
await context.onDelta?(chunk.separatorAfter)
|
|
}
|
|
}
|
|
} catch is CancellationError {
|
|
throw SprachmittlerError.cancelled
|
|
}
|
|
return accumulator
|
|
}
|
|
|
|
private struct ChunkTranslation {
|
|
let text: String
|
|
let doneReason: String?
|
|
let looped: Bool
|
|
let firstTokenAt: Date?
|
|
let promptTokens: Int?
|
|
let outputTokens: Int?
|
|
}
|
|
|
|
private func translateChunk(
|
|
_ chunk: TextChunk,
|
|
context: TranslationContext
|
|
) async throws -> ChunkTranslation {
|
|
let chunkTokens = context.tokens.filter { chunk.text.contains($0.value) }
|
|
var prompt = policy.initialPrompt(for: context.content)
|
|
var retried = false
|
|
var response = StreamResult(
|
|
text: "",
|
|
doneReason: nil,
|
|
metrics: .empty,
|
|
firstTokenAt: nil,
|
|
looped: false
|
|
)
|
|
var promptTokens: Int?
|
|
var outputTokens: Int?
|
|
|
|
while true {
|
|
let request = try makeRequest(chunk: chunk, prompt: prompt, context: context)
|
|
// A retry replaces the first attempt; do not stream both into the panel.
|
|
let deltaHandler = retried ? nil : context.onDelta
|
|
let attempt = try await stream(request, onDelta: deltaHandler)
|
|
response = attempt
|
|
promptTokens = sum(promptTokens, attempt.metrics.promptEvalCount)
|
|
outputTokens = sum(outputTokens, attempt.metrics.evalCount)
|
|
|
|
let translated = TextNormalization.normalizeOutput(attempt.text)
|
|
let missing = validator.missingTokens(
|
|
source: chunk.text,
|
|
translation: translated,
|
|
tokens: chunkTokens
|
|
)
|
|
let retryPrompt = missing.isEmpty
|
|
? nil
|
|
: policy.retryPrompt(for: context.content, lostToken: missing[0])
|
|
if !retried, let retryPrompt {
|
|
retried = true
|
|
prompt = retryPrompt
|
|
continue
|
|
}
|
|
break
|
|
}
|
|
|
|
return ChunkTranslation(
|
|
text: TextNormalization.normalizeOutput(response.text),
|
|
doneReason: response.doneReason,
|
|
looped: response.looped,
|
|
firstTokenAt: response.firstTokenAt,
|
|
promptTokens: promptTokens,
|
|
outputTokens: outputTokens
|
|
)
|
|
}
|
|
|
|
private func makeRequest(
|
|
chunk: TextChunk,
|
|
prompt: PromptVariant,
|
|
context: TranslationContext
|
|
) throws -> ChatRequest {
|
|
try registry.makeRequest(
|
|
AdapterRequest(
|
|
text: chunk.text,
|
|
target: context.target,
|
|
model: context.model,
|
|
keepAlive: context.keepAlive,
|
|
prompt: prompt,
|
|
sampling: context.sampling
|
|
)
|
|
)
|
|
}
|
|
|
|
private struct StreamResult {
|
|
let text: String
|
|
let doneReason: String?
|
|
let metrics: ChatMetrics
|
|
let firstTokenAt: Date?
|
|
let looped: Bool
|
|
}
|
|
|
|
private func stream(
|
|
_ request: ChatRequest,
|
|
onDelta: (@Sendable (String) async -> Void)?
|
|
) async throws -> StreamResult {
|
|
var text = ""
|
|
var doneReason: String?
|
|
var metrics = ChatMetrics.empty
|
|
var firstTokenAt: Date?
|
|
var repetition = RepetitionDetector()
|
|
var looped = false
|
|
|
|
do {
|
|
for try await event in chat.chat(request) {
|
|
try Task.checkCancellation()
|
|
switch event {
|
|
case let .delta(delta):
|
|
if firstTokenAt == nil {
|
|
firstTokenAt = clock()
|
|
}
|
|
text += delta
|
|
await onDelta?(delta)
|
|
if repetition.append(delta) {
|
|
looped = true
|
|
}
|
|
case let .done(reason, doneMetrics):
|
|
doneReason = reason
|
|
metrics = doneMetrics
|
|
}
|
|
if looped {
|
|
break
|
|
}
|
|
}
|
|
} catch let error as OllamaError {
|
|
throw SprachmittlerError(ollama: error)
|
|
} catch is CancellationError {
|
|
throw SprachmittlerError.cancelled
|
|
}
|
|
|
|
return StreamResult(
|
|
text: text,
|
|
doneReason: doneReason,
|
|
metrics: metrics,
|
|
firstTokenAt: firstTokenAt,
|
|
looped: looped
|
|
)
|
|
}
|
|
|
|
private func sum(_ current: Int?, _ next: Int?) -> Int? {
|
|
switch (current, next) {
|
|
case let (current?, next?): current + next
|
|
case let (current?, nil): current
|
|
case let (nil, next?): next
|
|
case (nil, nil): nil
|
|
}
|
|
}
|
|
|
|
private func deduplicated(_ warnings: [TranslationWarning]) -> [TranslationWarning] {
|
|
var seen = Set<TranslationWarning>()
|
|
return warnings.filter { seen.insert($0).inserted }
|
|
}
|
|
}
|