Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(voice): live microphone trace while dictating

purple8da050d424e4
diff --git a/e2e/mic-level-trace.spec.ts b/e2e/mic-level-trace.spec.ts
new file mode 100644
index 00000000..1760b139
--- /dev/null
+++ b/e2e/mic-level-trace.spec.ts
@@ -0,0 +1,101 @@
+import { mkdirSync } from 'fs'
+import { test, expect, type Page } from '@playwright/test'
+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME } from './support/tauri-mock'
+import { seedOnboardingDone } from './support/cloud-mock'
+import { appModules, openNewChat, type AppWindow } from './support/ui'
+
+/**
+ * The live trace of the microphone while dictating (David, 14.11.2026): a
+ * slim waveform that moves with the voice, the running time, and "No sound
+ * from mic" when nothing arrives for a few seconds.
+ *
+ * The microphone is a WebAudio stream made in the page: an oscillator whose
+ * loudness swings like speech, or nothing at all. It goes through the real
+ * path of the app: the recorder asks getUserMedia, the level meter listens
+ * through an AnalyserNode, the composer draws it. Speech-to-text is switched
+ * on directly; it is not the subject here.
+ *
+ * LU_SHOTS_DIR=<dir> also saves the screens, light and dark.
+ */
+
+const VOICE_STORE = '/src/stores/voiceStore.ts'
+
+async function boot(page: Page, mic: 'speech' | 'silent') {
+ await page.addInitScript(tauriMockInit, { assistantReply: DEFAULT_ASSISTANT_REPLY, modelName: DEFAULT_MODEL_NAME })
+ await page.addInitScript((kind) => {
+ const devices = navigator.mediaDevices
+ devices.getUserMedia = async () => {
+ const ctx = new AudioContext()
+ const out = ctx.createMediaStreamDestination()
+ if (kind === 'speech') {
+ const tone = ctx.createOscillator()
+ tone.frequency.value = 220
+ const voice = ctx.createGain()
+ voice.gain.value = 0.35
+ // A slow swing of the loudness, like syllables.
+ const lfo = ctx.createOscillator()
+ lfo.frequency.value = 3
+ const depth = ctx.createGain()
+ depth.gain.value = 0.3
+ lfo.connect(depth).connect(voice.gain)
+ tone.connect(voice).connect(out)
+ tone.start()
+ lfo.start()
+ }
+ return out.stream
+ }
+ }, mic)
+ await seedOnboardingDone(page)
+ await page.goto('/')
+ await expect(page.getByRole('button', { name: 'Settings' })).toBeVisible()
+ await appModules(page, [VOICE_STORE])
+ await openNewChat(page)
+ await page.evaluate((path) => {
+ (window as unknown as AppWindow).__APP__[path].useVoiceStore.getState().setSttAvailable(true)
+ }, VOICE_STORE)
+}
+
+const bars = (page: Page) => page.getByTestId('mic-level-bars').locator('i').evaluateAll((all) =>
+ all.map((bar) => Number(/scaleY\(([\d.]+)\)/.exec((bar as HTMLElement).style.transform)?.[1] ?? 0)))
+
+async function shot(page: Page, name: string) {
+ const dir = process.env.LU_SHOTS_DIR
+ if (!dir) return
+ mkdirSync(dir, { recursive: true })
+ const composer = page.locator('textarea[data-lu-composer]').locator('xpath=ancestor::div[contains(@class,"rounded")][1]')
+ await composer.screenshot({ path: `${dir}/${name}-composer.png` })
+ await page.screenshot({ path: `${dir}/${name}-page.png` })
+}
+
+for (const theme of ['dark', 'light'] as const) {
+ test(`speech moves the trace, the clock runs, no warning (${theme})`, async ({ page }) => {
+ await boot(page, 'speech')
+ if (theme === 'light') await page.getByRole('button', { name: 'Light Mode' }).click()
+ await expect(page.getByTestId('mic-level-trace')).toHaveCount(0)
+
+ await page.getByRole('button', { name: 'Start voice input' }).click()
+ const trace = page.getByTestId('mic-level-trace')
+ await expect(trace).toBeVisible()
+ await expect.poll(async () => Math.max(...(await bars(page))), { timeout: 5_000 }).toBeGreaterThan(0.5)
+ // A waveform, not one block: the bars stand at different heights.
+ await expect.poll(async () => new Set((await bars(page)).map((h) => h.toFixed(2))).size).toBeGreaterThan(3)
+ await expect(page.getByTestId('mic-level-clock')).toHaveText('0:02', { timeout: 5_000 })
+ await page.waitForTimeout(1_500)
+ await expect(page.getByTestId('mic-level-quiet')).toHaveCount(0)
+ await shot(page, `mic-sprache-${theme}`)
+
+ await page.getByRole('button', { name: 'Stop recording' }).click()
+ await expect(trace).toHaveCount(0)
+ })
+
+ test(`a silent microphone stays flat and says so after a few seconds (${theme})`, async ({ page }) => {
+ await boot(page, 'silent')
+ if (theme === 'light') await page.getByRole('button', { name: 'Light Mode' }).click()
+ await page.getByRole('button', { name: 'Start voice input' }).click()
+ await expect(page.getByTestId('mic-level-trace')).toBeVisible()
+ await expect(page.getByTestId('mic-level-quiet')).toHaveCount(0)
+ await expect(page.getByTestId('mic-level-quiet')).toHaveText('No sound from mic', { timeout: 6_000 })
+ expect(Math.max(...(await bars(page)))).toBeLessThan(0.1)
+ await shot(page, `mic-stille-${theme}`)
+ })
+}
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index da346e30..c2a0d6f2 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -4,6 +4,7 @@ import { SamplingControls } from './SamplingControls'
import { Send, Square, Paperclip, X, Brain, Gauge, Terminal, Film, Music } from 'lucide-react'
import { matchAgentCommands, type AgentCommand, type CommandScope } from '../../lib/agent-commands'
import { VoiceButton, type VoiceButtonHandle } from './VoiceButton'
+import { MicLevelTrace } from '../voice/MicLevelTrace'
import { ApprovalDialog } from './ApprovalDialog'
import { ComputerQuestionSlot } from '../computer/ComputerQuestion'
import { ComputerNote } from '../computer/ComputerNote'
@@ -172,6 +173,8 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
const imageJob = useRef({ busy: false, epoch: 0 })
const fileJob = useRef({ busy: false })
const [isVoiceRecording, setIsVoiceRecording] = useState(false)
+ // When the take started, for the running time of the live trace.
+ const [recordingSince, setRecordingSince] = useState(0)
const voiceRef = useRef<VoiceButtonHandle>(null)
// Slash-command autocomplete (v2.5.3). When the input is a lone "/token", show
// the matching agent commands; ↑/↓ to move, Enter/Tab to pick, Esc to dismiss.
@@ -937,6 +940,10 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
still keeps one height while it works (see below). */}
{/* The query container sits one level out: a container query cannot
style the container itself, and the row has to wrap. */}
+ {/* The live trace of the microphone while a take runs (14.11.2026):
+ a line of its own under the text, so the action row keeps its
+ room; moves with the voice, says so when nothing arrives. */}
+ {isVoiceRecording && <MicLevelTrace since={recordingSince} className="px-3 pb-1.5" />}
<div className="@container">
<div className="flex flex-nowrap items-center gap-1 px-2 py-1.5 min-h-[38px] border-t border-gray-200 dark:border-white/[0.05] @max-[26rem]:flex-wrap">
{/* Clip button */}
@@ -965,7 +972,10 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
onInterim={applyDictation}
onTranscript={applyDictation}
onRecordingChange={(r) => {
- if (r) dictationBaseRef.current = input
+ if (r) {
+ dictationBaseRef.current = input
+ setRecordingSince(Date.now())
+ }
setIsVoiceRecording(r)
}}
// The microphone stays free while an answer streams: a take that
diff --git a/src/components/chat/__tests__/mic-level-in-the-composer.test.tsx b/src/components/chat/__tests__/mic-level-in-the-composer.test.tsx
new file mode 100644
index 00000000..a680332b
--- /dev/null
+++ b/src/components/chat/__tests__/mic-level-in-the-composer.test.tsx
@@ -0,0 +1,34 @@
+// @vitest-environment jsdom
+/**
+ * The composer shows the live microphone trace while a take runs, and only
+ * then (David, 14.11.2026). One composer serves Chat, Agent and Code.
+ *
+ * Run: npx vitest run src/components/chat/__tests__/mic-level-in-the-composer.test.tsx
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+vi.mock('../VoiceButton', () => ({
+ VoiceButton: ({ onRecordingChange }: { onRecordingChange?: (r: boolean) => void }) => (
+ <>
+ <button type="button" onClick={() => onRecordingChange?.(true)}>fake start</button>
+ <button type="button" onClick={() => onRecordingChange?.(false)}>fake stop</button>
+ </>
+ ),
+}))
+
+import { ChatInput } from '../ChatInput'
+
+afterEach(() => cleanup())
+
+describe('the composer and the microphone', () => {
+ it('shows the trace while recording and takes it away after', () => {
+ render(<ChatInput onSend={() => {}} onStop={() => {}} isGenerating={false} modelReady={() => true} />)
+ expect(screen.queryByTestId('mic-level-trace')).toBeNull()
+ act(() => { fireEvent.click(screen.getByText('fake start')) })
+ expect(screen.getByTestId('mic-level-trace')).toBeTruthy()
+ expect(screen.getByTestId('mic-level-clock').textContent).toBe('0:00')
+ act(() => { fireEvent.click(screen.getByText('fake stop')) })
+ expect(screen.queryByTestId('mic-level-trace')).toBeNull()
+ })
+})
diff --git a/src/components/voice/MicLevelTrace.tsx b/src/components/voice/MicLevelTrace.tsx
new file mode 100644
index 00000000..abdc2259
--- /dev/null
+++ b/src/components/voice/MicLevelTrace.tsx
@@ -0,0 +1,80 @@
+import { useEffect, useRef, useState } from 'react'
+import { LEVEL_INTERVAL_MS, voiceLevel } from '../../hooks/useVoice'
+import {
+ HEARD_LEVEL, NO_SOUND_TEXT, barHeight, emptyHistory, formatClock, isQuiet, pushLevel,
+} from '../../lib/mic-level'
+
+export interface MicActivity {
+ /** The last readings, oldest first, 0 to 1. */
+ history: number[]
+ /** Nothing above room noise for a few seconds. */
+ quiet: boolean
+ /** Running time of the take, "0:07". */
+ clock: string
+}
+
+/**
+ * The microphone's activity since `since` (ms epoch). One reading per meter
+ * tick, also in silence, so the trace runs on as a flat line instead of
+ * standing still. Only the component that draws it repaints.
+ */
+export function useMicActivity(since: number): MicActivity {
+ const [state, setState] = useState<MicActivity>(() => ({
+ history: emptyHistory(), quiet: false, clock: formatClock(0),
+ }))
+ const lastHeardRef = useRef(since)
+
+ useEffect(() => {
+ lastHeardRef.current = since
+ const tick = () => {
+ const now = Date.now()
+ const level = voiceLevel()
+ if (level >= HEARD_LEVEL) lastHeardRef.current = now
+ setState((prev) => ({
+ history: pushLevel(prev.history, level),
+ quiet: isQuiet(lastHeardRef.current, now),
+ clock: formatClock(now - since),
+ }))
+ }
+ const timer = window.setInterval(tick, LEVEL_INTERVAL_MS)
+ return () => window.clearInterval(timer)
+ }, [since])
+
+ return state
+}
+
+/**
+ * The live trace while a dictation records: a slim waveform from the real
+ * microphone level, the running time, and "No sound from mic" when nothing
+ * has arrived for a few seconds. Neutral grey; the bars take `currentColor`,
+ * so the host decides the tone. Shared by the desktop composer and the web
+ * composer; the phone draws the same `useMicActivity` numbers.
+ */
+export function MicLevelTrace({ since, className = '' }: { since: number; className?: string }) {
+ const { history, quiet, clock } = useMicActivity(since)
+ return (
+ <div
+ data-testid="mic-level-trace"
+ data-quiet={quiet ? '' : undefined}
+ className={`flex min-w-0 items-center gap-2 t-micro tabular-nums text-gray-500 dark:text-gray-400 ${className}`}
+ >
+ <span
+ aria-hidden="true"
+ data-testid="mic-level-bars"
+ className="flex h-4 shrink-0 items-center gap-[2px] text-gray-600 dark:text-gray-300"
+ >
+ {history.map((level, i) => (
+ <i
+ key={i}
+ className="block h-full w-[2px] rounded-full bg-current transition-transform duration-75"
+ style={{ transform: `scaleY(${barHeight(level).toFixed(2)})`, opacity: quiet ? 0.45 : 1 }}
+ />
+ ))}
+ </span>
+ <span data-testid="mic-level-clock">{clock}</span>
+ {quiet && (
+ <span role="status" data-testid="mic-level-quiet" className="truncate">{NO_SOUND_TEXT}</span>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/voice/__tests__/mic-level-trace.test.tsx b/src/components/voice/__tests__/mic-level-trace.test.tsx
new file mode 100644
index 00000000..af76c404
--- /dev/null
+++ b/src/components/voice/__tests__/mic-level-trace.test.tsx
@@ -0,0 +1,80 @@
+// @vitest-environment jsdom
+/**
+ * The live trace of the microphone while a dictation records (David,
+ * 14.11.2026): flat in silence, moving with the voice, the running time next
+ * to it, and "No sound from mic" after a few seconds without any level.
+ *
+ * Run: npx vitest run src/components/voice/__tests__/mic-level-trace.test.tsx
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, render, screen } from '@testing-library/react'
+
+const mic = vi.hoisted(() => ({ level: 0 }))
+vi.mock('../../../hooks/useVoice', () => ({
+ LEVEL_INTERVAL_MS: 90,
+ voiceLevel: () => mic.level,
+}))
+
+import { MicLevelTrace } from '../MicLevelTrace'
+import { BAR_FLOOR, LEVEL_HISTORY, NO_SOUND_TEXT, QUIET_AFTER_MS } from '../../../lib/mic-level'
+
+function heights(): number[] {
+ return [...screen.getByTestId('mic-level-bars').querySelectorAll('i')].map((bar) =>
+ Number(/scaleY\(([\d.]+)\)/.exec((bar as HTMLElement).style.transform)?.[1]),
+ )
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-11-14T16:00:00Z'))
+ mic.level = 0
+})
+afterEach(() => {
+ cleanup()
+ vi.useRealTimers()
+})
+
+describe('MicLevelTrace', () => {
+ it('is a flat line in silence and moves when the voice comes', () => {
+ render(<MicLevelTrace since={Date.now()} />)
+ expect(heights()).toHaveLength(LEVEL_HISTORY)
+ act(() => { vi.advanceTimersByTime(900) })
+ expect(heights().every((h) => h === BAR_FLOOR)).toBe(true)
+
+ mic.level = 0.4
+ act(() => { vi.advanceTimersByTime(450) })
+ const now = heights()
+ expect(now[now.length - 1]).toBeGreaterThan(0.6)
+ // the newest readings stand, the older ones are still the flat line
+ expect(now[0]).toBe(BAR_FLOOR)
+ })
+
+ it('shows the running time', () => {
+ render(<MicLevelTrace since={Date.now()} />)
+ expect(screen.getByTestId('mic-level-clock').textContent).toBe('0:00')
+ act(() => { vi.advanceTimersByTime(7_050) })
+ expect(screen.getByTestId('mic-level-clock').textContent).toBe('0:07')
+ })
+
+ it('says "No sound from mic" after a few seconds without level, and takes it back when sound comes', () => {
+ render(<MicLevelTrace since={Date.now()} />)
+ act(() => { vi.advanceTimersByTime(QUIET_AFTER_MS - 200) })
+ expect(screen.queryByTestId('mic-level-quiet')).toBeNull()
+ act(() => { vi.advanceTimersByTime(400) })
+ expect(screen.getByTestId('mic-level-quiet').textContent).toBe(NO_SOUND_TEXT)
+
+ mic.level = 0.3
+ act(() => { vi.advanceTimersByTime(100) })
+ expect(screen.queryByTestId('mic-level-quiet')).toBeNull()
+ })
+
+ it('also says it in the middle of a long take, not only at the start', () => {
+ mic.level = 0.3
+ render(<MicLevelTrace since={Date.now()} />)
+ act(() => { vi.advanceTimersByTime(60_000) })
+ expect(screen.queryByTestId('mic-level-quiet')).toBeNull()
+ mic.level = 0
+ act(() => { vi.advanceTimersByTime(QUIET_AFTER_MS + 100) })
+ expect(screen.getByTestId('mic-level-quiet')).toBeTruthy()
+ })
+})
diff --git a/src/hooks/__tests__/voice-pegel-und-systemstimme.test.ts b/src/hooks/__tests__/voice-pegel-und-systemstimme.test.ts
index 5177693a..96d3070c 100644
--- a/src/hooks/__tests__/voice-pegel-und-systemstimme.test.ts
+++ b/src/hooks/__tests__/voice-pegel-und-systemstimme.test.ts
@@ -182,10 +182,13 @@ describe('the level of the microphone', () => {
off()
})
- it('the hook hands the level out and starts the meter only on a phone', () => {
+ // 3.1.0: the live trace in every composer needs the level on desktop and
+ // web too, so the meter starts on every device (it was phone only, L18).
+ it('the hook hands the level out and starts the meter on every device', () => {
expect(hookSource).toMatch(/getLevel: voiceLevel,/)
- expect(hookSource).toMatch(/if \(isMobile\(\)\) \{\s+\/\/[^\n]*\n\s+const stream = await startRecorderWithStream\(recorder\);/)
- expect(hookSource).toMatch(/\} else \{\s+await recorder\.start\(\);\s+\}/)
+ expect(hookSource).toMatch(/const stream = await startRecorderWithStream\(recorder\);\s+dropMeter\(meterRef\);\s+meterRef\.current = stream \? startLevelMeter\(stream\) : null;/)
+ expect(hookSource).not.toMatch(/if \(isMobile\(\)\) \{\s+\/\/[^\n]*\n\s+const stream = await startRecorderWithStream/)
+ expect(hookSource).not.toMatch(/\} else \{\s+await recorder\.start\(\);\s+\}/)
})
it('every way a take ends also ends the meter', () => {
diff --git a/src/hooks/useVoice.ts b/src/hooks/useVoice.ts
index 36dc0797..d6e87fd5 100644
--- a/src/hooks/useVoice.ts
+++ b/src/hooks/useVoice.ts
@@ -287,9 +287,9 @@ export function systemVoiceUsable(): boolean {
//
// The recorder (api/voice.ts) does not hand out its stream, so the meter
// takes the stream at the moment the recorder asks the browser for it and
-// listens to it through an analyser of its own. Measured only on a phone, so
-// a desktop recording is exactly what it was. A meter that cannot be built
-// never costs the take: the level then stays at 0.
+// listens to it through an analyser of its own. Measured on the phone since
+// L18 and on desktop and web since 3.1.0 (the live trace in the composer). A
+// meter that cannot be built never costs the take: the level then stays at 0.
let micLevel = 0;
const levelListeners = new Set<() => void>();
@@ -721,14 +721,11 @@ export function useVoice() {
recorderRef.current = recorder;
try {
- if (isMobile()) {
- // The same start, with the stream handed out for the level meter.
- const stream = await startRecorderWithStream(recorder);
- dropMeter(meterRef);
- meterRef.current = stream ? startLevelMeter(stream) : null;
- } else {
- await recorder.start();
- }
+ // The same start, with the stream handed out for the level meter
+ // (the live trace in every composer, 14.11.2026).
+ const stream = await startRecorderWithStream(recorder);
+ dropMeter(meterRef);
+ meterRef.current = stream ? startLevelMeter(stream) : null;
store.setRecording(true);
store.setTranscript("");
diff --git a/src/lib/__tests__/mic-level.test.ts b/src/lib/__tests__/mic-level.test.ts
new file mode 100644
index 00000000..5c37ad9c
--- /dev/null
+++ b/src/lib/__tests__/mic-level.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest'
+import {
+ BAR_FLOOR, HEARD_LEVEL, LEVEL_HISTORY, QUIET_AFTER_MS,
+ barHeight, emptyHistory, formatClock, isQuiet, pushLevel,
+} from '../mic-level'
+
+/** The live trace of the microphone (David, 14.11.2026): the pure numbers. */
+describe('mic level trace', () => {
+ it('starts flat and moves one reading to the left per tick', () => {
+ const start = emptyHistory()
+ expect(start).toHaveLength(LEVEL_HISTORY)
+ expect(start.every((v) => v === 0)).toBe(true)
+ const next = pushLevel(start, 0.5)
+ expect(next).toHaveLength(LEVEL_HISTORY)
+ expect(next[LEVEL_HISTORY - 1]).toBe(0.5)
+ expect(pushLevel(next, 0.2).slice(-2)).toEqual([0.5, 0.2])
+ })
+
+ it('keeps readings between 0 and 1, also for garbage', () => {
+ expect(pushLevel([0, 0], 4)).toEqual([0, 1])
+ expect(pushLevel([0, 0], -1)).toEqual([0, 0])
+ expect(pushLevel([0, 0], Number.NaN)).toEqual([0, 0])
+ })
+
+ it('is flat in silence and clearly up when someone speaks', () => {
+ expect(barHeight(0)).toBe(BAR_FLOOR)
+ expect(barHeight(HEARD_LEVEL / 2)).toBe(BAR_FLOOR)
+ // quiet speech already stands at more than a third of the height
+ expect(barHeight(0.1)).toBeGreaterThan(0.35)
+ expect(barHeight(0.5)).toBeGreaterThan(0.8)
+ expect(barHeight(1)).toBe(1)
+ })
+
+ it('says quiet only after a few seconds without sound', () => {
+ expect(isQuiet(1000, 1000 + QUIET_AFTER_MS - 1)).toBe(false)
+ expect(isQuiet(1000, 1000 + QUIET_AFTER_MS)).toBe(true)
+ })
+
+ it('shows the running time like a clock', () => {
+ expect(formatClock(0)).toBe('0:00')
+ expect(formatClock(7_400)).toBe('0:07')
+ expect(formatClock(750_000)).toBe('12:30')
+ expect(formatClock(3_723_000)).toBe('1:02:03')
+ })
+})
diff --git a/src/lib/mic-level.ts b/src/lib/mic-level.ts
new file mode 100644
index 00000000..099da4ca
--- /dev/null
+++ b/src/lib/mic-level.ts
@@ -0,0 +1,66 @@
+/**
+ * The live trace of the microphone while a dictation records (David,
+ * 14.11.2026): a slim waveform that moves with the voice, the running time
+ * next to it, and a quiet word when the microphone has heard nothing for a
+ * few seconds. So a long dictation shows all along that sound arrives.
+ *
+ * Pure on purpose: the level comes from `useVoiceLevel()` (an AnalyserNode on
+ * the real microphone stream, hooks/useVoice.ts), the drawing from
+ * components/voice/MicLevelTrace.tsx. Desktop, web and phone use the same
+ * numbers.
+ */
+
+/** How many readings the trace shows, oldest left, newest right. */
+export const LEVEL_HISTORY = 28
+
+/** Below this the microphone hears nothing worth showing: room noise, a fan. */
+export const HEARD_LEVEL = 0.06
+
+/** After this long without a level above HEARD_LEVEL the trace says so. */
+export const QUIET_AFTER_MS = 3000
+
+/** A bar never disappears: at silence the trace is a flat line of dots. */
+export const BAR_FLOOR = 0.08
+
+export const NO_SOUND_TEXT = 'No sound from mic'
+
+/** An empty trace: flat. */
+export function emptyHistory(size = LEVEL_HISTORY): number[] {
+ return new Array<number>(size).fill(0)
+}
+
+function clamp01(value: number): number {
+ return Math.max(0, Math.min(1, Number.isFinite(value) ? value : 0))
+}
+
+/** The trace with one more reading at the right end; the oldest one drops out. */
+export function pushLevel(history: readonly number[], level: number): number[] {
+ if (history.length === 0) return []
+ return [...history.slice(1), clamp01(level)]
+}
+
+/**
+ * The height of one bar, 0 to 1, for a level. Speech sits at 0.1 to 0.5 of
+ * the stretched level, so it is lifted with a square root; silence stays at
+ * the floor.
+ */
+export function barHeight(level: number): number {
+ const l = clamp01(level)
+ if (l < HEARD_LEVEL) return BAR_FLOOR
+ return Math.max(BAR_FLOOR, Math.min(1, Math.sqrt(l) * 1.2))
+}
+
+/** Whether the microphone has been silent long enough to say so. */
+export function isQuiet(lastHeardAt: number, now: number): boolean {
+ return now - lastHeardAt >= QUIET_AFTER_MS
+}
+
+/** Milliseconds as "0:07", "12:30" or "1:02:03". */
+export function formatClock(ms: number): string {
+ const total = Math.max(0, Math.floor(ms / 1000))
+ const h = Math.floor(total / 3600)
+ const m = Math.floor((total % 3600) / 60)
+ const s = total % 60
+ const two = (n: number) => String(n).padStart(2, '0')
+ return h > 0 ? `${h}:${two(m)}:${two(s)}` : `${m}:${two(s)}`
+}