Skip to content

feat(ai): useTranscribe and useMicrophone with 120 s chunked transcription (#523 3.3/3.4) - #628

Open
mayankmahavar1mg wants to merge 1 commit into
feature/ai-21-live-voicefrom
feature/ai-22-transcribe
Open

mayankmahavar1mg wants to merge 1 commit into
feature/ai-21-live-voicefrom
feature/ai-22-transcribe

Conversation

@mayankmahavar1mg

@mayankmahavar1mg mayankmahavar1mg commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #621 (base feature/ai-21-live-voice). Part of #523 (audio track 3.3 and 3.4), related to #611.

What

  • Chunked transcription (catalyst-ai): splitAudio and prepareAudioChunks decode a clip once and cut it into 28 s pieces at the quietest 20 ms frame before each limit, so a word is rarely split. Pieces do not overlap (a speech model cannot merge overlapping transcripts, so overlap would repeat words). A clip over 120 s comes back with truncated: true; nothing is cut silently.
  • useTranscribe (catalyst-core/hooks, modelled on useVision):
    • pieces run in order on the engine the first piece chose; silent pieces are skipped
    • the transcript and "part N of M" progress update as it runs
    • the model is unloaded once at the end, not per piece
    • stops at needs-consent / denied on the first piece; approve() applies to every piece
    • supports cancel and supersede; chunkSeconds: null sends the clip whole (for a cloud model that takes long audio)
  • Routing pin: Consent.pin keeps a multi-call job on one candidate. Auto routing re-ranks on every call (observed speed, loaded model), so chunks of one recording could otherwise land on different models. The privacy policy still applies to the pinned candidate.
  • useMicrophone (catalyst-core/hooks): the recorder moved out of the Pipeline lab. MediaRecorder, live level, silence auto-stop, maxSeconds (default 120), supported flag.
  • Pipeline lab: the on-device speech stage uses useTranscribe and shows progress.

Verification

  • catalyst-core: 682 tests pass (34 new for useTranscribe and useMicrophone); catalyst-ai: 319 pass (5 new for the splitter); tsc declarations clean.
  • I broke the engine pin and the single-unload behaviour on purpose and confirmed the tests fail.
  • Run in a browser: record, then on-device Whisper, Gemma JSON, and SD-Turbo image completed end to end on a short (about 5 s) clip.

Not verified / limits

  • A clip longer than 30 s has not been run on real audio, so the chunk boundaries, "part N of M" progress and the single unload are covered by unit tests only.
  • useMicrophone is web only: the Android WebView only grants camera permission requests and the iOS shell declares no microphone usage. A native recorder bridge is a follow-up.
  • The native Gemma audio path and the lab's Gemini path are unchanged (no chunking).
  • Not included: the voice-notes example page, docs and knowledge-base entries, and the native speech engines from 6.10 (SpeechAnalyzer, ML Kit).

🤖 Generated with Claude Code



DeputyDev generated PR summary:


Size XL: This PR changes include 904 lines and should take approximately 3-6 hours to review


This PR adds a reusable browser microphone and long-form transcription flow.

Main changes

  • Adds useMicrophone

    • Captures audio using MediaRecorder and getUserMedia.
    • Returns the recording as a base64 data URL.
    • Provides recording state, elapsed time, input level, errors, start, stop, and cancel.
    • Can automatically stop after silence or after a maximum duration of 120 seconds.
    • Reports unsupported environments, such as the current Android WebView/iOS shell without microphone support.
  • Adds useTranscribe

    • Accepts an audio data URL, Blob, or File.
    • Decodes and converts audio to 16 kHz mono WAV.
    • Splits recordings into approximately 28-second chunks, leaving headroom below the model’s 30-second encoder limit.
    • Searches for quiet moments near chunk boundaries to avoid cutting words.
    • Supports recordings up to 120 seconds; longer recordings are truncated and reported with truncated: true.
    • Skips silent chunks by default.
    • Transcribes chunks sequentially and joins their text in order.
    • Exposes progress such as “chunk 2 of 5”, partial text, routing information, errors, cancellation, and model download state.
    • Unloads the on-device model once after the entire transcription rather than after every chunk.
  • Improves routing consistency

    • The first chunk’s selected AI candidate is pinned for subsequent chunks, preventing a recording from switching models midway through transcription.
    • Existing routing, privacy, cloud-consent, and download-consent behavior is preserved.
    • Transcription can pause in needs-consent or denied states, with approve() available to retry using the requested consent.
  • Updates PipelineLab

    • Replaces the direct one-shot Whisper useAI().generate() call with useTranscribe.
    • Displays chunk transcription progress.
    • Uses the new model download progress shape.
    • Warns when a recording exceeds the 120-second limit.
  • Adds tests

    • Audio splitting and silence detection.
    • 120-second truncation and WAV conversion.
    • Microphone permissions, recording, cancellation, auto-stop, and cleanup.
    • Multi-chunk transcription, routing pinning, consent, errors, cancellation, and model unloading.

In short, the PR changes transcription from a single short audio request into a consent-aware, chunked voice-recording pipeline that can process up to two minutes of audio on supported devices.


DeputyDev generated PR summary until b561603

…iption (#523 3.3/3.4)

Speech to text as a hook, on the device when it can, and the recorder moved out of
the Pipeline lab into the library.

- catalyst-ai: splitAudio / prepareAudioChunks decode a clip once and cut it into
  28 s pieces at the quietest 20 ms frame before each limit (no overlap, so no
  repeated words). Over 120 s the result says truncated; nothing is cut silently.
- useTranscribe (catalyst-core/hooks): modelled on useVision. Pieces are
  transcribed in order on the engine the first piece chose, silent pieces are
  skipped, the transcript and "part N of M" progress update as it runs, and the
  model is unloaded once at the end. Stops at needs-consent / denied on the first
  piece; approve() applies to every piece. chunkSeconds: null sends the clip whole.
- Routing: Consent.pin keeps a multi-call job on one candidate. Routing re-ranks
  on every call, so chunks could otherwise land on different models. The privacy
  policy still applies to the pinned candidate.
- useMicrophone (catalyst-core/hooks): MediaRecorder with live level, silence
  auto-stop and maxSeconds (default 120). Web only: the Android WebView grants
  camera but not microphone requests and the iOS shell declares no microphone
  usage, so a native recorder bridge is a follow-up.
- Pipeline lab: the on-device speech stage uses useTranscribe and shows progress.

Not covered: the native Gemma audio path and the lab's Gemini path are unchanged
(no chunking); the voice-notes example page and docs are not written.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@deputydev-agent

Copy link
Copy Markdown

DeputyDev has started reviewing your pull request.

return (result?.output ?? "").trim()
const heard = await asrRef.current.transcribe(data)
if (!heard) throw asrRef.current.lastError() ?? new Error("The recording could not be transcribed")
if (heard.truncated) console.warn(`[pipeline-lab] recording is ${heard.durationSec}s; only the first ${heard.durationSec}s were transcribed`)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ERROR: This warning presents heard.durationSec as the original recording length, but that value is already capped at maxSeconds. For any truncated recording, both interpolations therefore show the transcribed prefix rather than the actual source duration. Reword this as exceeding the transcription limit, or expose the uncapped duration separately.
A recording longer than 120 seconds is misleadingly reported as being exactly 120 seconds.

if (heard.truncated) console.warn(`[pipeline-lab] recording exceeded the ${heard.durationSec}s transcription limit; only the first ${heard.durationSec}s were transcribed`)

// pushing a chunk past the truncation in toMono16k.
export const CHUNK_SECONDS = MAX_AUDIO_SECONDS - 2
// The longest clip one transcription takes. Longer input is refused with `truncated: true`, never cut silently.
export const MAX_CLIP_SECONDS = 120

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DOCUMENTATION: Please update the package documentation for this new limit. The README still describes a 30-second on-device audio cap, while this API now distinguishes the per-chunk encoder limit from a 120-second chunked transcription limit and reports truncated beyond it.
Consumers cannot infer the new per-chunk versus per-recording limits from the existing README.

Document the 30-second encoder limit, the default 28-second chunks, the 120-second overall limit, and the `truncated` result.

* to merge two overlapping transcripts, so overlap would repeat words). Pure; no decoding.
* -> [{ samples, startSec, endSec, silent }]
*/
export function splitAudio(samples, { chunkSeconds = CHUNK_SECONDS, searchSeconds = 4 } = {}) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ERROR: Validate chunkSeconds before deriving limit. With chunkSeconds: 0, cut remains equal to start, so push(cut) makes no progress and this loop runs forever for non-empty input; negative values can move start backward. Because this function is exported and the option is forwarded by prepareAudioChunks, malformed runtime configuration can block the browser thread.
A non-positive chunk size creates a deterministic non-terminating public API call.

if (!Number.isFinite(chunkSeconds) || chunkSeconds <= 0) throw new RangeError("chunkSeconds must be a finite positive number")

if (typeof dataUrl !== "string" || !dataUrl.startsWith("data:")) throw new Error("Audio must be a base64 data URL")
const { channels, sampleRate } = await decode(base64ToBytes(dataUrl.slice(dataUrl.indexOf(",") + 1)))
const fullSeconds = channels[0].length / sampleRate
const samples = toMono16k(channels, sampleRate, { maxSeconds })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PERFORMANCE_OPTIMIZATION: The 120-second cap currently bounds only the resampled output. toMono16k first allocates and fills a mono buffer for the complete decoded recording, so a long file still consumes CPU and an extra Float32Array proportional to its full duration even though the tail is discarded. Limit the input frame count before downmixing.
Preprocessing memory and CPU remain proportional to the full source duration rather than the advertised transcription limit.

Downmix only `Math.min(channels[0].length, Math.ceil(maxSeconds * sampleRate))` input frames before resampling.

export { useAI } from "./useAI.js"
export { useVision, VisionError } from "./useVision.js"
export type { UseVisionOptions, UseVisionResult, VisionStatus, VisionConsent, VisionModelState, Schema, ImageSource } from "./useVision.js"
export { useTranscribe, TranscribeError } from "./useTranscribe.js"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DOCUMENTATION: These hooks are now part of the public export surface, but the package README does not document how to connect recording to transcription or handle supported, permission errors, consent, denial, and truncation. Add a public usage example and the relevant browser/platform limitations.
The newly exported consumer API has behavior-critical contracts that are currently available only in source comments.

Document `useMicrophone({ onRecorded: clip => transcription.transcribe(clip) })` together with `supported`, permission failures, `needs-consent`/`approve`, denial, and the transcription limit.

release()
}, [stop, release])

