diff --git a/apps/mobile/deps/README.md b/apps/mobile/deps/README.md
index 4a42287173b25..f6e41b27043db 100644
--- a/apps/mobile/deps/README.md
+++ b/apps/mobile/deps/README.md
@@ -1,4 +1,4 @@
-The Enriched Markdown tarball comes from Julius's [`fork/t3-mobile` branch](https://github.com/pingdotgg/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. React block renderers, signed image sources, the `onLinksChange` link list (`renderers`, `resolveImageSource`, `onLinksChange`) and the iOS streaming memory bounds are upstream. The fork carries only changes with an open upstream PR: clipboard link metadata ([#962](https://github.com/software-mansion/enriched-markdown/pull/962)), development-host autolinks ([#961](https://github.com/software-mansion/enriched-markdown/pull/961)) and hash-route link fragments ([mity/md4c#454](https://github.com/mity/md4c/pull/454), arriving through [md4c#7](https://github.com/software-mansion-labs/md4c/pull/7)), `md4cFlags.preserveWindowsPaths`, which keeps backslashes in Windows drive paths in prose ([#1105](https://github.com/software-mansion/enriched-markdown/pull/1105), after [mity/md4c#477](https://github.com/mity/md4c/pull/477)), GitHub's strikethrough rules for `~` ([md4c#6](https://github.com/software-mansion-labs/md4c/pull/6)), `\(…\)` and `\[…\]` math delimiters ([#1043](https://github.com/software-mansion/enriched-markdown/pull/1043), [md4c#4](https://github.com/software-mansion-labs/md4c/pull/4)), iOS Copy as Markdown keeping bold spans whole ([#1143](https://github.com/software-mansion/enriched-markdown/pull/1143)), line breaks in copied table cells written as `
` ([#1144](https://github.com/software-mansion/enriched-markdown/pull/1144)), and Android measuring text in the span order its view draws it, so code blocks nested in list items no longer make a reply overlap the next message ([#1145](https://github.com/software-mansion/enriched-markdown/pull/1145)). It also carries two fork-only changes: iOS code blocks too big for one backing store draw through tiles, so a tall block with long lines no longer shows an empty pane ([pingdotgg/enriched-markdown#15](https://github.com/pingdotgg/enriched-markdown/pull/15)), and a long-pressed iOS blockquote lifts on the background it sits on instead of drawing its text over the thread.
+The Enriched Markdown tarball comes from Julius's [`fork/t3-mobile` branch](https://github.com/pingdotgg/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. React block renderers, signed image sources, the `onLinksChange` link list (`renderers`, `resolveImageSource`, `onLinksChange`) and the iOS streaming memory bounds are upstream. The fork carries only changes with an open upstream PR: clipboard link metadata ([#962](https://github.com/software-mansion/enriched-markdown/pull/962)), development-host autolinks ([#961](https://github.com/software-mansion/enriched-markdown/pull/961)) and hash-route link fragments ([mity/md4c#454](https://github.com/mity/md4c/pull/454), arriving through [md4c#7](https://github.com/software-mansion-labs/md4c/pull/7)), `md4cFlags.preserveWindowsPaths`, which keeps backslashes in Windows drive paths in prose ([#1105](https://github.com/software-mansion/enriched-markdown/pull/1105), after [mity/md4c#477](https://github.com/mity/md4c/pull/477)), GitHub's strikethrough rules for `~` ([md4c#6](https://github.com/software-mansion-labs/md4c/pull/6)), `\(…\)` and `\[…\]` math delimiters ([#1043](https://github.com/software-mansion/enriched-markdown/pull/1043), [md4c#4](https://github.com/software-mansion-labs/md4c/pull/4)), iOS Copy as Markdown keeping bold spans whole ([#1143](https://github.com/software-mansion/enriched-markdown/pull/1143)), line breaks in copied table cells written as `
` ([#1144](https://github.com/software-mansion/enriched-markdown/pull/1144)), and Android measuring text in the span order its view draws it, so code blocks nested in list items no longer make a reply overlap the next message ([#1145](https://github.com/software-mansion/enriched-markdown/pull/1145)). Until [pingdotgg/enriched-markdown#17](https://github.com/pingdotgg/enriched-markdown/pull/17) lands, the tarball comes from that PR's branch (commit `3431ed09`). That PR adds text highlight ranges ([#1218](https://github.com/software-mansion/enriched-markdown/pull/1218)), which read aloud uses to tint the paragraph and the word it speaks. It also carries two fork-only changes: iOS code blocks too big for one backing store draw through tiles, so a tall block with long lines no longer shows an empty pane ([pingdotgg/enriched-markdown#15](https://github.com/pingdotgg/enriched-markdown/pull/15)), and a long-pressed iOS blockquote lifts on the background it sits on instead of drawing its text over the thread.
To replace it, commit the fork changes, run `yarn install --immutable` and `yarn workspace react-native-enriched-markdown prepare` in the fork checkout, then `node scripts/pack-t3.mjs /path/to/t3code/apps/mobile/deps`. Keep the package version aligned with Julius's `fork/t3-mobile` branch. Rename the archive to include the first eight characters of the source commit, such as `react-native-enriched-markdown-1.2.0-t3.18-4287c5d3.tgz`, so each build has a distinct dependency path without version bumps. Update the tarball path in `apps/mobile/package.json` and `pnpm-workspace.yaml`'s `allowBuilds`, and run `vp i` to update the lockfile. Native clients need rebuilding when this dependency changes.
diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz
deleted file mode 100644
index 10495faf6f9c2..0000000000000
Binary files a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz and /dev/null differ
diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-3431ed09.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-3431ed09.tgz
new file mode 100644
index 0000000000000..5ee1a04b5d86a
Binary files /dev/null and b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-3431ed09.tgz differ
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index b1a1142545ae8..b9584f0cf7c2f 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -128,7 +128,7 @@
"react": "catalog:",
"react-dom": "catalog:",
"react-native": "0.88.1",
- "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz",
+ "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.18-3431ed09.tgz",
"react-native-gesture-handler": "~3.5.0",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.23.0",
diff --git a/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx b/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx
index d745ef5853f17..56bae8cdc9aa8 100644
--- a/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx
+++ b/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx
@@ -7,8 +7,20 @@ import { Pressable } from "react-native";
import { mobilePreferencesAtom } from "../../state/preferences";
import { SymbolView } from "../../components/ui/AppSymbol";
import * as Dialog from "../../components/ui/Dialog";
+import type { ReadAloudHighlight } from "@t3tools/client-runtime/read-aloud";
import { readAloudController, warmReadAloud } from "./playback";
+/**
+ * The block and word being read in message `id` (the button's id), as markdown ranges of the
+ * text that message renders plus text cues, or null while another message or none is read.
+ */
+export function useReadAloudHighlight(id: string): ReadAloudHighlight | null {
+ return useSyncExternalStore(readAloudController.subscribeHighlight, () => {
+ const highlight = readAloudController.getHighlight();
+ return highlight?.id === id ? highlight : null;
+ });
+}
+
export function ReadAloudButton({
id,
text,
diff --git a/apps/mobile/src/features/read-aloud/ReadAloudMarkdownText.tsx b/apps/mobile/src/features/read-aloud/ReadAloudMarkdownText.tsx
new file mode 100644
index 0000000000000..433944694476a
--- /dev/null
+++ b/apps/mobile/src/features/read-aloud/ReadAloudMarkdownText.tsx
@@ -0,0 +1,85 @@
+import { readAloudShownText } from "@t3tools/shared/read-aloud";
+import { useRef, useState } from "react";
+import { View, type ViewInstance } from "react-native";
+import type {
+ HighlightLayoutEvent,
+ RenderedTextChangeEvent,
+ TextHighlight,
+} from "react-native-enriched-markdown";
+import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
+import { SelectableMarkdownText } from "../../native/SelectableMarkdownText";
+import type { SelectableMarkdownTextProps } from "../../native/SelectableMarkdownText.types";
+import { useReadAloudHighlight } from "./ReadAloudButton";
+import { followReadAloud } from "./readAloudFollow";
+
+/** The web's `--read-aloud-block` and `--read-aloud-word`: its info blue at these strengths. */
+const READ_ALOUD_TINT = {
+ light: { block: "rgba(59, 130, 246, 0.09)", word: "rgba(59, 130, 246, 0.32)" },
+ dark: { block: "rgba(59, 130, 246, 0.22)", word: "rgba(59, 130, 246, 0.55)" },
+};
+const NO_HIGHLIGHTS: ReadonlyArray = [];
+
+// Built on the first word read in a view, not for every reply on screen, and kept per render.
+const locators = new WeakMap<
+ RenderedTextChangeEvent,
+ { readonly markdown: string; readonly locate: ReturnType }
+>();
+function locator(markdown: string, shown: RenderedTextChangeEvent) {
+ const cached = locators.get(shown);
+ if (cached?.markdown === markdown) return cached.locate;
+ const locate = readAloudShownText(markdown, shown.text);
+ locators.set(shown, { markdown, locate });
+ return locate;
+}
+
+/**
+ * Markdown of a reply that read aloud can read: tints the paragraph and word being read and keeps
+ * the word in view. `readAloud.markdown` is the text read aloud reads, which can differ from the
+ * part of it this view shows.
+ */
+export function ReadAloudMarkdownText(
+ props: SelectableMarkdownTextProps & {
+ readonly readAloud: { readonly id: string; readonly markdown: string };
+ },
+) {
+ const { readAloud, ...markdownProps } = props;
+ const highlight = useReadAloudHighlight(readAloud.id);
+ const { themeAppearance } = useAppearancePreferences();
+ const [shown, setShown] = useState(null);
+ const container = useRef(null);
+ const ranges = highlight && shown ? locator(readAloud.markdown, shown)(highlight) : null;
+ // Code blocks and tables are tinted whole, so only the paragraph tint marks them.
+ const opaque = shown?.blocks.find(
+ (block) =>
+ block.kind !== "text" &&
+ ranges?.word &&
+ ranges.word.start < block.end &&
+ ranges.word.end > block.start,
+ );
+ const tint = READ_ALOUD_TINT[themeAppearance === "dark" ? "dark" : "light"];
+ const highlights = ranges
+ ? [
+ ...(ranges.block ? [{ ...ranges.block, color: tint.block, borderRadius: 4 }] : []),
+ ...(ranges.word && !opaque
+ ? [{ ...ranges.word, color: tint.word, borderRadius: 4, padding: 1 }]
+ : []),
+ ]
+ : NO_HIGHLIGHTS;
+ const onHighlightLayout = ({ highlights: rects }: HighlightLayoutEvent) => {
+ const target = rects.at(-1);
+ if (!target) return;
+ container.current?.measureInWindow((_x, y) =>
+ followReadAloud(readAloud.id, { top: y + target.y, height: target.height }),
+ );
+ };
+ return (
+
+
+
+ );
+}
diff --git a/apps/mobile/src/features/read-aloud/playback.test.ts b/apps/mobile/src/features/read-aloud/playback.test.ts
index 3e7ea0df9e590..26ac65bb616b3 100644
--- a/apps/mobile/src/features/read-aloud/playback.test.ts
+++ b/apps/mobile/src/features/read-aloud/playback.test.ts
@@ -42,6 +42,7 @@ vi.mock("../../state/session", () => ({
}));
vi.mock("@t3tools/client-runtime/voice-input", () => ({
startSpeechSynthesis: vi.fn(() => ({ kind: "audio" })),
+ getSpeechSynthesisTimings: vi.fn(() => ({ kind: "timings" })),
getSpeechSynthesisModels: vi.fn((_prepared: unknown, provider: string) => ({
kind: "catalog",
provider,
@@ -57,7 +58,9 @@ vi.mock("../voice-input/voiceDestination", async () => {
defaultModel: "server-model",
speedAppliedByProvider: operation.provider !== "openrouter",
}
- : "https://host.test/api/voice/synthesis/audio?token=stream",
+ : operation.kind === "timings"
+ ? { words: [], done: true }
+ : { url: "https://host.test/api/voice/synthesis/audio?token=stream", token: "stream" },
};
});
diff --git a/apps/mobile/src/features/read-aloud/playback.ts b/apps/mobile/src/features/read-aloud/playback.ts
index a79a4d904a330..7ee9504487542 100644
--- a/apps/mobile/src/features/read-aloud/playback.ts
+++ b/apps/mobile/src/features/read-aloud/playback.ts
@@ -2,13 +2,17 @@ import { m } from "../../i18n/messages";
import {
createReadAloudController,
createReadAloudWarmup,
+ createTimedWords,
type SpeechPlayback,
+ type SpokenWord,
} from "@t3tools/client-runtime/read-aloud";
import {
getSpeechSynthesisModels,
+ getSpeechSynthesisTimings,
prepareSpeechSynthesis,
startSpeechSynthesis,
} from "@t3tools/client-runtime/voice-input";
+import { spokenWordAt } from "@t3tools/shared/read-aloud";
import { createAudioPlayer } from "expo-audio";
import * as Speech from "expo-speech";
import * as Option from "effect/Option";
@@ -46,6 +50,7 @@ function systemPlayback(text: string, settings: ReadAloudSettings): SpeechPlayba
let started = false;
let offset = 0;
let generation = 0;
+ const listeners = new Set<(word: SpokenWord | null) => void>();
const player = {
play() {
if (pauseInBackground(settings)) return;
@@ -62,7 +67,10 @@ function systemPlayback(text: string, settings: ReadAloudSettings): SpeechPlayba
rate: settings.speed,
useApplicationAudioSession: true,
onBoundary: (event: { charIndex: number }) => {
- if (current === generation) offset = start + event.charIndex;
+ if (current !== generation) return;
+ offset = start + event.charIndex;
+ const word = spokenWordAt(text, offset);
+ for (const listener of listeners) listener(word);
},
onDone: () => {
if (current === generation) done();
@@ -103,6 +111,12 @@ function systemPlayback(text: string, settings: ReadAloudSettings): SpeechPlayba
done();
},
finished,
+ words: (listener) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
};
}
@@ -143,7 +157,7 @@ export const readAloudController = createReadAloudController(async (text, settin
signal.throwIfAborted();
if (catalog.error) throw new Error(catalog.error);
const model = settings.model || catalog.defaultModel;
- const url = await runSpeech(
+ const { url, token } = await runSpeech(
startSpeechSynthesis(prepared, settings.provider, {
text,
model,
@@ -175,10 +189,12 @@ export const readAloudController = createReadAloudController(async (text, settin
// Native lock-screen Play bypasses JS, so a paused player must keep revocable ownership.
settings.backgroundPlayback,
);
+ let timed: ReturnType | null = null;
let done: () => void = () => {};
const finished = new Promise((resolve, reject) => {
done = resolve;
player.addListener("playbackStatusUpdate", (status) => {
+ timed?.refresh();
if (status.didJustFinish) resolve();
else if (status.error) reject(new Error("Could not play the generated speech."));
else if (
@@ -209,11 +225,26 @@ export const readAloudController = createReadAloudController(async (text, settin
},
pause: () => session.pause(),
stop: () => {
+ timed?.stop();
stopWatching();
session.stop();
disposeAudioPlayer(player);
done();
},
finished,
+ words: (listener) => {
+ timed ??= createTimedWords({
+ text,
+ wordTimings: catalog.wordTimings ?? "estimated",
+ load: (after, signal) =>
+ runSpeech(getSpeechSynthesisTimings(prepared, token, after), signal),
+ clock: () => ({
+ seconds: player.currentTime,
+ rate: player.playbackRate,
+ playing: player.playing,
+ }),
+ });
+ return timed.subscribe(listener);
+ },
};
}, m);
diff --git a/apps/mobile/src/features/read-aloud/readAloudFollow.test.ts b/apps/mobile/src/features/read-aloud/readAloudFollow.test.ts
new file mode 100644
index 0000000000000..9b86b8352c30c
--- /dev/null
+++ b/apps/mobile/src/features/read-aloud/readAloudFollow.test.ts
@@ -0,0 +1,17 @@
+import { expect, it } from "vite-plus/test";
+import { readAloudFollowDelta } from "./readAloudFollow";
+
+const view = { top: 100, height: 1000 };
+
+it("keeps the word in the middle of the feed and pauses after the user scrolls", () => {
+ const at = (top: number, userScrolledAt: number | null = null, now = 10_000) =>
+ readAloudFollowDelta({ target: { top, height: 20 }, view, userScrolledAt, now });
+ expect(at(500)).toEqual({ delta: 0, resumed: true });
+ expect(at(1000)).toEqual({ delta: 500, resumed: true });
+ expect(at(150)).toEqual({ delta: -350, resumed: true });
+ // A recent scroll waits, even with the word in view.
+ expect(at(1000, 9_000)).toEqual({ delta: 0, resumed: false });
+ // Later, a word scrolled out of view stays put until the user brings it back.
+ expect(at(2000, 1_000)).toEqual({ delta: 0, resumed: false });
+ expect(at(1000, 1_000)).toEqual({ delta: 500, resumed: true });
+});
diff --git a/apps/mobile/src/features/read-aloud/readAloudFollow.ts b/apps/mobile/src/features/read-aloud/readAloudFollow.ts
new file mode 100644
index 0000000000000..971e93e647c98
--- /dev/null
+++ b/apps/mobile/src/features/read-aloud/readAloudFollow.ts
@@ -0,0 +1,77 @@
+/** After the user scrolls, following waits this long and for the word to be back in view. */
+const FOLLOW_PAUSE_MS = 3_000;
+/** The word stays in the middle of the feed; leaving that band scrolls it to 40%. As on the web. */
+const FOLLOW_BAND = { top: 0.2, bottom: 0.8, target: 0.4 };
+
+/** A vertical span in window coordinates. */
+export interface ReadAloudSpan {
+ readonly top: number;
+ readonly height: number;
+}
+
+/** The thread feed read aloud scrolls: its visible area and a relative scroll. */
+export interface ReadAloudFeed {
+ readonly measure: (callback: (view: ReadAloudSpan) => void) => void;
+ readonly scrollBy: (delta: number) => void;
+}
+
+/**
+ * How far to scroll so `target` sits in the follow band of `view`, or 0. While the user's own
+ * scroll is recent, or has left the word out of view, following waits and never pulls them back.
+ */
+export function readAloudFollowDelta(input: {
+ readonly target: ReadAloudSpan;
+ readonly view: ReadAloudSpan;
+ readonly userScrolledAt: number | null;
+ readonly now: number;
+}): { readonly delta: number; readonly resumed: boolean } {
+ const { target, view, userScrolledAt, now } = input;
+ const bottom = target.top + target.height;
+ if (userScrolledAt !== null) {
+ if (now - userScrolledAt < FOLLOW_PAUSE_MS) return { delta: 0, resumed: false };
+ if (bottom < view.top || target.top > view.top + view.height)
+ return { delta: 0, resumed: false };
+ }
+ const inBand =
+ target.top >= view.top + view.height * FOLLOW_BAND.top &&
+ bottom <= view.top + view.height * FOLLOW_BAND.bottom;
+ return {
+ delta: inBand ? 0 : target.top - (view.top + view.height * FOLLOW_BAND.target),
+ resumed: true,
+ };
+}
+
+let feed: ReadAloudFeed | null = null;
+let userScrolledAt: number | null = null;
+let followingId: string | null = null;
+
+/** The mounted thread feed; read aloud only reads replies on screen, so there is one. */
+export function registerReadAloudFeed(next: ReadAloudFeed) {
+ feed = next;
+ return () => {
+ if (feed === next) feed = null;
+ };
+}
+
+/** The user dragged the feed; following pauses so it does not fight them. */
+export function markReadAloudUserScroll() {
+ userScrolledAt = Date.now();
+}
+
+/**
+ * Scrolls the feed so the line read in message `id`, in window coordinates, stays in view.
+ * Starting another message follows at once, whatever the user scrolled before.
+ */
+export function followReadAloud(id: string, target: ReadAloudSpan) {
+ if (id !== followingId) {
+ followingId = id;
+ userScrolledAt = null;
+ }
+ const current = feed;
+ current?.measure((view) => {
+ const next = readAloudFollowDelta({ target, view, userScrolledAt, now: Date.now() });
+ if (!next.resumed) return;
+ userScrolledAt = null;
+ if (Math.abs(next.delta) >= 1) current.scrollBy(next.delta);
+ });
+}
diff --git a/apps/mobile/src/features/settings/ReadAloudSection.tsx b/apps/mobile/src/features/settings/ReadAloudSection.tsx
index 1455448e262ff..eb1b60bec50c9 100644
--- a/apps/mobile/src/features/settings/ReadAloudSection.tsx
+++ b/apps/mobile/src/features/settings/ReadAloudSection.tsx
@@ -254,6 +254,11 @@ export function ReadAloudSection() {
value={settings.skipCodeBlocks}
onValueChange={(skipCodeBlocks) => change({ skipCodeBlocks })}
/>
+ change({ highlightWords })}
+ />
void) | undefined;
readonly renderImage: MarkdownImageRenderer;
readonly skills?: ReadonlyArray | undefined;
+ /** The read-aloud button's id for this reply; its text is `markdown`. */
+ readonly readAloudId?: string | undefined;
}) {
const models = useModelMentions(props.environmentId, props.markdown);
const liveMarkdown = useLiveThreadLinkLabels(props.markdown, props.environmentId);
@@ -1341,6 +1346,9 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
renderImage={props.renderImage}
skills={props.skills}
models={models}
+ readAloud={
+ props.readAloudId ? { id: props.readAloudId, markdown: props.markdown } : undefined
+ }
/>
);
});
@@ -1356,6 +1364,7 @@ function AssistantMarkdownBlocks(props: {
readonly renderImage: MarkdownImageRenderer;
readonly skills?: ReadonlyArray | undefined;
readonly models: ReturnType;
+ readonly readAloud?: { readonly id: string; readonly markdown: string } | undefined;
}) {
const m = useMessages();
const { blocks, definitions } = useMemo(() => {
@@ -1396,18 +1405,24 @@ function AssistantMarkdownBlocks(props: {
);
}
if (segment.markdown.trim().length === 0) return null;
- return (
-
+ ) : (
+
);
});
});
@@ -2556,6 +2571,7 @@ function renderFeedEntry(
return null;
}
+ const readAloudId = `${props.environmentId}:${props.threadId}:${message.id}`;
const enterAnimated = isFreshTimestamp(message.createdAt);
return (
) : null}
@@ -2613,7 +2630,7 @@ function renderFeedEntry(
/>
) : null}
(null);
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers this feed so read aloud can scroll the word it reads into view
+ useEffect(
+ () =>
+ registerReadAloudFeed({
+ measure: (callback) =>
+ viewportRef.current?.measureInWindow((_x, top, _width, height) =>
+ callback({ top, height }),
+ ),
+ scrollBy: (delta) => {
+ const list = listRef.current;
+ if (list)
+ void list.scrollToOffset({
+ offset: Math.max(0, list.getState().scroll + delta),
+ animated: true,
+ });
+ },
+ }),
+ [listRef],
+ );
+
const handleViewportLayout = (event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
const nextHeight = Math.round(event.nativeEvent.layout.height);
@@ -4206,7 +4244,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
return (
-
+
{/* In a split, rows only re-wrap in the render that hands the list its new width. A native
column resize would re-wrap them first, and the list would place the taller or shorter
rows at their old offsets until their measurements came back. */}
@@ -4279,6 +4317,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onLayout={handleMetricsChange}
onItemSizeChanged={handleItemSizeChanged}
onScroll={handleScroll}
+ onScrollBeginDrag={markReadAloudUserScroll}
scrollEventThrottle={16}
ListHeaderComponent={
<>
diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json
index dd52d35eba2e9..25923d3e868ce 100644
--- a/apps/mobile/src/i18n/translations/de.json
+++ b/apps/mobile/src/i18n/translations/de.json
@@ -3171,6 +3171,7 @@
"15126dd4380d9809": "{speed}×",
"28aa23301e49739e": "Wiedergabe im Hintergrund",
"2fc5076786a6b6ed": "Codeblöcke überspringen",
+ "1a0689369d19aa2c": "Wörter hervorheben",
"0dde517387ea2d57": "Vorschau beenden",
"88f2bec553b72827": "Vorschau abspielen",
"4b009ef01c76df8e": "Das ist T3 Code. Die Antwort Ihres Agenten kann jetzt vorgelesen werden.",
diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json
index 3a3b5ee7fbda3..d7841e04108c7 100644
--- a/apps/mobile/src/i18n/translations/en.json
+++ b/apps/mobile/src/i18n/translations/en.json
@@ -3172,6 +3172,7 @@
"15126dd4380d9809": "{speed}×",
"28aa23301e49739e": "Background playback",
"2fc5076786a6b6ed": "Skip code blocks",
+ "1a0689369d19aa2c": "Highlight words",
"0dde517387ea2d57": "Stop preview",
"88f2bec553b72827": "Play preview",
"4b009ef01c76df8e": "This is T3 Code. Your agent’s response is ready to read aloud.",
diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json
index bafa1b7832c70..adb6b3017746b 100644
--- a/apps/mobile/src/i18n/translations/es.json
+++ b/apps/mobile/src/i18n/translations/es.json
@@ -3166,6 +3166,7 @@
"15126dd4380d9809": "{speed}×",
"28aa23301e49739e": "Reproducción en segundo plano",
"2fc5076786a6b6ed": "Omitir bloques de código",
+ "1a0689369d19aa2c": "Resaltar palabras",
"0dde517387ea2d57": "Detener la vista previa",
"88f2bec553b72827": "Reproducir vista previa",
"4b009ef01c76df8e": "Esto es T3 Code. La respuesta de tu agente está lista para leerse en voz alta.",
diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json
index a1083ec5f8a13..59457bf29fea5 100644
--- a/apps/mobile/src/i18n/translations/fr.json
+++ b/apps/mobile/src/i18n/translations/fr.json
@@ -3166,6 +3166,7 @@
"15126dd4380d9809": "{speed}×",
"28aa23301e49739e": "Lecture en arrière-plan",
"2fc5076786a6b6ed": "Ignorer les blocs de code",
+ "1a0689369d19aa2c": "Surligner les mots",
"0dde517387ea2d57": "Arrêter l’aperçu",
"88f2bec553b72827": "Lire l’aperçu",
"4b009ef01c76df8e": "Voici T3 Code. La réponse de votre agent est prête à être lue à voix haute.",
diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json
index eb4dd108f345f..742c69eaf6990 100644
--- a/apps/mobile/src/i18n/translations/ja.json
+++ b/apps/mobile/src/i18n/translations/ja.json
@@ -3163,6 +3163,7 @@
"15126dd4380d9809": "{speed}×",
"28aa23301e49739e": "バックグラウンド再生",
"2fc5076786a6b6ed": "コードブロックをスキップ",
+ "1a0689369d19aa2c": "単語をハイライト",
"0dde517387ea2d57": "プレビューを停止",
"88f2bec553b72827": "プレビューを再生",
"4b009ef01c76df8e": "T3 Code です。エージェントの応答を読み上げる準備ができました。",
diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json
index e05771054bb13..7dcc6d0d69736 100644
--- a/apps/mobile/src/i18n/translations/ko.json
+++ b/apps/mobile/src/i18n/translations/ko.json
@@ -3167,6 +3167,7 @@
"15126dd4380d9809": "{speed}×",
"28aa23301e49739e": "백그라운드 재생",
"2fc5076786a6b6ed": "코드 블록 건너뛰기",
+ "1a0689369d19aa2c": "단어 강조",
"0dde517387ea2d57": "미리 듣기 중지",
"88f2bec553b72827": "미리 듣기 재생",
"4b009ef01c76df8e": "T3 Code입니다. 에이전트의 응답을 소리 내어 읽을 준비가 되었습니다.",
diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json
index 4d8b09ce28e75..3704d1d9baea1 100644
--- a/apps/mobile/src/i18n/translations/pt-BR.json
+++ b/apps/mobile/src/i18n/translations/pt-BR.json
@@ -3166,6 +3166,7 @@
"15126dd4380d9809": "{speed}×",
"28aa23301e49739e": "Reprodução em segundo plano",
"2fc5076786a6b6ed": "Pular blocos de código",
+ "1a0689369d19aa2c": "Destacar palavras",
"0dde517387ea2d57": "Parar prévia",
"88f2bec553b72827": "Reproduzir prévia",
"4b009ef01c76df8e": "Este é o T3 Code. A resposta do seu agente está pronta para ser lida em voz alta.",
diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json
index 0cba232cd0b32..4fd519f16fd6f 100644
--- a/apps/mobile/src/i18n/translations/ru.json
+++ b/apps/mobile/src/i18n/translations/ru.json
@@ -3220,6 +3220,7 @@
"15126dd4380d9809": "{speed}×",
"28aa23301e49739e": "Воспроизведение в фоне",
"2fc5076786a6b6ed": "Пропускать блоки кода",
+ "1a0689369d19aa2c": "Выделять слова",
"0dde517387ea2d57": "Остановить пример",
"88f2bec553b72827": "Воспроизвести пример",
"4b009ef01c76df8e": "Это T3 Code. Ответ вашего агента готов к чтению вслух.",
diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json
index cf3eb9a4faf3b..886d8e14ac048 100644
--- a/apps/mobile/src/i18n/translations/sv.json
+++ b/apps/mobile/src/i18n/translations/sv.json
@@ -3172,6 +3172,7 @@
"15126dd4380d9809": "{speed}×",
"28aa23301e49739e": "Uppspelning i bakgrunden",
"2fc5076786a6b6ed": "Hoppa över kodblock",
+ "1a0689369d19aa2c": "Markera ord",
"0dde517387ea2d57": "Stoppa förhandsvisningen",
"88f2bec553b72827": "Spela upp förhandsvisning",
"4b009ef01c76df8e": "Det här är T3 Code. Agentens svar är redo att läsas upp.",
diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json
index 59440ec7afe20..d550795a0ec07 100644
--- a/apps/mobile/src/i18n/translations/zh.json
+++ b/apps/mobile/src/i18n/translations/zh.json
@@ -3167,6 +3167,7 @@
"15126dd4380d9809": "{speed}×",
"28aa23301e49739e": "后台播放",
"2fc5076786a6b6ed": "跳过代码块",
+ "1a0689369d19aa2c": "高亮单词",
"0dde517387ea2d57": "停止试听",
"88f2bec553b72827": "播放试听",
"4b009ef01c76df8e": "这里是 T3 Code。你的代理回复已可以朗读。",
diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts
index 5c6d1dd6a5fc4..c9f371818b6ba 100644
--- a/apps/mobile/src/lib/filePreview.test.ts
+++ b/apps/mobile/src/lib/filePreview.test.ts
@@ -64,7 +64,10 @@ const audio = vi.hoisted(() => ({
navigate: vi.fn(),
query: vi.fn(),
}));
-vi.mock("../features/read-aloud/ReadAloudButton", () => ({ ReadAloudButton: () => null }));
+vi.mock("../features/read-aloud/ReadAloudButton", () => ({
+ ReadAloudButton: () => null,
+ useReadAloudHighlight: () => null,
+}));
vi.mock("../features/read-aloud/playback", () => ({
readAloudController: { getSnapshot: () => ({ id: null }), stop: vi.fn() },
}));
diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsx
index e51aa893f8ead..e49584b4f5d29 100644
--- a/apps/mobile/src/native/EnrichedMarkdownText.tsx
+++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx
@@ -467,6 +467,9 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
linkContextMenuItems={linkContextMenuItems}
linkPillContent={linkPillContent}
accessibilityLabels={accessibilityLabels}
+ highlights={props.highlights}
+ onRenderedTextChange={props.onRenderedTextChange}
+ onHighlightLayout={props.onHighlightLayout}
/>
);
diff --git a/apps/mobile/src/native/SelectableMarkdownText.types.ts b/apps/mobile/src/native/SelectableMarkdownText.types.ts
index 63f8429c386fd..ade0dd5f98fab 100644
--- a/apps/mobile/src/native/SelectableMarkdownText.types.ts
+++ b/apps/mobile/src/native/SelectableMarkdownText.types.ts
@@ -94,6 +94,14 @@ export interface SelectableMarkdownTextProps {
readonly checked: boolean;
readonly text: string;
}) => void;
+ /** Ranges of the text the view shows, painted behind it; see `onRenderedTextChange`. */
+ readonly highlights?: ReadonlyArray;
+ readonly onRenderedTextChange?: (
+ event: import("react-native-enriched-markdown").RenderedTextChangeEvent,
+ ) => void;
+ readonly onHighlightLayout?: (
+ event: import("react-native-enriched-markdown").HighlightLayoutEvent,
+ ) => void;
readonly marginTop?: number;
readonly marginBottom?: number;
readonly writingDirection?: "ltr" | "rtl";
diff --git a/apps/server/src/speech/CloudSpeech.ts b/apps/server/src/speech/CloudSpeech.ts
index 91a2d5bd6e806..9c18131f83a36 100644
--- a/apps/server/src/speech/CloudSpeech.ts
+++ b/apps/server/src/speech/CloudSpeech.ts
@@ -3,6 +3,7 @@ import {
type SpeechSynthesisProvider,
type SpeechSynthesisRequest,
type SpeechSynthesisCatalog,
+ type SpeechSynthesisWord,
} from "@t3tools/contracts";
import {
CloudSpeechApiKey,
@@ -19,7 +20,7 @@ import {
type SpeechTranscriptionOptions,
} from "@t3tools/contracts";
import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
-import { splitReadAloudText } from "@t3tools/shared/read-aloud";
+import { splitReadAloudSpans } from "@t3tools/shared/read-aloud";
import { cloudSpeechLanguages, effectiveSpeechLanguage } from "@t3tools/shared/speech";
import * as Context from "effect/Context";
import * as ByteSize from "effect/ByteSize";
@@ -37,6 +38,7 @@ import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts";
import { applySpeechAliases } from "./customWords.ts";
import { removeSpeechFillerWords } from "./fillerWords.ts";
import { decodeSpeechPcm, SpeechInvalidAudioError } from "./SpeechService.ts";
+import { alignedWords, mp3Duration, type CharacterAlignment } from "./synthesisTimings.ts";
const isSynthesisError = Schema.is(SpeechSynthesisError);
@@ -101,6 +103,24 @@ const decodeElevenLabsModels = Schema.decodeUnknownEffect(
),
);
+// `alignment` follows the request text; `normalized_alignment` follows ElevenLabs' rewrite of it.
+const decodeElevenLabsTimedChunk = Schema.decodeUnknownEffect(
+ Schema.fromJsonString(
+ Schema.Struct({
+ audio_base64: Schema.NullOr(Schema.String),
+ alignment: Schema.optionalKey(
+ Schema.NullOr(
+ Schema.Struct({
+ characters: Schema.Array(Schema.String),
+ character_start_times_seconds: Schema.Array(Schema.Finite),
+ character_end_times_seconds: Schema.Array(Schema.Finite),
+ }),
+ ),
+ ),
+ }),
+ ),
+);
+
const decodeElevenLabsVoices = Schema.decodeUnknownEffect(
Schema.fromJsonString(
Schema.Struct({
@@ -194,8 +214,20 @@ type SynthesisBackend = {
input: SpeechSynthesisRequest,
) => { readonly rate: number; readonly channels: number } | undefined;
errorReason: (status: number) => SpeechSynthesisError["reason"];
+ /** Responses that interleave audio with timings for each character of the request text. */
+ alignedAudio?: (
+ response: HttpClientResponse.HttpClientResponse,
+ ) => Stream.Stream<
+ { readonly audio: Uint8Array; readonly alignment: CharacterAlignment | null },
+ unknown
+ >;
};
+/** Audio, or the words of the request text that the audio so far speaks. */
+export type SpeechSynthesisPart =
+ | Uint8Array
+ | { readonly words: ReadonlyArray };
+
// gpt-4o-mini-tts accepts 2,000 tokens, which Chinese or Japanese reaches near 2,000 characters,
// and OpenRouter's Seed Audio accepts 3,000 characters. Pieces stream back to back, so small is cheap.
const CLOUD_SYNTHESIS_TEXT_LIMIT = 1000;
@@ -284,11 +316,11 @@ export class CloudSpeech extends Context.Service<
readonly synthesisModels: (
provider: CloudSpeechProvider,
) => Effect.Effect;
- /** MP3 that streams through as the provider produces it. */
+ /** MP3 that streams through as the provider produces it, with word timings where it has them. */
readonly stream: (
provider: CloudSpeechProvider,
request: SpeechSynthesisRequest,
- ) => Stream.Stream;
+ ) => Stream.Stream;
readonly configured: Effect.Effect;
/** OpenRouter's public transcription catalog, cached briefly on this server. */
readonly models: Effect.Effect, CloudSpeechError>;
@@ -568,6 +600,7 @@ export const layer = Layer.effect(
supportsVoiceSelection: true,
// Eleven v4 has no speed setting, so players speed up every model alike.
speedAppliedByProvider: false,
+ wordTimings: "provider",
},
models: loadSynthesisModels("elevenlabs"),
request: (input) =>
@@ -575,7 +608,7 @@ export const layer = Layer.effect(
HttpClientRequest.post(
`${ELEVENLABS_API}/v1/text-to-speech/${encodeURIComponent(
input.voice || ELEVENLABS_DEFAULT_VOICE,
- )}/stream?output_format=mp3_44100_64`,
+ )}/stream/with-timestamps?output_format=mp3_44100_64`,
).pipe(
HttpClientRequest.bodyJsonUnsafe({
text: input.text,
@@ -584,6 +617,20 @@ export const layer = Layer.effect(
),
),
errorReason: synthesisErrorReason,
+ // One JSON object per line; the alignment of a chunk arrives with or before its audio.
+ alignedAudio: (response) =>
+ response.stream.pipe(
+ Stream.decodeText(),
+ Stream.splitLines,
+ Stream.filter((line) => line.trim() !== ""),
+ Stream.mapEffect((line) => decodeElevenLabsTimedChunk(line)),
+ Stream.map((chunk) => ({
+ audio: chunk.audio_base64
+ ? Uint8Array.from(Buffer.from(chunk.audio_base64, "base64"))
+ : new Uint8Array(0),
+ alignment: chunk.alignment ?? null,
+ })),
+ ),
},
} satisfies Record;
const synthesisModels = Effect.fn("CloudSpeech.synthesisCatalog")(function* (
@@ -634,12 +681,31 @@ export const layer = Layer.effect(
return encodeMp3(pcm, format.rate, format.channels).pipe(Stream.mapError(unavailable));
}
let size = 0;
- return response.stream.pipe(
+ const words = alignedWords(input.text);
+ const parts: Stream.Stream = backend.alignedAudio
+ ? backend.alignedAudio(response).pipe(
+ Stream.flatMap(({ audio, alignment }) => {
+ const spoken = alignment ? words.push(alignment) : [];
+ return Stream.fromIterable(
+ spoken.length ? [{ words: spoken }, audio] : [audio],
+ );
+ }),
+ Stream.concat(
+ Stream.suspend(() => {
+ const last = words.end();
+ return Stream.fromIterable(
+ last.length ? [{ words: last }] : [],
+ );
+ }),
+ ),
+ )
+ : response.stream;
+ return parts.pipe(
Stream.mapError(unavailable),
- Stream.mapEffect((chunk) =>
- (size += chunk.byteLength) > MAX_SYNTHESIS_BYTES
+ Stream.mapEffect((part) =>
+ part instanceof Uint8Array && (size += part.byteLength) > MAX_SYNTHESIS_BYTES
? Effect.fail(unavailable())
- : Effect.succeed(chunk),
+ : Effect.succeed(part),
),
// The request timeout ends at the headers; a body that stalls must fail too.
Stream.timeoutOrElse({
@@ -657,12 +723,44 @@ export const layer = Layer.effect(
}),
),
);
- // Pieces play back to back as one stream; each is requested once the last one ends.
+ // Pieces play back to back as one stream; each is requested once the last one ends. A piece's
+ // words move to its place in the request text and to where its audio starts.
const stream = (provider: CloudSpeechProvider, request: SpeechSynthesisRequest) =>
- Stream.fromIterable(splitReadAloudText(request.text, CLOUD_SYNTHESIS_TEXT_LIMIT)).pipe(
- Stream.flatMap((text) => Stream.unwrap(synthesizePiece(provider, { ...request, text }))),
- Stream.withSpan("CloudSpeech.stream"),
- );
+ Stream.suspend(() => {
+ let elapsed = 0;
+ return Stream.fromIterable(
+ splitReadAloudSpans(request.text, CLOUD_SYNTHESIS_TEXT_LIMIT),
+ ).pipe(
+ Stream.flatMap((span) =>
+ Stream.suspend(() => {
+ const offset = elapsed;
+ const duration = mp3Duration();
+ return Stream.unwrap(synthesizePiece(provider, { ...request, text: span.text })).pipe(
+ Stream.map((part): SpeechSynthesisPart => {
+ if (part instanceof Uint8Array) {
+ duration.push(part);
+ return part;
+ }
+ return {
+ words: part.words.map((word) => ({
+ start: word.start + span.start,
+ end: word.end + span.start,
+ startSeconds: word.startSeconds + offset,
+ endSeconds: word.endSeconds + offset,
+ })),
+ };
+ }),
+ Stream.onEnd(
+ Effect.sync(() => {
+ elapsed = offset + duration.seconds;
+ }),
+ ),
+ );
+ }),
+ ),
+ Stream.withSpan("CloudSpeech.stream"),
+ );
+ });
const setKey = Effect.fn("CloudSpeech.setKey")(function* (
provider: CloudSpeechProvider,
key: Redacted.Redacted | SecretReference | null,
diff --git a/apps/server/src/speech/http.ts b/apps/server/src/speech/http.ts
index 94288273e7136..6ce14226ce899 100644
--- a/apps/server/src/speech/http.ts
+++ b/apps/server/src/speech/http.ts
@@ -151,6 +151,13 @@ export const speechHttpApiLayer = HttpApiBuilder.group(
return { token };
}),
)
+ .handle(
+ "synthesisTimings",
+ Effect.fn("environment.voice.synthesisTimings")(function* (args) {
+ yield* guard(args.endpoint.name);
+ return yield* synthesisStreams.timings(args.payload.token, args.payload.after);
+ }),
+ )
.handle(
"prepareSynthesisModel",
Effect.fn("environment.voice.prepareSynthesisModel")(function* (args) {
diff --git a/apps/server/src/speech/synthesis.test.ts b/apps/server/src/speech/synthesis.test.ts
index 28a213039c031..84fa30f8c95ff 100644
--- a/apps/server/src/speech/synthesis.test.ts
+++ b/apps/server/src/speech/synthesis.test.ts
@@ -124,16 +124,22 @@ it.effect("lists ElevenLabs voices by name and sends its key only in its own hea
can_do_text_to_speech: false,
},
])
- : new Response(new Uint8Array([73, 68, 51, 1]), {
- headers: { "content-type": "audio/mpeg" },
- }),
+ : new Response(
+ `${JSON.stringify({
+ audio_base64: Buffer.from([73, 68, 51, 1]).toString("base64"),
+ alignment: null,
+ })}\n`,
+ { headers: { "content-type": "application/json" } },
+ ),
);
yield* Effect.gen(function* () {
const service = yield* CloudSpeech.CloudSpeech;
const synthesize = (request: Parameters[1]) =>
service.stream("elevenlabs", request).pipe(
Stream.runCollect,
- Effect.map((chunks) => Uint8Array.from(chunks.flatMap((chunk) => [...chunk]))),
+ Effect.map((parts) =>
+ Uint8Array.from(parts.flatMap((part) => (part instanceof Uint8Array ? [...part] : []))),
+ ),
);
const request = {
text: "Read this reply.",
@@ -149,6 +155,7 @@ it.effect("lists ElevenLabs voices by name and sends its key only in its own hea
apiKeyProvider: "elevenlabs",
defaultModel: "eleven_multilingual_v2",
speedAppliedByProvider: false,
+ wordTimings: "provider",
models: [
{
id: "eleven_multilingual_v2",
@@ -169,14 +176,14 @@ it.effect("lists ElevenLabs voices by name and sends its key only in its own hea
}
const [defaultUrl, defaultInit] = upstream.mock.calls.at(-2)!;
expect(String(defaultUrl)).toBe(
- "https://api.elevenlabs.io/v1/text-to-speech/JBFqnCBsd6RMkjVDRZzb/stream?output_format=mp3_44100_64",
+ "https://api.elevenlabs.io/v1/text-to-speech/JBFqnCBsd6RMkjVDRZzb/stream/with-timestamps?output_format=mp3_44100_64",
);
expect(JSON.parse(String(defaultInit?.body))).toEqual({
text: "Read this reply.",
model_id: "eleven_multilingual_v2",
});
const [chosenUrl, chosenInit] = upstream.mock.calls.at(-1)!;
- expect(String(chosenUrl)).toContain("/v1/text-to-speech/voice-123/stream");
+ expect(String(chosenUrl)).toContain("/v1/text-to-speech/voice-123/stream/with-timestamps");
expect(JSON.parse(String(chosenInit?.body)).model_id).toBe("eleven_v3");
}).pipe(
Effect.provide(
@@ -192,6 +199,65 @@ it.effect("lists ElevenLabs voices by name and sends its key only in its own hea
}),
);
+it.effect("places ElevenLabs word timings of later pieces after the earlier pieces' audio", () =>
+ Effect.gen(function* () {
+ // Two MPEG-1 Layer III frames at 64 kbps and 44.1 kHz.
+ const frame = Uint8Array.from({ length: 208 }, (_, index) =>
+ index === 0 ? 0xff : index === 1 ? 0xfb : index === 2 ? 0x50 : 0,
+ );
+ const pieceSeconds = (2 * 1152) / 44100;
+ const upstream = vi.fn(async (_url, init) => {
+ const { text } = JSON.parse(String(init?.body)) as { text: string };
+ const characters = Array.from(text);
+ return new Response(
+ [
+ {
+ audio_base64: null,
+ alignment: {
+ characters,
+ character_start_times_seconds: characters.map((_, index) => index / 100),
+ character_end_times_seconds: characters.map((_, index) => (index + 1) / 100),
+ },
+ },
+ { audio_base64: Buffer.from([...frame, ...frame]).toString("base64"), alignment: null },
+ ]
+ .map((chunk) => JSON.stringify(chunk))
+ .join("\n"),
+ );
+ });
+ const text = Array.from({ length: 250 }, (_, index) => `w${index}.`).join(" ");
+ const words = yield* Effect.gen(function* () {
+ const service = yield* CloudSpeech.CloudSpeech;
+ yield* service.setKey("elevenlabs", Redacted.make("speech-key"));
+ return yield* service
+ .stream("elevenlabs", { text, model: "", voice: "", speed: 1, language: "en" })
+ .pipe(
+ Stream.runCollect,
+ Effect.map((parts) => parts.flatMap((part) => ("words" in part ? part.words : []))),
+ );
+ }).pipe(
+ Effect.provide(
+ CloudSpeech.layer.pipe(
+ Layer.provide(NodeServices.layer),
+ Layer.provide(ServerSettings.ServerSettingsService.layerTest()),
+ Layer.provide(FetchHttpClient.layer),
+ Layer.provide(Layer.mock(SecretResolver.SecretResolver)({})),
+ ),
+ ),
+ Effect.provideService(FetchHttpClient.Fetch, upstream),
+ );
+ expect(upstream).toHaveBeenCalledTimes(2);
+ expect(words.map((word) => text.slice(word.start, word.end))).toEqual(text.split(" "));
+ const second = (JSON.parse(String(upstream.mock.calls[1]?.[1]?.body)) as { text: string }).text;
+ const first = words.find((word) => word.start === text.indexOf(second));
+ expect(first?.startSeconds).toBeCloseTo(pieceSeconds, 6);
+ expect(words.at(-1)?.startSeconds).toBeCloseTo(
+ pieceSeconds + (second.length - second.split(" ").at(-1)!.length) / 100,
+ 6,
+ );
+ }),
+);
+
it.effect.each(["openai", "xai", "openrouter"] as const)(
"synthesizes with %s without leaking keys to another destination",
(provider) =>
@@ -219,7 +285,11 @@ it.effect.each(["openai", "xai", "openrouter"] as const)(
const synthesize = (...args: Parameters) =>
service.stream(...args).pipe(
Stream.runCollect,
- Effect.map((chunks) => Uint8Array.from(chunks.flatMap((chunk) => [...chunk]))),
+ Effect.map((parts) =>
+ Uint8Array.from(
+ parts.flatMap((part) => (part instanceof Uint8Array ? [...part] : [])),
+ ),
+ ),
);
yield* service.setKey(
provider === "openai" ? "xai" : "openai",
diff --git a/apps/server/src/speech/synthesisStreams.test.ts b/apps/server/src/speech/synthesisStreams.test.ts
index 6faf53c0bf8c0..55329e329ce3d 100644
--- a/apps/server/src/speech/synthesisStreams.test.ts
+++ b/apps/server/src/speech/synthesisStreams.test.ts
@@ -23,7 +23,7 @@ const request: SpeechSynthesisRequest = {
language: "en",
};
-const withSource = (source: Stream.Stream) =>
+const withSource = (source: Stream.Stream) =>
SpeechSynthesisStreams.layer.pipe(
Layer.provide(Layer.mock(CloudSpeech.CloudSpeech)({ stream: () => source })),
Layer.provide(Layer.mock(LocalSpeechSynthesis.LocalSpeechSynthesis)({})),
@@ -52,6 +52,36 @@ it.effect("hands every reader the audio from its start while synthesis continues
}),
);
+it.effect("answers word timings as they arrive and the audio length once synthesis ends", () =>
+ Effect.gen(function* () {
+ const source = yield* Queue.unbounded<
+ CloudSpeech.SpeechSynthesisPart,
+ SpeechSynthesisError | Cause.Done
+ >();
+ // One MPEG-1 Layer III frame at 64 kbps and 44.1 kHz.
+ const frame = Uint8Array.from({ length: 208 }, (_, index) =>
+ index === 0 ? 0xff : index === 1 ? 0xfb : index === 2 ? 0x50 : 0,
+ );
+ const word = (start: number) => ({ start, end: start + 4, startSeconds: start, endSeconds: 1 });
+ yield* Effect.gen(function* () {
+ const streams = yield* SpeechSynthesisStreams.SpeechSynthesisStreams;
+ yield* Queue.offerAll(source, [{ words: [word(0)] }, frame]);
+ const token = yield* streams.start("elevenlabs", request);
+ expect(yield* streams.timings(token, 0)).toEqual({ words: [word(0)], done: false });
+ const waiting = yield* Effect.forkChild(streams.timings(token, 1));
+ yield* Queue.offer(source, { words: [word(5)] });
+ expect(yield* Fiber.join(waiting)).toEqual({ words: [word(5)], done: false });
+ yield* Queue.end(source);
+ expect(yield* streams.timings(token, 2)).toEqual({
+ words: [],
+ done: true,
+ durationSeconds: 1152 / 44100,
+ });
+ expect(yield* streams.timings("unknown", 0)).toEqual({ words: [], done: true });
+ }).pipe(Effect.provide(withSource(Stream.fromQueue(source))));
+ }),
+);
+
it.effect.each([
[
"a provider error",
diff --git a/apps/server/src/speech/synthesisStreams.ts b/apps/server/src/speech/synthesisStreams.ts
index ffdad9008e33a..a5a93d48e0002 100644
--- a/apps/server/src/speech/synthesisStreams.ts
+++ b/apps/server/src/speech/synthesisStreams.ts
@@ -4,6 +4,8 @@ import {
type ServerSettingsError,
type SpeechSynthesisProvider,
type SpeechSynthesisRequest,
+ type SpeechSynthesisTimings,
+ type SpeechSynthesisWord,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
@@ -20,6 +22,7 @@ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
import * as CloudSpeech from "./CloudSpeech.ts";
import * as LocalSpeechSynthesis from "./LocalSpeechSynthesis.ts";
+import { mp3Duration } from "./synthesisTimings.ts";
// A started stream nobody opens is abandoned.
const UNREAD_GRACE: Duration.Input = "30 seconds";
@@ -27,11 +30,16 @@ const UNREAD_GRACE: Duration.Input = "30 seconds";
const RECONNECT_GRACE: Duration.Input = "5 seconds";
// Finished audio stays for players that re-request it after playing.
const FINISHED_RETENTION: Duration.Input = "2 minutes";
+// A timings read answers by then even when nothing changed, so a lost client is not held.
+const TIMINGS_WAIT: Duration.Input = "10 seconds";
type Job = {
readonly chunks: Uint8Array[];
+ readonly words: SpeechSynthesisWord[];
+ readonly duration: ReturnType;
readonly progress: SubscriptionRef.SubscriptionRef<{
readonly count: number;
+ readonly words: number;
readonly done: boolean;
}>;
fiber?: Fiber.Fiber;
@@ -51,6 +59,8 @@ export class SpeechSynthesisStreams extends Context.Service<
) => Effect.Effect;
/** The audio from its start, then live as it is produced; `undefined` once expired. */
readonly read: (token: string) => Effect.Effect | undefined>;
+ /** Words after the first `after`, once there are any or synthesis ends. */
+ readonly timings: (token: string, after: number) => Effect.Effect;
}
>()("t3/speech/synthesisStreams/SpeechSynthesisStreams") {}
@@ -75,26 +85,44 @@ const make = Effect.gen(function* () {
provider: SpeechSynthesisProvider,
request: SpeechSynthesisRequest,
) {
- const source = provider === "local" ? local.stream(request) : cloud.stream(provider, request);
+ const source: Stream.Stream<
+ CloudSpeech.SpeechSynthesisPart,
+ SpeechSynthesisError | ServerSettingsError
+ > = provider === "local" ? local.stream(request) : cloud.stream(provider, request);
const first = yield* Deferred.make();
const job: Job = {
chunks: [],
- progress: yield* SubscriptionRef.make({ count: 0, done: false }),
+ words: [],
+ duration: mp3Duration(),
+ progress: yield* SubscriptionRef.make({ count: 0, words: 0, done: false }),
failed: false,
readers: 0,
everRead: false,
idle: 0,
};
job.fiber = yield* source.pipe(
- Stream.runForEach((chunk) => {
- job.chunks.push(chunk);
- return SubscriptionRef.set(job.progress, { count: job.chunks.length, done: false }).pipe(
- Effect.andThen(Deferred.succeed(first, undefined)),
- );
+ Stream.runForEach((part) => {
+ if (!(part instanceof Uint8Array)) {
+ job.words.push(...part.words);
+ return SubscriptionRef.update(job.progress, (progress) => ({
+ ...progress,
+ words: job.words.length,
+ }));
+ }
+ job.chunks.push(part);
+ job.duration.push(part);
+ return SubscriptionRef.update(job.progress, (progress) => ({
+ ...progress,
+ count: job.chunks.length,
+ })).pipe(Effect.andThen(Deferred.succeed(first, undefined)));
}),
Effect.onExit((exit) => {
job.failed = Exit.isFailure(exit);
- return SubscriptionRef.set(job.progress, { count: job.chunks.length, done: true }).pipe(
+ return SubscriptionRef.set(job.progress, {
+ count: job.chunks.length,
+ words: job.words.length,
+ done: true,
+ }).pipe(
Effect.andThen(
Exit.isFailure(exit)
? Deferred.failCause(first, exit.cause)
@@ -160,7 +188,26 @@ const make = Effect.gen(function* () {
);
});
- return SpeechSynthesisStreams.of({ start, read });
+ const timings = Effect.fn("SpeechSynthesisStreams.timings")(function* (
+ token: string,
+ after: number,
+ ) {
+ const job = jobs.get(token);
+ if (!job) return { words: [], done: true };
+ yield* SubscriptionRef.changes(job.progress).pipe(
+ Stream.filter((progress) => progress.done || progress.words > after),
+ Stream.runHead,
+ Effect.timeoutOption(TIMINGS_WAIT),
+ );
+ const { done } = yield* SubscriptionRef.get(job.progress);
+ return {
+ words: job.words.slice(after),
+ done,
+ ...(done && !job.failed ? { durationSeconds: job.duration.seconds } : {}),
+ };
+ });
+
+ return SpeechSynthesisStreams.of({ start, read, timings });
});
export const layer = Layer.effect(SpeechSynthesisStreams, make);
diff --git a/apps/server/src/speech/synthesisTimings.test.ts b/apps/server/src/speech/synthesisTimings.test.ts
new file mode 100644
index 0000000000000..85f7f69ffd1d5
--- /dev/null
+++ b/apps/server/src/speech/synthesisTimings.test.ts
@@ -0,0 +1,38 @@
+import { expect, it } from "vite-plus/test";
+import { alignedWords, mp3Duration } from "./synthesisTimings.ts";
+
+it("counts MP3 playing time across split chunks and after an ID3 tag", () => {
+ // MPEG-1 Layer III at 64 kbps and 44.1 kHz: 208 bytes and 1152 samples per frame.
+ const frame = Uint8Array.from({ length: 208 }, (_, index) =>
+ index === 0 ? 0xff : index === 1 ? 0xfb : index === 2 ? 0x50 : 0,
+ );
+ const tag = Uint8Array.of(0x49, 0x44, 0x33, 4, 0, 0, 0, 0, 0, 3, 0xff, 0xfb, 0x50);
+ const bytes = Uint8Array.from([...tag, ...frame, ...frame, ...frame.subarray(0, 100)]);
+ const duration = mp3Duration();
+ for (let at = 0; at < bytes.length; at += 7) duration.push(bytes.subarray(at, at + 7));
+ expect(duration.seconds).toBeCloseTo((2 * 1152) / 44100, 9);
+});
+
+it("builds words from character alignment that spans chunks", () => {
+ const text = "Hi 🙂 there, you";
+ const characters = Array.from(text);
+ const times = characters.map((character, index) =>
+ character === "🙂" ? [index / 10, index / 10] : [index / 10, (index + 1) / 10],
+ );
+ const words = alignedWords(text);
+ const alignment = (from: number, to: number) => ({
+ characters: characters.slice(from, to),
+ character_start_times_seconds: times.slice(from, to).map(([start]) => start!),
+ character_end_times_seconds: times.slice(from, to).map(([, end]) => end!),
+ });
+ const spoken = [...words.push(alignment(0, 6)), ...words.push(alignment(6, 99)), ...words.end()];
+ expect(spoken.map((word) => [text.slice(word.start, word.end), word.startSeconds])).toEqual([
+ ["Hi", 0],
+ ["there,", 0.5],
+ ["you", 1.2],
+ ]);
+ const mismatch = alignedWords("Hi there");
+ expect([...mismatch.push(alignment(0, 6)), ...mismatch.end()]).toEqual([
+ { start: 0, end: 2, startSeconds: 0, endSeconds: 0.2 },
+ ]);
+});
diff --git a/apps/server/src/speech/synthesisTimings.ts b/apps/server/src/speech/synthesisTimings.ts
new file mode 100644
index 0000000000000..774b3c7a19120
--- /dev/null
+++ b/apps/server/src/speech/synthesisTimings.ts
@@ -0,0 +1,132 @@
+import type { SpeechSynthesisWord } from "@t3tools/contracts";
+
+const MPEG1_LAYER3_KBPS = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320];
+const MPEG2_LAYER3_KBPS = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
+const MPEG1_RATES = [44100, 48000, 32000];
+
+/** Layer III frame length and duration at `at`, or undefined when no frame header starts there. */
+function frameAt(bytes: Uint8Array, at: number) {
+ const [sync, flags, info] = [bytes[at], bytes[at + 1], bytes[at + 2]];
+ if (sync !== 0xff || flags === undefined || info === undefined || (flags & 0xe0) !== 0xe0)
+ return undefined;
+ const version = (flags >> 3) & 3;
+ if (version === 1 || ((flags >> 1) & 3) !== 1) return undefined;
+ const mpeg1 = version === 3;
+ const kbps = (mpeg1 ? MPEG1_LAYER3_KBPS : MPEG2_LAYER3_KBPS)[info >> 4];
+ const base = MPEG1_RATES[(info >> 2) & 3];
+ if (!kbps || base === undefined) return undefined;
+ const rate = mpeg1 ? base : version === 2 ? base / 2 : base / 4;
+ const samples = mpeg1 ? 1152 : 576;
+ return {
+ length: Math.floor(((samples / 8) * kbps * 1000) / rate) + ((info >> 1) & 1),
+ seconds: samples / rate,
+ };
+}
+
+/**
+ * Counts the playing time of an MP3 stream from its frame headers as chunks arrive. Word timings
+ * of later synthesis pieces start where the earlier pieces' audio ends.
+ */
+export function mp3Duration() {
+ let carry = new Uint8Array(0);
+ let skip = 0;
+ let started = false;
+ let seconds = 0;
+ return {
+ push(chunk: Uint8Array) {
+ let bytes = new Uint8Array(carry.length + chunk.length);
+ bytes.set(carry);
+ bytes.set(chunk, carry.length);
+ if (!started) {
+ if (bytes.length < 10) {
+ carry = bytes;
+ return;
+ }
+ started = true;
+ // An ID3v2 tag holds metadata, not audio; its size is four 7-bit bytes.
+ if (bytes[0] === 0x49 && bytes[1] === 0x44 && bytes[2] === 0x33)
+ skip = 10 + ((bytes[6]! << 21) | (bytes[7]! << 14) | (bytes[8]! << 7) | bytes[9]!);
+ }
+ const skipped = Math.min(skip, bytes.length);
+ skip -= skipped;
+ bytes = bytes.subarray(skipped);
+ let at = 0;
+ while (at + 4 <= bytes.length) {
+ const frame = frameAt(bytes, at);
+ if (!frame) {
+ at++;
+ continue;
+ }
+ if (at + frame.length > bytes.length) break;
+ seconds += frame.seconds;
+ at += frame.length;
+ }
+ carry = bytes.slice(at);
+ },
+ get seconds() {
+ return seconds;
+ },
+ };
+}
+
+export interface CharacterAlignment {
+ readonly characters: ReadonlyArray;
+ readonly character_start_times_seconds: ReadonlyArray;
+ readonly character_end_times_seconds: ReadonlyArray;
+}
+
+const round = (seconds: number) => Math.round(seconds * 1000) / 1000;
+
+/**
+ * Turns streamed character alignment for `text` into words. Each alignment entry is one code
+ * point; offsets become UTF-16. Once the characters stop matching `text` no more words come,
+ * since a wrong highlight is worse than none.
+ */
+export function alignedWords(text: string) {
+ let offset = 0;
+ let matching = true;
+ let open: SpeechSynthesisWord | null = null;
+ let voiced = false;
+ const close = (words: SpeechSynthesisWord[]) => {
+ // Emoji are aligned with zero duration because they are not spoken.
+ if (open && voiced) words.push(open);
+ open = null;
+ voiced = false;
+ };
+ return {
+ push(alignment: CharacterAlignment) {
+ const words: SpeechSynthesisWord[] = [];
+ alignment.characters.forEach((character, index) => {
+ const startSeconds = alignment.character_start_times_seconds[index];
+ const endSeconds = alignment.character_end_times_seconds[index];
+ if (!matching) return;
+ if (
+ startSeconds === undefined ||
+ endSeconds === undefined ||
+ !text.startsWith(character, offset)
+ ) {
+ matching = false;
+ open = null;
+ return;
+ }
+ if (/^\s+$/u.test(character)) close(words);
+ else {
+ open = {
+ start: open ? open.start : offset,
+ end: offset + character.length,
+ startSeconds: open ? open.startSeconds : round(startSeconds),
+ endSeconds: round(endSeconds),
+ };
+ if (endSeconds > startSeconds) voiced = true;
+ }
+ offset += character.length;
+ });
+ return words;
+ },
+ end() {
+ const words: SpeechSynthesisWord[] = [];
+ if (matching && offset === text.length) close(words);
+ return words;
+ },
+ };
+}
diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx
index e3ed31ee6902c..8aeb68acbc81a 100644
--- a/apps/web/src/components/ChatMarkdown.browser.test.tsx
+++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx
@@ -1,5 +1,6 @@
import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets";
-import { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { DEFAULT_READ_ALOUD_SETTINGS, EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { readAloudText } from "@t3tools/shared/read-aloud";
import { AsyncResult } from "effect/reactivity";
import { type ReactElement } from "react";
import remarkGfm from "remark-gfm";
@@ -136,9 +137,37 @@ vi.mock(import("../hooks/useSettings"), async (original) => {
return { ...actual, useClientSettings };
});
+// Read aloud speaks through a playback that reports the words the test names.
+const readAloudWords = vi.hoisted(() => ({
+ emit: (_word: { start: number; end: number } | null) => {},
+}));
+vi.mock(import("../speech/readAloud"), async () => {
+ const { createReadAloudController } = await import("@t3tools/client-runtime/read-aloud");
+ return {
+ warmReadAloud: () => {},
+ readAloudController: createReadAloudController(async () => {
+ const finished = Promise.withResolvers();
+ return {
+ play: async () => {},
+ pause: () => {},
+ stop: () => finished.resolve(),
+ finished: finished.promise,
+ words: (listener) => {
+ readAloudWords.emit = listener;
+ return () => {
+ readAloudWords.emit = () => {};
+ };
+ },
+ };
+ }),
+ };
+});
+
import ChatMarkdown from "./ChatMarkdown";
import { chatMarkdownClipboardPayload } from "../markdown-clipboard";
import { AudioPreview } from "./files/AudioPreview";
+import { readAloudController } from "../speech/readAloud";
+import { readAloudHighlightRoot } from "../speech/readAloudHighlight";
it("keeps compact audio playback loaded across signed URL renewals", async () => {
const original =
@@ -162,6 +191,33 @@ it("keeps compact audio playback loaded across signed URL renewals", async () =>
expect(screen.container.querySelector("audio")?.getAttribute("src")).toBe(renewed);
});
+it("paints the block and the repeated word being read aloud, and clears them on stop", async () => {
+ const markdown = "Intro.\n\n- The cat saw the **cat** nap.\n - nested cat";
+ await using _screen = await render(
+
+
+
,
+ );
+ const reading = readAloudController.start("reply", markdown, {
+ ...DEFAULT_READ_ALOUD_SETTINGS,
+ provider: "system",
+ });
+ await vi.waitFor(() => expect(readAloudController.getSnapshot().status).toBe("playing"));
+ const spoken = readAloudText(markdown, true);
+ const second = spoken.indexOf("cat nap");
+ await act(() => readAloudWords.emit({ start: second, end: second + 3 }));
+ const painted = (name: string) => [...(CSS.highlights.get(name) ?? [])].map(String);
+ expect(painted("t3-read-aloud-word")).toEqual(["cat"]);
+ expect(
+ [...(CSS.highlights.get("t3-read-aloud-word") ?? [])][0]?.startContainer.parentElement?.tagName,
+ ).toBe("STRONG");
+ expect(painted("t3-read-aloud-block")).toEqual(["The cat saw the cat nap."]);
+ readAloudController.stop();
+ await reading;
+ expect(painted("t3-read-aloud-word")).toEqual([]);
+ expect(painted("t3-read-aloud-block")).toEqual([]);
+});
+
function setup() {
appearance.value = "light";
parsedSources.length = 0;
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index e92ea73ec4f97..ddd0daab20c76 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -223,6 +223,7 @@ import { MarkdownFileLink } from "./chat/MarkdownFileLink";
import { canUseMarkdownFileShellActions } from "./chat/MarkdownFileLink.logic";
import { rehypeChipPunctuation } from "./chat/markdownChipPunctuation";
import { handleMarkdownFragmentClick, rehypeHeadingIds } from "./chat/markdownFragments";
+import { rehypeSpeechOffsets } from "../speech/rehypeSpeechOffsets";
import { rehypeTextDirection } from "./chat/markdownTextDirection";
import { hastHasText, hastPlainTextDeep, plainHastText } from "./chat/markdownHast.logic";
import {
@@ -420,12 +421,14 @@ const CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS = [
rehypeHeadingIds,
rehypeTextDirection,
rehypeChipPunctuation,
+ rehypeSpeechOffsets,
] satisfies NonNullable;
const CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS = [
rehypeHeadingIds,
rehypeTextDirection,
rehypeChipPunctuation,
+ rehypeSpeechOffsets,
] satisfies NonNullable;
function markdownUrlTransform(href: string) {
diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx
index d4787d28885f2..624e977c968c5 100644
--- a/apps/web/src/components/chat/TimelineAssistantRows.tsx
+++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx
@@ -1,4 +1,5 @@
import { ReadAloudButton } from "./ReadAloudButton";
+import { readAloudHighlightRoot } from "../../speech/readAloudHighlight";
import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
import { MessageId, type RunId, type TurnItemId } from "@t3tools/contracts";
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
@@ -56,7 +57,10 @@ export function AssistantTimelineRow({ row }: { row: Extract
T3 Code
-
+
}
/>
+
change({ highlightWords })}
+ />
+ }
+ />
reject(new Error("The system voice could not read this response."));
+ const listeners = new Set<(word: SpokenWord | null) => void>();
+ // Some voices, such as Chrome's network voices, send no boundaries; those read unhighlighted.
+ utterance.onboundary = (event) => {
+ if (event.name !== "word") return;
+ const word = spokenWordAt(text, event.charIndex);
+ for (const listener of listeners) listener(word);
+ };
let started = false;
return {
play: async () => {
@@ -50,9 +61,18 @@ function systemPlayback(
done();
},
finished,
+ words: (listener) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
};
}
+// Each one moves the media clock or starts or stops it.
+const CLOCK_EVENTS = ["play", "playing", "pause", "seeked", "ratechange", "waiting"] as const;
+
const catalogs = new WeakMap>();
export const warmReadAloud = createReadAloudWarmup(async (environmentId, model) => {
@@ -79,7 +99,7 @@ export const readAloudController = createReadAloudController(async (text, settin
signal.throwIfAborted();
if (catalog.error) throw new Error(catalog.error);
const model = settings.model || catalog.defaultModel;
- const url = await runEnvironmentSpeech(
+ const { url, token } = await runEnvironmentSpeech(
startSpeechSynthesis(prepared, settings.provider, {
text,
model,
@@ -98,15 +118,35 @@ export const readAloudController = createReadAloudController(async (text, settin
audio.onended = () => resolve();
audio.onerror = () => reject(new Error("Could not play the generated speech."));
});
+ let timed: ReturnType | null = null;
return {
play: () => audio.play(),
pause: () => audio.pause(),
stop: () => {
+ if (timed) for (const type of CLOCK_EVENTS) audio.removeEventListener(type, timed.refresh);
+ timed?.stop();
audio.pause();
audio.removeAttribute("src");
audio.load();
done();
},
finished,
+ words: (listener) => {
+ if (!timed) {
+ timed = createTimedWords({
+ text,
+ wordTimings: catalog.wordTimings ?? "estimated",
+ load: (after, signal) =>
+ runEnvironmentSpeech(getSpeechSynthesisTimings(prepared, token, after), { signal }),
+ clock: () => ({
+ seconds: audio.currentTime,
+ rate: audio.playbackRate,
+ playing: !audio.paused,
+ }),
+ });
+ for (const type of CLOCK_EVENTS) audio.addEventListener(type, timed.refresh);
+ }
+ return timed.subscribe(listener);
+ },
};
}, m);
diff --git a/apps/web/src/speech/readAloudHighlight.ts b/apps/web/src/speech/readAloudHighlight.ts
new file mode 100644
index 0000000000000..7f32b6eaf3e77
--- /dev/null
+++ b/apps/web/src/speech/readAloudHighlight.ts
@@ -0,0 +1,187 @@
+import type { ReadAloudHighlight } from "@t3tools/client-runtime/read-aloud";
+import type { ReadAloudCue } from "@t3tools/shared/read-aloud";
+import { readAloudController } from "./readAloud";
+
+const BLOCK_HIGHLIGHT = "t3-read-aloud-block";
+const WORD_HIGHLIGHT = "t3-read-aloud-word";
+/** Text a listener never hears: controls, icons, labels the UI adds, and math markup. */
+const UNSPOKEN_SELECTOR =
+ "svg, button, [role=button], [data-thread-find-ignore], [aria-hidden=true], .katex";
+/** After the user scrolls, following waits this long and for the word to be back in view. */
+const FOLLOW_PAUSE_MS = 3_000;
+/** The word stays in the middle of the timeline; leaving that band scrolls it to 40%. */
+const FOLLOW_BAND = { top: 0.2, bottom: 0.8, target: 0.4 };
+const SCROLL_KEYS = new Set(["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "]);
+
+const roots = new Map();
+let highlights: { readonly block: Highlight; readonly word: Highlight } | null = null;
+let scroller: HTMLElement | null = null;
+let userScrolledAt: number | null = null;
+let readingId: string | null = null;
+
+const supported = () =>
+ typeof CSS !== "undefined" && "highlights" in CSS && typeof Highlight !== "undefined";
+
+/**
+ * A ref for the element that renders message `id`'s markdown. Rows mount and unmount as the
+ * timeline virtualizes, so the highlight is painted again whenever the row returns.
+ */
+export function readAloudHighlightRoot(id: string) {
+ return (element: HTMLElement | null) => {
+ if (!element || !supported()) return;
+ if (!highlights) {
+ highlights = { block: new Highlight(), word: new Highlight() };
+ // Thread find paints over read aloud where they overlap.
+ highlights.block.priority = -2;
+ highlights.word.priority = -1;
+ CSS.highlights.set(BLOCK_HIGHLIGHT, highlights.block);
+ CSS.highlights.set(WORD_HIGHLIGHT, highlights.word);
+ readAloudController.subscribeHighlight(paint);
+ }
+ roots.set(id, element);
+ paint();
+ return () => {
+ if (roots.get(id) === element) roots.delete(id);
+ };
+ };
+}
+
+function paint() {
+ if (!highlights) return;
+ const highlight = readAloudController.getHighlight();
+ highlights.block.clear();
+ highlights.word.clear();
+ if (!highlight) {
+ readingId = null;
+ watchScroller(null);
+ return;
+ }
+ if (highlight.id !== readingId) {
+ readingId = highlight.id;
+ userScrolledAt = null;
+ }
+ const root = roots.get(highlight.id);
+ const block = root?.isConnected ? blockElement(root, highlight.block) : null;
+ if (!block) return;
+ const text = spokenText(block);
+ const first = locate(text, highlight.block.first);
+ const last = locate(text, highlight.block.last);
+ const word = locate(text, highlight.word.cue);
+ const blockRange =
+ first && last && first.start < last.end ? range(text, first.start, last.end) : null;
+ if (blockRange) highlights.block.add(blockRange);
+ else {
+ const whole = document.createRange();
+ whole.selectNodeContents(block);
+ highlights.block.add(whole);
+ }
+ const wordRange = word ? range(text, word.start, word.end) : null;
+ if (wordRange) highlights.word.add(wordRange);
+ watchScroller(block.closest(".messages-timeline-scroll"));
+ follow(wordRange ?? blockRange);
+}
+
+/** The innermost tagged element that holds the whole block. */
+function blockElement(root: HTMLElement, block: ReadAloudHighlight["block"]) {
+ let best: { element: HTMLElement; start: number } | null = null;
+ for (const element of root.querySelectorAll("[data-speech-start]")) {
+ const start = Number(element.dataset.speechStart);
+ const end = Number(element.dataset.speechEnd);
+ // Document order puts descendants after ancestors, so a tie goes to the inner one.
+ if (start <= block.start && end >= block.end && (!best || start >= best.start))
+ best = { element, start };
+ }
+ return best ? best.element : null;
+}
+
+type SpokenText = {
+ readonly value: string;
+ readonly nodes: ReadonlyArray<{ readonly node: Text; readonly at: number }>;
+};
+
+function spokenText(block: HTMLElement): SpokenText {
+ const nodes: Array<{ node: Text; at: number }> = [];
+ let value = "";
+ const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT);
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ if (!(node instanceof Text)) continue;
+ const unspoken = node.parentElement?.closest(UNSPOKEN_SELECTOR);
+ if (unspoken && block.contains(unspoken)) continue;
+ nodes.push({ node, at: value.length });
+ value += node.data;
+ }
+ return { value, nodes };
+}
+
+/** The cue's place in the rendered text: its `occurrence`-th appearance, counted as the cue was. */
+function locate(text: SpokenText, cue: ReadAloudCue) {
+ let at = text.value.indexOf(cue.text);
+ for (let seen = 0; at !== -1 && seen < cue.occurrence; seen++)
+ at = text.value.indexOf(cue.text, at + cue.text.length);
+ return at === -1 ? null : { start: at, end: at + cue.text.length };
+}
+
+function point(text: SpokenText, offset: number, end: boolean) {
+ for (let index = text.nodes.length - 1; index >= 0; index--) {
+ const entry = text.nodes[index];
+ if (entry && (entry.at < offset || (!end && entry.at === offset)))
+ return { node: entry.node, offset: offset - entry.at };
+ }
+ return null;
+}
+
+function range(text: SpokenText, start: number, end: number) {
+ const from = point(text, start, false);
+ const to = point(text, end, true);
+ if (!from || !to) return null;
+ const result = document.createRange();
+ result.setStart(from.node, from.offset);
+ result.setEnd(to.node, to.offset);
+ return result;
+}
+
+function follow(target: Range | null) {
+ if (!target || !scroller) return;
+ const rect = target.getClientRects()[0] ?? target.getBoundingClientRect();
+ if (rect.width === 0 && rect.height === 0) return;
+ const view = scroller.getBoundingClientRect();
+ if (userScrolledAt !== null) {
+ if (performance.now() - userScrolledAt < FOLLOW_PAUSE_MS) return;
+ // Never pull the user back; follow again once they bring the word into view themselves.
+ if (rect.bottom < view.top || rect.top > view.bottom) return;
+ userScrolledAt = null;
+ }
+ if (
+ rect.top >= view.top + view.height * FOLLOW_BAND.top &&
+ rect.bottom <= view.top + view.height * FOLLOW_BAND.bottom
+ )
+ return;
+ scroller.scrollBy({
+ top: rect.top - (view.top + view.height * FOLLOW_BAND.target),
+ behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth",
+ });
+}
+
+const markUserScroll = () => {
+ userScrolledAt = performance.now();
+};
+const markScrollKey = (event: KeyboardEvent) => {
+ if (SCROLL_KEYS.has(event.key)) markUserScroll();
+};
+// Dragging the scrollbar targets the scroll element itself.
+const markScrollbarDrag = (event: PointerEvent) => {
+ if (event.target === scroller) markUserScroll();
+};
+
+function watchScroller(next: HTMLElement | null) {
+ if (next === scroller) return;
+ scroller?.removeEventListener("wheel", markUserScroll);
+ scroller?.removeEventListener("touchmove", markUserScroll);
+ scroller?.removeEventListener("keydown", markScrollKey);
+ scroller?.removeEventListener("pointerdown", markScrollbarDrag);
+ scroller = next;
+ next?.addEventListener("wheel", markUserScroll, { passive: true });
+ next?.addEventListener("touchmove", markUserScroll, { passive: true });
+ next?.addEventListener("keydown", markScrollKey);
+ next?.addEventListener("pointerdown", markScrollbarDrag);
+}
diff --git a/apps/web/src/speech/rehypeSpeechOffsets.ts b/apps/web/src/speech/rehypeSpeechOffsets.ts
new file mode 100644
index 0000000000000..c3c79b32be460
--- /dev/null
+++ b/apps/web/src/speech/rehypeSpeechOffsets.ts
@@ -0,0 +1,20 @@
+import type { Element, Root, RootContent } from "hast";
+
+// Not `table`: each row is read as its own block.
+const SPEECH_BLOCK_TAGS = new Set(["p", "li", "h1", "h2", "h3", "h4", "h5", "h6", "tr"]);
+
+/** Tags block elements with their markdown range so read aloud can find the block it reads. */
+export function rehypeSpeechOffsets() {
+ const visit = (node: Root | RootContent) => {
+ if (node.type === "element" && SPEECH_BLOCK_TAGS.has(node.tagName)) tag(node);
+ if ("children" in node) node.children.forEach(visit);
+ };
+ return visit;
+}
+
+function tag(node: Element) {
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ if (start !== undefined && end !== undefined)
+ node.properties = { ...node.properties, dataSpeechStart: start, dataSpeechEnd: end };
+}
diff --git a/docs/user/composer.md b/docs/user/composer.md
index 0116e1c02de88..4812d01ff398b 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -202,6 +202,10 @@ Choose a speech provider in **Settings → Voice → Read aloud**, then use **Re
beside a completed assistant reply. Select it again to stop playback. Leaving the
thread stops it. Code blocks are skipped by default.
+On web and desktop, the paragraph and the word being read are highlighted, and the thread
+scrolls along until you scroll away. ElevenLabs reports exact word timings. With other
+providers the word position is an estimate. Turn this off with **Highlight words**.
+
System voices run on your device. OpenAI, Grok TTS, OpenRouter, and ElevenLabs send the reply text
through your selected environment and use API billing. They share the API keys saved for dictation. Choose a model and
voice, then use the preview to try it.
diff --git a/packages/client-runtime/src/readAloud.test.ts b/packages/client-runtime/src/readAloud.test.ts
index a4d7808a2ea32..0f9c99c1251e0 100644
--- a/packages/client-runtime/src/readAloud.test.ts
+++ b/packages/client-runtime/src/readAloud.test.ts
@@ -3,7 +3,9 @@ import { DEFAULT_READ_ALOUD_SETTINGS, EnvironmentId } from "@t3tools/contracts";
import {
createReadAloudController,
createReadAloudWarmup,
+ createTimedWords,
type SpeechPlayback,
+ type SpokenWord,
} from "./readAloud.ts";
function deferred() {
@@ -235,3 +237,105 @@ it("warms each local model once per interval, and again after a failed request",
"broken",
]);
});
+
+it("highlights the spoken word by its markdown range, across chunks, while highlighting is on", async () => {
+ const markdown = `Intro **bold** words.\n\n${"filler ".repeat(520)}\n\nLast \`code\` part.`;
+ const emit: Array<(word: SpokenWord | null) => void> = [];
+ // The intro, the filler up to the limit, and the rest.
+ const finished = [deferred(), deferred(), deferred()];
+ const playing = [deferred(), deferred(), deferred()];
+ const texts: string[] = [];
+ const controller = createReadAloudController(async (text) => {
+ const index = texts.push(text) - 1;
+ return {
+ play: async () => playing[index]?.resolve(),
+ pause: () => {},
+ stop: () => {},
+ finished: finished[index]?.promise ?? Promise.resolve(),
+ words: (listener) => {
+ emit[index] = listener;
+ return () => {
+ delete emit[index];
+ };
+ },
+ };
+ });
+ const settings = { ...DEFAULT_READ_ALOUD_SETTINGS, provider: "system" as const };
+ const run = controller.start("1", markdown, settings);
+ await playing[0]?.promise;
+ const bold = texts[0]!.indexOf("bold");
+ emit[0]?.({ start: bold, end: bold + 4 });
+ expect(controller.getHighlight()).toMatchObject({
+ id: "1",
+ word: { start: markdown.indexOf("bold"), end: markdown.indexOf("bold") + 4 },
+ block: { start: 0, first: { text: "Intro" }, last: { text: "words." } },
+ });
+ finished[0]?.resolve();
+ await playing[1]?.promise;
+ expect(controller.getHighlight()).toBeNull();
+ finished[1]?.resolve();
+ await playing[2]?.promise;
+ const code = texts[2]!.indexOf("code");
+ emit[2]?.({ start: code, end: code + 4 });
+ expect(controller.getHighlight()?.word).toMatchObject({
+ start: markdown.indexOf("code"),
+ cue: { text: "code", occurrence: 0 },
+ });
+ controller.stop();
+ expect(controller.getHighlight()).toBeNull();
+ expect(emit.filter(Boolean)).toHaveLength(0);
+ await run;
+
+ const off = controller.start("2", "Short reply.", { ...settings, highlightWords: false });
+ await Promise.resolve();
+ controller.stop();
+ await off;
+ expect(emit.filter(Boolean)).toHaveLength(0);
+});
+
+it("follows provider word timings on the audio clock and estimates them when there are none", async () => {
+ vi.useFakeTimers();
+ try {
+ let seconds = 0;
+ const clock = () => ({ seconds, rate: 2, playing: true });
+ const words = [
+ { start: 0, end: 3, startSeconds: 0, endSeconds: 1 },
+ { start: 4, end: 7, startSeconds: 1, endSeconds: 2 },
+ ];
+ const provider = createTimedWords({
+ text: "one two",
+ wordTimings: "provider",
+ load: async () => ({ words, done: true }),
+ clock,
+ });
+ const heard: Array = [];
+ provider.subscribe((word) => heard.push(word));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(heard).toEqual([{ start: 0, end: 3 }]);
+ seconds = 1;
+ // At 2× the next word starts after half a second of wall time.
+ await vi.advanceTimersByTimeAsync(499);
+ expect(heard).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(heard).toEqual([
+ { start: 0, end: 3 },
+ { start: 4, end: 7 },
+ ]);
+ provider.stop();
+
+ seconds = 2.5;
+ const estimated = createTimedWords({
+ text: "one two three.",
+ wordTimings: "estimated",
+ load: async () => ({ words: [], done: true, durationSeconds: 3 }),
+ clock,
+ });
+ const guessed: Array = [];
+ estimated.subscribe((word) => guessed.push(word));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(guessed).toEqual([{ start: 8, end: 14 }]);
+ estimated.stop();
+ } finally {
+ vi.useRealTimers();
+ }
+});
diff --git a/packages/client-runtime/src/readAloud.ts b/packages/client-runtime/src/readAloud.ts
index 2289c98038601..b5311c9a1a50c 100644
--- a/packages/client-runtime/src/readAloud.ts
+++ b/packages/client-runtime/src/readAloud.ts
@@ -2,8 +2,16 @@ import {
SPEECH_SYNTHESIS_MAX_TEXT,
type EnvironmentId,
type ReadAloudSettings,
+ type ReadAloudWordTimings,
+ type SpeechSynthesisTimings,
+ type SpeechSynthesisWord,
} from "@t3tools/contracts";
-import { readAloudText, splitReadAloudText } from "@t3tools/shared/read-aloud";
+import {
+ readAloudPosition,
+ readAloudSpeech,
+ splitReadAloudSpans,
+ type ReadAloudPosition,
+} from "@t3tools/shared/read-aloud";
import { mFallback, msg } from "gt-i18n";
import type { MFunctionType } from "gt-i18n/types";
@@ -28,13 +36,129 @@ export function createReadAloudWarmup(
};
}
+/** A word as UTF-16 offsets in the text a playback speaks. */
+export type SpokenWord = { readonly start: number; readonly end: number };
+
export type SpeechPlayback = {
play: () => Promise;
pause: () => void;
stop: () => void;
finished: Promise;
+ /** Reports each word as it is spoken, and null when none is; returns the unsubscribe. */
+ words?: (listener: (word: SpokenWord | null) => void) => () => void;
+};
+
+/** What a read-aloud message is reading now, for clients to highlight. */
+export type ReadAloudHighlight = ReadAloudPosition & { readonly id: string };
+
+/** Index of the word being spoken at `seconds`: the last one started, or -1 before the first. */
+function wordIndexAt(words: ReadonlyArray, seconds: number) {
+ let low = 0;
+ let high = words.length - 1;
+ let found = -1;
+ while (low <= high) {
+ const middle = (low + high) >> 1;
+ if ((words[middle]?.startSeconds ?? Infinity) <= seconds) {
+ found = middle;
+ low = middle + 1;
+ } else high = middle - 1;
+ }
+ return found;
+}
+
+/** Spreads the words of `text` over its audio by length, with longer pauses after punctuation. */
+function estimateWordTimings(text: string, durationSeconds: number): SpeechSynthesisWord[] {
+ const matches = [...text.matchAll(/\S+/g)];
+ const weights = matches.map(
+ ([word]) =>
+ word.length + 1 + (/[.!?。!?]$/u.test(word) ? 4 : /[,;:,、;:]$/u.test(word) ? 2 : 0),
+ );
+ const total = weights.reduce((sum, weight) => sum + weight, 0);
+ let elapsed = 0;
+ return matches.map((match, index) => {
+ const startSeconds = (elapsed / total) * durationSeconds;
+ elapsed += weights[index] ?? 0;
+ return {
+ start: match.index,
+ end: match.index + match[0].length,
+ startSeconds,
+ endSeconds: (elapsed / total) * durationSeconds,
+ };
+ });
+}
+
+export type PlaybackClock = {
+ readonly seconds: number;
+ readonly rate: number;
+ readonly playing: boolean;
};
+/**
+ * Follows a synthesis' word timings on its audio clock. Players call `refresh` on each media event
+ * that moves the clock; between events one timer waits for the next word, not a frame loop.
+ * Without provider timings, words are estimated once the environment reports the audio length.
+ */
+export function createTimedWords(input: {
+ readonly text: string;
+ readonly wordTimings: ReadAloudWordTimings;
+ readonly load: (after: number, signal: AbortSignal) => Promise;
+ readonly clock: () => PlaybackClock;
+}) {
+ const loading = new AbortController();
+ const listeners = new Set<(word: SpokenWord | null) => void>();
+ let words: ReadonlyArray = [];
+ let current = -1;
+ let timer: ReturnType | undefined;
+ const refresh = () => {
+ clearTimeout(timer);
+ timer = undefined;
+ if (loading.signal.aborted) return;
+ const clock = input.clock();
+ const index = wordIndexAt(words, clock.seconds);
+ if (index !== current) {
+ current = index;
+ const word = words[index];
+ for (const listener of listeners)
+ listener(word ? { start: word.start, end: word.end } : null);
+ }
+ const next = words[index + 1];
+ if (clock.playing && next)
+ // @effect-diagnostics-next-line globalTimers:off - Players call this outside an Effect runtime.
+ timer = setTimeout(
+ refresh,
+ Math.max(0, ((next.startSeconds - clock.seconds) / Math.max(clock.rate, 0.1)) * 1000),
+ );
+ };
+ const load = async () => {
+ const received: SpeechSynthesisWord[] = [];
+ for (;;) {
+ const timings = await input.load(received.length, loading.signal);
+ received.push(...timings.words);
+ if (input.wordTimings !== "estimated") words = received;
+ if (timings.done && words.length === 0 && timings.durationSeconds)
+ words = estimateWordTimings(input.text, timings.durationSeconds);
+ refresh();
+ if (timings.done) return;
+ }
+ };
+ // Highlighting is best effort; the audio plays on without it.
+ void load().catch(() => {});
+ return {
+ subscribe: (listener: (word: SpokenWord | null) => void) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ refresh,
+ stop: () => {
+ loading.abort();
+ clearTimeout(timer);
+ listeners.clear();
+ },
+ };
+}
+
export function createReadAloudController(
prepare: (
text: string,
@@ -74,7 +198,22 @@ export function createReadAloudController(
state = next;
for (const listener of listeners) listener();
};
+ // Separate from `state` so a new word re-renders only the message being read.
+ let highlight: ReadAloudHighlight | null = null;
+ let unfollow: (() => void) | null = null;
+ const highlightListeners = new Set<() => void>();
+ const publishHighlight = (next: ReadAloudHighlight | null) => {
+ if (next === highlight) return;
+ highlight = next;
+ for (const listener of highlightListeners) listener();
+ };
+ const stopFollowing = () => {
+ unfollow?.();
+ unfollow = null;
+ publishHighlight(null);
+ };
const stop = () => {
+ stopFollowing();
active?.abort();
active = null;
paused = false;
@@ -93,6 +232,13 @@ export function createReadAloudController(
listeners.delete(listener);
};
},
+ getHighlight: () => highlight,
+ subscribeHighlight: (listener: () => void) => {
+ highlightListeners.add(listener);
+ return () => {
+ highlightListeners.delete(listener);
+ };
+ },
stop,
pause() {
if (disposing || !active || (state.status !== "playing" && state.status !== "loading"))
@@ -136,9 +282,10 @@ export function createReadAloudController(
async start(id: string, markdown: string, settings: ReadAloudSettings) {
stop();
if (settings.provider === "off") return;
+ const speech = readAloudSpeech(markdown, settings.skipCodeBlocks);
// Platform speech engines cap utterance length; environments stream a whole reply.
- const chunks = splitReadAloudText(
- readAloudText(markdown, settings.skipCodeBlocks),
+ const chunks = splitReadAloudSpans(
+ speech.text,
settings.provider === "system" ? undefined : SPEECH_SYNTHESIS_MAX_TEXT,
);
if (!chunks.length) return;
@@ -147,12 +294,18 @@ export function createReadAloudController(
try {
for (const chunk of chunks) {
publish({ id, status: paused ? "paused" : "loading" });
- const next = await prepare(chunk, settings, owner.signal);
+ const next = await prepare(chunk.text, settings, owner.signal);
if (active !== owner) {
dispose(next);
return;
}
playback = next;
+ if (settings.highlightWords && next.words)
+ unfollow = next.words((word) => {
+ const position =
+ word && readAloudPosition(speech, chunk.start + word.start, chunk.start + word.end);
+ publishHighlight(position ? { id, ...position } : null);
+ });
// Playback can fail while the platform is still activating its audio session.
void next.finished.catch(() => {});
await waitForResume();
@@ -171,6 +324,7 @@ export function createReadAloudController(
publish({ id, status: "playing" });
await next.finished;
if (active !== owner) return;
+ stopFollowing();
dispose(next);
playback = null;
}
diff --git a/packages/client-runtime/src/voice-input/environment.test.ts b/packages/client-runtime/src/voice-input/environment.test.ts
index 1e0bdcae480c5..b1b64a236a2aa 100644
--- a/packages/client-runtime/src/voice-input/environment.test.ts
+++ b/packages/client-runtime/src/voice-input/environment.test.ts
@@ -31,11 +31,12 @@ const start = (response: Response) =>
}).pipe(Effect.provide(RpcHttp.layerRemoteHttpClient(() => Promise.resolve(response))));
describe("startSpeechSynthesis", () => {
- it.effect("returns the environment's stream URL for the started synthesis", () =>
+ it.effect("returns the environment's stream URL and token for the started synthesis", () =>
Effect.gen(function* () {
- expect(yield* start(Response.json({ token: "stream-token" }))).toBe(
- "https://environment.example.test/api/voice/synthesis/audio?token=stream-token",
- );
+ expect(yield* start(Response.json({ token: "stream-token" }))).toEqual({
+ url: "https://environment.example.test/api/voice/synthesis/audio?token=stream-token",
+ token: "stream-token",
+ });
}),
);
diff --git a/packages/client-runtime/src/voice-input/environment.ts b/packages/client-runtime/src/voice-input/environment.ts
index 457e106fab2af..95b5bd2011d09 100644
--- a/packages/client-runtime/src/voice-input/environment.ts
+++ b/packages/client-runtime/src/voice-input/environment.ts
@@ -331,7 +331,7 @@ export const getSpeechSynthesisModels = (
run: ({ client, headers }) => client.synthesisModels({ headers, params: { provider } }),
});
-/** Starts synthesis and resolves, once audio exists, with the URL of its live MP3 stream. */
+/** Starts synthesis and resolves, once audio exists, with the URL of its live MP3 stream and its token. */
export const startSpeechSynthesis = (
prepared: PreparedConnection,
provider: SpeechSynthesisProvider,
@@ -357,11 +357,25 @@ export const startSpeechSynthesis = (
Effect.map(({ token }) => {
const url = new URL(SPEECH_SYNTHESIS_AUDIO_PATH, endpoint);
url.searchParams.set("token", token);
- return url.toString();
+ return { url: url.toString(), token };
}),
);
};
+/** Word timings of a started synthesis after the first `after`; the environment holds the request until there are some. */
+export const getSpeechSynthesisTimings = (
+ prepared: PreparedConnection,
+ token: string,
+ after: number,
+) =>
+ request({
+ group: "voice",
+ prepared,
+ method: "POST",
+ path: (urls) => urls.synthesisTimings(),
+ run: ({ client, headers }) => client.synthesisTimings({ headers, payload: { token, after } }),
+ });
+
/** Loads the environment's local model ahead of playback; an empty model is its default. */
export const prepareSpeechSynthesis = (prepared: PreparedConnection, model: string) =>
request({
diff --git a/packages/client-runtime/src/voice-input/index.ts b/packages/client-runtime/src/voice-input/index.ts
index 709904e4b8275..1564b58057710 100644
--- a/packages/client-runtime/src/voice-input/index.ts
+++ b/packages/client-runtime/src/voice-input/index.ts
@@ -45,6 +45,7 @@ export {
cancelSpeechSynthesisModelDownload,
downloadSpeechSynthesisModel,
getSpeechSynthesisModels,
+ getSpeechSynthesisTimings,
linkSpeechSynthesisModels,
prepareSpeechSynthesis,
removeSpeechSynthesisModel,
diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts
index ecd3353d92f01..f2bffabaf8714 100644
--- a/packages/contracts/src/environmentHttp.ts
+++ b/packages/contracts/src/environmentHttp.ts
@@ -6,6 +6,8 @@ import {
SpeechSynthesisModelRequest,
SpeechSynthesisPrepareRequest,
SpeechSynthesisStream,
+ SpeechSynthesisTimings,
+ SpeechSynthesisTimingsRequest,
} from "./readAloud.ts";
import * as Context from "effect/Context";
import type * as DateTime from "effect/DateTime";
@@ -871,6 +873,15 @@ export class EnvironmentVoiceHttpApi extends HttpApiGroup.make("voice")
],
}).middleware(EnvironmentAuthenticatedAuth),
)
+ .add(
+ // A token that expired or never existed reads as finished with no words.
+ HttpApiEndpoint.post("synthesisTimings", "/api/voice/synthesis/timings", {
+ headers: OptionalBearerHeaders,
+ payload: SpeechSynthesisTimingsRequest,
+ success: SpeechSynthesisTimings,
+ error: EnvironmentScopedOperationErrors,
+ }).middleware(EnvironmentAuthenticatedAuth),
+ )
.add(
HttpApiEndpoint.post("prepareSynthesisModel", "/api/voice/synthesis/local/prepare", {
headers: OptionalBearerHeaders,
diff --git a/packages/contracts/src/readAloud.ts b/packages/contracts/src/readAloud.ts
index f9a0b32526ae8..c5a32e4ebc9d1 100644
--- a/packages/contracts/src/readAloud.ts
+++ b/packages/contracts/src/readAloud.ts
@@ -1,7 +1,7 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SchemaTransformation from "effect/SchemaTransformation";
-import { EnvironmentId } from "./baseSchemas.ts";
+import { EnvironmentId, NonNegativeInt } from "./baseSchemas.ts";
import { CloudSpeechProvider } from "./speech.ts";
/** `local` runs a downloaded model on the selected environment; the rest are hosted APIs. */
@@ -43,6 +43,7 @@ export const ReadAloudSettings = Schema.Struct({
language: Schema.String.check(Schema.isMinLength(2), Schema.isMaxLength(16)),
skipCodeBlocks: Schema.Boolean,
backgroundPlayback: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
+ highlightWords: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
});
export type ReadAloudSettings = typeof ReadAloudSettings.Type;
export const DEFAULT_READ_ALOUD_SETTINGS: ReadAloudSettings = {
@@ -54,6 +55,7 @@ export const DEFAULT_READ_ALOUD_SETTINGS: ReadAloudSettings = {
language: "auto",
skipCodeBlocks: true,
backgroundPlayback: true,
+ highlightWords: true,
};
export const ReadAloudPreference = ReadAloudSettings.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_READ_ALOUD_SETTINGS)),
@@ -72,6 +74,32 @@ export const SpeechSynthesisRequest = Schema.Struct({
export type SpeechSynthesisRequest = typeof SpeechSynthesisRequest.Type;
/** Single-purpose credential for `SPEECH_SYNTHESIS_AUDIO_PATH`, so media elements need no headers. */
export const SpeechSynthesisStream = Schema.Struct({ token: Schema.String });
+/**
+ * Where a provider's word timings come from: `provider` timestamps from its API, `boundary`
+ * events from a platform voice, or an `estimated` spread of the text over the audio.
+ */
+export const ReadAloudWordTimings = Schema.Literals(["provider", "boundary", "estimated"]);
+export type ReadAloudWordTimings = typeof ReadAloudWordTimings.Type;
+/** A spoken word: UTF-16 offsets in the request text and seconds into its audio. */
+export const SpeechSynthesisWord = Schema.Struct({
+ start: Schema.Int,
+ end: Schema.Int,
+ startSeconds: Schema.Finite,
+ endSeconds: Schema.Finite,
+});
+export type SpeechSynthesisWord = typeof SpeechSynthesisWord.Type;
+/** Reads the word timings of a started synthesis after the first `after` words. */
+export const SpeechSynthesisTimingsRequest = Schema.Struct({
+ token: Schema.String,
+ after: NonNegativeInt,
+});
+/** Answers once new words exist or synthesis ends; `durationSeconds` comes with the end. */
+export const SpeechSynthesisTimings = Schema.Struct({
+ words: Schema.Array(SpeechSynthesisWord),
+ done: Schema.Boolean,
+ durationSeconds: Schema.optionalKey(Schema.Finite),
+});
+export type SpeechSynthesisTimings = typeof SpeechSynthesisTimings.Type;
export const SpeechSynthesisModelInstall = Schema.Struct({
state: Schema.Literals(["downloadable", "downloading", "verifying", "installed"]),
/** Bytes to download, including the speech runtime when this environment lacks it. */
@@ -94,6 +122,8 @@ export const SpeechSynthesisCatalog = Schema.Struct({
supportsModelSelection: Schema.Boolean,
supportsVoiceSelection: Schema.Boolean,
speedAppliedByProvider: Schema.Boolean,
+ /** Absent when the timings are `estimated`. */
+ wordTimings: Schema.optionalKey(ReadAloudWordTimings),
error: Schema.optionalKey(Schema.String),
models: Schema.Array(
Schema.Struct({
diff --git a/packages/shared/src/readAloud.test.ts b/packages/shared/src/readAloud.test.ts
index e05e00774bfba..51a47dad6f228 100644
--- a/packages/shared/src/readAloud.test.ts
+++ b/packages/shared/src/readAloud.test.ts
@@ -1,5 +1,13 @@
import { expect, it } from "vite-plus/test";
-import { readAloudText, splitReadAloudText } from "./readAloud.ts";
+import {
+ readAloudPosition,
+ readAloudShownText,
+ readAloudSpeech,
+ readAloudText,
+ splitReadAloudSpans,
+ splitReadAloudText,
+ spokenWordAt,
+} from "./readAloud.ts";
it("reads visible prose and identifiers without link targets or fenced code", () => {
const text =
@@ -26,6 +34,110 @@ it("ends every heading, list item, and table row as its own sentence", () => {
);
});
+it("maps each spoken word back to its markdown, leaving added punctuation unmapped", () => {
+ const markdown =
+ "# Findings\n\nUse **readAloud** and `message.id`.\nNext line\n\nTom & Jerry\n\n| a | b |\n| - | - |\n| c | d |\n\n```ts\ncode();\n```";
+ const speech = readAloudSpeech(markdown, false);
+ const source = (word: string) => {
+ const at = speech.text.indexOf(word);
+ const mapped = speech.sources.slice(at, at + word.length);
+ return markdown.slice(Math.min(...mapped), Math.max(...mapped) + 1);
+ };
+ expect(source("readAloud")).toBe("readAloud");
+ expect(source("message.id")).toBe("message.id");
+ expect(source("code();")).toBe("code();");
+ expect(source("Next line")).toBe("Next line");
+ expect(speech.sources[speech.text.indexOf("Findings.") + "Findings".length]).toBe(-1);
+ expect(speech.sources[speech.text.indexOf("c, d") + 1]).toBe(-1);
+ expect(
+ speech.blocks.map((block) => [
+ speech.text.slice(block.spokenStart, block.spokenEnd),
+ markdown.slice(block.sourceStart, block.sourceEnd),
+ ]),
+ ).toEqual([
+ ["Findings.", "# Findings"],
+ [
+ "Use readAloud and message.id.\nNext line.",
+ "Use **readAloud** and `message.id`.\nNext line",
+ ],
+ ["Tom & Jerry.", "Tom & Jerry"],
+ ["a, b.", "| a | b |"],
+ ["c, d.", "| c | d |"],
+ ["code();", "```ts\ncode();\n```"],
+ ]);
+});
+
+it("locates a spoken word by markdown range and by its repeats in the block", () => {
+ const markdown = "Intro.\n\nThe cat saw the **cat**.";
+ const speech = readAloudSpeech(markdown, true);
+ const second = speech.text.lastIndexOf("cat.");
+ const position = readAloudPosition(speech, second, second + "cat.".length);
+ expect(position).toEqual({
+ block: {
+ start: markdown.indexOf("The"),
+ end: markdown.length,
+ first: { text: "The", occurrence: 0 },
+ last: { text: "cat.", occurrence: 0 },
+ },
+ word: {
+ start: markdown.lastIndexOf("cat"),
+ end: markdown.length,
+ cue: { text: "cat.", occurrence: 0 },
+ },
+ });
+ const cat = speech.text.indexOf("cat");
+ expect(readAloudPosition(speech, second, second + 3)?.word.cue).toEqual({
+ text: "cat",
+ occurrence: 1,
+ });
+ expect(readAloudPosition(speech, cat, cat + 3)?.word.cue).toEqual({ text: "cat", occurrence: 0 });
+ expect(spokenWordAt(speech.text, speech.text.indexOf("saw") + 1)).toEqual({
+ start: speech.text.indexOf("saw"),
+ end: speech.text.indexOf("saw") + 3,
+ });
+});
+
+it("finds the block and word being read in text a renderer shows", () => {
+ const markdown = [
+ "# Plan",
+ "Use **readAloud** and see [the docs](https://example.com).",
+ "- First item\n- Second item",
+ "| File | Change |\n| --- | --- |\n| a.ts | Adds `x` |",
+ "```ts\ncode();\n```",
+ "The cat saw the **cat**.",
+ ].join("\n\n");
+ const shown =
+ "Plan\nUse readAloud and see the docs.\n• First item\n• Second item\nFile\tChange\na.ts\tAdds x\ncode();\nThe cat saw the cat.";
+ const speech = readAloudSpeech(markdown, true);
+ const locate = readAloudShownText(markdown, shown);
+ const at = (spoken: string, from = 0) => {
+ const start = speech.text.indexOf(spoken, from);
+ const position = readAloudPosition(speech, start, start + spoken.length);
+ if (!position) throw new Error(`no position for ${spoken}`);
+ const found = locate(position);
+ const slice = (range: { start: number; end: number } | null) =>
+ range && shown.slice(range.start, range.end);
+ return { block: slice(found.block), word: slice(found.word) };
+ };
+ expect(at("readAloud")).toEqual({ block: "Use readAloud and see the docs.", word: "readAloud" });
+ expect(at("docs.")).toEqual({ block: "Use readAloud and see the docs.", word: "docs." });
+ expect(at("Second")).toEqual({ block: "Second item", word: "Second" });
+ expect(at("Adds")).toEqual({ block: "a.ts\tAdds x", word: "Adds" });
+ expect(at("cat.")).toEqual({ block: "The cat saw the cat.", word: "cat." });
+
+ // A renderer that shows only part of the reply still finds the words it shows.
+ const tail = readAloudShownText(markdown, "The cat saw the cat.");
+ const cat = speech.text.lastIndexOf("cat");
+ const position = readAloudPosition(speech, cat, cat + 3);
+ expect(position && tail(position)).toEqual({
+ block: { start: 0, end: 20 },
+ word: { start: 16, end: 20 },
+ });
+ const first = speech.text.indexOf("First");
+ const elsewhere = readAloudPosition(speech, first, first + 5);
+ expect(elsewhere && tail(elsewhere)).toEqual({ block: null, word: null });
+});
+
it("splits long replies without losing content or cutting surrogate pairs", () => {
const text = "First sentence. " + "🙂".repeat(15) + " tail";
const chunks = splitReadAloudText(text, 20);
@@ -33,4 +145,7 @@ it("splits long replies without losing content or cutting surrogate pairs", () =
expect(chunks.every((chunk) => chunk.length <= 20)).toBe(true);
expect(chunks.join("").replaceAll(" ", "")).toBe(text.replaceAll(" ", ""));
expect(chunks.every((chunk) => !/[\uD800-\uDBFF]$/.test(chunk))).toBe(true);
+ const padded = ` ${text}\n`;
+ for (const span of splitReadAloudSpans(padded, 20))
+ expect(padded.slice(span.start, span.start + span.text.length)).toBe(span.text);
});
diff --git a/packages/shared/src/readAloud.ts b/packages/shared/src/readAloud.ts
index d54004d6abe57..21dc21beab0ee 100644
--- a/packages/shared/src/readAloud.ts
+++ b/packages/shared/src/readAloud.ts
@@ -1,4 +1,4 @@
-import type { RootContent, Root } from "mdast";
+import type { Node, RootContent, Root } from "mdast";
import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkGfm from "remark-gfm";
@@ -7,55 +7,331 @@ const parser = unified().use(remarkParse).use(remarkGfm);
// Already ends a sentence, allowing closing quotes or brackets after the punctuation.
const SENTENCE_END = /[.!?…:;。!?:;]["'”’)\]]*$/u;
+const SPACE = /\s/;
+
+/** Marks a spoken character that the markdown does not contain, such as an added full stop. */
+const ADDED = -1;
+
+/** A spoken block: its range in the spoken text and the markdown range it was read from. */
+export interface ReadAloudBlock {
+ readonly spokenStart: number;
+ readonly spokenEnd: number;
+ readonly sourceStart: number;
+ readonly sourceEnd: number;
+}
+
+export interface ReadAloudSpeech {
+ readonly text: string;
+ /** The markdown offset of each UTF-16 unit of `text`, or -1 for punctuation added for speech. */
+ readonly sources: ReadonlyArray;
+ readonly blocks: ReadonlyArray;
+}
+
+type Run = { text: string; sources: number[] };
+type Positioned = Pick;
+
+const added = (text: string): Run => ({ text, sources: Array.from(text, () => ADDED) });
+
+function concat(runs: ReadonlyArray): Run {
+ return {
+ text: runs.map((run) => run.text).join(""),
+ sources: runs.flatMap((run) => run.sources),
+ };
+}
+
+function trim(run: Run): Run {
+ let start = 0;
+ let end = run.text.length;
+ while (start < end && SPACE.test(run.text.charAt(start))) start++;
+ while (end > start && SPACE.test(run.text.charAt(end - 1))) end--;
+ return { text: run.text.slice(start, end), sources: run.sources.slice(start, end) };
+}
+
+/** A node's text with the markdown offset of each character. */
+function located(markdown: string, value: string, node: Positioned): Run {
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ if (start === undefined || end === undefined) return added(value);
+ const at = markdown.slice(start, end) === value ? start : markdown.indexOf(value, start);
+ if (at !== -1 && at + value.length <= end)
+ return { text: value, sources: Array.from({ length: value.length }, (_, index) => at + index) };
+ // Escapes and entities change the text, so its characters spread over the node's source.
+ const span = Math.max(end - start, 1);
+ return {
+ text: value,
+ sources: Array.from(
+ { length: value.length },
+ (_, index) => start + Math.floor((index * span) / value.length),
+ ),
+ };
+}
/**
- * Plain text with one sentence per line. Speech engines read newlines as spaces, so every
- * heading, paragraph, list item, and table row ends in punctuation to keep its pause.
+ * Plain text with one sentence per line, and where each spoken character came from in the
+ * markdown. Speech engines read newlines as spaces, so every heading, paragraph, list item, and
+ * table row ends in punctuation to keep its pause.
*/
-export function readAloudText(markdown: string, skipCodeBlocks: boolean) {
- const sentences: string[] = [];
- const speak = (text: string) => {
- for (const line of text.split("\n")) {
- const sentence = line.replace(/\s+/g, " ").trim();
- if (sentence) sentences.push(SENTENCE_END.test(sentence) ? sentence : `${sentence}.`);
+export function readAloudSpeech(markdown: string, skipCodeBlocks: boolean): ReadAloudSpeech {
+ let text = "";
+ const sources: number[] = [];
+ const blocks: ReadAloudBlock[] = [];
+ const push = (run: Run) => {
+ text += run.text;
+ sources.push(...run.sources);
+ };
+ const speak = (run: Run, node: Positioned) => {
+ let spokenStart: number | null = null;
+ let lineStart = 0;
+ while (lineStart <= run.text.length) {
+ const newline = run.text.indexOf("\n", lineStart);
+ const lineEnd = newline === -1 ? run.text.length : newline;
+ const line: Run = { text: "", sources: [] };
+ for (let index = lineStart; index < lineEnd; index++) {
+ const character = run.text.charAt(index);
+ const space = SPACE.test(character);
+ if (space && line.text.endsWith(" ")) continue;
+ line.text += space ? " " : character;
+ line.sources.push(run.sources[index] ?? ADDED);
+ }
+ const sentence = trim(line);
+ if (sentence.text) {
+ if (text) push(added("\n"));
+ spokenStart ??= text.length;
+ push(sentence);
+ if (!SENTENCE_END.test(sentence.text)) push(added("."));
+ }
+ lineStart = lineEnd + 1;
}
+ const sourceStart = node.position?.start.offset;
+ const sourceEnd = node.position?.end.offset;
+ if (spokenStart !== null && sourceStart !== undefined && sourceEnd !== undefined)
+ blocks.push({ spokenStart, spokenEnd: text.length, sourceStart, sourceEnd });
};
- const inline = (node: RootContent): string => {
- if (node.type === "break") return "\n";
- if (node.type === "html" || node.type === "image" || node.type === "imageReference") return "";
- if ("children" in node) return node.children.map(inline).join("");
- return "value" in node ? node.value : "";
+ const inline = (node: RootContent): Run => {
+ if (node.type === "break") return added("\n");
+ if (node.type === "html" || node.type === "image" || node.type === "imageReference")
+ return added("");
+ if ("children" in node) return concat(node.children.map(inline));
+ return "value" in node ? located(markdown, node.value, node) : added("");
};
const block = (node: Root | RootContent) => {
- if (node.type === "paragraph" || node.type === "heading") speak(inline(node));
+ if (node.type === "paragraph" || node.type === "heading") speak(inline(node), node);
else if (node.type === "tableRow")
speak(
- node.children
- .map((cell) => inline(cell).trim())
- .filter(Boolean)
- .join(", "),
+ concat(
+ node.children
+ .map((cell) => trim(inline(cell)))
+ .filter((cell) => cell.text)
+ .flatMap((cell, index) => (index ? [added(", "), cell] : [cell])),
+ ),
+ node,
);
else if (node.type === "code") {
- if (!skipCodeBlocks) speak(node.value);
+ if (!skipCodeBlocks) speak(located(markdown, node.value, node), node);
} else if (node.type !== "html" && node.type !== "definition" && "children" in node)
for (const child of node.children) block(child);
};
block(parser.parse(markdown));
- return sentences.join("\n");
+ return { text, sources, blocks };
}
-export function splitReadAloudText(text: string, limit = 3500) {
- const chunks: string[] = [];
+export function readAloudText(markdown: string, skipCodeBlocks: boolean) {
+ return readAloudSpeech(markdown, skipCodeBlocks).text;
+}
+
+/** Splits at sentence ends below `limit`; `start` is each piece's offset in `text`. */
+export function splitReadAloudSpans(text: string, limit = 3500) {
+ const spans: Array<{ readonly start: number; readonly text: string }> = [];
let rest = text.trim();
+ let offset = text.length - text.trimStart().length;
while (rest.length > limit) {
const part = rest.slice(0, limit);
const sentence = [...part.matchAll(/[.!?。!?](?:\s|$)/gu)].at(-1);
let at = sentence ? sentence.index + sentence[0].length : part.lastIndexOf(" ");
if (at <= 0) at = limit;
if (/[\uD800-\uDBFF]/.test(rest[at - 1] ?? "")) at--;
- chunks.push(rest.slice(0, at).trim());
- rest = rest.slice(at).trim();
+ spans.push({ start: offset, text: rest.slice(0, at).trim() });
+ const next = rest.slice(at);
+ rest = next.trim();
+ offset += at + next.length - next.trimStart().length;
}
- if (rest) chunks.push(rest);
- return chunks;
+ if (rest) spans.push({ start: offset, text: rest });
+ return spans;
+}
+
+export function splitReadAloudText(text: string, limit = 3500) {
+ return splitReadAloudSpans(text, limit).map((span) => span.text);
+}
+
+/** The whitespace-delimited word of `text` that holds `index`, such as a speech boundary. */
+export function spokenWordAt(text: string, index: number) {
+ let start = Math.max(0, Math.min(index, text.length));
+ while (start < text.length && SPACE.test(text.charAt(start))) start++;
+ let end = start;
+ while (start > 0 && !SPACE.test(text.charAt(start - 1))) start--;
+ while (end < text.length && !SPACE.test(text.charAt(end))) end++;
+ return { start, end };
+}
+
+/**
+ * A word as a renderer finds it: the text shown for it and how many times that text appears
+ * earlier in its block. Renderers search their own text, which can differ from the markdown.
+ */
+export interface ReadAloudCue {
+ readonly text: string;
+ readonly occurrence: number;
+}
+
+/** What is being read, as markdown offsets plus cues for renderers that search their text. */
+export interface ReadAloudPosition {
+ readonly block: {
+ readonly start: number;
+ readonly end: number;
+ readonly first: ReadAloudCue;
+ readonly last: ReadAloudCue;
+ };
+ readonly word: { readonly start: number; readonly end: number; readonly cue: ReadAloudCue };
+}
+
+const occurrences = (text: string, find: string) => {
+ let count = 0;
+ for (let at = text.indexOf(find); at !== -1; at = text.indexOf(find, at + find.length)) count++;
+ return count;
+};
+
+/** The block and word at a spoken range, or null when the range has no markdown source. */
+export function readAloudPosition(
+ speech: ReadAloudSpeech,
+ spokenStart: number,
+ spokenEnd: number,
+): ReadAloudPosition | null {
+ const block = speech.blocks.find(
+ (entry) => spokenStart >= entry.spokenStart && spokenStart < entry.spokenEnd,
+ );
+ if (!block) return null;
+ const shown = (start: number, end: number) => {
+ let result = "";
+ for (let index = start; index < end; index++)
+ if ((speech.sources[index] ?? ADDED) !== ADDED) result += speech.text[index];
+ return result;
+ };
+ const cue = (start: number, end: number) => {
+ const text = shown(start, end);
+ return text
+ ? { text, occurrence: occurrences(shown(block.spokenStart, start), text) }
+ : undefined;
+ };
+ const words = [...speech.text.slice(block.spokenStart, block.spokenEnd).matchAll(/\S+/g)];
+ const first = words[0];
+ const last = words.at(-1);
+ const firstCue =
+ first &&
+ cue(block.spokenStart + first.index, block.spokenStart + first.index + first[0].length);
+ const lastCue =
+ last && cue(block.spokenStart + last.index, block.spokenStart + last.index + last[0].length);
+ const wordCue = cue(spokenStart, spokenEnd);
+ const wordSources = speech.sources
+ .slice(spokenStart, spokenEnd)
+ .filter((source) => source !== ADDED);
+ if (!firstCue || !lastCue || !wordCue || wordSources.length === 0) return null;
+ return {
+ block: { start: block.sourceStart, end: block.sourceEnd, first: firstCue, last: lastCue },
+ word: { start: Math.min(...wordSources), end: Math.max(...wordSources) + 1, cue: wordCue },
+ };
+}
+
+/** A UTF-16 range of the text a renderer shows. */
+export interface ReadAloudTextRange {
+ readonly start: number;
+ readonly end: number;
+}
+
+type ComparedWord = ReadAloudTextRange & { readonly key: string };
+
+/** How far ahead a word may be found before the match is resynchronized on a run of words. */
+const ALIGN_WINDOW = 8;
+const RESYNC_RUN = 3;
+
+/** Words of `text` compared by letters and digits only, so markup and punctuation do not count. */
+function comparedWords(text: string): ComparedWord[] {
+ const words: ComparedWord[] = [];
+ for (const match of text.matchAll(/\S+/g)) {
+ const key = match[0].toLowerCase().replace(/[^\p{L}\p{N}]/gu, "");
+ if (key) words.push({ key, start: match.index, end: match.index + match[0].length });
+ }
+ return words;
+}
+
+/**
+ * The shown word each spoken word appears as, or -1. Matches move forward; a skip needs the next
+ * words to agree, and a lost match resyncs on the next run of equal words anywhere ahead.
+ */
+function alignWords(spoken: ReadonlyArray, shown: ReadonlyArray) {
+ const anchors = Array.from(spoken, () => -1);
+ const agrees = (from: number, to: number, length: number) => {
+ for (let offset = 0; offset < length; offset++) {
+ const a = spoken[from + offset];
+ const b = shown[to + offset];
+ if (!a || !b) return offset > 0;
+ if (a.key !== b.key) return false;
+ }
+ return true;
+ };
+ let i = 0;
+ let j = 0;
+ // A lone equal word is trusted only right after a match; elsewhere "the" would match anywhere.
+ let synced = false;
+ while (i < spoken.length && j < shown.length) {
+ let next: { i: number; j: number } | null = null;
+ for (let distance = 0; distance <= ALIGN_WINDOW && !next; distance++)
+ for (let skip = 0; skip <= distance && !next; skip++)
+ if (agrees(i + skip, j + distance - skip, distance === 0 && synced ? 1 : 2))
+ next = { i: i + skip, j: j + distance - skip };
+ if (!next)
+ for (let at = j + 1; at < shown.length && !next; at++)
+ if (agrees(i, at, RESYNC_RUN)) next = { i, j: at };
+ synced = next !== null;
+ if (!next) {
+ i++;
+ continue;
+ }
+ anchors[next.i] = next.j;
+ i = next.i + 1;
+ j = next.j + 1;
+ }
+ return anchors;
+}
+
+/**
+ * Finds what read aloud is reading in a renderer's own text, such as a native view that reports
+ * the text it shows but not where it came from in the markdown. The reply's words are matched to
+ * the shown words in order; a word without a safe match is left unhighlighted.
+ */
+export function readAloudShownText(markdown: string, shown: string) {
+ const speech = readAloudSpeech(markdown, false);
+ const spoken = comparedWords(speech.text).map((word) => {
+ const sources = speech.sources.slice(word.start, word.end).filter((at) => at !== ADDED);
+ return { ...word, sourceStart: Math.min(...sources), sourceEnd: Math.max(...sources) + 1 };
+ });
+ const shownWords = comparedWords(shown);
+ const anchors = alignWords(spoken, shownWords);
+ const span = (inside: (word: (typeof spoken)[number]) => boolean): ReadAloudTextRange | null => {
+ let start = Infinity;
+ let end = -Infinity;
+ spoken.forEach((word, index) => {
+ const match = shownWords[anchors[index] ?? -1];
+ if (!match || !inside(word)) return;
+ start = Math.min(start, match.start);
+ end = Math.max(end, match.end);
+ });
+ return start < end ? { start, end } : null;
+ };
+ return (position: ReadAloudPosition) => ({
+ block: span(
+ (word) => word.sourceStart >= position.block.start && word.sourceEnd <= position.block.end,
+ ),
+ word: span(
+ (word) => word.sourceStart < position.word.end && word.sourceEnd > position.word.start,
+ ),
+ });
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8f9f94f9ff720..01e297acf0951 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -766,8 +766,8 @@ importers:
specifier: 0.88.1
version: 0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6)
react-native-enriched-markdown:
- specifier: file:deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz
- version: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz(katex@0.16.47)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
+ specifier: file:deps/react-native-enriched-markdown-1.2.0-t3.18-3431ed09.tgz
+ version: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-3431ed09.tgz(katex@0.16.47)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
react-native-gesture-handler:
specifier: 3.5.0
version: 3.5.0(patch_hash=171379dd378f8f11e9187876dec2116e5cbf5f21cef6576cdde6956518324f98)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
@@ -11628,8 +11628,8 @@ packages:
'@types/react': '>=18'
react: '>=18'
- react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz:
- resolution: {integrity: sha512-TdP2nTxn8W4jPJ5EU+9Ctgf6aOncENP/kMa9aEZpJDmWNLXkxPpcugHMWyZJt2o5WDYE4SPi0V6zV6mOl3+8cA==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz}
+ react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-3431ed09.tgz:
+ resolution: {integrity: sha512-gHpJ4nB6a3+ihlvbNR7K6s+zVJWauxpa/p0SNvUZu7iPGQkks4Fhgx3aFELOiW1g/3DIFDDR/btgTEEbi+uMvg==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-3431ed09.tgz}
version: 1.2.0-t3.18
peerDependencies:
katex: '>=0.16.0'
@@ -22565,7 +22565,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
- react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz(katex@0.16.47)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0):
+ react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-3431ed09.tgz(katex@0.16.47)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0):
dependencies:
react: 19.3.0
react-native: 0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6)
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 04f881d6f124d..0c6c70e3bfd5b 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -23,7 +23,7 @@ allowBuilds:
node-pty: true
# Ships N-API prebuilds; its install script only rebuilds from source.
objc-js: false
- "react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz": true
+ "react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-3431ed09.tgz": true
sharp: true
utf-8-validate: false
workerd: false