The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(mobile): turn voice mic into a morphing capsule
tonye5ad23b78a65
diff --git a/mobile/lib/phone/terminal_action_column.dart b/mobile/lib/phone/terminal_action_column.dartindex d0cf38a9e..d037ff3d6 100644--- a/mobile/lib/phone/terminal_action_column.dart+++ b/mobile/lib/phone/terminal_action_column.dart@@ -1,4 +1,5 @@import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart' show OverflowBoxFit;import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';@@ -15,8 +16,8 @@ import 'voice_status_pill.dart';/// the mic, then Search.////// ```-/// ( Listening… × ) (🎤)-/// (🔍)+/// ( × ● ▂▃▅▇▅▃▂ 0:07 (↑) )+/// (🔍)/// ```////// ⚠️ **The mic is on top, and that is what "moved up" means.** It used to sit@@ -24,12 +25,18 @@ import 'voice_status_pill.dart';/// corner under it, and the mic rides above. The two share one column so they/// read as one set of controls rather than two strays.///+/// ⚠️ **The mic and what it is doing are one capsule.** The status body is+/// stacked UNDER the mic and reaches out to its left, with the mic's circle+/// closing its right end — see `voice_status_pill.dart`. The mic never moves:+/// the body grows away from it, and the row keeps the mic's height however+/// many lines a notice wraps to.+////// ⚠️ **The gaps are set by the mic's hit area, not by the look.** The mic's/// target spills [VoiceMicButton.touchOverhang] past its slot on every side and/// is generous on purpose — a button under it that sat any closer would lose/// the top of its own target to the mic, and a tap aimed at Search would start/// a recording.-class TerminalActionColumn extends StatelessWidget {+class TerminalActionColumn extends StatefulWidget {const TerminalActionColumn({super.key,required this.voice,@@ -67,12 +74,46 @@ class TerminalActionColumn extends StatelessWidget {static const double _underMic =_gap - (VoiceMicButton.extent - VoiceMicCore.diameter) / 2;+ /// How far the capsule's right end sits in from the mic's slot: the slack+ /// between the slot and the circle, so the circle closes the capsule exactly.+ static const double _capsuleInset =+ (VoiceMicButton.extent - VoiceMicCore.diameter) / 2;++ /// The capsule's widest, however wide the phone: a notice is easier to read+ /// in two lines of a sensible length than in one line across a tablet.+ static const double _capsuleMaxWidth = 360;++ /// What the capsule leaves clear at the terminal's left edge.+ static const double _capsuleLeftMargin = 16;++ @override+ State<TerminalActionColumn> createState() => _TerminalActionColumnState();+}++class _TerminalActionColumnState extends State<TerminalActionColumn> {+ /// Whether a hold has been dragged off the mic — [VoiceMicMode.holdToTalk]+ /// only. The mic reports it; the capsule body is what says so, where the+ /// thumb is not covering it.+ final ValueNotifier<bool> _slipped = ValueNotifier(false);++ @override+ void dispose() {+ _slipped.dispose();+ super.dispose();+ }++ /// ⚠️ Guarded by [mounted]: the mic reports its last slip from a microtask+ /// scheduled in its own `dispose`, which can land after this column is gone+ /// as well.+ void _onSlipChanged(bool value) {+ if (mounted) _slipped.value = value;+ }+@overrideWidget build(BuildContext context) {AppTheme.watch(context);- final session = this.session;// One backdrop read for the buttons' blurs — see [FloatingGlass].- return BackdropGroup(child: _column(context, session));+ return BackdropGroup(child: _column(context, widget.session));}Widget _column(BuildContext context, TerminalSession? session) {@@ -81,44 +122,76 @@ class TerminalActionColumn extends StatelessWidget {crossAxisAlignment: CrossAxisAlignment.end,children: [if (session != null)- Row(- mainAxisSize: MainAxisSize.min,- children: [- // Left of the mic, on its centreline: the words the mic has- // nowhere to put, and the `×` that calls it off.- ConstrainedBox(- constraints: BoxConstraints(- maxWidth:- (MediaQuery.sizeOf(context).width -- width -- inset * 2 -- 24)- .clamp(0, double.infinity),- ),- child: VoiceStatusPill(voice: voice),- ),- const SizedBox(width: 6),- VoiceMicFab(voice: voice, session: session),- ],- )+ _capsule(context, session)else// Still attaching: the mic in its place, dimmed and dead.const VoiceMicButton(face: VoiceMicFace.talk, onPressed: null),- const SizedBox(height: _underMic),+ const SizedBox(height: TerminalActionColumn._underMic),_centred(TerminalRoundAction(key: const ValueKey('terminal-search'),icon: LucideIcons.search300,label: 'Search harnesses and machines',- onTap: onSearch,+ onTap: widget.onSearch,),),],);}+ /// The mic, with the capsule body under it reaching out to the left.+ ///+ /// ⚠️ **Held at the mic's height.** A notice that wraps makes the body+ /// taller than the mic's slot, and a row that grew with it would lift the mic+ /// — the one control the thumb is on — every time a sentence ran long. The+ /// body overflows the row evenly above and below instead.+ Widget _capsule(BuildContext context, TerminalSession session) {+ final maxWidth =+ (MediaQuery.sizeOf(context).width -+ TerminalActionColumn.inset -+ TerminalActionColumn._capsuleInset -+ TerminalActionColumn._capsuleLeftMargin)+ .clamp(+ VoiceMicCore.diameter,+ TerminalActionColumn._capsuleMaxWidth,+ );+ return SizedBox(+ height: VoiceMicButton.extent,+ child: Stack(+ alignment: Alignment.centerRight,+ clipBehavior: Clip.none,+ children: [+ Padding(+ padding: const EdgeInsets.only(+ right: TerminalActionColumn._capsuleInset,+ ),+ child: OverflowBox(+ fit: OverflowBoxFit.deferToChild,+ maxHeight: double.infinity,+ alignment: Alignment.centerRight,+ child: ConstrainedBox(+ constraints: BoxConstraints(maxWidth: maxWidth),+ child: VoiceStatusPill(+ voice: widget.voice,+ slipped: _slipped,+ micClearance: VoiceMicCore.diameter,+ ),+ ),+ ),+ ),+ // Last, so it paints over the body's end and takes the taps there.+ VoiceMicFab(+ voice: widget.voice,+ session: session,+ onSlipChanged: _onSlipChanged,+ ),+ ],+ ),+ );+ }+Widget _centred(Widget child) => SizedBox(- width: width,+ width: TerminalActionColumn.width,child: Center(child: child),);}diff --git a/mobile/lib/phone/voice_input_controller.dart b/mobile/lib/phone/voice_input_controller.dartindex d6777fdbc..0464ad4a1 100644--- a/mobile/lib/phone/voice_input_controller.dart+++ b/mobile/lib/phone/voice_input_controller.dart@@ -116,6 +116,26 @@ class VoiceInputController extends ChangeNotifier {String get transcript => _heard;String? get notice => _notice;+ /// How loud the microphone is right now, 0…1 — what the waveform beside the+ /// mic draws while a take is recorded. Silence from a recorder that has no+ /// meter (see [VoiceLevelMeter]).+ ValueListenable<double> get level => switch (_recorder) {+ final VoiceLevelMeter meter => meter.level,+ _ => _silence,+ };++ static final ValueListenable<double> _silence = ValueNotifier(0);++ /// How long the take being recorded has run; zero before the first one.+ ///+ /// ⚠️ Kept here rather than by the widget that shows it: this controller is+ /// shared by every page of the pager, and a page swiped to mid-take has to+ /// show the take's time, not the time since that page appeared.+ Duration get takeLength => _takeClock?.elapsed ?? Duration.zero;++ /// Runs from the moment a take starts recording until it ends.+ Stopwatch? _takeClock;+/// Nothing being recorded, heard or sent — the mic at rest. A refused/// microphone is at rest too: nothing is in flight.bool get isIdle =>@@ -160,6 +180,7 @@ class VoiceInputController extends ChangeNotifier {return;}_takeLimit = Timer(maxTake, () => unawaited(stopListening()));+ _takeClock = Stopwatch()..start();_setStatus(VoiceInputStatus.listening);}@@ -296,6 +317,7 @@ class VoiceInputController extends ChangeNotifier {Future<_Take> _transcribeTake() async {final take = _take;_takeLimit?.cancel();+ _takeClock?.stop();_setStatus(VoiceInputStatus.transcribing);try {final recording = await _recorder.stop();@@ -352,6 +374,7 @@ class VoiceInputController extends ChangeNotifier {void _abandonTake() {_take++;_takeLimit?.cancel();+ _takeClock?.stop();if (_status == VoiceInputStatus.starting ||_status == VoiceInputStatus.listening) {unawaited(_recorder.cancel());diff --git a/mobile/lib/phone/voice_mic_action.dart b/mobile/lib/phone/voice_mic_action.dartindex 51e8ab722..7531e5585 100644--- a/mobile/lib/phone/voice_mic_action.dart+++ b/mobile/lib/phone/voice_mic_action.dart@@ -47,7 +47,7 @@ VoiceMicAction voiceMicAction(VoiceMicAction _tapAction(VoiceInputController voice, TerminalSession session) {final canSend = session.acceptsInput;void send() => unawaited(voice.submit(session.sendComposerText));- if (voice.isSending) return _face(VoiceMicFace.busy);+ if (voice.isSending) return _face(VoiceMicFace.sending);return switch (voice.status) {VoiceInputStatus.transcribing => _face(VoiceMicFace.busy),VoiceInputStatus.starting => _face(@@ -95,7 +95,7 @@ VoiceMicAction _holdAction(VoiceInputController voice,TerminalSession session,) {- if (voice.isSending) return _face(VoiceMicFace.busy);+ if (voice.isSending) return _face(VoiceMicFace.sending);if (voice.status == VoiceInputStatus.transcribing) {return _face(VoiceMicFace.busy);}diff --git a/mobile/lib/phone/voice_mic_button.dart b/mobile/lib/phone/voice_mic_button.dartindex 530d2ffe0..1571d61d9 100644--- a/mobile/lib/phone/voice_mic_button.dart+++ b/mobile/lib/phone/voice_mic_button.dart@@ -21,9 +21,10 @@ import 'voice_mic_mode.dart';/// the take away, and the face turns to a `×` to say so. No long-press:/// that gesture is what records.///-/// ⚠️ **The swell is painted, never laid out.** The breathing ring scales past-/// the button's box with [Clip.none] rather than growing it, so nothing around-/// the button moves while it breathes.+/// ⚠️ **It is the right end of the voice capsule, and draws nothing past its+/// circle.** What it is doing — the waveform, the words, the `×` — is in the+/// capsule body behind it (`voice_status_pill.dart`), so the button's own box+/// never grows and nothing around it moves.class VoiceMicButton extends StatefulWidget {const VoiceMicButton({super.key,@@ -115,6 +116,9 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {/// first one's take.int? _holdPointer;+ /// A finger is on the live mic, and the circle sinks a little under it.+ bool _pressed = false;+bool get _live => widget.onPressed != null;/// What to draw: the face given, unless a hold has been dragged off the@@ -123,26 +127,35 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {? VoiceMicFace.cancelling: widget.face;- bool get _lit => switch (_face) {- VoiceMicFace.starting ||- VoiceMicFace.listening ||- VoiceMicFace.cancelling ||- VoiceMicFace.retry => true,- VoiceMicFace.talk || VoiceMicFace.busy || VoiceMicFace.off => false,- };+ /// Transcribing or sending: nothing to press, but not dead either.+ ///+ /// ⚠️ Kept apart from [_live] for the drawing only. Neither face has an+ /// `onPressed`, and it is still what decides whether the button takes a+ /// press — but dimming a button that is visibly working reads as "broken",+ /// and its arc is the one thing saying the words are on their way.+ bool get _working =>+ _face == VoiceMicFace.busy || _face == VoiceMicFace.sending;++ bool get _dead => !_live && !_working;String get _semanticLabel => switch (_face) {- VoiceMicFace.talk =>+ VoiceMicFace.talk || VoiceMicFace.sent =>micHoldsToTalk ? 'Hold to talk to the harness' : 'Talk to the harness',VoiceMicFace.starting => 'Cancel',VoiceMicFace.listening =>micHoldsToTalk ? 'Release to send' : 'Done talking',VoiceMicFace.cancelling => 'Release to cancel',- VoiceMicFace.busy => 'Working',+ VoiceMicFace.busy || VoiceMicFace.sending => 'Working',VoiceMicFace.retry => 'Send again',VoiceMicFace.off => 'Voice input is off',};+ void _setPressed(bool value) {+ if (value == _pressed) return;+ _pressed = value;+ if (mounted) setState(() {});+ }+/// Whether [point], in the hit area's own coordinates, still counts as on the/// button.///@@ -162,6 +175,7 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {if (!_live || _holdPointer != null) return;_holdPointer = event.pointer;_setSlipped(false);+ _setPressed(true);HapticFeedback.lightImpact();widget.onHoldStart?.call();}@@ -181,6 +195,7 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {_holdPointer = null;final cancelled = _slippedOff;_setSlipped(false);+ _setPressed(false);widget.onHoldFinish?.call(cancelled: cancelled);}@@ -190,6 +205,7 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {if (event.pointer != _holdPointer) return;_holdPointer = null;_setSlipped(false);+ _setPressed(false);widget.onHoldFinish?.call(cancelled: true);}@@ -238,6 +254,10 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {@overridevoid didUpdateWidget(VoiceMicButton old) {super.didUpdateWidget(old);+ // Gone dead under a finger — the terminal stopped taking input mid-press.+ // The tap callbacks are dropped with it, so no tap-up will ever come to+ // raise the circle again.+ if (widget.onPressed == null && _holdPointer == null) _pressed = false;if (!micHoldsToTalk) return;if (old.face != VoiceMicFace.listening &&widget.face == VoiceMicFace.listening) {@@ -258,10 +278,6 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {// [OverflowBox] is what allows a child bigger than its parent without the// parent growing — so the row, and the terminal above it, keep their// heights while the finger gets a target half again as wide.- //- // `Clip.none` on the stack matters for the same reason: the ring already- // paints past the core, and clipping to the slot would cut both it and- // the overflowing hit area back to nothing.child: SizedBox.square(dimension: VoiceMicButton.extent,child: OverflowBox(@@ -272,17 +288,17 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {dimension: VoiceMicButton.touchExtent,child: AnimatedOpacity(duration: const Duration(milliseconds: 160),- opacity: _live ? 1 : 0.4,- child: Stack(- alignment: Alignment.center,- clipBehavior: Clip.none,- children: [- // ⚠️ Not while cancelling: the ring means "listening, carry- // on talking", and leaving it breathing under a `×` would- // say both things at once.- if (_face == VoiceMicFace.listening) const VoiceMicRing(),- VoiceMicCore(face: _face, lit: _lit),- ],+ opacity: _dead ? 0.4 : 1,+ child: Center(+ // Sinks under the finger. Not while a hold is slid off: the+ // thumb is no longer on it, and the `×` it now wears is the+ // thing to read.+ child: AnimatedScale(+ duration: const Duration(milliseconds: 140),+ curve: Curves.easeOut,+ scale: _pressed && !_slippedOff ? 0.92 : 1,+ child: VoiceMicCore(face: _face, dead: _dead),+ ),),),),@@ -308,6 +324,9 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {return GestureDetector(key: const ValueKey('voice-mic'),behavior: HitTestBehavior.opaque,+ onTapDown: _live ? (_) => _setPressed(true) : null,+ onTapUp: _live ? (_) => _setPressed(false) : null,+ onTapCancel: _live ? () => _setPressed(false) : null,onTap: _live? () {HapticFeedback.lightImpact();diff --git a/mobile/lib/phone/voice_mic_fab.dart b/mobile/lib/phone/voice_mic_fab.dartindex d0b7446eb..ada5ab8b3 100644--- a/mobile/lib/phone/voice_mic_fab.dart+++ b/mobile/lib/phone/voice_mic_fab.dart@@ -9,6 +9,7 @@ import 'voice_language_store.dart';import 'voice_input_controller.dart';import 'voice_mic_action.dart';import 'voice_mic_button.dart';+import 'voice_mic_face.dart';import 'voice_mic_mode.dart';/// The mic, floating over the terminal's bottom right corner at the top of@@ -22,8 +23,8 @@ import 'voice_mic_mode.dart';/// terminal's newest output is the line being read, and it runs left to right:/// the right end of the last few lines is the least of it.///-/// ⚠️ **The `×` is NOT here.** It is in the pill beside the mic, next to the-/// words it dismisses — see `voice_status_pill.dart`.+/// ⚠️ **The `×` is NOT here.** It is in the capsule body behind the mic, at the+/// far end from it — see `voice_status_pill.dart`.class VoiceMicFab extends StatefulWidget {const VoiceMicFab({super.key,@@ -48,26 +49,96 @@ class VoiceMicFab extends StatefulWidget {/// How far the cluster sits from the terminal's right and bottom edges.static const double inset = 8;+ /// How long a landed send wears its tick before the mic is back at rest.+ static const Duration sentHold = Duration(milliseconds: 900);+@overrideState<VoiceMicFab> createState() => _VoiceMicFabState();}-class _VoiceMicFabState extends State<VoiceMicFab> {+class _VoiceMicFabState extends State<VoiceMicFab>+ with SingleTickerProviderStateMixin {VoiceInputController get voice => widget.voice;+ /// Runs for [VoiceMicFab.sentHold] after a send lands; the tick shows while+ /// it does. A controller rather than a timer so the page settles when it ends+ /// and nothing is left pending if the page goes away first.+ late final AnimationController _sent = AnimationController(+ vsync: this,+ duration: VoiceMicFab.sentHold,+ )..addStatusListener(_onSentStatus);++ Listenable? _watched;++ /// The face at the last change — what tells a send that landed from any+ /// other way back to rest.+ VoiceMicFace? _lastFace;+@override- Widget build(BuildContext context) {- AppTheme.watch(context);- return ListenableBuilder(- listenable: Listenable.merge([voice, widget.session]),- builder: (context, _) => _mic(context),- );+ void initState() {+ super.initState();+ _watch();+ }++ @override+ void didUpdateWidget(VoiceMicFab old) {+ super.didUpdateWidget(old);+ if (old.voice != widget.voice || old.session != widget.session) {+ _unwatch();+ _watch();+ }+ }++ @override+ void dispose() {+ _unwatch();+ _sent.dispose();+ super.dispose();+ }++ void _watch() {+ final watched = Listenable.merge([widget.voice, widget.session]);+ watched.addListener(_onChange);+ _watched = watched;+ _lastFace = voiceMicAction(widget.voice, widget.session).face;+ }++ void _unwatch() {+ _watched?.removeListener(_onChange);+ _watched = null;+ }++ /// ⚠️ **The one place a landed send is seen.** The controller goes from+ /// sending straight back to rest, and rest is also where a cleared or an+ /// abandoned take ends up. Sending → rest with no notice is the only path+ /// that means the words arrived: a send that failed always leaves+ /// `VoiceNotice.notSent` behind, and keeps its words for the retry face.+ void _onChange() {+ final face = voiceMicAction(voice, widget.session).face;+ if (_lastFace == VoiceMicFace.sending &&+ face == VoiceMicFace.talk &&+ voice.notice == null) {+ _sent.forward(from: 0);+ }+ _lastFace = face;+ if (mounted) setState(() {});+ }++ void _onSentStatus(AnimationStatus status) {+ if (status == AnimationStatus.completed && mounted) setState(() {});}- Widget _mic(BuildContext context) {+ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);final action = voiceMicAction(voice, widget.session);+ // Over [VoiceMicFace.talk] only: a take started during the tick is the+ // take to show, and nothing else may be hidden behind it.+ final face = action.face == VoiceMicFace.talk && _sent.isAnimating+ ? VoiceMicFace.sent+ : action.face;return VoiceMicButton(- face: action.face,+ face: face,onPressed: action.onPressed,// ⚠️ No language shortcut in hold-to-talk: press-and-hold is what records// there, and a picker opening out of a held mic would fire in the middlediff --git a/mobile/lib/phone/voice_mic_face.dart b/mobile/lib/phone/voice_mic_face.dartindex 6c42ccb09..8ce03ed28 100644--- a/mobile/lib/phone/voice_mic_face.dart+++ b/mobile/lib/phone/voice_mic_face.dart@@ -1,8 +1,9 @@+import 'dart:math' as math;+import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';-import 'package:harness_mobile/shared/widgets/pulse.dart';import 'floating_glass.dart';import 'voice_mic_mode.dart';@@ -15,13 +16,26 @@ enum VoiceMicFace {/// The microphone is opening: tap to call it off.starting,- /// Recording: tap Send, and what was said is sent. It breathes while it- /// listens.+ /// Recording: tap, and what was said is sent. The waveform in the capsule+ /// beside it is what shows it listening — see `voice_take_meter.dart`.listening,- /// Transcribing or sending: nothing to tap until that is back.+ /// Transcribing: nothing to tap until the words are back.busy,+ /// The words are on their way to the terminal: nothing to tap until that is+ /// back.+ sending,++ /// A send just landed: a tick where the arrow was, for a moment, before the+ /// mic is back at rest.+ ///+ /// ⚠️ **Never produced by `voiceMicAction`.** Nothing in the controller says+ /// "sent" — it goes from sending straight back to rest — so [VoiceMicFab]+ /// lays this over [talk] when it sees that happen, and it taps exactly like+ /// [talk], because that is what it is.+ sent,+/// A send failed and its words are held: tap to send them again.retry,@@ -32,153 +46,485 @@ enum VoiceMicFace {/// the take away. [VoiceMicMode.holdToTalk] only.////// Its own face rather than a flag on [listening] because it is the opposite- /// promise: the ring stops breathing, the fill goes to the warning colour and- /// the glyph becomes a `×`. What is about to happen has to be readable at a- /// glance, by someone whose thumb is covering the button.+ /// promise: the fill goes to the warning colour and the glyph becomes a `×`.+ /// What is about to happen has to be readable at a glance, by someone whose+ /// thumb is covering the button.cancelling,}-/// The mic's fill for [face].-///-/// Cancelling takes the warning colour: the button is about to throw away what-/// was just said, and that is not something the accent — which everywhere else-/// in the app means "go" — should be saying.-///-/// Listening is the accent's blue: the next tap sends.-Color voiceMicTint(VoiceMicFace face) => switch (face) {- VoiceMicFace.cancelling => AppPalette.warn,- _ => AppPalette.accent,+/// What the circle is filled with.+enum _Fill {+ /// The accent: the mic at rest, and everything it can be tapped to do. The+ /// mic is the page's one action, and it is filled like one.+ accent,++ /// The floating buttons' frosted glass: nothing this mic can do right now —+ /// dead, refused, or waiting on the transcription.+ glass,++ /// Letting go throws the take away, and that is not something the accent —+ /// which everywhere else in the app means "go" — should be saying.+ warn,+}++_Fill _fillFor(VoiceMicFace face, {required bool dead}) {+ if (dead) return _Fill.glass;+ return switch (face) {+ VoiceMicFace.cancelling => _Fill.warn,+ VoiceMicFace.busy || VoiceMicFace.off => _Fill.glass,+ VoiceMicFace.talk ||+ VoiceMicFace.starting ||+ VoiceMicFace.listening ||+ VoiceMicFace.sending ||+ VoiceMicFace.sent ||+ VoiceMicFace.retry => _Fill.accent,+ };+}++/// The glyph for what a press will do.+enum _Glyph { mic, micOff, send, cancel, check, dots }++_Glyph _glyphFor(VoiceMicFace face) => switch (face) {+ VoiceMicFace.talk || VoiceMicFace.starting => _Glyph.mic,+ // ⚠️ The arrow only in the tap mode, where the next tap IS the send — the+ // fill no longer says so, because the mic is filled at rest too. In+ // hold-to-talk the arrow would be a lie: nothing is sent by pressing, it is+ // sent by letting go, and the thumb never leaves the button to press again.+ VoiceMicFace.listening => micHoldsToTalk ? _Glyph.mic : _Glyph.send,+ VoiceMicFace.busy => _Glyph.dots,+ VoiceMicFace.sending || VoiceMicFace.retry => _Glyph.send,+ VoiceMicFace.sent => _Glyph.check,+ VoiceMicFace.off => _Glyph.micOff,+ VoiceMicFace.cancelling => _Glyph.cancel,};+/// Whether the arc runs round the inside of the circle: something is under+/// way that the person is waiting on.+bool _spins(VoiceMicFace face) =>+ face == VoiceMicFace.starting ||+ face == VoiceMicFace.busy ||+ face == VoiceMicFace.sending;+/// The round, filled part of the mic: its colour, its glow, and the glyph for/// what a press will do.class VoiceMicCore extends StatelessWidget {- const VoiceMicCore({super.key, required this.face, required this.lit});+ const VoiceMicCore({super.key, required this.face, required this.dead});- /// The visible circle's diameter — the ring breathes out from the same size.- static const double diameter = 48;+ /// The visible circle's diameter — and the voice capsule's height, so the+ /// circle closes the capsule's right end. See `voice_status_pill.dart`.+ static const double diameter = 52;final VoiceMicFace face;- final bool lit;- Color get _tint => voiceMicTint(face);+ /// Drawn as a button that cannot be pressed: frosted, not filled.+ final bool dead;++ static const Duration _morph = Duration(milliseconds: 300);@override- Widget build(BuildContext context) => FloatingGlass(child: _circle());+ Widget build(BuildContext context) {+ final motion = !MediaQuery.disableAnimationsOf(context);+ final fill = _fillFor(face, dead: dead);+ final ink = _inkFor(fill);+ final glyph = _glyphFor(face);+ return FloatingGlass(+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 240),+ curve: Curves.easeOutCubic,+ width: diameter,+ height: diameter,+ decoration: _decoration(fill),+ child: Stack(+ alignment: Alignment.center,+ clipBehavior: Clip.none,+ children: [+ AnimatedOpacity(+ duration: const Duration(milliseconds: 200),+ opacity: _spins(face) ? 1 : 0,+ child: _BusyArc(+ color: fill == _Fill.accent+ ? Colors.white.withValues(alpha: 0.9)+ : AppPalette.accentOnSurface,+ spin: motion && _spins(face),+ ),+ ),+ AnimatedSwitcher(+ duration: motion ? _morph : const Duration(milliseconds: 120),+ transitionBuilder: motion+ ? _morphIn+ : AnimatedSwitcher.defaultTransitionBuilder,+ child: KeyedSubtree(+ key: ValueKey(glyph),+ child: _glyph(+ glyph,+ ink,+ bob: motion && face == VoiceMicFace.sending,+ motion: motion,+ ),+ ),+ ),+ // On the rim, top right — where a badge sits on any icon.+ Positioned(+ top: 1,+ right: 1,+ child: _HeldBadge(shown: face == VoiceMicFace.retry),+ ),+ ],+ ),+ ),+ );+ }- Widget _circle() => AnimatedContainer(- duration: const Duration(milliseconds: 220),- curve: Curves.easeOutCubic,- width: VoiceMicCore.diameter,- height: VoiceMicCore.diameter,- decoration: BoxDecoration(+ Color _inkFor(_Fill fill) => switch (fill) {+ _Fill.accent => Colors.white,+ // White on the dark theme's bright amber is 2:1; dark ink there, white on+ // the light theme's deep one.+ _Fill.warn => AppTheme.pick(Colors.white, const Color(0xFF241800)),+ _Fill.glass =>+ face == VoiceMicFace.off+ ? AppPalette.textFaint+ : face == VoiceMicFace.busy+ ? AppPalette.accentOnSurface+ : AppPalette.textPrimary,+ };++ /// ⚠️ **Two different shadows for two different jobs, and the frosted one+ /// is not optional.** Filled, the button glows in its own colour. Frosted, it+ /// casts a plain drop shadow instead: it floats over streaming output rather+ /// than over a surface, and without one its edge disappears against every+ /// dark line it happens to sit on.+ BoxDecoration _decoration(_Fill fill) {+ if (fill == _Fill.glass) {+ return BoxDecoration(+ shape: BoxShape.circle,+ color: floatingButtonFill,+ border: Border.all(color: floatingButtonRim),+ // ⚠️ Kept light: a box shadow paints under the WHOLE circle, and the+ // fill is not opaque — a heavy one showed through as a dark disc.+ boxShadow: floatingButtonShadow,+ );+ }+ final tint = fill == _Fill.warn ? AppPalette.warn : AppPalette.accent;+ return BoxDecoration(shape: BoxShape.circle,- gradient: lit- ? LinearGradient(- begin: Alignment.topLeft,- end: Alignment.bottomRight,- colors: [Color.lerp(_tint, Colors.white, 0.18)!, _tint],- )- : null,- color: lit ? null : floatingButtonFill,- border: Border.all(- color: lit ? Colors.white.withValues(alpha: 0.28) : floatingButtonRim,+ gradient: LinearGradient(+ begin: Alignment.topLeft,+ end: Alignment.bottomRight,+ colors: [Color.lerp(tint, Colors.white, 0.18)!, tint],),- // ⚠️ **Two different shadows for two different jobs, and the resting one- // is not optional.** Lit, the button glows in its own colour — that is- // state, saying the mic is open. At rest it casts a plain drop shadow- // instead: it floats over streaming output rather than over a surface, and- // without one its edge disappears against every dark line it happens to- // sit on. The screenshot that prompted this had it all but invisible.- boxShadow: lit- ? [- BoxShadow(color: _tint.withValues(alpha: 0.4), blurRadius: 12),- // The lift, under the glow. The glow says "recording"; it does- // not separate the circle from the text behind it, because it is- // the same brightness as the accent the terminal itself uses.- BoxShadow(- color: Colors.black.withValues(alpha: 0.35),- blurRadius: 10,- offset: const Offset(0, 3),- ),- ]- // ⚠️ Kept light: a box shadow paints under the WHOLE circle, and- // the fill is not opaque — a heavy one showed through as a dark disc.- : floatingButtonShadow,- ),- child: Center(- child: AnimatedSwitcher(- duration: const Duration(milliseconds: 160),- child: _Glyph(key: ValueKey(face), face: face, lit: lit),+ border: Border.all(color: Colors.white.withValues(alpha: 0.28)),+ boxShadow: [+ BoxShadow(color: tint.withValues(alpha: 0.4), blurRadius: 12),+ // The lift, under the glow. The glow does not separate the circle from+ // the text behind it: it is the same brightness as the accent the+ // terminal itself uses.+ BoxShadow(+ color: Colors.black.withValues(alpha: 0.35),+ blurRadius: 10,+ offset: const Offset(0, 3),+ ),+ ],+ );+ }++ static Widget _glyph(+ _Glyph glyph,+ Color ink, {+ required bool bob,+ required bool motion,+ }) {+ Icon icon(IconData data) => Icon(data, size: 25, color: ink);+ return switch (glyph) {+ _Glyph.mic => icon(LucideIcons.mic300),+ _Glyph.micOff => icon(LucideIcons.micOff300),+ _Glyph.send => _Bob(active: bob, child: icon(LucideIcons.arrowUp300)),+ _Glyph.cancel => icon(LucideIcons.x300),+ _Glyph.check => icon(LucideIcons.check300),+ _Glyph.dots => _Dots(color: ink, animate: motion),+ };+ }++ /// One glyph turns into the next: the old one shrinks away and the new one+ /// swings up out of it, a little past full size. The press changes what the+ /// button means, and the change is meant to be seen.+ static Widget _morphIn(Widget child, Animation<double> animation) {+ final spring = CurvedAnimation(+ parent: animation,+ curve: Curves.easeOutBack,+ );+ return FadeTransition(+ opacity: CurvedAnimation(parent: animation, curve: Curves.easeOut),+ child: RotationTransition(+ turns: Tween<double>(begin: -40 / 360, end: 0).animate(spring),+ child: ScaleTransition(+ scale: Tween<double>(begin: 0.5, end: 1).animate(spring),+ child: child,+ ),+ ),+ );+ }+}++/// A short arc running round the inside of the circle while the mic is+/// opening, transcribing or sending.+///+/// ⚠️ Held still, not hidden, under Reduce Motion: the arc still says "under+/// way"; it only stops going round.+class _BusyArc extends StatefulWidget {+ const _BusyArc({required this.color, required this.spin});++ final Color color;+ final bool spin;++ @override+ State<_BusyArc> createState() => _BusyArcState();+}++class _BusyArcState extends State<_BusyArc>+ with SingleTickerProviderStateMixin {+ late final AnimationController _turn = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 900),+ );++ @override+ void initState() {+ super.initState();+ _sync();+ }++ @override+ void didUpdateWidget(_BusyArc old) {+ super.didUpdateWidget(old);+ _sync();+ }++ /// ⚠️ Stopped whenever it is not showing. It is always in the tree — so it+ /// can fade rather than blink — and a controller left repeating under an+ /// invisible arc would keep the page drawing frames for nothing.+ void _sync() {+ if (!widget.spin) {+ _turn.stop();+ } else if (!_turn.isAnimating) {+ _turn.repeat();+ }+ }++ @override+ void dispose() {+ _turn.dispose();+ super.dispose();+ }++ // The boundary keeps the turning arc off the glass: without it every frame+ // would repaint the backdrop blur under the whole button.+ @override+ Widget build(BuildContext context) => RepaintBoundary(+ child: RotationTransition(+ turns: _turn,+ child: CustomPaint(+ size: const Size.square(44),+ painter: _ArcPainter(widget.color),),),);}-class _Glyph extends StatelessWidget {- const _Glyph({super.key, required this.face, required this.lit});+class _ArcPainter extends CustomPainter {+ const _ArcPainter(this.color);- final VoiceMicFace face;- final bool lit;+ final Color color;++ static const double _stroke = 2.25;++ /// A quarter of the way round, and a little over.+ static const double _sweep = math.pi * 2 * 0.26;@override- Widget build(BuildContext context) {- if (face == VoiceMicFace.busy) {- return SizedBox.square(- dimension: 21,- child: CircularProgressIndicator(- strokeWidth: 2.4,- color: AppPalette.accent,- ),- );- }- return Icon(- switch (face) {- // ⚠️ In hold-to-talk the arrow would be a lie: nothing is sent by- // pressing this, it is sent by letting go. The mic stays up for the- // whole take and the thumb never leaves it, so there is no second press- // for an arrow to describe.- //- // The mic stays the glyph while it listens; the blue fill is what- // says the next tap sends — see [voiceMicTint].- VoiceMicFace.listening => LucideIcons.mic300,- VoiceMicFace.retry => LucideIcons.arrowUp300,- VoiceMicFace.cancelling => LucideIcons.x300,- VoiceMicFace.off => LucideIcons.micOff300,- VoiceMicFace.talk ||- VoiceMicFace.starting ||- VoiceMicFace.busy => LucideIcons.mic300,- },- size: 25,- color: lit- ? Colors.white- : face == VoiceMicFace.off- ? AppPalette.textFaint- : AppPalette.textPrimary,+ void paint(Canvas canvas, Size size) {+ canvas.drawArc(+ (Offset.zero & size).deflate(_stroke / 2),+ -math.pi / 2,+ _sweep,+ false,+ Paint()+ ..color = color+ ..style = PaintingStyle.stroke+ ..strokeWidth = _stroke+ ..strokeCap = StrokeCap.round,);}++ @override+ bool shouldRepaint(_ArcPainter old) => old.color != color;}-/// The glow that swells out of the button while it listens, on the app's one-/// [Pulse] — which is also what holds it still under Reduce Motion.-class VoiceMicRing extends StatelessWidget {- const VoiceMicRing({super.key});+/// Three dots rising in turn: the words are being worked out.+class _Dots extends StatefulWidget {+ const _Dots({required this.color, required this.animate});++ final Color color;+ final bool animate;@override- Widget build(BuildContext context) => Pulse(- duration: const Duration(milliseconds: 900),- curve: Curves.easeOut,- builder: (context, t, _) => Transform.scale(- scale: 1 + 0.45 * t,- child: Container(- width: VoiceMicCore.diameter,- height: VoiceMicCore.diameter,- decoration: BoxDecoration(- shape: BoxShape.circle,- color: voiceMicTint(VoiceMicFace.listening)- .withValues(alpha: 0.35 * (1 - t)),+ State<_Dots> createState() => _DotsState();+}++class _DotsState extends State<_Dots> with SingleTickerProviderStateMixin {+ late final AnimationController _beat = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 1100),+ );++ static const double _dot = 5;+ static const double _gap = 4;++ @override+ void initState() {+ super.initState();+ _sync();+ }++ @override+ void didUpdateWidget(_Dots old) {+ super.didUpdateWidget(old);+ _sync();+ }++ void _sync() {+ if (!widget.animate) {+ _beat.stop();+ } else if (!_beat.isAnimating) {+ _beat.repeat();+ }+ }++ @override+ void dispose() {+ _beat.dispose();+ super.dispose();+ }++ /// How far up a dot is at [phase] of its beat: up and down in the first+ /// four fifths, then resting until the next.+ static double _rise(double phase) =>+ phase < 0.8 ? math.sin(math.pi * phase / 0.8) : 0;++ @override+ Widget build(BuildContext context) => RepaintBoundary(+ child: AnimatedBuilder(+ animation: _beat,+ builder: (context, _) => Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ for (var i = 0; i < 3; i++) ...[+ if (i > 0) const SizedBox(width: _gap),+ _dotAt(widget.animate ? _rise((_beat.value - i * 0.14) % 1.0) : 1),+ ],+ ],+ ),+ ),+ );++ Widget _dotAt(double rise) => Transform.translate(+ offset: Offset(0, widget.animate ? -4 * rise : 0),+ child: Container(+ width: _dot,+ height: _dot,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: widget.color.withValues(+ alpha: widget.color.a * (0.45 + 0.55 * rise),),),),);}++/// The send arrow, nudging upward while the words are on their way.+class _Bob extends StatefulWidget {+ const _Bob({required this.active, required this.child});++ final bool active;+ final Widget child;++ @override+ State<_Bob> createState() => _BobState();+}++class _BobState extends State<_Bob> with SingleTickerProviderStateMixin {+ late final AnimationController _lift = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 450),+ );+ late final Animation<double> _eased = CurvedAnimation(+ parent: _lift,+ curve: Curves.easeInOut,+ );++ @override+ void initState() {+ super.initState();+ _sync();+ }++ @override+ void didUpdateWidget(_Bob old) {+ super.didUpdateWidget(old);+ _sync();+ }++ void _sync() {+ if (!widget.active) {+ _lift+ ..stop()+ ..value = 0;+ } else if (!_lift.isAnimating) {+ _lift.repeat(reverse: true);+ }+ }++ @override+ void dispose() {+ _lift.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => AnimatedBuilder(+ animation: _eased,+ child: widget.child,+ builder: (context, child) => Transform.translate(+ offset: Offset(0, widget.active ? 1 - 4 * _eased.value : 0),+ child: child,+ ),+ );+}++/// The amber dot on the rim of the retry face: the last send did not land and+/// its words are still here.+class _HeldBadge extends StatelessWidget {+ const _HeldBadge({required this.shown});++ final bool shown;++ static const double size = 13;++ @override+ Widget build(BuildContext context) => AnimatedScale(+ duration: const Duration(milliseconds: 300),+ curve: shown ? Curves.easeOutBack : Curves.easeIn,+ scale: shown ? 1 : 0,+ child: Container(+ width: size,+ height: size,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: AppPalette.warn,+ // A ring the terminal's own near-black, so the dot reads as sitting+ // ON the rim rather than as a stain on the fill.+ border: Border.all(color: const Color(0xFF141414), width: 2),+ ),+ ),+ );+}diff --git a/mobile/lib/phone/voice_recorder.dart b/mobile/lib/phone/voice_recorder.dartindex 66bfa1829..7deabf9b7 100644--- a/mobile/lib/phone/voice_recorder.dart+++ b/mobile/lib/phone/voice_recorder.dart@@ -1,6 +1,7 @@import 'dart:async';import 'dart:typed_data';+import 'package:flutter/foundation.dart';import 'package:record/record.dart';import 'voice_wav.dart';@@ -32,12 +33,24 @@ abstract interface class VoiceRecorder {Future<void> dispose();}+/// A [VoiceRecorder] that can also say how loud the microphone is right now.+///+/// ⚠️ **Its own interface rather than a member of [VoiceRecorder].** The level+/// only feeds the waveform beside the mic; a recorder with nothing to measure —+/// a test's fake — should not have to invent one, and+/// `VoiceInputController.level` reads silence from it instead.+abstract interface class VoiceLevelMeter {+ /// The loudness of the latest buffer the microphone delivered, 0…1 — see+ /// `pcm16Level`. Back to 0 whenever no take is being recorded.+ ValueListenable<double> get level;+}+/// [VoiceRecorder] over the phone's microphone.////// Streams raw PCM and wraps it here, rather than recording a file: a file/// needs somewhere to live and something to delete it, and a phrase of speech/// is a few hundred kilobytes that are about to be uploaded anyway.-class MicVoiceRecorder implements VoiceRecorder {+class MicVoiceRecorder implements VoiceRecorder, VoiceLevelMeter {/// What the backend's transcription is tuned on — the dial sends 8–16 kHz/// mono — and a minute of it is under 2 MB to upload.static const _requested = RecordConfig(@@ -76,6 +89,16 @@ class MicVoiceRecorder implements VoiceRecorder {/// already in hand.static const _drainLimit = Duration(seconds: 2);+ /// ⚠️ **Never disposed, on purpose.** The waveform listens to it from the+ /// widget tree, and this recorder is torn down from the controller's own+ /// `dispose` — which can run before the widgets listening here have let go.+ /// A notifier holds no platform resource; dropping it with the recorder is+ /// enough.+ final ValueNotifier<double> _level = ValueNotifier(0);++ @override+ ValueListenable<double> get level => _level;+@overrideFuture<bool> allowed() => _recorder.hasPermission();@@ -119,7 +142,13 @@ class MicVoiceRecorder implements VoiceRecorder {if (!drained.isCompleted) drained.complete();}- _subscription = stream.listen(_pcm.add, onDone: finish, onError: finish);+ _subscription = stream.listen(_onBuffer, onDone: finish, onError: finish);+ }++ /// Keeps the buffer for the take, and reports how loud it was.+ void _onBuffer(Uint8List buffer) {+ _pcm.add(buffer);+ _level.value = pcm16Level(buffer);}@override@@ -150,6 +179,7 @@ class MicVoiceRecorder implements VoiceRecorder {await _subscription?.cancel();_subscription = null;_drained = null;+ _level.value = 0;final pcm = _pcm.takeBytes();if (pcm.isEmpty) return null;final samples = pcm.length ~/ (2 * _channels);@@ -210,5 +240,6 @@ class MicVoiceRecorder implements VoiceRecorder {_subscription = null;_drained = null;_pcm.clear();+ _level.value = 0;}}diff --git a/mobile/lib/phone/voice_status_pill.dart b/mobile/lib/phone/voice_status_pill.dartindex fe33cfec3..3564d0615 100644--- a/mobile/lib/phone/voice_status_pill.dart+++ b/mobile/lib/phone/voice_status_pill.dart@@ -1,140 +1,740 @@+import 'dart:math' as math;++import 'package:flutter/foundation.dart';import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/widgets/pulse.dart';import 'voice_input_controller.dart';import 'voice_mic_action.dart';+import 'voice_mic_face.dart';+import 'voice_mic_mode.dart';+import 'voice_take_meter.dart';-/// What the mic is doing, in words, floating beside it — with the `×` that-/// calls it off.+/// The body of the voice capsule: what the mic is doing, and the `×` that calls+/// it off.////// ```-/// ( Listening… tap to send × ) (🎤)+/// ( × ● ▂▃▅▇▅▃▂▁▃▆ 0:07 (↑) ) listening+/// ( × Transcribing… (•••) )+/// ( × ⓘ Didn't catch that. Tap (🎤) )+/// ( the mic to try again. )/// ```///+/// ⚠️ **It sits BEHIND the mic, and the mic closes its right end.** The column+/// stacks the mic over this body's last [micClearance] points, so the two read+/// as one control that changes shape — growing out from behind the button to+/// say what it is doing, and tucking back behind it when there is nothing to+/// say. The `×` is at the far end, away from the thumb that works the mic.+////// The `×` is the way out of every step: while the mic is opening, recording/// or transcribing it throws the take away, with words held from a failed send/// it drops them, and with a notice up it dismisses it.///-/// ⚠️ **Nothing at rest.** The pill exists only while there is something to-/// read; a label that stayed would sit over the terminal's newest lines.-class VoiceStatusPill extends StatelessWidget {- const VoiceStatusPill({super.key, required this.voice});+/// ⚠️ **Nothing at rest.** The body exists only while there is something to+/// read; one that stayed would sit over the terminal's newest lines.+///+/// ⚠️ **Tucking in and out is PAINTED, never laid out.** The body takes its+/// full size on the first frame and only its drawing grows from behind the+/// mic — see [_CapsuleReveal]. Laid out, the `×` would spend the first frames+/// of every take with no width to be pressed in; changes of content once it is+/// out are laid out ([AnimatedSize]), since by then the `×` is already there.+class VoiceStatusPill extends StatefulWidget {+ const VoiceStatusPill({+ super.key,+ required this.voice,+ this.slipped,+ this.micClearance = 0,+ });final VoiceInputController voice;- /// The pill's height: the mic's visible circle, less a little, so the two- /// read as one control rather than two of a size.- static const double height = 36;+ /// Whether a hold has been dragged off the mic, as the mic reports it —+ /// [VoiceMicMode.holdToTalk] only. The thumb covers the button's own `×`+ /// face, so this body is what says letting go will now cancel. Null where+ /// nothing reports it.+ final ValueListenable<bool>? slipped;++ /// How much of the body's right end the mic sits over. Zero for a body that+ /// stands on its own.+ final double micClearance;++ /// The body's least height: the mic's circle, so the circle closes its end.+ static const double height = VoiceMicCore.diameter;@override- Widget build(BuildContext context) {- AppTheme.watch(context);- return ListenableBuilder(- listenable: voice,- builder: (context, _) {- final notice = voice.notice;- final label =- notice ??- voiceActivityLabel(voice) ??- (voice.transcript.isNotEmpty ? 'Tap ↑ to send again' : null);- return AnimatedSwitcher(- duration: const Duration(milliseconds: 180),- transitionBuilder: (child, animation) =>- FadeTransition(opacity: animation, child: child),- layoutBuilder: (current, previous) => Stack(- alignment: Alignment.centerRight,- children: [...previous, ?current],- ),- child: label == null- ? const SizedBox.shrink(key: ValueKey('voice-pill-none'))- : _Pill(- key: const ValueKey('voice-pill'),- label: label,- warn: notice != null,- // A send already on its way cannot be recalled, so no `×`- // offers to.- onCancel: voice.isSending ? null : voice.clear,- ),- );- },- );- }+ State<VoiceStatusPill> createState() => _VoiceStatusPillState();}-class _Pill extends StatelessWidget {- const _Pill({- super.key,- required this.label,- required this.warn,- required this.onCancel,+/// What the body is saying, one of a handful of shapes.+enum _Kind {+ starting,+ listening,+ transcribing,+ sending,+ retry,+ notice,+ cancelling,+}++@immutable+class _Status {+ const _Status(+ this.kind,+ this.label, {+ required this.cancellable,+ this.lingers = false,});+ final _Kind kind;++ /// The words — shown, or given to the screen reader where the body draws+ /// something else (the take meter).final String label;- /// A notice — something that went wrong — rather than what the mic is doing.- final bool warn;+ /// Whether the `×` is offered. Not while sending — a send already on its way+ /// cannot be recalled — nor with a hold slid off, where letting go is itself+ /// the cancel.+ final bool cancellable;- final VoidCallback? onCancel;+ /// A notice that clears itself after [VoiceInputController.noticeLinger],+ /// and so draws the time it has left.+ final bool lingers;+}++class _VoiceStatusPillState extends State<VoiceStatusPill>+ with SingleTickerProviderStateMixin {+ /// Fast out, long settle: the body reaches most of its size quickly and eases+ /// into the rest, so it reads as springing out rather than being dragged.+ static const Curve _morph = Cubic(0.3, 0.9, 0.25, 1);+ static const Duration _spreadDuration = Duration(milliseconds: 340);++ static final List<BoxShadow> _shadow = [+ // It floats over streaming output, like the mic, and needs the same lift+ // to keep its edge over a bright line.+ BoxShadow(+ color: Colors.black.withValues(alpha: 0.35),+ blurRadius: 10,+ offset: const Offset(0, 2),+ ),+ ];++ /// 0 tucked behind the mic, 1 all the way out.+ late final AnimationController _reveal = AnimationController(+ vsync: this,+ duration: _spreadDuration,+ )..addStatusListener(_onRevealStatus);++ late final Animation<double> _spread = CurvedAnimation(+ parent: _reveal,+ curve: _morph,+ reverseCurve: Curves.easeInCubic,+ );++ /// Visible early on the way out, and gone only at the very end of the way+ /// back — by then the body is behind the mic anyway.+ late final Animation<double> _fade = CurvedAnimation(+ parent: _reveal,+ curve: const Interval(0, 0.35),+ );++ /// What the voice says right now.+ _Status? _status;++ /// What is drawn: [_status], held while the body tucks away after it has+ /// gone null, so it leaves with what it said rather than blank.+ _Status? _shown;++ String? _lastNotice;++ /// Counts the notices that have landed. Replays the nudge and restarts the+ /// countdown when a new one arrives on top of whatever was showing.+ int _noticeRun = 0;++ bool _motion = true;++ @override+ void initState() {+ super.initState();+ _subscribe(widget);+ _status = _read();+ _shown = _status;+ // Already out when it mounts mid-take — a page swiped to while talking —+ // rather than springing out as though it had just begun.+ _reveal.value = _status == null ? 0 : 1;+ }++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _motion = !MediaQuery.disableAnimationsOf(context);+ }++ @override+ void didUpdateWidget(VoiceStatusPill old) {+ super.didUpdateWidget(old);+ if (old.voice != widget.voice || old.slipped != widget.slipped) {+ _unsubscribe(old);+ _subscribe(widget);+ _apply(_read());+ }+ }++ @override+ void dispose() {+ _unsubscribe(widget);+ _reveal.dispose();+ super.dispose();+ }++ void _subscribe(VoiceStatusPill pill) {+ pill.voice.addListener(_sync);+ pill.slipped?.addListener(_sync);+ }++ void _unsubscribe(VoiceStatusPill pill) {+ pill.voice.removeListener(_sync);+ pill.slipped?.removeListener(_sync);+ }++ void _sync() {+ if (!mounted) return;+ setState(() => _apply(_read()));+ }++ /// Shows [next], or tucks the body away behind the mic when there is nothing+ /// to say.+ void _apply(_Status? next) {+ _status = next;+ if (next != null) {+ _shown = next;+ if (_motion) {+ _reveal.forward();+ } else {+ _reveal.value = 1;+ }+ return;+ }+ // Nothing out to tuck away, or no motion to tuck it with: gone at once.+ // [_shown] is cleared FIRST, so the dismissal this causes has nothing left+ // for [_onRevealStatus] to do — this can run inside `didUpdateWidget`,+ // where a `setState` would be one too many.+ if (!_motion || _reveal.value == 0) {+ _shown = null;+ _reveal.value = 0;+ return;+ }+ _reveal.reverse();+ }++ void _onRevealStatus(AnimationStatus status) {+ if (status != AnimationStatus.dismissed ||+ _status != null ||+ _shown == null ||+ !mounted) {+ return;+ }+ setState(() => _shown = null);+ }++ /// What the voice is doing, in the order the old single-line pill read it:+ /// a notice over everything, then what the mic is doing, then words held+ /// from a send that did not land.+ _Status? _read() {+ final voice = widget.voice;+ final notice = voice.notice;+ if (notice != _lastNotice) {+ _lastNotice = notice;+ if (notice != null) _noticeRun++;+ }+ final cancellable = !voice.isSending;+ if (notice != null) {+ return _Status(+ _Kind.notice,+ notice,+ cancellable: cancellable,+ // ⚠️ Not the refused microphone's: that one stays until it is+ // dismissed (see `VoiceInputController._restartNoticeTimer`), and a+ // countdown under it would promise it goes away.+ lingers: voice.status != VoiceInputStatus.unavailable,+ );+ }+ if (voice.status == VoiceInputStatus.listening &&+ (widget.slipped?.value ?? false)) {+ return const _Status(+ _Kind.cancelling,+ 'Release to cancel',+ cancellable: false,+ );+ }+ final activity = voiceActivityLabel(voice);+ final kind = voice.isSending+ ? _Kind.sending+ : switch (voice.status) {+ VoiceInputStatus.starting => _Kind.starting,+ VoiceInputStatus.listening => _Kind.listening,+ VoiceInputStatus.transcribing => _Kind.transcribing,+ VoiceInputStatus.idle || VoiceInputStatus.unavailable => null,+ };+ if (kind != null && activity != null) {+ return _Status(kind, activity, cancellable: cancellable);+ }+ if (voice.transcript.isNotEmpty) {+ return _Status(+ _Kind.retry,+ 'Tap ↑ to send again',+ cancellable: cancellable,+ );+ }+ return null;+ }@overrideWidget build(BuildContext context) {AppTheme.watch(context);- final onCancel = this.onCancel;- return Container(- height: VoiceStatusPill.height,- padding: EdgeInsets.only(left: 14, right: onCancel == null ? 14 : 2),- decoration: BoxDecoration(- color: AppGlass.surfaceFill,- borderRadius: BorderRadius.circular(VoiceStatusPill.height / 2),- border: Border.all(color: AppGlass.lift),- // It floats over streaming output, like the buttons beside it, and- // needs the same lift to keep its edge over a bright line.- boxShadow: [- BoxShadow(- color: Colors.black.withValues(alpha: 0.35),- blurRadius: 10,- offset: const Offset(0, 2),+ final shown = _shown;+ if (shown == null) return const SizedBox.shrink();+ final warn = shown.kind == _Kind.notice || shown.kind == _Kind.cancelling;+ return IgnorePointer(+ // Tucking away: what is still drawn is what WAS, and a `×` pressed on it+ // would clear a state that no longer exists.+ ignoring: _status == null,+ child: _Nudge(+ run: _noticeRun,+ enabled: _motion,+ child: FadeTransition(+ opacity: _fade,+ child: _CapsuleReveal(+ reveal: _spread,+ tucked: widget.micClearance > 0+ ? widget.micClearance+ : VoiceStatusPill.height,+ fill: shown.kind == _Kind.cancelling+ ? Color.alphaBlend(+ AppPalette.warn.withValues(alpha: 0.16),+ AppGlass.surfaceFill,+ )+ : AppGlass.surfaceFill,+ rim: warn ? AppPalette.warn.withValues(alpha: 0.42) : AppGlass.lift,+ shadows: _shadow,+ child: AnimatedSize(+ duration: _motion ? _spreadDuration : Duration.zero,+ curve: _morph,+ alignment: Alignment.centerLeft,+ child: _body(shown),+ ),),- ],+ ),),- child: Row(- mainAxisSize: MainAxisSize.min,+ );+ }++ Widget _body(_Status shown) {+ // The room the mic covers, and a gap before it.+ final trailing = widget.micClearance + 12;+ return ConstrainedBox(+ constraints: const BoxConstraints(minHeight: VoiceStatusPill.height),+ child: Stack(+ alignment: AlignmentDirectional.centerStart,children: [- Flexible(- child: Text(- label,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: TextStyle(- fontSize: 12.5,- fontWeight: FontWeight.w500,- color: warn ? AppPalette.warn : AppPalette.accentOnSurface,- ),- ),- ),- if (onCancel != null)- Semantics(- button: true,- label: 'Cancel',- child: GestureDetector(- key: const ValueKey('voice-cancel'),- behavior: HitTestBehavior.opaque,- onTap: onCancel,- child: SizedBox(- width: 34,- height: VoiceStatusPill.height,- child: Icon(- LucideIcons.x300,- size: 16,- color: AppPalette.textSecondary,+ Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (shown.cancellable)+ _CancelButton(onTap: widget.voice.clear)+ else+ const SizedBox(width: 18),+ Flexible(+ child: Padding(+ padding: const EdgeInsets.symmetric(vertical: 8),+ child: AnimatedSwitcher(+ duration: _motion+ ? const Duration(milliseconds: 240)+ : Duration.zero,+ reverseDuration: _motion+ ? const Duration(milliseconds: 100)+ : Duration.zero,+ switchInCurve: Curves.easeOutCubic,+ switchOutCurve: Curves.easeIn,+ layoutBuilder: _layoutMiddle,+ transitionBuilder: _enterMiddle,+ child: KeyedSubtree(+ key: ValueKey<Object>((+ shown.kind,+ shown.kind == _Kind.notice ? _noticeRun : 0,+ )),+ child: _middle(shown),+ ),),),),+ SizedBox(width: trailing),+ ],+ ),+ if (shown.lingers && _motion)+ Positioned(+ left: 24,+ right: trailing,+ bottom: 5,+ child: _Countdown(run: _noticeRun),),],),);}++ Widget _middle(_Status shown) {+ final style = TextStyle(+ fontSize: 13,+ height: 17 / 13,+ fontWeight: FontWeight.w500,+ color: AppPalette.textPrimary,+ );+ switch (shown.kind) {+ case _Kind.listening:+ // ⚠️ Words, not the meter, in hold-to-talk: the thumb is on the button+ // and the line to its left is the only thing that says what letting go+ // will do — and how to get out without sending.+ if (micHoldsToTalk) {+ return _lead(+ PulseDot(color: AppPalette.accentOnSurface, size: 7),+ _label(shown.label, style),+ );+ }+ return Semantics(+ label: shown.label,+ excludeSemantics: true,+ child: VoiceTakeMeter(+ level: widget.voice.level,+ elapsed: () => widget.voice.takeLength,+ ),+ );+ case _Kind.transcribing:+ case _Kind.sending:+ // Breathes rather than shimmers: the app's one "still working" rhythm,+ // and the reason the skeletons do not sweep either (see [Pulse]).+ return Pulse(+ duration: const Duration(milliseconds: 900),+ child: _label(shown.label, style),+ builder: (context, t, child) =>+ Opacity(opacity: 0.55 + 0.45 * t, child: child),+ );+ case _Kind.retry:+ return _lead(_Dot(color: AppPalette.warn), _label(shown.label, style));+ case _Kind.notice:+ return _lead(+ Icon(LucideIcons.circleAlert300, size: 16, color: AppPalette.warn),+ _label(shown.label, style),+ );+ case _Kind.cancelling:+ return _lead(+ Icon(LucideIcons.circleAlert300, size: 16, color: AppPalette.warn),+ _label(shown.label, style.copyWith(color: AppPalette.warn)),+ );+ case _Kind.starting:+ return _label(shown.label, style);+ }+ }++ /// Up to three lines, and it wraps: the notices are whole sentences, and cut+ /// to one line they lost the half that said what to do.+ static Widget _label(String text, TextStyle style) =>+ Text(text, maxLines: 3, overflow: TextOverflow.ellipsis, style: style);++ static Widget _lead(Widget mark, Widget label) => Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ SizedBox.square(dimension: 16, child: Center(child: mark)),+ const SizedBox(width: 8),+ Flexible(child: label),+ ],+ );++ /// ⚠️ **Only the incoming middle sizes the body.** The outgoing one is laid+ /// out beside it but positioned, so it neither holds the body at the larger+ /// of the two sizes while it fades nor stops [AnimatedSize] from heading+ /// straight for the new one.+ ///+ /// ⚠️ **Every child is a keyed [Positioned], the incoming one too** — with no+ /// offsets it is not positioned at all, and sizes the stack. What matters is+ /// that the widget around a child does not change type when it goes from+ /// incoming to outgoing: wrapped only on the way out, it was rebuilt from+ /// scratch there, and the take meter fading out restarted with flat bars.+ static Widget _layoutMiddle(Widget? current, List<Widget> previous) => Stack(+ alignment: AlignmentDirectional.centerStart,+ children: [+ for (final child in previous)+ Positioned(key: child.key, left: 0, child: child),+ if (current != null) Positioned(key: current.key, child: current),+ ],+ );++ static Widget _enterMiddle(Widget child, Animation<double> animation) =>+ FadeTransition(+ opacity: animation,+ child: SlideTransition(+ position: Tween<Offset>(+ begin: const Offset(0, 0.2),+ end: Offset.zero,+ ).animate(animation),+ child: child,+ ),+ );+}++/// The `×`: at the far end of the capsule, away from the thumb on the mic.+class _CancelButton extends StatelessWidget {+ const _CancelButton({required this.onTap});++ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) => Semantics(+ button: true,+ label: 'Cancel',+ child: GestureDetector(+ key: const ValueKey('voice-cancel'),+ behavior: HitTestBehavior.opaque,+ onTap: onTap,+ child: SizedBox(+ width: 44,+ height: VoiceStatusPill.height,+ child: Icon(+ LucideIcons.x300,+ size: 18,+ color: AppPalette.textSecondary,+ ),+ ),+ ),+ );+}++class _Dot extends StatelessWidget {+ const _Dot({required this.color});++ final Color color;++ @override+ Widget build(BuildContext context) => Container(+ width: 8,+ height: 8,+ decoration: BoxDecoration(shape: BoxShape.circle, color: color),+ );+}++/// A small sideways shake when a notice lands: something went wrong, and it+/// should be noticed without being loud.+///+/// ⚠️ **Driven by [run] climbing, never by a key.** A key would rebuild the+/// whole capsule beneath it and cut short the resize and the cross-fade it is+/// in the middle of. The tween heads for the new count instead, and the shake+/// is drawn from how far it still has to go.+class _Nudge extends StatelessWidget {+ const _Nudge({required this.run, required this.enabled, required this.child});++ final int run;+ final bool enabled;+ final Widget child;++ @override+ Widget build(BuildContext context) {+ if (!enabled) return child;+ return TweenAnimationBuilder<double>(+ tween: Tween<double>(end: run.toDouble()),+ duration: const Duration(milliseconds: 340),+ child: child,+ builder: (context, value, child) {+ final t = 1 - (run - value).clamp(0.0, 1.0);+ final dx = t >= 1 ? 0.0 : 3 * math.sin(t * math.pi * 3) * (1 - t);+ return Transform.translate(offset: Offset(dx, 0), child: child);+ },+ );+ }+}++/// A hairline along the bottom of a notice, running out as the notice's time+/// on screen does.+class _Countdown extends StatelessWidget {+ const _Countdown({required this.run});++ /// Which notice it counts for; a new one starts it again from full.+ final int run;++ @override+ Widget build(BuildContext context) => TweenAnimationBuilder<double>(+ key: ValueKey(run),+ tween: Tween<double>(begin: 1, end: 0),+ duration: VoiceInputController.noticeLinger,+ builder: (context, left, _) => Align(+ alignment: Alignment.centerLeft,+ child: FractionallySizedBox(+ widthFactor: left,+ child: Container(+ height: 2,+ decoration: BoxDecoration(+ color: AppPalette.warn.withValues(alpha: 0.6),+ borderRadius: BorderRadius.circular(1),+ ),+ ),+ ),+ ),+ );+}++/// Draws the capsule — its fill, rim and shadow — and clips what is inside it+/// to the capsule's shape, with the capsule growing out from the RIGHT edge as+/// [reveal] runs from 0 to 1.+///+/// ⚠️ **Paint only: layout and hit testing see the full size throughout.**+/// That is the point of it — see [VoiceStatusPill].+class _CapsuleReveal extends SingleChildRenderObjectWidget {+ const _CapsuleReveal({+ required this.reveal,+ required this.tucked,+ required this.fill,+ required this.rim,+ required this.shadows,+ super.child,+ });++ final Animation<double> reveal;++ /// The drawn width at `reveal == 0`: what the mic covers.+ final double tucked;++ final Color fill;+ final Color rim;+ final List<BoxShadow> shadows;++ @override+ RenderObject createRenderObject(BuildContext context) =>+ _RenderCapsuleReveal(reveal, tucked, fill, rim, shadows);++ @override+ void updateRenderObject(+ BuildContext context,+ _RenderCapsuleReveal renderObject,+ ) {+ renderObject+ ..reveal = reveal+ ..tucked = tucked+ ..fill = fill+ ..rim = rim+ ..shadows = shadows;+ }+}++class _RenderCapsuleReveal extends RenderProxyBox {+ _RenderCapsuleReveal(+ this._reveal,+ this._tucked,+ this._fill,+ this._rim,+ this._shadows,+ );++ Animation<double> _reveal;+ set reveal(Animation<double> value) {+ if (identical(value, _reveal)) return;+ if (attached) _reveal.removeListener(markNeedsPaint);+ _reveal = value;+ if (attached) _reveal.addListener(markNeedsPaint);+ markNeedsPaint();+ }++ double _tucked;+ set tucked(double value) {+ if (value == _tucked) return;+ _tucked = value;+ markNeedsPaint();+ }++ Color _fill;+ set fill(Color value) {+ if (value == _fill) return;+ _fill = value;+ markNeedsPaint();+ }++ Color _rim;+ set rim(Color value) {+ if (value == _rim) return;+ _rim = value;+ markNeedsPaint();+ }++ List<BoxShadow> _shadows;+ set shadows(List<BoxShadow> value) {+ if (listEquals(value, _shadows)) return;+ _shadows = value;+ markNeedsPaint();+ }++ final LayerHandle<ClipRRectLayer> _clip = LayerHandle<ClipRRectLayer>();++ @override+ void attach(PipelineOwner owner) {+ super.attach(owner);+ _reveal.addListener(markNeedsPaint);+ }++ @override+ void detach() {+ _reveal.removeListener(markNeedsPaint);+ super.detach();+ }++ @override+ void dispose() {+ _clip.layer = null;+ super.dispose();+ }++ /// The capsule as drawn right now, in local coordinates.+ RRect _capsule() {+ final full = size.width;+ final from = math.min(_tucked, full);+ final width = from + (full - from) * _reveal.value.clamp(0.0, 1.0);+ return RRect.fromLTRBR(+ full - width,+ 0,+ full,+ size.height,+ const Radius.circular(VoiceStatusPill.height / 2),+ );+ }++ @override+ void paint(PaintingContext context, Offset offset) {+ if (child == null) return;+ final capsule = _capsule();+ final drawn = capsule.shift(offset);+ final canvas = context.canvas;+ for (final shadow in _shadows) {+ canvas.drawRRect(+ drawn.shift(shadow.offset).inflate(shadow.spreadRadius),+ shadow.toPaint(),+ );+ }+ canvas.drawRRect(drawn, Paint()..color = _fill);+ _clip.layer = context.pushClipRRect(+ needsCompositing,+ offset,+ capsule.outerRect,+ capsule,+ super.paint,+ oldLayer: _clip.layer,+ );+ // The rim over the content, so nothing inside draws across the edge.+ context.canvas.drawRRect(+ drawn.deflate(0.5),+ Paint()+ ..style = PaintingStyle.stroke+ ..strokeWidth = 1+ ..color = _rim,+ );+ }}diff --git a/mobile/lib/phone/voice_take_meter.dart b/mobile/lib/phone/voice_take_meter.dartnew file mode 100644index 000000000..5ab57c74f--- /dev/null+++ b/mobile/lib/phone/voice_take_meter.dart@@ -0,0 +1,242 @@+import 'dart:math' as math;++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/scheduler.dart';++import 'package:harness_mobile/logging/app_log.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/widgets/pulse.dart';++/// A take being recorded, drawn: a live dot, the microphone's level scrolling+/// past as bars, and how long the take has run.+///+/// ```+/// ● ▂▃▅▇▅▃▂▁▃▆▇▅▃▁ 0:07+/// ```+///+/// ⚠️ **The bars are the proof that the mic is hearing.** The ring this+/// replaced breathed at the same pace whether or not a word was reaching the+/// microphone, so a muted input looked exactly like a working one until the+/// take came back empty. These move with the voice, and stay flat without it.+///+/// ⚠️ **Sampled on a fixed step, not per buffer.** The platform delivers audio+/// in bursts of uneven size and spacing; drawn per buffer the bars would+/// stutter and skip. Each step takes the loudest buffer since the last one,+/// and a step that got none lets the last bar fall away instead of repeating+/// it — which is also how a real meter's needle behaves.+///+/// ⚠️ Under Reduce Motion the bars hold still, as every other long-running+/// motion in the app does (see [Pulse]); the dot and the clock still say the+/// take is running.+class VoiceTakeMeter extends StatefulWidget {+ const VoiceTakeMeter({super.key, required this.level, required this.elapsed});++ /// The microphone's loudness, 0…1 — `VoiceInputController.level`.+ final ValueListenable<double> level;++ /// How long the take has run — `VoiceInputController.takeLength`. Read, not+ /// counted here, so a page swiped to mid-take shows the take's time.+ final Duration Function() elapsed;++ static const int bars = 22;+ static const double barWidth = 3;+ static const double barGap = 2;+ static const double height = 28;+ static const double minBar = 3;++ /// One bar per step: 22 of them cover the last second and a half.+ static const Duration step = Duration(milliseconds: 70);++ static double get waveWidth => bars * barWidth + (bars - 1) * barGap;++ @override+ State<VoiceTakeMeter> createState() => _VoiceTakeMeterState();+}++class _VoiceTakeMeterState extends State<VoiceTakeMeter>+ with SingleTickerProviderStateMixin {+ late final Ticker _ticker = createTicker(_tick);++ /// Oldest first; the newest bar is drawn on the right, nearest the mic.+ ///+ /// ⚠️ Growable, though its length never changes: each step drops the oldest+ /// bar and adds the newest, and `List.filled` is fixed-length by default —+ /// the first `removeAt` threw, every frame, and left the bars and the clock+ /// frozen.+ final List<double> _history = List<double>.filled(+ VoiceTakeMeter.bars,+ 0,+ growable: true,+ );+ final _Repaint _repaint = _Repaint();++ /// The loudest buffer since the last step, and whether one arrived at all.+ double _loudest = 0;+ bool _heard = false;++ Duration _lastStep = Duration.zero;+ String _clock = '';+ bool _motion = true;++ /// What this meter was given over its life, for the one line it logs when it+ /// goes: flat bars are either no buffers reaching it or buffers that were+ /// all silence, and this says which.+ int _buffers = 0;+ double _peak = 0;+ int _steps = 0;++ @override+ void initState() {+ super.initState();+ widget.level.addListener(_onLevel);+ _clock = _format(widget.elapsed());+ _ticker.start();+ }++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _motion = !MediaQuery.disableAnimationsOf(context);+ }++ @override+ void didUpdateWidget(VoiceTakeMeter old) {+ super.didUpdateWidget(old);+ if (old.level != widget.level) {+ old.level.removeListener(_onLevel);+ widget.level.addListener(_onLevel);+ }+ }++ @override+ void dispose() {+ // Levels only, never audio or words.+ appLog.info(+ 'voice',+ 'meter: $_clock buffers=$_buffers peak=${_peak.toStringAsFixed(2)} '+ 'steps=$_steps motion=$_motion',+ );+ widget.level.removeListener(_onLevel);+ _ticker.dispose();+ _repaint.dispose();+ super.dispose();+ }++ void _onLevel() {+ final level = widget.level.value;+ _loudest = math.max(_loudest, level);+ _heard = true;+ _buffers++;+ _peak = math.max(_peak, level);+ }++ void _tick(Duration now) {+ if (_motion && now - _lastStep >= VoiceTakeMeter.step) {+ _lastStep = now;+ final next = _heard ? _loudest : _history.last * 0.6;+ _history+ ..removeAt(0)+ ..add(next);+ _loudest = 0;+ _heard = false;+ _steps++;+ _repaint.ping();+ }+ // Rebuilt once a second, not every frame: the bars repaint on their own.+ final clock = _format(widget.elapsed());+ if (clock != _clock) setState(() => _clock = clock);+ }++ static String _format(Duration length) {+ final seconds = length.inSeconds;+ return '${seconds ~/ 60}:${(seconds % 60).toString().padLeft(2, '0')}';+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ SizedBox.square(+ dimension: 16,+ child: Center(+ child: PulseDot(color: AppPalette.accentOnSurface, size: 7),+ ),+ ),+ const SizedBox(width: 8),+ // Its own layer: the bars repaint every step, and the capsule and the+ // glass under the mic beside them should not repaint with them.+ RepaintBoundary(+ child: CustomPaint(+ size: Size(VoiceTakeMeter.waveWidth, VoiceTakeMeter.height),+ painter: _WavePainter(+ history: _history,+ color: AppPalette.textPrimary,+ repaint: _repaint,+ ),+ ),+ ),+ const SizedBox(width: 8),+ Text(+ _clock,+ style: TextStyle(+ fontSize: 12.5,+ fontWeight: FontWeight.w500,+ color: AppPalette.textSecondary,+ // The digits change every second; proportional ones would make the+ // capsule twitch in width as they did.+ fontFeatures: const [FontFeature.tabularFigures()],+ ),+ ),+ ],+ );+ }+}++class _Repaint extends ChangeNotifier {+ void ping() => notifyListeners();+}++class _WavePainter extends CustomPainter {+ _WavePainter({+ required this.history,+ required this.color,+ required Listenable repaint,+ }) : super(repaint: repaint);++ final List<double> history;+ final Color color;++ @override+ void paint(Canvas canvas, Size size) {+ final count = history.length;+ final paint = Paint();+ const width = VoiceTakeMeter.barWidth;+ for (var i = 0; i < count; i++) {+ final level = history[i].clamp(0.0, 1.0);+ final height =+ VoiceTakeMeter.minBar + level * (size.height - VoiceTakeMeter.minBar);+ // Older bars fade: the newest sound is the one nearest the mic.+ final age = count == 1 ? 1.0 : i / (count - 1);+ paint.color = color.withValues(alpha: color.a * (0.35 + 0.65 * age));+ canvas.drawRRect(+ RRect.fromRectAndRadius(+ Rect.fromLTWH(+ i * (width + VoiceTakeMeter.barGap),+ (size.height - height) / 2,+ width,+ height,+ ),+ const Radius.circular(width / 2),+ ),+ paint,+ );+ }+ }++ @override+ bool shouldRepaint(_WavePainter old) =>+ old.color != color || !identical(old.history, history);+}diff --git a/mobile/lib/phone/voice_wav.dart b/mobile/lib/phone/voice_wav.dartindex 882edffab..0e1f54983 100644--- a/mobile/lib/phone/voice_wav.dart+++ b/mobile/lib/phone/voice_wav.dart@@ -1,5 +1,32 @@+import 'dart:math' as math;import 'dart:typed_data';+/// How loud a buffer of 16-bit little-endian PCM sounds, from 0 (silence) to 1+/// (near full scale) — what the waveform beside the mic draws.+///+/// RMS rather than [pcm16Peak]: one click would otherwise read as a shout. And+/// on a decibel scale, because that is how loudness is heard — linear RMS puts+/// ordinary speech in the bottom tenth of the range and the bars barely move.+/// A quiet room sits near −60 dBFS and a voice at the phone near −30 to −20,+/// so [_quietDb]…[_loudDb] is spread over 0…1.+double pcm16Level(Uint8List pcm) {+ final count = pcm.length ~/ 2;+ if (count == 0) return 0;+ final data = ByteData.sublistView(pcm);+ var sum = 0.0;+ for (var offset = 0; offset + 1 < pcm.length; offset += 2) {+ final sample = data.getInt16(offset, Endian.little);+ sum += sample * sample;+ }+ final rms = math.sqrt(sum / count);+ if (rms < 1) return 0;+ final db = 20 * math.log(rms / 32768) / math.ln10;+ return ((db - _quietDb) / (_loudDb - _quietDb)).clamp(0.0, 1.0);+}++const double _quietDb = -55;+const double _loudDb = -10;+/// The loudest sample in 16-bit little-endian PCM, as a magnitude.int pcm16Peak(Uint8List pcm) {final data = ByteData.sublistView(pcm);