Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11), free to diverge. Tree copied sans upstream .git; upstream remote added for future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19. Preserves docs/ARCHITECTURE.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
180 lines
6.2 KiB
Swift
180 lines
6.2 KiB
Swift
import AVFoundation
|
|
import Foundation
|
|
|
|
@MainActor
|
|
public final class TalkSystemSpeechSynthesizer: NSObject {
|
|
public enum SpeakError: Error {
|
|
case canceled
|
|
}
|
|
|
|
public static let shared = TalkSystemSpeechSynthesizer()
|
|
|
|
private let synth = AVSpeechSynthesizer()
|
|
private var speakContinuation: CheckedContinuation<Void, Error>?
|
|
private var currentUtterance: AVSpeechUtterance?
|
|
private var didStartCallback: (() -> Void)?
|
|
private var currentToken = UUID()
|
|
private var watchdog: Task<Void, Never>?
|
|
|
|
public var isSpeaking: Bool {
|
|
self.synth.isSpeaking
|
|
}
|
|
|
|
override private init() {
|
|
super.init()
|
|
self.synth.delegate = self
|
|
}
|
|
|
|
public func stop() {
|
|
self.currentToken = UUID()
|
|
self.watchdog?.cancel()
|
|
self.watchdog = nil
|
|
self.didStartCallback = nil
|
|
self.synth.stopSpeaking(at: .immediate)
|
|
self.finishCurrent(with: SpeakError.canceled)
|
|
}
|
|
|
|
public func speak(
|
|
text: String,
|
|
language: String? = nil,
|
|
onStart: (() -> Void)? = nil) async throws
|
|
{
|
|
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
guard !trimmed.isEmpty else { return }
|
|
|
|
self.stop()
|
|
let token = UUID()
|
|
self.currentToken = token
|
|
self.didStartCallback = onStart
|
|
|
|
let utterance = AVSpeechUtterance(string: trimmed)
|
|
if let language, let voice = AVSpeechSynthesisVoice(language: language) {
|
|
utterance.voice = voice
|
|
}
|
|
self.currentUtterance = utterance
|
|
|
|
let watchdogTimeout = Self.watchdogTimeoutSeconds(
|
|
text: trimmed,
|
|
language: language ?? utterance.voice?.language)
|
|
self.watchdog?.cancel()
|
|
self.watchdog = Task { @MainActor [weak self] in
|
|
guard let self else { return }
|
|
try? await Task.sleep(nanoseconds: UInt64(watchdogTimeout * 1_000_000_000))
|
|
if Task.isCancelled { return }
|
|
guard self.currentToken == token else { return }
|
|
if self.synth.isSpeaking {
|
|
self.synth.stopSpeaking(at: .immediate)
|
|
}
|
|
self.finishCurrent(
|
|
with: NSError(domain: "TalkSystemSpeechSynthesizer", code: 408, userInfo: [
|
|
NSLocalizedDescriptionKey: "system TTS timed out after \(watchdogTimeout)s",
|
|
]))
|
|
}
|
|
|
|
try await withTaskCancellationHandler(operation: {
|
|
try await withCheckedThrowingContinuation { cont in
|
|
self.speakContinuation = cont
|
|
self.synth.speak(utterance)
|
|
}
|
|
}, onCancel: {
|
|
Task { @MainActor in
|
|
self.stop()
|
|
}
|
|
})
|
|
|
|
if self.currentToken != token {
|
|
throw SpeakError.canceled
|
|
}
|
|
}
|
|
|
|
static func watchdogTimeoutSeconds(text: String, language: String?) -> Double {
|
|
// Estimate speech duration per language, then apply 3x safety margin.
|
|
// The watchdog is a hang guard — normal completion relies on didFinish.
|
|
//
|
|
// Speech rates based on Pellegrino et al. (2019) syllable-per-second data,
|
|
// adjusted for TTS synthesis (slower than natural speech):
|
|
// https://www.science.org/doi/10.1126/sciadv.aaw2594
|
|
// Japanese: 7.84 SPS -> ~0.20s/char (mixed kana/kanji avg ~1.5 mora/char)
|
|
// Korean: 5.96 SPS -> ~0.25s/char (1 char = 1 syllable)
|
|
// Chinese: 5.18 SPS -> ~0.28s/char (1 char = 1 syllable)
|
|
// English: 6.19 SPS -> ~0.08s/char (avg ~5 chars/syllable)
|
|
let normalizedLanguage = language?.lowercased() ?? "en"
|
|
let perCharSeconds: Double
|
|
let minSeconds: Double
|
|
if normalizedLanguage.hasPrefix("ko") {
|
|
perCharSeconds = 0.25
|
|
minSeconds = 10.0
|
|
} else if normalizedLanguage.hasPrefix("zh") {
|
|
perCharSeconds = 0.28
|
|
minSeconds = 10.0
|
|
} else if normalizedLanguage.hasPrefix("ja") {
|
|
perCharSeconds = 0.20
|
|
minSeconds = 10.0
|
|
} else {
|
|
perCharSeconds = 0.08
|
|
minSeconds = 3.0
|
|
}
|
|
let estimatedSeconds = max(minSeconds, min(300.0, Double(text.count) * perCharSeconds))
|
|
return estimatedSeconds * 3.0
|
|
}
|
|
|
|
private func matchesCurrentUtterance(_ utteranceID: ObjectIdentifier) -> Bool {
|
|
guard let currentUtterance = self.currentUtterance else { return false }
|
|
return ObjectIdentifier(currentUtterance) == utteranceID
|
|
}
|
|
|
|
private func handleFinish(utteranceID: ObjectIdentifier, error: Error?) {
|
|
guard self.matchesCurrentUtterance(utteranceID) else { return }
|
|
self.watchdog?.cancel()
|
|
self.watchdog = nil
|
|
self.finishCurrent(with: error)
|
|
}
|
|
|
|
private func finishCurrent(with error: Error?) {
|
|
self.currentUtterance = nil
|
|
self.didStartCallback = nil
|
|
let cont = self.speakContinuation
|
|
self.speakContinuation = nil
|
|
if let error {
|
|
cont?.resume(throwing: error)
|
|
} else {
|
|
cont?.resume(returning: ())
|
|
}
|
|
}
|
|
}
|
|
|
|
extension TalkSystemSpeechSynthesizer: AVSpeechSynthesizerDelegate {
|
|
public nonisolated func speechSynthesizer(
|
|
_ synthesizer: AVSpeechSynthesizer,
|
|
didStart utterance: AVSpeechUtterance)
|
|
{
|
|
let utteranceID = ObjectIdentifier(utterance)
|
|
Task { @MainActor in
|
|
guard self.matchesCurrentUtterance(utteranceID) else { return }
|
|
let callback = self.didStartCallback
|
|
self.didStartCallback = nil
|
|
callback?()
|
|
}
|
|
}
|
|
|
|
public nonisolated func speechSynthesizer(
|
|
_ synthesizer: AVSpeechSynthesizer,
|
|
didFinish utterance: AVSpeechUtterance)
|
|
{
|
|
let utteranceID = ObjectIdentifier(utterance)
|
|
Task { @MainActor in
|
|
self.handleFinish(utteranceID: utteranceID, error: nil)
|
|
}
|
|
}
|
|
|
|
public nonisolated func speechSynthesizer(
|
|
_ synthesizer: AVSpeechSynthesizer,
|
|
didCancel utterance: AVSpeechUtterance)
|
|
{
|
|
let utteranceID = ObjectIdentifier(utterance)
|
|
Task { @MainActor in
|
|
self.handleFinish(utteranceID: utteranceID, error: SpeakError.canceled)
|
|
}
|
|
}
|
|
}
|