Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Add configurable voice playback speed

vincent1337979023a8
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
index ac5a800392..e754464a84 100644
--- a/packages/phone-protocol/src/wire.ts
+++ b/packages/phone-protocol/src/wire.ts
@@ -323,8 +323,7 @@ export interface WireBot extends DefaultBotFields, BotAccessFields {
speakReplies?: boolean;
/** How replies are shaped. Absent = "default". */
replyStyle?: ReplyStyle;
- /** This bot's own voice id, so a room of bots doesn't sound like one person. */
- voice?: string;
+ /** This bot's own voice id, so a room of bots doesn't sound like one person. */ voice?: string; /** Playback speed; absent follows the installation's setting. */ voicePlaybackRate?: number;
/** This bot's own Live call voice, a GPT-Live or Gemini Live voice id; absent, or not the call provider's, uses the app's. */ liveVoice?: string;
/** Whether this bot may send voice notes. Absent/true = allowed; false
* hides the tool and refuses the route even with a voice configured. */
diff --git a/screenshots/issue-3398/after-1440-daylight.png b/screenshots/issue-3398/after-1440-daylight.png
new file mode 100644
index 0000000000..ec171f78fd
Binary files /dev/null and b/screenshots/issue-3398/after-1440-daylight.png differ
diff --git a/screenshots/issue-3398/after-1440-midnight.png b/screenshots/issue-3398/after-1440-midnight.png
new file mode 100644
index 0000000000..2ff7fba21e
Binary files /dev/null and b/screenshots/issue-3398/after-1440-midnight.png differ
diff --git a/screenshots/issue-3398/after-390-daylight.png b/screenshots/issue-3398/after-390-daylight.png
new file mode 100644
index 0000000000..c40e9cf336
Binary files /dev/null and b/screenshots/issue-3398/after-390-daylight.png differ
diff --git a/screenshots/issue-3398/after-390-midnight.png b/screenshots/issue-3398/after-390-midnight.png
new file mode 100644
index 0000000000..00710059ac
Binary files /dev/null and b/screenshots/issue-3398/after-390-midnight.png differ
diff --git a/screenshots/issue-3398/after-768-daylight.png b/screenshots/issue-3398/after-768-daylight.png
new file mode 100644
index 0000000000..42685e2b78
Binary files /dev/null and b/screenshots/issue-3398/after-768-daylight.png differ
diff --git a/screenshots/issue-3398/after-768-midnight.png b/screenshots/issue-3398/after-768-midnight.png
new file mode 100644
index 0000000000..d4a9366cfc
Binary files /dev/null and b/screenshots/issue-3398/after-768-midnight.png differ
diff --git a/screenshots/issue-3398/before-1440-daylight.png b/screenshots/issue-3398/before-1440-daylight.png
new file mode 100644
index 0000000000..3971d160ee
Binary files /dev/null and b/screenshots/issue-3398/before-1440-daylight.png differ
diff --git a/screenshots/issue-3398/before-1440-midnight.png b/screenshots/issue-3398/before-1440-midnight.png
new file mode 100644
index 0000000000..f486c64a34
Binary files /dev/null and b/screenshots/issue-3398/before-1440-midnight.png differ
diff --git a/screenshots/issue-3398/before-390-daylight.png b/screenshots/issue-3398/before-390-daylight.png
new file mode 100644
index 0000000000..6dbb486337
Binary files /dev/null and b/screenshots/issue-3398/before-390-daylight.png differ
diff --git a/screenshots/issue-3398/before-390-midnight.png b/screenshots/issue-3398/before-390-midnight.png
new file mode 100644
index 0000000000..f146dcda82
Binary files /dev/null and b/screenshots/issue-3398/before-390-midnight.png differ
diff --git a/screenshots/issue-3398/before-768-daylight.png b/screenshots/issue-3398/before-768-daylight.png
new file mode 100644
index 0000000000..459cd38754
Binary files /dev/null and b/screenshots/issue-3398/before-768-daylight.png differ
diff --git a/screenshots/issue-3398/before-768-midnight.png b/screenshots/issue-3398/before-768-midnight.png
new file mode 100644
index 0000000000..d7eef933ee
Binary files /dev/null and b/screenshots/issue-3398/before-768-midnight.png differ
diff --git a/server/bot-profile.test.ts b/server/bot-profile.test.ts
index 1165c90bbe..c212f7757b 100644
--- a/server/bot-profile.test.ts
+++ b/server/bot-profile.test.ts
@@ -89,6 +89,12 @@ describe("parseBotProfilePatch (both modes)", () => {
expect(parseBotProfilePatch({ avatarFocusX: -0.1 }, true).ok).toBe(false);
});
+ it("accepts supported playback speeds and clears the per-bot override to follow the workspace", () => {
+ expect(parseBotProfilePatch({ voicePlaybackRate: 1.5 }, true)).toEqual({ ok: true, patch: { voicePlaybackRate: 1.5 } });
+ expect(parseBotProfilePatch({ voicePlaybackRate: null }, true)).toEqual({ ok: true, patch: { voicePlaybackRate: undefined } });
+ expect(parseBotProfilePatch({ voicePlaybackRate: 1.1 }, true).ok).toBe(false);
+ });
+
it("maps an avatarCrop issue to the readable message", () => {
expect(parseBotProfilePatch({ avatarCrop: "hexagon" } as never, true)).toEqual({
ok: false,
diff --git a/server/bot-profile.ts b/server/bot-profile.ts
index 2d2aa00e50..80511b57bb 100644
--- a/server/bot-profile.ts
+++ b/server/bot-profile.ts
@@ -14,6 +14,7 @@ import {
import { BOT_PROFILE_LIMITS, fitsOnOneLine } from "../shared/bot-profile.ts";
import { REPLY_STYLES } from "../shared/reply-style.ts";
import { BOT_BODY_IDS, botBodySchema } from "../shared/bot-body.ts";
+import { VOICE_PLAYBACK_RATES, type VoicePlaybackRate } from "../shared/voice-playback.ts";
import type { BotRecord } from "./store.ts";
@@ -35,6 +36,7 @@ export const BOT_PROFILE_PATCH_FIELDS = [
"mascotBodyColor",
"mascotMaterial",
"voice",
+ "voicePlaybackRate",
"speakReplies",
"replyStyle",
] as const;
@@ -79,6 +81,7 @@ export const profilePatchSchema = z.object({
.string({ error: "voice must be a string" })
.max(BOT_PROFILE_LIMITS.voice, { error: "voice must be at most 200 characters" })
.optional(),
+ voicePlaybackRate: z.union([z.number().refine((value): value is VoicePlaybackRate => VOICE_PLAYBACK_RATES.includes(value as VoicePlaybackRate)), z.null()]).optional(),
speakReplies: z.boolean({ error: "speakReplies must be true or false" }).optional(),
replyStyle: z.enum(REPLY_STYLES, { error: "replyStyle must be default or conversational" }).optional(),
});
@@ -103,6 +106,7 @@ export type BotProfilePatch = Partial<
| "mascotBodyColor"
| "mascotMaterial"
| "voice"
+ | "voicePlaybackRate"
| "speakReplies"
| "replyStyle"
>
@@ -142,8 +146,9 @@ export function parseBotProfilePatch(input: BotProfilePatchInput, strict = false
return { ok: false, error: issue?.message ?? "invalid profile patch" };
}
- const { avatarUrl, ...fields } = parsed.data;
+ const { avatarUrl, voicePlaybackRate, ...fields } = parsed.data;
const patch: BotProfilePatch = fields;
if (avatarUrl !== undefined) patch.avatarUrl = avatarUrl || undefined;
+ if (voicePlaybackRate !== undefined) patch.voicePlaybackRate = voicePlaybackRate ?? undefined;
return { ok: true, patch };
}
diff --git a/server/config.test.ts b/server/config.test.ts
index 32aee1cb98..b0ef7cff7a 100644
--- a/server/config.test.ts
+++ b/server/config.test.ts
@@ -151,6 +151,13 @@ describe("configuration boundaries", () => {
expect(() => parseConfigPatch({ tts: { fishModel: "s1" } })).toThrow("fishModel");
});
+ it("accepts only supported voice playback rates", () => {
+ for (const playbackRate of [0.75, 1, 1.25, 1.5, 1.75, 2]) {
+ expect(parseConfigPatch({ tts: { playbackRate } }).tts).toEqual({ playbackRate });
+ }
+ expect(() => parseConfigPatch({ tts: { playbackRate: 1.1 } })).toThrow("playbackRate");
+ });
+
it("keeps how the person is heard and the language they speak, and refuses anything else", () => {
expect(parseConfigPatch({ tts: { hearWith: "elevenlabs", hearLanguage: " ES " } }).tts).toEqual({ hearWith: "elevenlabs", hearLanguage: "es" });
expect(parseConfigPatch({ tts: { hearWith: "device", hearLanguage: "" } }).tts).toEqual({ hearWith: "device", hearLanguage: "" });
diff --git a/server/config.ts b/server/config.ts
index 502f1b16fa..4ac13da20d 100644
--- a/server/config.ts
+++ b/server/config.ts
@@ -17,7 +17,7 @@ import { anthropicKeyEnv } from "./anthropic-key-env.ts";
import { withoutComputerEngine } from "./computer-engine-removal.ts";
import { newBotDefaultsSchema, type NewBotDefaults } from "./new-bot-defaults.ts";
import { replaySettings } from "./replay-settings.ts";
-import { EFFORT_LEVELS, type EffortLevel } from "../shared/wire.ts";
+import { EFFORT_LEVELS, VOICE_PLAYBACK_RATES, type EffortLevel, type VoicePlaybackRate } from "../shared/wire.ts";
import { isModelVariant, type InstanceConfigMap, type McpServerSpec, type ModelSelection } from "./contracts.ts";
import { API_KEY_FLEET, DEFAULT_FLEET, OPENAI_API_INSTANCE, OPENROUTER_API_INSTANCE, CLAUDE_API_INSTANCE, PRODUCT_FLEET_ADDITIONS } from "./instance-fleets.ts";
export { CLAUDE_API_INSTANCE, OPENAI_API_INSTANCE, OPENROUTER_API_INSTANCE, XAI_API_INSTANCE } from "./instance-fleets.ts";
@@ -362,7 +362,7 @@ const appConfigSchema = z.object({
.refine((value) => !value || /^https?:\/\//i.test(value), "the Chatterbox server address must start with http:// or https://")
.optional(),
model: optionalText, ...hearingConfigShape,
- fishModel: z.enum(FISH_TTS_MODELS).optional(), everyReply: z.boolean().optional(), // a voice note with every reply unless a bot's voiceNoteEveryReply says otherwise
+ fishModel: z.enum(FISH_TTS_MODELS).optional(), everyReply: z.boolean().optional(), playbackRate: z.number().refine((value): value is VoicePlaybackRate => VOICE_PLAYBACK_RATES.includes(value as VoicePlaybackRate), "playbackRate must be a supported voice speed").optional(), // a voice note with every reply unless a bot's voiceNoteEveryReply says otherwise
}).optional(),
decider: deciderConfigSchema.optional(),
live: liveConfigSchema.optional(),
@@ -456,7 +456,7 @@ export interface AppConfig extends HelperConfig {
vps?: VpsConfig;
vpsServers?: VpsServer[];
opencodeGo?: { apiKey?: string; providerKeys?: Record<string, string> };
- tts?: { key?: string; fishKey?: string; geminiKey?: string; voice?: string; provider?: "elevenlabs" | "fish" | "system" | "chatterbox" | "xai" | "gemini" | "openai" | "deepseek"; baseUrl?: string; model?: string; fishModel?: FishTtsModel; everyReply?: boolean; hearWith?: "device" | "elevenlabs"; hearLanguage?: string };
+ tts?: { key?: string; fishKey?: string; geminiKey?: string; voice?: string; provider?: "elevenlabs" | "fish" | "system" | "chatterbox" | "xai" | "gemini" | "openai" | "deepseek"; baseUrl?: string; model?: string; fishModel?: FishTtsModel; everyReply?: boolean; playbackRate?: VoicePlaybackRate; hearWith?: "device" | "elevenlabs"; hearLanguage?: string };
decider?: DeciderConfig;
imageGen?: ImageGenerationConfig;
live?: LiveConfig;
diff --git a/server/routes/bot-patch.test.ts b/server/routes/bot-patch.test.ts
index 9e06fba33d..d59dc2350a 100644
--- a/server/routes/bot-patch.test.ts
+++ b/server/routes/bot-patch.test.ts
@@ -342,6 +342,21 @@ describe("PATCH /api/bots/:id toolsOff", () => {
});
});
+describe("PATCH /api/bots/:id voicePlaybackRate", () => {
+ it("saves a supported per-bot speed, rejects unsupported speeds, and clears back to workspace", async () => {
+ const { store, bot, patch } = fixture();
+ const saved = await patch(bot.id, { voicePlaybackRate: 1.5 });
+ expect(saved.status).toBe(200);
+ expect(saved.body.bot.voicePlaybackRate).toBe(1.5);
+ expect(store.bot(bot.id)?.voicePlaybackRate).toBe(1.5);
+
+ expect((await patch(bot.id, { voicePlaybackRate: 1.1 })).status).toBe(400);
+ expect(store.bot(bot.id)?.voicePlaybackRate).toBe(1.5);
+ expect((await patch(bot.id, { voicePlaybackRate: null })).status).toBe(200);
+ expect(store.bot(bot.id)?.voicePlaybackRate).toBeUndefined();
+ });
+});
+
describe("PATCH /api/bots/:id liveVoice", () => {
it.each(["nuri", "juni", "flitz", "brise", "sillage", "nira", "harema", "shida", "noeul"])("saves %s as the bot's Live call voice", async (liveVoice) => {
const { store, bot, patch } = fixture();
diff --git a/server/tts/index.ts b/server/tts/index.ts
index 8f96001ff1..1c445aa818 100644
--- a/server/tts/index.ts
+++ b/server/tts/index.ts
@@ -114,6 +114,7 @@ export function describeVoice(cfg: AppConfig) {
...(provider === "fish" ? { fishModel: cfg.tts?.fishModel ?? fish.DEFAULT_FISH_MODEL } : {}),
...(included ? { included: true as const } : {}),
...(cfg.tts?.everyReply ? { everyReply: true as const } : {}),
+ ...(cfg.tts?.playbackRate !== undefined ? { playbackRate: cfg.tts.playbackRate } : {}),
...(cfg.tts?.hearWith === "elevenlabs" ? { hearWith: "elevenlabs" as const } : {}),
...(cfg.tts?.hearLanguage ? { hearLanguage: cfg.tts.hearLanguage } : {}),
};
diff --git a/server/tts/tts.test.ts b/server/tts/tts.test.ts
index 61afa51f7e..4dd9eaa0b3 100644
--- a/server/tts/tts.test.ts
+++ b/server/tts/tts.test.ts
@@ -747,6 +747,7 @@ describe("included voice", () => {
const { describeVoice } = await voice();
const described = describeVoice(cfg({ voice: "v-1" }));
expect(described).toEqual({ configured: true, ready: true, voice: "v-1", provider: "elevenlabs", baseUrl: "", model: "", included: true });
+ expect(describeVoice(cfg({ voice: "v-1", playbackRate: 1.5 }))).toHaveProperty("playbackRate", 1.5);
expect(JSON.stringify(described)).not.toContain(INCLUDED);
expect(describeVoice(cfg({ key: "sk-own", voice: "v-1" }))).not.toHaveProperty("included");
expect(describeVoice(cfg({ provider: "fish", voice: "v-1" }))).toMatchObject({ configured: false });
diff --git a/shared/voice-playback.ts b/shared/voice-playback.ts
new file mode 100644
index 0000000000..9b46222562
--- /dev/null
+++ b/shared/voice-playback.ts
@@ -0,0 +1,2 @@
+export const VOICE_PLAYBACK_RATES = [0.75, 1, 1.25, 1.5, 1.75, 2] as const;
+export type VoicePlaybackRate = (typeof VOICE_PLAYBACK_RATES)[number];
diff --git a/shared/wire.ts b/shared/wire.ts
index 497e650087..6453fc317f 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -1,2 +1,4 @@
export * from "../packages/phone-protocol/src/effort-levels.ts";
export * from "../packages/phone-protocol/src/wire.ts";
+export { VOICE_PLAYBACK_RATES } from "./voice-playback.ts";
+export type { VoicePlaybackRate } from "./voice-playback.ts";
diff --git a/src/components/CallView.tsx b/src/components/CallView.tsx
index 27b1ae01b0..847e13467c 100644
--- a/src/components/CallView.tsx
+++ b/src/components/CallView.tsx
@@ -558,6 +558,7 @@ function Call({ bot }: { bot: Bot }) {
});
}, [bridge, bot.id, move]);
+ const playbackRate = bot.voicePlaybackRate ?? state.config?.tts?.playbackRate ?? 1;
const say = useCallback(
async (text: string) => {
if (!alive.current || currentCall() !== bot.id) return false;
@@ -566,10 +567,10 @@ function Call({ bot }: { bot: Bot }) {
// mic.
move("speaking");
hush();
- await speaker.speak(text, { botId: bot.id, voiceId: bot.voice });
+ await speaker.speak(text, { botId: bot.id, voiceId: bot.voice, playbackRate });
return alive.current && currentCall() === bot.id && sayGeneration.current === mine;
},
- [bot.id, bot.voice, hush, move],
+ [bot.id, bot.voice, playbackRate, hush, move],
);
const sayThenListen = useCallback(
diff --git a/src/components/ChatRows.tsx b/src/components/ChatRows.tsx
index 8b62397592..9e8042bcb2 100644
--- a/src/components/ChatRows.tsx
+++ b/src/components/ChatRows.tsx
@@ -15,7 +15,7 @@ import { ToolActivity } from "./ToolActivity";
export interface ChatRows {
botId: string; threadId: string; botName: string; botColor: Bot["color"]; voiceId?: string;
- tts: ConfigStatus["tts"]; localVoice: boolean;
+ tts: ConfigStatus["tts"]; localVoice: boolean; playbackRate: number;
hasMore: boolean; bots: readonly Bot[];
mentionPeers: readonly MentionPeer[]; mentionPerson: { profileName?: string };
speakerViewer?: string | null;
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index e65ab65517..48c06ee28a 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -298,7 +298,7 @@ const Bubble = memo(function Bubble({
replyTarget?: Message;
onReply: (message: Message) => void;
}) {
- const { botId, threadId, botName, voiceId, tts, localVoice, bots, mentionPeers, mentionPerson, focus, dispatch, onBranch, bubbleStyle, conversational, simple, canReact, openedAt, speakerViewer, phone } = useChatRows();
+ const { botId, threadId, botName, voiceId, tts, localVoice, playbackRate, bots, mentionPeers, mentionPerson, focus, dispatch, onBranch, bubbleStyle, conversational, simple, canReact, openedAt, speakerViewer, phone } = useChatRows();
const message = useLiveRow(threadId, row);
const forkAction = !phone && message.kind === "text" && !message.id.startsWith("optimistic-")
? [{ ...forkMessageItem({ kind: "bot", ownerId: botId, threadId, messageId: message.id }, dispatch, false), disabledWhileBusy: true }] : [];
@@ -318,7 +318,7 @@ const Bubble = memo(function Bubble({
text,
botId, threadId,
messageId: message.id,
- voiceId,
+ voiceId, playbackRate,
tts,
localVoice,
canSpeak: message.kind === "text" && !peer,
@@ -389,7 +389,7 @@ const Bubble = memo(function Bubble({
{canReact && !peer && <ReactAction threadId={threadId} message={message} />}
{!simple && text && <CopyButton text={text} className={messageActionClass} />}
{text && viewRaw && <RawToggleAction active onToggle={() => setViewRaw(false)} className={messageActionClass} />}
- {text && (speaking || (message.kind === "text" && !peer && speakReady(tts, voiceId, localVoice))) && <SpeakButton text={text} botId={botId} messageId={message.id} voiceId={voiceId} tts={tts} localVoice={localVoice} className={cn(messageActionClass, speaking && "text-accent")} />}
+ {text && (speaking || (message.kind === "text" && !peer && speakReady(tts, voiceId, localVoice))) && <SpeakButton text={text} botId={botId} messageId={message.id} voiceId={voiceId} playbackRate={playbackRate} tts={tts} localVoice={localVoice} className={cn(messageActionClass, speaking && "text-accent")} />}
</MessageActions>
);
@@ -507,7 +507,7 @@ const Bubble = memo(function Bubble({
{voiceNotes.length > 0 && (
<div className={cn("flex flex-col", (text || generatedPaths.length > 0 || linkedFiles.length > 0) && "mb-2")}>
{voiceNotes.map((note) => (
- <VoiceNoteBubble key={note.path} attachment={note} />
+ <VoiceNoteBubble key={note.path} attachment={note} playbackRate={playbackRate} />
))}
</div>
)}
@@ -808,8 +808,8 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal
const reactor = useReactor();
const speakerViewer = reactor !== "user" ? reactor : null;
const rows = useMemo<ChatRows>(
- () => ({ botId: bot.id, threadId: bot.threadId, botName: bot.name, botColor: bot.color, voiceId: bot.voice, tts, localVoice, hasMore, bots, mentionPeers, mentionPerson: { profileName: state.config?.profile?.name }, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, conversational: isConversational(bot.replyStyle), simple: !advanced, canReact: mayWrite, openedAt, speakerViewer, phone }),
- [bot.id, bot.threadId, bot.name, bot.color, bot.voice, tts, localVoice, hasMore, bots, mentionPeers, state.config?.profile?.name, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, bot.replyStyle, advanced, mayWrite, openedAt, speakerViewer, phone],
+ () => ({ botId: bot.id, threadId: bot.threadId, botName: bot.name, botColor: bot.color, voiceId: bot.voice, tts, localVoice, playbackRate: bot.voicePlaybackRate ?? tts?.playbackRate ?? 1, hasMore, bots, mentionPeers, mentionPerson: { profileName: state.config?.profile?.name }, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, conversational: isConversational(bot.replyStyle), simple: !advanced, canReact: mayWrite, openedAt, speakerViewer, phone }),
+ [bot.id, bot.threadId, bot.name, bot.color, bot.voice, bot.voicePlaybackRate, tts, localVoice, hasMore, bots, mentionPeers, state.config?.profile?.name, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, bot.replyStyle, advanced, mayWrite, openedAt, speakerViewer, phone],
);
const currentTask = bot.tasks?.find((task) => task.threadId === bot.threadId), place = effectivePlace(bot, currentTask), team = state.config?.team, privateChat = Boolean(team) && (currentTask?.private === true || isNewChatThread(bot.threadId) || (ownChatStarted(bot.threadId) && !currentTask?.shared)), ownHelper = Boolean(team) && !privateChat && Boolean(bot.defaultBot?.person), sharedChat = Boolean(team) && !privateChat && !ownHelper;
diff --git a/src/components/GroupCallView.tsx b/src/components/GroupCallView.tsx
index dc2df46592..6b6b63fb5e 100644
--- a/src/components/GroupCallView.tsx
+++ b/src/components/GroupCallView.tsx
@@ -151,6 +151,7 @@ function GroupCall({ group, members }: { group: Group; members: Bot[] }) {
[group.id, listen],
);
+ const defaultPlaybackRate = state.config?.tts?.playbackRate ?? 1;
const say = useCallback(
async (text: string, member?: Bot) => {
if (!alive.current || currentCall() !== group.id) return false;
@@ -158,10 +159,10 @@ function GroupCall({ group, members }: { group: Group; members: Bot[] }) {
move("speaking");
setSpeakingMemberId(member?.id ?? null);
hush();
- await speaker.speak(text, { botId: member?.id, voiceId: member?.voice });
+ await speaker.speak(text, { botId: member?.id, voiceId: member?.voice, playbackRate: member?.voicePlaybackRate ?? defaultPlaybackRate });
return alive.current && currentCall() === group.id && sayGeneration.current === mine;
},
- [group.id, hush, move],
+ [group.id, defaultPlaybackRate, hush, move],
);
const enqueueSpeech = useCallback(
diff --git a/src/components/RoomTextMessage.tsx b/src/components/RoomTextMessage.tsx
index 065de544da..ddb49db4f4 100644
--- a/src/components/RoomTextMessage.tsx
+++ b/src/components/RoomTextMessage.tsx
@@ -118,6 +118,7 @@ export const RoomTextMessage = memo(function RoomTextMessage({
botId: speakerBot?.id,
messageId: m.id,
voiceId: speakerBot?.voice,
+ playbackRate: speakerBot?.voicePlaybackRate ?? tts?.playbackRate ?? 1,
tts,
localVoice,
canSpeak: true,
@@ -134,7 +135,7 @@ export const RoomTextMessage = memo(function RoomTextMessage({
{canReact && m.from && <ReactAction threadId={threadId} message={m} />}
{botText && <CopyButton text={botText} className={messageActionClass} />}
{botText && viewRaw && <RawToggleAction active onToggle={() => setViewRaw(false)} className={messageActionClass} />}
- {botText && (speaking || speakReady(tts, speakerBot?.voice, localVoice)) && <SpeakButton text={botText} botId={speakerBot?.id} messageId={m.id} voiceId={speakerBot?.voice} tts={tts} localVoice={localVoice} className={cn(messageActionClass, speaking && "text-accent")} />}
+ {botText && (speaking || speakReady(tts, speakerBot?.voice, localVoice)) && <SpeakButton text={botText} botId={speakerBot?.id} messageId={m.id} voiceId={speakerBot?.voice} playbackRate={speakerBot?.voicePlaybackRate ?? tts?.playbackRate ?? 1} tts={tts} localVoice={localVoice} className={cn(messageActionClass, speaking && "text-accent")} />}
</MessageActions>
);
return (
@@ -215,7 +216,7 @@ export const RoomTextMessage = memo(function RoomTextMessage({
{(m.attachments ?? []).some((attachment) => attachment.kind === "audio") && (
<div className={cn("flex flex-col", (m.text || (m.attachments ?? []).some((attachment) => attachment.kind === "image")) && "mb-2")}>
{m.attachments!.filter((attachment): attachment is VoiceNoteAttachment => attachment.kind === "audio").map((note) => (
- <VoiceNoteBubble key={note.path} attachment={note} />
+ <VoiceNoteBubble key={note.path} attachment={note} playbackRate={speakerBot?.voicePlaybackRate ?? tts?.playbackRate ?? 1} />
))}
</div>
)}
diff --git a/src/components/SpeakButton.tsx b/src/components/SpeakButton.tsx
index 9630f1b80c..6366e2a1d9 100644
--- a/src/components/SpeakButton.tsx
+++ b/src/components/SpeakButton.tsx
@@ -12,6 +12,7 @@ type SpeakArgs = {
botId?: string;
messageId: string;
voiceId?: string;
+ playbackRate?: number;
tts: ConfigStatus["tts"];
localVoice: boolean;
};
@@ -21,7 +22,7 @@ export function speakReady(tts: ConfigStatus["tts"], voiceId: string | undefined
return localVoice || (Boolean(tts?.configured) && Boolean(voiceId || tts?.voice));
}
-export function useSpeakAction({ text, botId, messageId, voiceId, tts, localVoice }: SpeakArgs) {
+export function useSpeakAction({ text, botId, messageId, voiceId, playbackRate, tts, localVoice }: SpeakArgs) {
const speech = useSpeech();
const configured = localVoice || Boolean(tts?.configured);
const ready = speakReady(tts, voiceId, localVoice);
@@ -36,7 +37,7 @@ export function useSpeakAction({ text, botId, messageId, voiceId, tts, localVoic
: t("chat.speak.read");
const toggle = () => {
if (mine) return speaker.stop();
- void speaker.speak(text, { botId, messageId, voiceId });
+ void speaker.speak(text, { botId, messageId, voiceId, playbackRate });
};
return { ready, mine, preparing, label, toggle };
}
diff --git a/src/components/VoiceNoteBubble.transcript.test.ts b/src/components/VoiceNoteBubble.transcript.test.ts
index 1257a6533a..dc554c6d58 100644
--- a/src/components/VoiceNoteBubble.transcript.test.ts
+++ b/src/components/VoiceNoteBubble.transcript.test.ts
@@ -16,13 +16,26 @@ const note = {
text: "Deploy is green, every check passed.",
};
-function render() {
+function render(playbackRate = 1) {
const container = document.createElement("div"), root = createRoot(container);
- flushSync(() => root.render(createElement(VoiceNoteBubble, { attachment: note })));
+ flushSync(() => root.render(createElement(VoiceNoteBubble, { attachment: note, playbackRate })));
return { container, root };
}
describe("the voice note's transcript disclosure", () => {
+ it("applies playback speed and keeps pitch when the setting changes", () => {
+ const { container, root } = render(1.5);
+ try {
+ const audio = container.querySelector("audio")!;
+ expect(audio.playbackRate).toBe(1.5);
+ expect(audio.preservesPitch).toBe(true);
+ flushSync(() => root.render(createElement(VoiceNoteBubble, { attachment: note, playbackRate: 1.75 })));
+ expect(audio.playbackRate).toBe(1.75);
+ } finally {
+ root.unmount();
+ }
+ });
+
it("opens on a tap and closes on the next, never showing the words until asked", () => {
const { container, root } = render();
try {
diff --git a/src/components/VoiceNoteBubble.tsx b/src/components/VoiceNoteBubble.tsx
index bf7665e7a2..af391d77ac 100644
--- a/src/components/VoiceNoteBubble.tsx
+++ b/src/components/VoiceNoteBubble.tsx
@@ -25,9 +25,11 @@ function clock(seconds: number): string {
export function VoiceNoteBubble({
attachment,
+ playbackRate = 1,
className,
}: {
attachment: VoiceNoteAttachment;
+ playbackRate?: number;
className?: string;
}) {
const url = attachmentAudioUrl(attachment.path);
@@ -44,6 +46,7 @@ export function VoiceNoteBubble({
const transcript = attachment.text?.trim() ?? "";
const onLiveCall = isLiveCallRunning(useLiveMedia().phase);
+ useEffect(() => { if (audioRef.current) { audioRef.current.playbackRate = playbackRate; audioRef.current.preservesPitch = true; } }, [playbackRate]);
useEffect(() => () => releaseRef.current?.(), []);
if (!url) return null;
diff --git a/src/components/VoicePlaybackRateSetting.test.ts b/src/components/VoicePlaybackRateSetting.test.ts
new file mode 100644
index 0000000000..a779982cc9
--- /dev/null
+++ b/src/components/VoicePlaybackRateSetting.test.ts
@@ -0,0 +1,50 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const fixture = vi.hoisted(() => ({
+ api: vi.fn(),
+ dispatch: vi.fn(),
+ config: { tts: { playbackRate: 1 } } as Record<string, unknown>,
+}));
+vi.mock("@/state/store", async (importOriginal) => ({
+ ...await importOriginal<typeof import("@/state/store")>(),
+ api: fixture.api,
+ useStore: () => ({ state: { config: fixture.config }, dispatch: fixture.dispatch }),
+}));
+
+const { VoicePlaybackRateSetting } = await import("./VoicePlaybackRateSetting");
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let host: HTMLDivElement;
+let root: Root;
+beforeEach(() => {
+ fixture.config = { tts: { playbackRate: 1 } };
+ fixture.api.mockResolvedValue({ tts: { playbackRate: 1.5 } });
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+ vi.clearAllMocks();
+});
+
+describe("VoicePlaybackRateSetting", () => {
+ it("saves the selected installation speed", async () => {
+ await act(async () => root.render(createElement(VoicePlaybackRateSetting)));
+ const select = host.querySelector("select")!;
+ expect(select.value).toBe("1");
+ await act(async () => {
+ select.value = "1.5";
+ select.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ expect(fixture.api).toHaveBeenCalledWith("/api/config", {
+ method: "PUT",
+ body: JSON.stringify({ tts: { playbackRate: 1.5 } }),
+ });
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "configStatus", config: { tts: { playbackRate: 1.5 } } });
+ });
+});
diff --git a/src/components/VoicePlaybackRateSetting.tsx b/src/components/VoicePlaybackRateSetting.tsx
new file mode 100644
index 0000000000..0ab8d20793
--- /dev/null
+++ b/src/components/VoicePlaybackRateSetting.tsx
@@ -0,0 +1,49 @@
+import { useContext, useState } from "react";
+import { api, type ConfigStatus } from "@/state/store";
+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
+import { t } from "@/lib/i18n";
+import { VOICE_PLAYBACK_RATES } from "../../shared/voice-playback";
+import { Select } from "./Select";
+import { SettingRow, SettingsLook } from "./SettingsPrimitives";
+
+export function VoicePlaybackRateSetting() {
+ const dispatch = useStoreDispatch();
+ const playbackRate = useStoreSelector((state) => state.config?.tts?.playbackRate ?? 1);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const settings = useContext(SettingsLook);
+ const save = (value: number) => {
+ setSaving(true);
+ setError(null);
+ api("/api/config", { method: "PUT", body: JSON.stringify({ tts: { playbackRate: value } }) })
+ .then((status: ConfigStatus) => dispatch({ type: "configStatus", config: status }))
+ .catch((failure: Error) => setError(failure.message))
+ .finally(() => setSaving(false));
+ };
+ const picker = (
+ <Select size="sm" aria-label={t("voice.playbackRate")} value={String(playbackRate)} disabled={saving}
+ onChange={(event) => save(Number(event.target.value))}>
+ {VOICE_PLAYBACK_RATES.map((rate) => <option key={rate} value={rate}>{rate}×</option>)}
+ </Select>
+ );
+ const alert = error ? <span role="alert" className="text-danger">{error}</span> : undefined;
+ if (settings) {
+ return (
+ <div data-voice-playback-rate className="contents">
+ <SettingRow title={t("voice.playbackRate")} subtitle={t("voice.playbackRate.help")} leading={<span aria-hidden="true" />} message={alert}>
+ {picker}
+ </SettingRow>
+ </div>
+ );
+ }
+ return (
+ <div data-voice-playback-rate className="flex items-center justify-between gap-4 px-3 py-2.5">
+ <div className="min-w-0">
+ <div className="text-[14px] font-medium leading-5 text-ink">{t("voice.playbackRate")}</div>
+ <div className="mt-0.5 text-[12px] leading-4 text-ink-secondary">{t("voice.playbackRate.help")}</div>
+ {error && <div role="alert" className="mt-1 text-[12px] text-danger">{error}</div>}
+ </div>
+ {picker}
+ </div>
+ );
+}
diff --git a/src/components/VoiceSettings.test.ts b/src/components/VoiceSettings.test.ts
index a4807f41ae..ee7f4107d8 100644
--- a/src/components/VoiceSettings.test.ts
+++ b/src/components/VoiceSettings.test.ts
@@ -83,6 +83,19 @@ describe("VoiceSettings", () => {
expect(onPatch).not.toHaveBeenCalled();
});
+ it("lets a bot override and then follow the workspace playback speed", async () => {
+ fixture.api.mockResolvedValue({ voices: [] });
+ const onPatch = vi.fn();
+ await render({ ...bot("pepper"), voicePlaybackRate: 1.5 }, onPatch);
+ const select = host.querySelector<HTMLSelectElement>("[data-bot-voice-playback-rate] select")!;
+ expect(select.value).toBe("1.5");
+ await act(async () => {
+ select.value = "";
+ select.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ expect(onPatch).toHaveBeenCalledExactlyOnceWith({ voicePlaybackRate: null });
+ });
+
it("lays the eight voice services out four to a row, OpenAI beside the other online services", async () => {
fixture.api.mockResolvedValue({ voices: [] });
await render(bot("pepper"), vi.fn());
diff --git a/src/components/VoiceSettings.tsx b/src/components/VoiceSettings.tsx
index f3560766d9..72ad0eab7f 100644
--- a/src/components/VoiceSettings.tsx
+++ b/src/components/VoiceSettings.tsx
@@ -24,6 +24,7 @@ import { VoicePicker, type PickerVoice } from "./VoicePicker";
import { Select } from "./Select";
import { Switch } from "./SettingsPrimitives";
import { KeysLink } from "./keys/KeysLink";
+import { VOICE_PLAYBACK_RATES } from "../../shared/voice-playback";
const FISH_MODELS = [
{ value: "s2.1-pro", label: "voice.fish.modelPro" },
@@ -37,7 +38,7 @@ export function VoiceSettings({
workspaceConfigurationLocked = false,
}: {
bot: Bot;
- onPatch: (patch: Partial<Pick<Bot, "voice" | "speakReplies" | "voiceNotes" | "voiceNoteEveryReply">>) => void;
+ onPatch: (patch: Partial<Pick<Bot, "voice" | "speakReplies" | "voiceNotes" | "voiceNoteEveryReply">> & { voicePlaybackRate?: number | null }) => void;
workspaceConfigurationLocked?: boolean;
}) {
const { state, dispatch } = useStore();
@@ -556,7 +557,7 @@ export function VoiceSettings({
</Select>
)}
<button
- onClick={() => void speaker.speak(t("voice.sample"), { voiceId: bot.voice, botId: bot.id })}
+ onClick={() => void speaker.speak(t("voice.sample"), { voiceId: bot.voice, botId: bot.id, playbackRate: bot.voicePlaybackRate ?? tts?.playbackRate ?? 1 })}
disabled={!ready || preparingSample}
aria-busy={preparingSample}
title={ready ? t("voice.hear") : t("voice.pickFirst")}
@@ -606,6 +607,18 @@ export function VoiceSettings({
/>
</div>
+ <div data-bot-voice-playback-rate className="mt-4 flex items-center justify-between gap-4">
+ <div className="min-w-0">
+ <div className="text-[13px] font-medium text-ink">{t("voice.playbackRate")}</div>
+ <div className="mt-0.5 text-[12px] leading-relaxed text-ink-secondary">{t("voice.playbackRate.botHelp")}</div>
+ </div>
+ <Select size="sm" aria-label={t("voice.playbackRate")} value={String(bot.voicePlaybackRate ?? "")}
+ onChange={(event) => onPatch({ voicePlaybackRate: event.target.value ? Number(event.target.value) : null })}>
+ <option value="">{t("voice.playbackRate.default")}</option>
+ {VOICE_PLAYBACK_RATES.map((rate) => <option key={rate} value={rate}>{rate}×</option>)}
+ </Select>
+ </div>
+
<div data-voice-every-reply className="mt-4 flex items-center justify-between gap-4">
<div>
<div className="text-[13px] font-medium text-ink">{t("voice.everyReply")}</div>
diff --git a/src/components/keys/KeysPage.tsx b/src/components/keys/KeysPage.tsx
index 35b57dda57..600cf64bbc 100644
--- a/src/components/keys/KeysPage.tsx
+++ b/src/components/keys/KeysPage.tsx
@@ -8,6 +8,7 @@ import { t } from "@/lib/i18n";
import { BoatOfferPanel } from "../BoatOffer";
import { LiveProviderSettings } from "../LiveProviderSettings";
import { VoiceEveryReplySetting } from "../VoiceEveryReplySetting";
+import { VoicePlaybackRateSetting } from "../VoicePlaybackRateSetting";
import { VoiceHearingSetting } from "../VoiceHearingSetting";
import { BuiltInReplyWait, LmStudioServer, OtherOpenAiCompatServers } from "../OpenAiCompatServers";
import { OllamaServer } from "../OllamaServer";
@@ -110,6 +111,7 @@ function KeySection({ id, rows, open, onToggle }: { id: KeySectionId; rows: KeyE
</button>
<div id={bodyId} hidden={!open} className="flex flex-col gap-0.5 border-t border-hairline/40 px-1 py-1.5 in-data-[settings-look=simple]:border-t-[0.5px] in-data-[settings-look=simple]:border-(--settings-edge)">
{rows.map((entry) => <KeyCatalogRow key={entry.id} entry={entry} visible={open} />)}
+ {id === "voice" && <VoicePlaybackRateSetting />}
{id === "voice" && <VoiceEveryReplySetting />}
{id === "voice" && <VoiceHearingSetting />}
</div>
@@ -184,6 +186,7 @@ export function KeysPage({ bare = false, exclude = [] }: { bare?: boolean; exclu
value={count > 0 ? t("keys.section.connected", { count }) : undefined} open={open.has(id)} onToggle={() => toggle(id)}>
<div data-keys-section={id} className="flex flex-col gap-0.5 py-1.5">
{sectionRows.map((entry) => <KeyCatalogRow key={entry.id} entry={entry} visible={open.has(id)} />)}
+ {id === "voice" && <VoicePlaybackRateSetting />}
{id === "voice" && <VoiceEveryReplySetting />}
{id === "voice" && <VoiceHearingSetting />}
</div>
diff --git a/src/components/message-menu.tsx b/src/components/message-menu.tsx
index 764674f8a1..9380368bd9 100644
--- a/src/components/message-menu.tsx
+++ b/src/components/message-menu.tsx
@@ -55,6 +55,7 @@ export function useBotMessageMenu({
threadId,
messageId,
voiceId,
+ playbackRate,
tts,
localVoice,
canSpeak,
@@ -69,6 +70,7 @@ export function useBotMessageMenu({
threadId?: string;
messageId: string;
voiceId?: string;
+ playbackRate?: number;
tts: ConfigStatus["tts"];
localVoice: boolean;
canSpeak: boolean;
@@ -77,7 +79,7 @@ export function useBotMessageMenu({
onRegenerate?: () => void;
pin?: PinAction;
}): MessageMenuItem[] {
- const speak = useSpeakAction({ text, botId, messageId, voiceId, tts, localVoice });
+ const speak = useSpeakAction({ text, botId, messageId, voiceId, playbackRate, tts, localVoice });
const teamMemory = useTeamMemoryItem(text, messageId, botId, threadId);
const items: MessageMenuItem[] = [];
// Once a voice is set up, Read this aloud is its own button in the hover bar; the menu keeps only the setup hint.
diff --git a/src/lib/spoken-reply-stream.test.ts b/src/lib/spoken-reply-stream.test.ts
index f5b7caf30a..2e25cfa45e 100644
--- a/src/lib/spoken-reply-stream.test.ts
+++ b/src/lib/spoken-reply-stream.test.ts
@@ -3,10 +3,10 @@ import { redactSecretsInText } from "../../shared/redact";
import type { RuntimeEvent } from "../../shared/runtime-events";
import type { LiveCallState, LiveCallStatus } from "../../shared/wire";
import type { ReplySpeechSink, SpokenReplyOwner } from "./spoken-reply-stream";
-import { SpokenReplyStream } from "./spoken-reply-stream";
+import { speechOwner, SpokenReplyStream } from "./spoken-reply-stream";
interface FakeHandle {
- opts: { botId?: string; voiceId?: string; messageId?: string };
+ opts: { botId?: string; voiceId?: string; messageId?: string; playbackRate?: number };
pushes: string[];
inputs: string[];
identified: (string | undefined)[];
@@ -65,6 +65,21 @@ const settle = async (): Promise<void> => {
};
describe("SpokenReplyStream", () => {
+ it("uses a bot playback speed over the workspace speed and passes it to streaming speech", async () => {
+ const state = {
+ bots: [{ id: "bot", threadId: "t", speakReplies: true, voicePlaybackRate: 1.75 }],
+ liveCall: null,
+ };
+ const resolved = speechOwner(state, "t", 1.25)!;
+ expect(resolved.playbackRate).toBe(1.75);
+ expect(speechOwner({ bots: [{ id: "bot", threadId: "t", speakReplies: true }], liveCall: null }, "t", 1.25)?.playbackRate).toBe(1.25);
+
+ const { sink, handles } = fakeSpeech();
+ new SpokenReplyStream(sink).onRuntimeEvent(delta("One two. Three "), resolved);
+ await settle();
+ expect(handles[0]!.opts.playbackRate).toBe(1.75);
+ });
+
it("pushes the first closed block before the completed message frame arrives", async () => {
const { sink, handles } = fakeSpeech();
const stream = new SpokenReplyStream(sink);
diff --git a/src/lib/spoken-reply-stream.ts b/src/lib/spoken-reply-stream.ts
index 4db2c4322b..091161086f 100644
--- a/src/lib/spoken-reply-stream.ts
+++ b/src/lib/spoken-reply-stream.ts
@@ -25,24 +25,26 @@ import type { LiveCallState } from "../../shared/wire";
export interface SpokenReplyOwner {
botId: string;
voiceId?: string;
+ playbackRate?: number;
}
interface SpeechGateState {
- bots: readonly { id: string; threadId: string; voice?: string; speakReplies?: boolean; tasks?: readonly { threadId: string }[] }[];
+ bots: readonly { id: string; threadId: string; voice?: string; voicePlaybackRate?: number; speakReplies?: boolean; tasks?: readonly { threadId: string }[] }[];
liveCall: LiveCallState | null;
}
/** The speak gates: the thread's bot speaks its replies, and no call (in-app or live) holds the speaker. */
-export function speechOwner(state: SpeechGateState, threadId: string): SpokenReplyOwner | null {
+export function speechOwner(state: SpeechGateState, threadId: string, playbackRate?: number): SpokenReplyOwner | null {
const owner = state.bots.find((b) => b.threadId === threadId || b.tasks?.some((task) => task.threadId === threadId));
const live = state.liveCall;
if (!owner?.speakReplies || currentCall() !== null || (live && live.status !== "ended" && live.botId === owner.id)) return null;
- return { botId: owner.id, voiceId: owner.voice };
+ const rate = owner.voicePlaybackRate ?? playbackRate;
+ return { botId: owner.id, voiceId: owner.voice, ...(rate !== undefined ? { playbackRate: rate } : {}) };
}
/** The Speaker surface this stream drives. */
export interface ReplySpeechSink {
- begin(opts: { botId?: string; voiceId?: string; messageId?: string }): SpeechStream;
+ begin(opts: { botId?: string; voiceId?: string; messageId?: string; playbackRate?: number }): SpeechStream;
}
function speakableStreamText(buffer: string): string {
@@ -131,7 +133,7 @@ export class SpokenReplyStream {
threadId,
botId: owner.botId,
turnId,
- stream: this.speech.begin({ botId: owner.botId, voiceId: owner.voiceId, messageId }),
+ stream: this.speech.begin({ botId: owner.botId, voiceId: owner.voiceId, messageId, playbackRate: owner.playbackRate }),
buffer: "",
authoritativeCut: 0,
spoken: [],
@@ -159,7 +161,7 @@ export class SpokenReplyStream {
botId: owner.botId,
turnId,
// begin stops whatever was speaking: a new turn's audio supersedes it.
- stream: this.speech.begin({ botId: owner.botId, voiceId: owner.voiceId }),
+ stream: this.speech.begin({ botId: owner.botId, voiceId: owner.voiceId, playbackRate: owner.playbackRate }),
buffer: delta,
authoritativeCut: 0,
spoken: [],
diff --git a/src/lib/tts/index.test.ts b/src/lib/tts/index.test.ts
index bd5a2a8020..0c30f73895 100644
--- a/src/lib/tts/index.test.ts
+++ b/src/lib/tts/index.test.ts
@@ -9,6 +9,8 @@ class FakeAudio {
static latest: FakeAudio | null = null;
src: string;
+ playbackRate = 1;
+ preservesPitch = false;
onended: (() => void) | null = null;
onerror: (() => void) | null = null;
pause = vi.fn();
@@ -89,11 +91,13 @@ describe("Speaker lifecycle", () => {
}),
);
const speaker = new Speaker();
- const speaking = speaker.speak("Distinct voice.", { voiceId: "voice-bot" });
+ const speaking = speaker.speak("Distinct voice.", { voiceId: "voice-bot", playbackRate: 1.5 });
await vi.waitFor(() => expect(FakeAudio.latest).not.toBeNull());
FakeAudio.latest!.onended?.();
await speaking;
+ expect(FakeAudio.latest!.playbackRate).toBe(1.5);
+ expect(FakeAudio.latest!.preservesPitch).toBe(true);
expect(bodies).toEqual([
{ text: "Distinct voice.", voiceId: "voice-bot" },
{ text: "Distinct voice.", voiceId: "voice-bot" },
@@ -642,6 +646,7 @@ describe("local system voice stream", () => {
class FakeUtterance {
text: string;
voice: SpeechSynthesisVoice | null = null;
+ rate = 1;
onstart: (() => void) | null = null;
onend: (() => void) | null = null;
onerror: ((event: { error: string }) => void) | null = null;
@@ -680,7 +685,7 @@ describe("local system voice stream", () => {
const speaker = new Speaker();
const first = speaker.begin({ botId: "bot" });
first.push("Stale words.");
- const second = speaker.begin({ botId: "bot" });
+ const second = speaker.begin({ botId: "bot", playbackRate: 1.75 });
second.identify("m2");
await first.end();
@@ -688,6 +693,7 @@ describe("local system voice stream", () => {
second.push("Fresh words.");
await vi.waitFor(() => expect(spoken.map((utterance) => utterance.text)).toEqual(["Fresh words."]));
+ expect(spoken[0]!.rate).toBe(1.75);
spoken[0]!.onstart?.();
expect(speaker.state).toEqual({ status: "speaking", botId: "bot", messageId: "m2", caption: "Fresh words." });
spoken[0]!.onend?.();
diff --git a/src/lib/tts/index.ts b/src/lib/tts/index.ts
index 8ddb983a4d..f67d0411c6 100644
--- a/src/lib/tts/index.ts
+++ b/src/lib/tts/index.ts
@@ -21,6 +21,7 @@ interface SpeakOptions {
voiceId?: string;
botId?: string;
messageId?: string;
+ playbackRate?: number;
}
/** One spoken reply, fed block by block: blocks come from the committed
@@ -253,7 +254,7 @@ export class Speaker {
return;
}
this.set({ status: "speaking", botId: opts.botId, messageId: opts.messageId, caption: pending[at]! });
- const played = await this.play(rendered.blob, live, opts.messageId, at);
+ const played = await this.play(rendered.blob, live, opts.messageId, at, opts.playbackRate ?? 1);
if (!played || !live()) {
if (live()) this.set({ ...IDLE, error: t("voice.error.clip") });
controller.abort();
@@ -326,6 +327,7 @@ export class Speaker {
const synth = window.speechSynthesis;
const utterance = new window.SpeechSynthesisUtterance(value);
+ utterance.rate = opts.playbackRate ?? 1;
const selected = resolveLocalSystemVoice(remoteSystemVoice(opts.botId));
if (selected) utterance.voice = selected;
this.localUtterance = utterance;
@@ -398,12 +400,14 @@ export class Speaker {
return res.blob();
}
- private play(blob: Blob, live: () => boolean, probeMessageId?: string, probeBlock?: number): Promise<boolean> {
+ private play(blob: Blob, live: () => boolean, probeMessageId?: string, probeBlock?: number, playbackRate = 1): Promise<boolean> {
return new Promise((resolve) => {
if (!live()) return resolve(false);
this.teardownAudio();
const url = URL.createObjectURL(blob);
const audio = new Audio(url);
+ audio.playbackRate = playbackRate;
+ audio.preservesPitch = true;
this.audio = audio;
this.objectUrl = url;
let settled = false;
diff --git a/src/locales/en.json b/src/locales/en.json
index cf38252006..b89316dd95 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -996,6 +996,10 @@
"voice.readRepliesHelp": "Speak this agent’s answers as they arrive, even from another chat.",
"voice.notes": "Voice notes",
"voice.notesHelp": "Let this agent send spoken notes; on unless switched off here.",
+ "voice.playbackRate": "Playback speed",
+ "voice.playbackRate.help": "Applies to Read aloud, voice notes and Take turns.",
+ "voice.playbackRate.botHelp": "Sets how fast this bot's audio plays.",
+ "voice.playbackRate.default": "Use default speed",
"voice.everyReply": "Voice note with every reply",
"voice.everyReply.allHelp": "Every bot also sends each reply as a voice note. You can turn it on or off for one bot in that bot's settings.",
"voice.hearWithEleven": "Hear me with ElevenLabs",
diff --git a/src/state/config-status.ts b/src/state/config-status.ts
index d2375d98f5..95d35502b6 100644
--- a/src/state/config-status.ts
+++ b/src/state/config-status.ts
@@ -2,6 +2,7 @@
import type { EffortLevel, LiveSettings } from "../../shared/wire";
import type { ImageComplexity, ImageProvider } from "../../shared/image-generation";
import type { ToolGroup } from "../../shared/tool-groups";
+import type { VoicePlaybackRate } from "../../shared/voice-playback";
import type { OnboardingStatus } from "@/lib/onboarding";
import type { ModelSelection } from "./store";
@@ -100,6 +101,7 @@ export interface ConfigStatus {
model?: string;
/** Voice note with every reply, for every bot without its own choice. Absent from older servers. */
everyReply?: boolean;
+ playbackRate?: VoicePlaybackRate;
/** "elevenlabs": the person chose to be heard through their own ElevenLabs key (Scribe). Absent: the default. */
hearWith?: "elevenlabs";
/** The language the person speaks to Scribe (ISO 639 code); absent lets Scribe detect it. */
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 7d97bc8cdb..a678d06703 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -274,7 +274,7 @@ export interface TaskUsage {
context?: { tokens: number; window?: number };
}
-export interface Bot extends DefaultBotFields, Pick<WireBot, "mascotFaceColor" | "mascotBodyColor" | "mascotMaterial" | "access" | "yourAccess" | "onlyPeopleAdded"> {
+export interface Bot extends DefaultBotFields, Pick<WireBot, "mascotFaceColor" | "mascotBodyColor" | "mascotMaterial" | "access" | "yourAccess" | "onlyPeopleAdded" | "voicePlaybackRate"> {
toolScope?: ToolScope;
waitingForTeammates?: boolean;
id: string;
@@ -3047,7 +3047,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
});
}
if (frame.message?.role === "bot" && frame.message?.kind === "text") {
- const owner = speechOwner(stateRef.current, frame.threadId);
+ const owner = speechOwner(stateRef.current, frame.threadId, stateRef.current.config?.tts?.playbackRate);
spokenReplyStream.completeBotText(frame.threadId, frame.message.turnId, frame.message.text ?? "", owner, frame.message.id);
}
break;
@@ -3114,7 +3114,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
rawDispatch({ type: "webhookDeleted", webhookId: frame.webhookId });
break;
case "runtime": {
- spokenReplyStream.onRuntimeEvent(frame.event, speechOwner(stateRef.current, frame.event.threadId));
+ spokenReplyStream.onRuntimeEvent(frame.event, speechOwner(stateRef.current, frame.event.threadId, stateRef.current.config?.tts?.playbackRate));
const action = runtimeFrameAction(frame.event);
if (action) rawDispatch(action);
break;