Skip to content

Commit ff5cafb

Browse files
bkudiessCopilotCopilotshanselman
authored
Add resilient TTS fallback and readiness status (#806)
* Add TTS provider fallback and tts.status readiness command When the requested/configured TTS provider isn't usable (no ElevenLabs key, Piper voice not downloaded), gracefully fall back to Windows TTS instead of throwing, and report the effective vs requested provider plus a fellBack flag. A stale configured Windows voice now degrades to the system default voice so the fallback always speaks. Add a tts.status node command that reports per-provider readiness (ready/needs-api-key/needs-voice/voice-not-downloaded/unavailable) plus the configured/effective provider and willFallBack. PII-free. Wired across DangerousCommands gating, MCP descriptions, skill.md, and the setup allowlist export. Fix a stale pre-GA SHA-256 TODO docstring in PiperVoiceManager (verification is already implemented and enforced by AssetHashPinningTests). Co-authored-by: Copilot <[email protected]> * Preserve configured TTS fallback for chat playback Leave chat playback provider unset so TextToSpeechService can distinguish configured/default playback from explicit provider requests and apply the new Windows fallback when the configured provider is unavailable. Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Scott Hanselman <[email protected]>
1 parent c338d41 commit ff5cafb

12 files changed

Lines changed: 508 additions & 16 deletions

File tree

‎src/OpenClaw.SetupEngine/SetupContext.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ public sealed class CapabilitiesConfig
143143
if (Screen) result.Add(("screen", ["screen.snapshot", "screen.record"]));
144144
if (Camera) result.Add(("camera", ["camera.list", "camera.snap", "camera.clip"]));
145145
if (Location) result.Add(("location", ["location.get"]));
146-
if (Tts) result.Add(("tts", ["tts.speak"]));
146+
if (Tts) result.Add(("tts", ["tts.speak", "tts.status"]));
147147
if (Stt) result.Add(("stt", ["stt.transcribe", "stt.listen", "stt.status"]));
148148
if (Device) result.Add(("device", ["device.info", "device.status"]));
149149
if (Browser) result.Add(("browser", ["browser.proxy"]));

‎src/OpenClaw.Shared/Audio/PiperVoiceManager.cs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@ namespace OpenClaw.Shared.Audio;
2727
///
2828
/// Each voice is ~50 MB compressed, ~80 MB extracted (with espeak data).
2929
///
30-
/// **TODO (pre-GA):** SHA-256 verification of downloaded tarballs before
31-
/// extraction (Audio_FollowUps.md §2). The current implementation trusts
32-
/// HTTPS + the system trust chain only.
30+
/// **Integrity:** downloaded tarballs are SHA-256-verified against the pinned
31+
/// hash in <see cref="AvailableVoices"/> before extraction; a mismatch is a
32+
/// hard failure and the partial file is deleted (see Audio_FollowUps.md §2).
3333
/// </summary>
3434
public sealed class PiperVoiceManager
3535
{

‎src/OpenClaw.Shared/Capabilities/TtsCapability.cs‎

Lines changed: 164 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Linq;
34
using System.Threading;
45
using System.Threading.Tasks;
56

@@ -8,6 +9,7 @@ namespace OpenClaw.Shared.Capabilities;
89
public sealed class TtsCapability : NodeCapabilityBase
910
{
1011
public const string SpeakCommand = "tts.speak";
12+
public const string StatusCommand = "tts.status";
1113
public const string WindowsProvider = "windows";
1214
public const string ElevenLabsProvider = "elevenlabs";
1315
/// <summary>
@@ -17,13 +19,39 @@ public sealed class TtsCapability : NodeCapabilityBase
1719
public const string PiperProvider = "piper";
1820
public const int MaxTextLength = 5000;
1921

20-
private static readonly string[] _commands = [SpeakCommand];
22+
// ============================================================
23+
// Provider readiness reasons (PII-free; surfaced by tts.status and used
24+
// by the fallback resolver below). Kept as string constants rather than
25+
// an enum so the wire shape mirrors stt.status's readiness string.
26+
// ============================================================
27+
28+
/// <summary>Provider can serve a speak call right now.</summary>
29+
public const string ReadinessReady = "ready";
30+
/// <summary>ElevenLabs selected but no API key is configured.</summary>
31+
public const string ReadinessNeedsApiKey = "needs-api-key";
32+
/// <summary>ElevenLabs selected with a key but no voice id is configured.</summary>
33+
public const string ReadinessNeedsVoice = "needs-voice";
34+
/// <summary>Piper selected but the chosen voice isn't downloaded yet.</summary>
35+
public const string ReadinessVoiceNotDownloaded = "voice-not-downloaded";
36+
/// <summary>Provider is unknown or otherwise unusable.</summary>
37+
public const string ReadinessUnavailable = "unavailable";
38+
39+
/// <summary>All known providers, in catalog order (Piper is the default).</summary>
40+
public static readonly string[] AllProviders = [PiperProvider, WindowsProvider, ElevenLabsProvider];
41+
42+
private static readonly string[] _commands = [SpeakCommand, StatusCommand];
2143

2244
public override string Category => "tts";
2345
public override IReadOnlyList<string> Commands => _commands;
2446

2547
public event Func<TtsSpeakArgs, CancellationToken, Task<TtsSpeakResult>>? SpeakRequested;
2648

49+
/// <summary>
50+
/// Tray-side handler for <see cref="StatusCommand"/>: reports per-provider
51+
/// readiness plus the configured/effective provider. Carries no PII.
52+
/// </summary>
53+
public event Func<CancellationToken, Task<TtsStatusResult>>? StatusRequested;
54+
2755
public TtsCapability(IOpenClawLogger logger) : base(logger)
2856
{
2957
}
@@ -39,13 +67,57 @@ public static string ResolveProvider(string? requestedProvider, string? configur
3967
: provider.Trim().ToLowerInvariant();
4068
}
4169

70+
/// <summary>
71+
/// Resolve the provider that should actually serve a speak request given
72+
/// the set of providers that are currently usable. The requested (then
73+
/// configured, then default) provider wins when it is usable. Fallback to
74+
/// Windows is limited to configured/default provider degradation; explicit
75+
/// provider requests stay strict so callers can rely on provider selection.
76+
/// When no provider is usable (should not happen because Windows is always
77+
/// available) the preferred provider is returned unchanged so the caller's
78+
/// downstream error stays meaningful.
79+
/// </summary>
80+
/// <param name="requestedProvider">Per-call provider override (may be null).</param>
81+
/// <param name="configuredProvider">User's configured default provider.</param>
82+
/// <param name="readyProviders">Lower-cased provider ids that can serve a call now.</param>
83+
public static TtsProviderResolution ResolveEffectiveProvider(
84+
string? requestedProvider,
85+
string? configuredProvider,
86+
IReadOnlySet<string> readyProviders,
87+
bool allowFallback)
88+
{
89+
ArgumentNullException.ThrowIfNull(readyProviders);
90+
91+
var preferred = ResolveProvider(requestedProvider, configuredProvider);
92+
if (readyProviders.Contains(preferred))
93+
return new TtsProviderResolution(preferred, preferred, FellBack: false);
94+
95+
// Windows is the always-offline safety net for configured/default
96+
// provider degradation. Explicit per-call provider requests stay
97+
// strict and are not silently rerouted.
98+
if (allowFallback
99+
&& !string.Equals(preferred, WindowsProvider, StringComparison.Ordinal)
100+
&& readyProviders.Contains(WindowsProvider))
101+
{
102+
return new TtsProviderResolution(preferred, WindowsProvider, FellBack: true);
103+
}
104+
105+
// Nothing usable — surface the preferred provider so the dispatch
106+
// layer's "not configured" error is about the provider the user asked
107+
// for, not an arbitrary fallback.
108+
return new TtsProviderResolution(preferred, preferred, FellBack: false);
109+
}
110+
42111
public override Task<NodeInvokeResponse> ExecuteAsync(NodeInvokeRequest request)
43112
=> ExecuteAsync(request, CancellationToken.None);
44113

45114
public override async Task<NodeInvokeResponse> ExecuteAsync(
46115
NodeInvokeRequest request,
47116
CancellationToken cancellationToken)
48117
{
118+
if (string.Equals(request.Command, StatusCommand, StringComparison.Ordinal))
119+
return await HandleStatusAsync(cancellationToken).ConfigureAwait(false);
120+
49121
if (!string.Equals(request.Command, SpeakCommand, StringComparison.Ordinal))
50122
return Error($"Unknown command: {request.Command}");
51123

@@ -76,6 +148,8 @@ public override async Task<NodeInvokeResponse> ExecuteAsync(
76148
{
77149
spoken = result.Spoken,
78150
provider = result.Provider,
151+
requestedProvider = result.RequestedProvider ?? result.Provider,
152+
fellBack = result.FellBack,
79153
contentType = result.ContentType,
80154
durationMs = result.DurationMs
81155
});
@@ -97,6 +171,36 @@ public override async Task<NodeInvokeResponse> ExecuteAsync(
97171
}
98172
}
99173

174+
private async Task<NodeInvokeResponse> HandleStatusAsync(CancellationToken cancellationToken)
175+
{
176+
if (StatusRequested == null)
177+
return Error("TTS status not available");
178+
179+
try
180+
{
181+
var result = await StatusRequested(cancellationToken).ConfigureAwait(false);
182+
return Success(new
183+
{
184+
configuredProvider = result.ConfiguredProvider,
185+
effectiveProvider = result.EffectiveProvider,
186+
willFallBack = result.WillFallBack,
187+
providers = result.Providers.Select(p => new
188+
{
189+
provider = p.Provider,
190+
readiness = p.Readiness,
191+
isReady = p.IsReady
192+
}).ToArray()
193+
});
194+
}
195+
catch (Exception ex)
196+
{
197+
// Status must not leak provider internals (voice ids, key
198+
// fragments, device names); carry only a fixed message.
199+
Logger.Error("TTS status failed", ex);
200+
return Error("Status failed");
201+
}
202+
}
203+
100204
private static string? NormalizeOptional(string? value)
101205
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
102206
}
@@ -114,6 +218,65 @@ public sealed class TtsSpeakResult
114218
{
115219
public bool Spoken { get; set; } = true;
116220
public string Provider { get; set; } = TtsCapability.WindowsProvider;
221+
222+
/// <summary>
223+
/// The provider that was originally requested/configured before any
224+
/// fallback. Equals <see cref="Provider"/> when no fallback occurred.
225+
/// Null is treated as "same as Provider" by the response surface.
226+
/// </summary>
227+
public string? RequestedProvider { get; set; }
228+
229+
/// <summary>
230+
/// True when the requested/configured provider was not usable and the
231+
/// service fell back to another provider (Windows) to serve the call.
232+
/// </summary>
233+
public bool FellBack { get; set; }
234+
117235
public string? ContentType { get; set; }
118236
public int? DurationMs { get; set; }
119237
}
238+
239+
/// <summary>
240+
/// Result of <see cref="TtsCapability.ResolveEffectiveProvider"/>: the
241+
/// provider originally preferred and the one that should actually serve the
242+
/// call after fallback.
243+
/// </summary>
244+
/// <param name="RequestedProvider">The resolved requested/configured provider before fallback.</param>
245+
/// <param name="EffectiveProvider">The provider that should serve the call.</param>
246+
/// <param name="FellBack">True when <paramref name="EffectiveProvider"/> differs from <paramref name="RequestedProvider"/> because the latter wasn't usable.</param>
247+
public readonly record struct TtsProviderResolution(
248+
string RequestedProvider,
249+
string EffectiveProvider,
250+
bool FellBack);
251+
252+
/// <summary>Per-provider readiness snapshot (PII-free) for <c>tts.status</c>.</summary>
253+
public sealed class TtsProviderStatus
254+
{
255+
public string Provider { get; set; } = "";
256+
/// <summary>
257+
/// One of <see cref="TtsCapability.ReadinessReady"/>,
258+
/// <see cref="TtsCapability.ReadinessNeedsApiKey"/>,
259+
/// <see cref="TtsCapability.ReadinessNeedsVoice"/>,
260+
/// <see cref="TtsCapability.ReadinessVoiceNotDownloaded"/>, or
261+
/// <see cref="TtsCapability.ReadinessUnavailable"/>.
262+
/// </summary>
263+
public string Readiness { get; set; } = TtsCapability.ReadinessUnavailable;
264+
public bool IsReady { get; set; }
265+
}
266+
267+
/// <summary>
268+
/// Status surface for TTS, mirroring <c>stt.status</c>. Reports the
269+
/// configured default provider, the provider that would actually run now
270+
/// (after fallback), and per-provider readiness. The configured/effective
271+
/// view reflects the configured defaults only — a specific <c>tts.speak</c>
272+
/// call that supplies its own voiceId can still avoid a fallback that this
273+
/// snapshot reports. Carries no PII (no voice ids, no key fragments, no
274+
/// device names).
275+
/// </summary>
276+
public sealed class TtsStatusResult
277+
{
278+
public string ConfiguredProvider { get; set; } = TtsCapability.PiperProvider;
279+
public string EffectiveProvider { get; set; } = TtsCapability.PiperProvider;
280+
public bool WillFallBack { get; set; }
281+
public IReadOnlyList<TtsProviderStatus> Providers { get; set; } = Array.Empty<TtsProviderStatus>();
282+
}

‎src/OpenClaw.Shared/Mcp/McpToolBridge.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,9 @@ private object HandleToolsList()
247247

248248
// tts.*
249249
["tts.speak"] =
250-
"Speak text aloud on the Windows node. Args: text (string, required), provider ('piper'|'windows'|'elevenlabs', optional — falls back to the configured TtsProvider setting, default 'piper' for fresh installs), voiceId (string, optional — overrides the per-provider configured voice), model (string, optional, ElevenLabs only), interrupt (bool, default false — interrupts any in-progress playback). Returns { spoken, provider, contentType, durationMs }.",
250+
"Speak text aloud on the Windows node. Args: text (string, required), provider ('piper'|'windows'|'elevenlabs', optional — omit to use the configured TtsProvider setting, default 'piper' for fresh installs), voiceId (string, optional — overrides the per-provider configured voice), model (string, optional, ElevenLabs only), interrupt (bool, default false — interrupts any in-progress playback). When provider is omitted and the configured provider isn't usable (no ElevenLabs key, Piper voice not downloaded), the node falls back to Windows TTS so playback still happens. Explicit provider requests stay strict and do not silently reroute. Returns { spoken, provider (the provider that actually spoke), requestedProvider, fellBack, contentType, durationMs }.",
251+
["tts.status"] =
252+
"Report TTS provider readiness. No args. Returns { configuredProvider, effectiveProvider (the provider that would run now after fallback), willFallBack (bool), providers: [{ provider ('piper'|'windows'|'elevenlabs'), readiness ('ready'|'needs-api-key'|'needs-voice'|'voice-not-downloaded'|'unavailable'), isReady (bool) }] }. Carries no PII (no voice ids, no key fragments, no device names). Requires NodeTtsEnabled.",
251253

252254
// app.*
253255
["app.navigate"] =

‎src/OpenClaw.Shared/Models.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1160,6 +1160,7 @@ public static class CommandCenterCommandGroups
11601160
public static readonly string[] DangerousCommands =
11611161
[
11621162
.. CommonDangerousCommands,
1163+
"tts.status",
11631164
"stt.transcribe",
11641165
"stt.listen",
11651166
"stt.status"

‎src/OpenClaw.Tray.WinUI/Chat/OpenClawChatCoordinator.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,9 @@ private async Task SpeakConfiguredTextAsync(string text, bool muteVoiceCapture,
138138
var speakArgs = new TtsSpeakArgs
139139
{
140140
Text = speakText,
141-
Provider = _settings.TtsProvider ?? TtsCapability.PiperProvider,
141+
// Leave provider unset so TextToSpeechService treats this as
142+
// configured/default playback and can fall back when needed.
143+
Provider = null,
142144
Interrupt = true
143145
};
144146

‎src/OpenClaw.Tray.WinUI/Services/NodeService.cs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,7 @@ private void RegisterCapabilities()
367367
_textToSpeechService ??= new TextToSpeechService(_logger, settings);
368368
_ttsCapability = new TtsCapability(_logger);
369369
_ttsCapability.SpeakRequested += OnTtsSpeakAsync;
370+
_ttsCapability.StatusRequested += OnTtsStatusAsync;
370371
Register(_ttsCapability);
371372
}
372373

@@ -1868,6 +1869,14 @@ private Task<TtsSpeakResult> OnTtsSpeakAsync(TtsSpeakArgs args, CancellationToke
18681869
return _textToSpeechService.SpeakAsync(args, cancellationToken);
18691870
}
18701871

1872+
private Task<TtsStatusResult> OnTtsStatusAsync(CancellationToken cancellationToken)
1873+
{
1874+
if (_textToSpeechService == null)
1875+
throw new InvalidOperationException("Text-to-speech service not available");
1876+
1877+
return Task.FromResult(_textToSpeechService.GetStatus());
1878+
}
1879+
18711880
// ============================================================
18721881
// ============================================================
18731882
// STT handlers

0 commit comments

Comments
 (0)