const start = useCallback(async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CODE_MAINTAINABILTIY: live.current is not assigned until after getUserMedia() resolves, so two rapid start() calls can both pass this guard and create sessions, with the later one overwriting the earlier reference. Unmount or cancellation while permission is pending has the same ownership gap: cleanup sees no session, then the continuation can start recording afterward. Track an in-flight start token, reject duplicates, and stop any stream returned for a stale or unmounted request.
Concurrent or delayed permission results can leave microphone tracks, recorders, and timers unreachable by release().

Set a pending generation before awaiting `getUserMedia`; invalidate it on cancel/unmount, and stop all returned tracks when the generation is stale or the hook is unmounted.

}
try {
const blob = new Blob(chunks, { type: recorder.mimeType || "audio/webm" })
onRecorded.current?.(await readAsDataUrl(blob), { seconds: secs })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CODE_MAINTAINABILTIY: The mounted/discard check occurs before await readAsDataUrl(blob). If the hook unmounts or the operation is canceled while FileReader is pending, this callback still delivers the completed microphone clip to the stale consumer. Re-check lifecycle state after the await using a cancellation token that remains valid after release().
Recorded audio can be delivered for processing after the hook's lifecycle has ended.

const dataUrl = await readAsDataUrl(blob)
if (!mounted.current || token !== generation.current) return
onRecorded.current?.(dataUrl, { seconds: secs })

setError(err?.name === "NotAllowedError" ? "Microphone permission was denied." : `Could not open the microphone: ${err?.message || err}`)
return
}
const mimeType = MIME_TYPES.find((t) => MediaRecorder.isTypeSupported?.(t))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CODE_MAINTAINABILTIY: After the stream is acquired, recorder construction, audio-context setup, and recorder.start() are outside an error-cleanup path. A thrown setup/start error can leave tracks, a context, or the installed timer active without setting the hook's error; asynchronous recorder failures also have no handler. Route all of these failures through one cleanup path.
Browser API failures after permission succeeds can leak an active microphone session and leave hook state inconsistent.

Wrap recorder/context setup and `recorder.start()` in a cleanup-aware try/catch, and attach `recorder.onerror` to release the session and set a meaningful error.

lastLoud: number
}

export function useMicrophone(options: UseMicrophoneOptions = {}): UseMicrophoneResult {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CODE_MAINTAINABILTIY: Pipeline Lab still uses its local useVoiceRecorder, which independently implements the same MediaRecorder, AudioContext, RMS, silence timeout, and cleanup lifecycle as this new shared hook. Migrate that consumer to useMicrophone or reduce the local hook to a compatibility wrapper so recorder fixes do not diverge.
Two full recorder implementations must now receive the same permission, cleanup, and option-handling fixes independently.

Replace the Pipeline Lab `useVoiceRecorder` usage with `useMicrophone`, then remove the local implementation or delegate it to the shared hook.

lastLoud: number
}

export function useMicrophone(options: UseMicrophoneOptions = {}): UseMicrophoneResult {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DOCUMENTATION: Add declaration-level JSDoc to this newly exported hook. The current // block is detached from the symbol, so generated API/IDE documentation will not expose its web-only limitation or the contracts around supported, permission errors, onRecorded, stop, and cancel.
The public symbol omits behavior and platform constraints that consumers need when invoking it.

/** Records microphone input in a supported browser and delivers a data URL through `onRecorded`. Check `supported`, handle permission errors, and use `stop()` or `cancel()` to finish or discard the clip. */

let pieces: { data: string; silent: boolean }[]
let durationSec = 0
let truncated = false
if (chunkSeconds === null) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SECURITY: A Blob can finish blobToDataUrl after this request was canceled or superseded. The chunked branch checks requestId after preparation, but this whole-recording branch has no equivalent check before generate, so stale audio is still submitted. Check the request ID immediately after source conversion and before selecting either branch.
Cancellation or a newer transcription does not prevent an older whole-recording Blob from reaching the model.

if (id !== requestId.current) return null

let pieces: { data: string; silent: boolean }[]
let durationSec = 0
let truncated = false
if (chunkSeconds === null) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ERROR: Whole-recording mode bypasses prepareAudioChunks, so maxSeconds is not enforced and the source is sent as one unbounded piece, while durationSec and truncated remain at their 0/false defaults. This contradicts the public option and result contracts. Either enforce and populate those fields in this branch, or explicitly document whole-recording mode as unlimited and exempt from that metadata guarantee.
A real whole-clip transcription can return false duration metadata and submit input beyond the documented maximum.

Apply duration/maxSeconds handling before constructing the whole-recording piece and assign `durationSec`/`truncated`; otherwise revise the option and result documentation to define this mode as uncapped.

@deputydev-agent

Copy link
Copy Markdown

DeputyDev has completed a review of your pull request for commit b561603.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant