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: Implement voice input functionality with recorder and transcriber
Dev jacob0b7ed6ed1aae
diff --git a/mobile/RELEASE.md b/mobile/RELEASE.mdindex 2eb921f9a..b2d96e832 100644--- a/mobile/RELEASE.md+++ b/mobile/RELEASE.md@@ -183,6 +183,10 @@ owned by the user's own machine, which is why an account with no paired machineThe camera permission is used only when sending a photo into a session (Agents ▸ a session ▸ theimage button).++The microphone permission is used only for voice input: tapping a session's terminal records what is+said, and it is transcribed into the message sent to that session (Agents ▸ a session ▸ tap the+terminal).```## Submittingdiff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xmlindex a9f0ae0b3..9257336e7 100644--- a/mobile/android/app/src/main/AndroidManifest.xml+++ b/mobile/android/app/src/main/AndroidManifest.xml@@ -18,6 +18,11 @@cannot run without: a tablet or emulator with no camera must stillinstall and show every other screen. --><uses-feature android:name="android.hardware.camera" android:required="false" />+ <!-- Voice input, the terminal's default way to type. The recording is+ transcribed by the Harness backend (`/api/voice/stt`), so the+ microphone is the only permission it needs. -->+ <uses-permission android:name="android.permission.RECORD_AUDIO" />+ <uses-feature android:name="android.hardware.microphone" android:required="false" /><applicationandroid:label="harness"android:name="${applicationName}"diff --git a/mobile/ios/Runner/Info.plist b/mobile/ios/Runner/Info.plistindex 60b32dda6..bca31ae23 100644--- a/mobile/ios/Runner/Info.plist+++ b/mobile/ios/Runner/Info.plist@@ -43,6 +43,12 @@be shown and is deliberately absent. --><key>NSCameraUsageDescription</key><string>Take a photo to send to an agent in a terminal.</string>+ <!-- Voice input, what tapping a terminal opens. Asked for on the first tap,+ not at launch. The microphone alone: the recording is transcribed by+ the Harness backend (`/api/voice/stt`, the dial's own path), not by the+ OS, so there is no Speech Recognition permission to ask for. -->+ <key>NSMicrophoneUsageDescription</key>+ <string>Talk to an agent in a terminal instead of typing.</string><key>UIApplicationSceneManifest</key><dict><key>UIApplicationSupportsMultipleScenes</key>diff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dartindex cd17ca6a5..b38c2521f 100644--- a/mobile/lib/api/api_client.dart+++ b/mobile/lib/api/api_client.dart@@ -1,3 +1,5 @@+import 'dart:typed_data';+import 'package:dio/dio.dart';import '../auth/auth_session.dart';@@ -6,6 +8,7 @@ import '../core/models.dart';import '../logging/http_log.dart';import 'access_token_source.dart';import 'bearer_auth_interceptor.dart';+import 'multipart_body.dart';/// Control-plane REST client.///@@ -81,6 +84,38 @@ class ApiClient {);unwrapApiResponse(res);}++ // -- voice (backend only: the viewer's own SSO session signs it) --++ /// The words in one WAV recording, in [lang] — `POST /api/voice/stt`, the+ /// endpoint the dial's recordings reach through the CLI, called here with the+ /// token this viewer already holds.+ ///+ /// [lang] must be one the backend serves (`VOICE_WAV_LANGS` in the backend's+ /// `lib/deepgramWav.ts`); anything else is transcribed as English there.+ Future<String> transcribeVoice(Uint8List wav, {required String lang}) async {+ final body = multipartFileBody(+ field: 'file',+ filename: 'voice.wav',+ fileContentType: 'audio/wav',+ file: wav,+ boundary: 'harness-${DateTime.now().microsecondsSinceEpoch}',+ );+ final res = await _dio.post(+ '/api/voice/stt',+ queryParameters: {'lang': lang},+ data: body.bytes,+ options: Options(+ contentType: body.contentType,+ // A take can run five minutes — megabytes on a phone connection — and+ // the backend waits on the transcription provider before it answers.+ sendTimeout: const Duration(minutes: 2),+ receiveTimeout: const Duration(minutes: 2),+ ),+ );+ final data = unwrapApiResponse(res) as Map<String, dynamic>;+ return (data['transcript'] as String? ?? '').trim();+ }}class ApiException implements Exception {diff --git a/mobile/lib/api/multipart_body.dart b/mobile/lib/api/multipart_body.dartnew file mode 100644index 000000000..719f0d778--- /dev/null+++ b/mobile/lib/api/multipart_body.dart@@ -0,0 +1,28 @@+import 'dart:convert';+import 'dart:typed_data';++/// A `multipart/form-data` body holding one file, as plain bytes.+///+/// Built by hand rather than with Dio's `FormData`, because a `FormData` can be+/// sent exactly once: [BearerAuthInterceptor] answers a 401 by refreshing the+/// token and re-sending the SAME request, and a finalized `FormData` throws+/// there instead of going out again. Bytes go out as many times as asked.+({Uint8List bytes, String contentType}) multipartFileBody({+ required String field,+ required String filename,+ required String fileContentType,+ required Uint8List file,+ required String boundary,+}) {+ final head =+ '--$boundary\r\n'+ 'Content-Disposition: form-data; name="$field"; filename="$filename"\r\n'+ 'Content-Type: $fileContentType\r\n\r\n';+ final bytes =+ (BytesBuilder(copy: false)+ ..add(utf8.encode(head))+ ..add(file)+ ..add(utf8.encode('\r\n--$boundary--\r\n')))+ .takeBytes();+ return (bytes: bytes, contentType: 'multipart/form-data; boundary=$boundary');+}diff --git a/mobile/lib/phone/agent_swipe.dart b/mobile/lib/phone/agent_swipe.dartindex 1ea23c9eb..bce3fa1a5 100644--- a/mobile/lib/phone/agent_swipe.dart+++ b/mobile/lib/phone/agent_swipe.dart@@ -6,6 +6,7 @@ import 'package:harness_mobile/state/app_state.dart';import 'agent_index.dart';import 'terminal_page.dart';+import 'voice_input_controller.dart';/// The agents a terminal page can swipe between, in the order the list drew them.///@@ -123,6 +124,17 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {/// and the panes to close are the ones actually opened, not the ones a fresh list would name.final Set<({String machineId, String agentId})> _attached = {};+ /// Voice input for every page of this pager: open or closed, and what has been heard so far,+ /// survive a swipe the way a keyboard that is up does. Disposed with the pager, which is what+ /// turns the microphone off on the way out.+ ///+ /// Transcribes through `notifier.api` read at CALL time, not captured here: the notifier replaces+ /// its client when the session changes, and a captured one would sign with a token that is gone.+ late final VoiceInputController _voice = VoiceInputController(+ transcriber: (wav, lang) =>+ widget.notifier.api.transcribeVoice(wav, lang: lang),+ );+@overridevoid initState() {super.initState();@@ -152,6 +164,7 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {@overridevoid dispose() {+ _voice.dispose();_controller?.dispose();_detachAll();// Leaving the terminal means the next launch starts on the list. A process the OS kills never@@ -191,6 +204,7 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {notifier: widget.notifier,machineId: widget.machineId,agentId: widget.agentId,+ voice: _voice,isActive: true,);}@@ -221,6 +235,7 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {notifier: widget.notifier,machineId: entry.machineId,agentId: entry.agent.id,+ voice: _voice,// Exactly one mounted page, by page number — see [_page].isActive: i == _page,);diff --git a/mobile/lib/phone/phone_sheet.dart b/mobile/lib/phone/phone_sheet.dartindex be605148d..957947bb3 100644--- a/mobile/lib/phone/phone_sheet.dart+++ b/mobile/lib/phone/phone_sheet.dart@@ -48,16 +48,26 @@ Future<void> showPhoneSheet(style: TextStyle(color: AppPalette.textSecondary, fontSize: 13),),),- for (final action in actions)- _SheetRow(- action: action,- // Close first, then act: an action that opens a dialog or pushes a page must not do it- // underneath a sheet that is still animating out.- onTap: () {- Navigator.of(sheetContext).pop();- action.onTap();- },+ // Scrolls once the rows outgrow the sheet — voice input's six languages do on a short phone —+ // and is laid out exactly like a plain column until then.+ Flexible(+ child: ListView(+ shrinkWrap: true,+ padding: EdgeInsets.zero,+ children: [+ for (final action in actions)+ _SheetRow(+ action: action,+ // Close first, then act: an action that opens a dialog or pushes a page must not+ // do it underneath a sheet that is still animating out.+ onTap: () {+ Navigator.of(sheetContext).pop();+ action.onTap();+ },+ ),+ ],),+ ),const SizedBox(height: 8),],),diff --git a/mobile/lib/phone/terminal_input_dock.dart b/mobile/lib/phone/terminal_input_dock.dartnew file mode 100644index 000000000..858334111--- /dev/null+++ b/mobile/lib/phone/terminal_input_dock.dart@@ -0,0 +1,78 @@+import 'dart:async';++import 'package:flutter/material.dart';++import 'package:harness_mobile/terminal/terminal_session.dart';++import 'terminal_key_bar.dart';+import 'voice_input_controller.dart';+import 'voice_input_panel.dart';++/// The bottom of a terminal page: [TerminalKeyBar] over the keyboard, or+/// [VoiceInputPanel] in its place.+///+/// Voice is what a tap on the terminal opens; the keyboard is what its+/// Keyboard button hands over to. One at a time, and the key bar goes with the+/// keyboard: `esc`, the arrows and the digits are keys to TYPE with, and while+/// someone is talking they are two rows of terminal the panel does not need.+class TerminalInputDock extends StatelessWidget {+ const TerminalInputDock({+ super.key,+ required this.session,+ required this.voice,+ required this.keyboardUp,+ required this.onDismiss,+ required this.onUseKeyboard,+ this.onPickImage,+ this.onTakePhoto,+ });++ final TerminalSession session;+ final VoiceInputController voice;++ /// The software keyboard is up, or has been asked for and is on its way.+ final bool keyboardUp;++ /// `⌄`, on the key bar or on the panel: puts away whichever input is up.+ final VoidCallback onDismiss;+ final VoidCallback onUseKeyboard;+ final VoidCallback? onPickImage;+ final VoidCallback? onTakePhoto;++ @override+ Widget build(BuildContext context) => ValueListenableBuilder<bool>(+ valueListenable: voice.openState,+ builder: (context, voiceOpen, _) {+ if (!keyboardUp && !voiceOpen) return const SizedBox.shrink();+ return ListenableBuilder(+ listenable: session,+ builder: (context, _) => Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (keyboardUp)+ TerminalKeyBar(+ terminal: session.terminal,+ enabled: session.acceptsInput,+ controlArmed: session.controlArmed,+ onControlToggle: session.armControl,+ onDismissKeyboard: onDismiss,+ onPickImage: onPickImage,+ onTakePhoto: onTakePhoto,+ )+ else+ VoiceInputPanel(+ voice: voice,+ canSend: session.acceptsInput,+ // The composer's own path, not typed bytes: the machine injects+ // it as one turn and owns the submit Enter — see+ // `TerminalSession.sendComposerText`.+ onSend: () => unawaited(voice.submit(session.sendComposerText)),+ onUseKeyboard: onUseKeyboard,+ onDismiss: onDismiss,+ ),+ ],+ ),+ );+ },+ );+}diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dartindex 98bde6341..c93824db3 100644--- a/mobile/lib/phone/terminal_page.dart+++ b/mobile/lib/phone/terminal_page.dart@@ -24,7 +24,8 @@ import 'phone_search_page.dart' show openPhoneSearch;import 'phone_sheet.dart';import 'phone_status.dart';import 'status_pill.dart';-import 'terminal_key_bar.dart';+import 'terminal_input_dock.dart';+import 'voice_input_controller.dart';/// One agent's terminal, filling the phone. The header says whose it is and whether it is live;/// everything below it is the same [TerminalPanel] a desktop tile draws, minus that tile's own@@ -38,6 +39,7 @@ class TerminalPage extends StatefulWidget {required this.notifier,required this.machineId,required this.agentId,+ required this.voice,this.isActive = true,});@@ -45,6 +47,10 @@ class TerminalPage extends StatefulWidget {final String machineId;final String agentId;+ /// Voice input, shared by every page of the pager this page is in — see+ /// [VoiceInputController] for why it is not this page's own.+ final VoiceInputController voice;+/// Whether this is the page being LOOKED AT, rather than one parked beside it in the pager.////// ⚠️ **Load-bearing for correctness, not just for tidiness.** [TerminalPanel] claims the keyboard@@ -64,42 +70,24 @@ class TerminalPage extends StatefulWidget {/// Whether the software keyboard is up, as one fact rather than as a flag each/// page keeps for itself.///-/// ⚠️ Per-page state cannot answer the question the pager asks. A page keeps-/// [_TerminalPageState._claimSpent] to stop itself re-summoning a keyboard the-/// person dismissed — but that flag is only ever armed by a keyboard this page-/// WATCHED rise. Swiping A → B → C and hiding the keyboard at C leaves B-/// having mounted while it was already down: its claim was never spent, so on-/// the way back it looked exactly like a page arriving fresh and pulled the-/// keyboard up again. Whether the keyboard is up is a property of the SCREEN,-/// not of any one page, so it is kept once here.+/// ⚠️ Per-page state cannot answer the question the pager asks. Swiping to the+/// next agent while typing must HOLD the keyboard — the outgoing page releases+/// focus, and unless the incoming one takes it in the same frame the platform+/// closes the keyboard — and a page built while the keyboard was down, then+/// swiped to after it rose, never watched it rise. Whether the keyboard is up is+/// a property of the SCREEN, not of any one page, so it is kept once here.////// Written by every mounted page's `didChangeMetrics` — they all see the same/// inset, so they all write the same value.bool _keyboardIsUp = false;-/// Whether the keyboard has been PUT AWAY while the pager was open, as opposed-/// to never having been raised.-///-/// ⚠️ The pager's second half, and per-page state cannot hold it either. A page-/// raises the keyboard on arrival because that is what opening an agent should-/// do — but once somebody has dismissed it, every page reached by swiping after-/// that must leave it down, including pages that have never been on screen and-/// so have nothing of their own to remember. It is the PERSON's choice, made-/// once, and it outlives any one page.-///-/// Set when the inset falls to zero with the pager open; cleared when it rises-/// again, so tapping a pane to type re-arms the ordinary behaviour.-bool _keyboardDismissed = false;-/// Forgets what the keyboard did during the last run of terminal pages.///-/// Called when a pager opens. The dismissal above is deliberately sticky ACROSS-/// pages so a swipe cannot undo it, which makes it sticky across whole visits-/// too unless something clears it — and "I put the keyboard away on that agent-/// an hour ago" should not decide what opening a different agent does now.+/// Called when a pager opens. A pager popped with the keyboard up is disposed+/// before the inset falls, so no page is left to see it fall — and the next+/// pager would otherwise open believing the keyboard is up, and summon it.void resetKeyboardSession() {_keyboardIsUp = false;- _keyboardDismissed = false;}class _TerminalPageState extends State<TerminalPage>@@ -116,44 +104,18 @@ class _TerminalPageState extends State<TerminalPage>/// TerminalPage still sitting in the Agents tab's stack.bool _hadPane = false;- /// Whether this page has already used its one chance to summon the keyboard.- ///- /// It starts `false`, so the terminal is focused on arrival and the keyboard- /// rises by itself. It flips the moment the keyboard IS up, and NEVER goes- /// back: from then on `TerminalPanel` is passed `focused: false` and stops- /// claiming, for the life of the page. Bringing the keyboard back is the- /// terminal's own job — xterm's tap handler calls `requestKeyboard()` without- /// consulting this flag, so nothing here needs to re-arm.+ /// Whether the Keyboard button in voice input has asked for the keyboard,+ /// and it has not risen yet.///- /// ⚠️ Without this, Back could not put the keyboard away at all:- /// `TerminalPanel._claimFocus` calls `TerminalView.requestKeyboard()`, which- /// RE-TAKES focus when it finds none, so the keyboard returned a frame after- /// the system dismissed it. Measured on a Pixel 8 Pro — `onRequestShow`- /// ELEVEN times against a single `onRequestHide`.+ /// What makes [TerminalPanel] claim focus at all: arriving on a page raises+ /// nothing, and a tap on the terminal opens voice input, so this is the one+ /// way the keyboard is SUMMONED. Spent the moment the keyboard is up — from+ /// then on [_keyboardIsUp] holds it — so Back or `⌄` can put it away without+ /// a claim fetching it straight back.///- /// ⚠️ It flips on the keyboard APPEARING, not on it going away, and that is- /// the difference between Back working on the first press and on the second.- /// `_claimFocus` runs from a post-frame callback and BEATS `didChangeMetrics`- /// to the news that the keyboard is gone:- ///- /// onDispatched keyboard hidden- /// CLAIM focused=true claim ran first — re-took focus- /// onRequestShow keyboard on its way back- /// KB raw=0.0 our metrics callback, one beat too late- ///- /// Arming on the way up removes the race: by the time any Back arrives,- /// claiming has been off for as long as the keyboard has been visible.- bool _claimSpent = false;-- /// Whether this page has already had a turn on screen and been swiped away.- ///- /// ⚠️ What separates "arriving" from "coming back", which [_claimSpent]- /// cannot. A page the pager built while the keyboard was down never spent its- /// claim, so on its second turn it looked exactly like one opened fresh — and- /// summoned the keyboard again after the person had dismissed it two agents- /// away. A page raises the keyboard on its FIRST turn only; after that it- /// holds whatever is there and summons nothing.- bool _hasHadATurn = false;+ /// It stays set when no inset ever arrives, which is what a hardware keyboard+ /// looks like: the terminal keeps its focus, and the key bar stays for `esc`.+ bool _keyboardRequested = false;/// Whether the software keyboard is up, and with it [TerminalKeyBar].///@@ -201,10 +163,9 @@ class _TerminalPageState extends State<TerminalPage>void didUpdateWidget(TerminalPage oldWidget) {super.didUpdateWidget(oldWidget);if (oldWidget.isActive && !widget.isActive) {- // Marked on the way OUT, not on the way in: the flag means "has had its- // turn", and a page still on its first one must keep the summon it has- // not used yet.- _hasHadATurn = true;+ // A keyboard asked for and still on its way belongs to the page that+ // asked; a parked page must not claim it when it comes.+ _keyboardRequested = false;_cancelSettle();if (_keyboardSettling) setState(() => _keyboardSettling = false);}@@ -232,19 +193,16 @@ class _TerminalPageState extends State<TerminalPage>super.didChangeMetrics();if (!mounted) return;final inset = View.of(context).viewInsets.bottom;- // The FIRST frame of the keyboard rising is enough — it need not finish.- // Spending the claim this early is the point: it is off long before any- // Back press can arrive.final up = inset > 0;// Every mounted page writes it, and they all see the same inset — so a page// that was parked while the keyboard came and went still reads the truth.- if (up != _keyboardIsUp) {- _keyboardIsUp = up;- // Falling to zero is a dismissal; rising again is somebody asking for it- // back, which restores what a freshly opened agent does.- _keyboardDismissed = !up;- }- final claim = _claimSpent || up;+ _keyboardIsUp = up;+ // The FIRST frame of the keyboard rising spends the request — it need not+ // finish. Spending it this early is the point: it is off long before any+ // Back press can arrive.+ final requested = _keyboardRequested && !up;+ // One input at a time. Whatever raised the keyboard, voice input yields.+ if (up && widget.voice.isOpen) widget.voice.close();// Every tick that MOVES the inset is the animation still running; the run// ends when one window passes without another move. Gated on a real change@@ -267,47 +225,61 @@ class _TerminalPageState extends State<TerminalPage>final settling = _settleTimer != null;if (up == _keyboardUp &&- claim == _claimSpent &&+ requested == _keyboardRequested &&settling == _keyboardSettling) {return;}setState(() {_keyboardUp = up;- _claimSpent = claim;+ _keyboardRequested = requested;_keyboardSettling = settling;});}- /// Whether [TerminalPanel] should hold the input connection.- ///- /// Two different questions, and [_claimSpent] alone can only answer one:+ /// Whether [TerminalPanel] should hold the input connection: while the+ /// keyboard is up, and while one is on its way — see [_keyboardRequested].///- /// - **Raise a keyboard that is down.** One chance per page, spent the- /// moment the keyboard appears, so Back can put it away without the claim- /// fetching it straight back — see [_claimSpent].- /// - **Hold a keyboard that is already up.** What swiping between agents- /// needs: the outgoing page releases focus, and unless the incoming one- /// takes it in the same frame the platform closes the keyboard.- ///- /// ⚠️ The second case reads [_keyboardIsUp], the one screen-wide fact, rather- /// than anything this page remembers. Per-page flags get the pager wrong in- /// both directions: [_claimSpent] is armed by a parked neighbour merely- /// WATCHING the keyboard rise, and it is never armed at all on a page built- /// while the keyboard was down — so a page coming back for its second turn- /// was indistinguishable from one opened fresh, and summoned a keyboard the- /// person had dismissed two agents away. [_hasHadATurn] closes that: the- /// summon belongs to a page's first turn only.+ /// ⚠️ Holding reads [_keyboardIsUp], the one screen-wide fact, rather than+ /// anything this page remembers — see that flag for why swiping needs it.bool get _shouldFocus =>- widget.isActive &&- (_keyboardIsUp || (!_claimSpent && !_hasHadATurn && !_keyboardDismissed));+ widget.isActive && (_keyboardIsUp || _keyboardRequested);++ /// A tap on the terminal while no keyboard is up or coming: voice input,+ /// already recording. Null while the keyboard is, so the tap is xterm's and+ /// the keyboard stays.+ VoidCallback? get _onInputTap =>+ _shouldFocus ? null : () => unawaited(widget.voice.open());++ /// The Keyboard button in voice input. What was heard is typed into the+ /// prompt rather than dropped, so the keyboard picks up where the voice left+ /// off — to correct a word, or to finish the sentence. A take still being+ /// recorded is transcribed first: pressing Keyboard mid-sentence is asking to+ /// fix that sentence, not to lose it.+ Future<void> _useKeyboard(TerminalSession session) async {+ final heard = await widget.voice.takeTranscript();+ if (!mounted) return;+ widget.voice.close();+ if (heard.isNotEmpty && session.acceptsInput) {+ session.terminal.textInput(heard);+ }+ setState(() => _keyboardRequested = true);+ }- /// Puts the keyboard away without leaving the page — the `⌄` key on- /// [TerminalKeyBar]. Dropping focus is what closes the input connection;- /// xterm reopens it on the next tap in the pane.- void _dismissKeyboard() => FocusManager.instance.primaryFocus?.unfocus();+ /// Puts away whichever input is up without leaving the page — the `⌄` key on+ /// [TerminalKeyBar]. Dropping focus is what closes the input connection.+ void _dismissInput() {+ widget.voice.close();+ FocusManager.instance.primaryFocus?.unfocus();+ if (_keyboardRequested) setState(() => _keyboardRequested = false);+ }- /// Whether the keyboard on screen is THIS page's — the question the header- /// chrome asks, which [_keyboardUp] alone answers wrongly.+ /// Whether an input on screen is THIS page's — the keyboard, or voice input+ /// in its place — the question the header chrome asks, which [_keyboardUp]+ /// alone answers wrongly.+ ///+ /// Voice input counts for the same reason the keyboard does: the panel takes+ /// the keyboard's place, so the fab would float over its Send button and the+ /// machine row would sit under it.////// ⚠️ [_keyboardUp] means "an inset exists", not "this page raised it". A/// pushed page with a text field — search, rename — raises one of its own,@@ -324,8 +296,9 @@ class _TerminalPageState extends State<TerminalPage>/// Not used for [_shouldFocus] or for the key bar: those are about the/// keyboard ITSELF, which is screen-wide, and a covered page must keep/// tracking it to know what to do when it is uncovered.- bool get _ownsKeyboard =>- _keyboardUp && (ModalRoute.of(context)?.isCurrent ?? true);+ bool get _ownsInput =>+ (_keyboardUp || widget.voice.isOpen) &&+ (ModalRoute.of(context)?.isCurrent ?? true);/// Guards against a second picker while one is already up.///@@ -394,7 +367,9 @@ class _TerminalPageState extends State<TerminalPage>@overrideWidget build(BuildContext context) {return ListenableBuilder(- listenable: widget.notifier,+ // The panel opening or closing moves the header chrome — see+ // [_ownsInput]. Its open STATE only: what it hears repaints the panel.+ listenable: Listenable.merge([widget.notifier, widget.voice.openState]),builder: (context, _) {AppTheme.watch(context);final pane = widget.notifier.panes@@ -443,12 +418,12 @@ class _TerminalPageState extends State<TerminalPage>// password cannot host a new agent. Null rather than disabled, the// convention [PhoneFab] documents.//- // ⚠️ Gone while the keyboard is up, for the reason the header- // controls are: a Scaffold's fab floats over the body, so it would- // sit on top of [TerminalKeyBar] — the one row the thumb is actually- // aiming at while typing.+ // ⚠️ Gone while the keyboard or voice input is up, for the reason+ // the header controls are: a Scaffold's fab floats over the body, so+ // it would sit on top of [TerminalKeyBar] — the one row the thumb is+ // actually aiming at while typing — or on voice input's Send.floatingActionButton:- !_ownsKeyboard &&+ !_ownsInput &&machine != null &&phoneMachineStatusOf(machine) == PhoneMachineStatus.ready? PhoneFab(@@ -514,16 +489,16 @@ class _TerminalPageState extends State<TerminalPage>// creates something; the fab says that by being the only// filled thing on the page.//- // ⚠️ Still hidden while the keyboard is up. The header is- // one row, and a terminal being typed into is the one- // moment search is not what the thumb is reaching for —- // the key bar directly under it is.+ // ⚠️ Still hidden while the keyboard or voice input is+ // up. The header is one row, and a terminal being typed or+ // talked into is the one moment search is not what the+ // thumb is reaching for.// ⚠️ Not [PhoneSearchButton], which pushes and forgets. A// page that pops back onto the top gets no rebuild of its- // own, so [_ownsKeyboard] would keep answering with what+ // own, so [_ownsInput] would keep answering with what// was true while the search was covering it. Awaiting the// push is what turns "the search closed" into a frame.- if (!_ownsKeyboard)+ if (!_ownsInput)AppIconButton(icon: LucideIcons.search300,size: 22,@@ -556,17 +531,6 @@ class _TerminalPageState extends State<TerminalPage>Expanded(child: pane == null || session == null? const _Attaching()- // ⚠️ Nothing re-arms [_claimSpent] on tap, and that- // is deliberate. A `Listener` doing so was written- // and removed: xterm's own `_onTapDown` already- // calls `requestKeyboard()`, so the tap opened the- // keyboard and THEN the re-armed claim asked for it- // a second time — Android answers a show arriving- // mid-animation by cancelling and restarting it.- // Measured: two `onRequestShow` and two- // `onCancelled at PHASE_CLIENT_APPLY_ANIMATION` per- // tap. The claim exists only to raise the keyboard- // on arrival; after that the terminal handles it.: TerminalPanel(key: ValueKey(pane.id),notifier: widget.notifier,@@ -586,47 +550,51 @@ class _TerminalPageState extends State<TerminalPage>// must NOT release focus — the animation being// waited on is the one that focus started.settling: _keyboardSettling,+ // ⚠️ The tap is taken in the panel, not by a+ // `Listener` over it. xterm's own `_onTapDown`+ // calls `requestKeyboard()`, so anything that+ // merely ALSO reacted to the tap would get the+ // keyboard rising under voice input — and a+ // re-armed claim on top of it was measured+ // asking Android twice per tap, which answers a+ // show mid-animation by cancelling and+ // restarting it.+ onInputTap: _onInputTap,showHeader: false,// No composer, and so no grip above it: the// page hands the pane its full height and the// software keyboard drives the terminal- // directly — `TerminalPanel` autofocuses the- // view precisely when no box is covering it.- // What goes with the box is the batched send,- // and the Esc/Tab/Ctrl an on-screen keyboard- // never had anyway.+ // directly. Voice input's Send is what kept+ // the composer's batched turn.),),// The bottom of this page IS just above the keyboard:// `PhoneShell`'s Scaffold has already resized for it —// the same resize that empties this page's MediaQuery// insets (see [didChangeMetrics]).- if (_keyboardUp && session != null)- ListenableBuilder(- listenable: session,- builder: (context, _) => TerminalKeyBar(- terminal: session.terminal,- enabled: session.acceptsInput,- controlArmed: session.controlArmed,- onControlToggle: session.armControl,- onDismissKeyboard: _dismissKeyboard,- // Only where the far side can actually take one: an- // older CLI never advertises the binary kind, so the- // upload would go nowhere silently. Null leaves the- // buttons undrawn rather than drawn dead.- onPickImage:- machine?.terminalImagePasteAvailable == true- ? () => unawaited(- _sendImage(session, ImageSource.gallery),- )- : null,- onTakePhoto:- machine?.terminalImagePasteAvailable == true- ? () => unawaited(- _sendImage(session, ImageSource.camera),- )- : null,- ),+ if (session != null)+ TerminalInputDock(+ session: session,+ voice: widget.voice,+ keyboardUp: _keyboardUp || _keyboardRequested,+ onDismiss: _dismissInput,+ onUseKeyboard: () => unawaited(_useKeyboard(session)),+ // Only where the far side can actually take one: an+ // older CLI never advertises the binary kind, so the+ // upload would go nowhere silently. Null leaves the+ // buttons undrawn rather than drawn dead.+ onPickImage:+ machine?.terminalImagePasteAvailable == true+ ? () => unawaited(+ _sendImage(session, ImageSource.gallery),+ )+ : null,+ onTakePhoto:+ machine?.terminalImagePasteAvailable == true+ ? () => unawaited(+ _sendImage(session, ImageSource.camera),+ )+ : null,),// Which computer this is running on, and whether it is// still answering — the pair that used to sit under the@@ -643,7 +611,7 @@ class _TerminalPageState extends State<TerminalPage>// tall, and a status line wedged under it is a row of// chrome the terminal loses for nothing — state is not// what is being read mid-typing.- if (!_ownsKeyboard)+ if (!_ownsInput)_MachineBar(name: machine?.machine.displayName ?? '',// ⚠️ The machine ALONE once the reclaim button is up.diff --git a/mobile/lib/phone/voice_input_controller.dart b/mobile/lib/phone/voice_input_controller.dartnew file mode 100644index 000000000..3f5efb4bc--- /dev/null+++ b/mobile/lib/phone/voice_input_controller.dart@@ -0,0 +1,309 @@+import 'dart:async';+import 'dart:ui' show Locale;++import 'package:flutter/foundation.dart';++import 'package:harness_mobile/core/harness_file_store.dart';+import 'package:harness_mobile/core/local_key_value_store.dart';+import 'package:harness_mobile/logging/app_log.dart';++import 'voice_language.dart';+import 'voice_notice.dart';+import 'voice_recorder.dart';++/// Turns one WAV recording into the words in it — `ApiClient.transcribeVoice`.+typedef VoiceTranscriber = Future<String> Function(Uint8List wav, String lang);++enum VoiceInputStatus {+ /// Not recording. What was heard so far stays.+ idle,++ /// Waiting on the microphone permission prompt, or the microphone opening.+ starting,++ /// Recording.+ listening,++ /// The recording is with the backend, and its words are not back yet.+ transcribing,++ /// The microphone was refused: the keyboard is the only way in until the+ /// person allows it in Settings.+ unavailable,+}++/// Voice input for one pager of terminal pages: whether its panel is open, what+/// has been heard, and the language it is transcribed in.+///+/// Record, then transcribe — the dial's shape, and the backend's: its+/// `/api/voice/stt` takes a finished recording and answers with its words, so+/// nothing appears while someone is still talking. Each take's words join the+/// transcript when it ends.+///+/// Owned by `AgentSwipeHost`, not by a page, for the reason the keyboard is one+/// screen-wide fact in `terminal_page.dart`: swiping to the next agent must not+/// close what is open, nor drop what was said. What is SENT goes to whichever+/// page is active when Send is pressed.+class VoiceInputController extends ChangeNotifier {+ VoiceInputController({+ required this.transcriber,+ VoiceRecorder? recorder,+ LocalKeyValueStore? storage,+ List<Locale>? preferredLocales,+ }) : _recorder = recorder ?? MicVoiceRecorder(),+ _storage = storage ?? HarnessFileStore.shared,+ _language = defaultVoiceLanguage(+ preferredLocales ?? PlatformDispatcher.instance.locales,+ ) {+ unawaited(_loadLanguage());+ }++ static const _languageKey = 'voice_input_language';++ /// Below this, a take is silence rather than quiet speech: digital zero, or+ /// the hiss of an input nobody is speaking into. Speech peaks in the+ /// thousands. Caught here, it is a clear notice instead of an upload that+ /// comes back empty and reads as "didn't catch that".+ static const silencePeak = 64;++ /// The longest one take runs before it ends by itself. The backend takes+ /// 25 MB; five minutes of 16 kHz mono is under 10.+ static const maxTake = Duration(minutes: 5);++ final VoiceTranscriber transcriber;+ final VoiceRecorder _recorder;+ final LocalKeyValueStore _storage;++ final ValueNotifier<bool> _open = ValueNotifier(false);+ VoiceInputStatus _status = VoiceInputStatus.idle;+ String _heard = '';+ String? _notice;+ String _language;+ bool _languageChosen = false;+ bool _isSending = false;+ bool _disposed = false;+ Timer? _takeLimit;++ /// Bumped by everything that abandons a take, so a recording or a+ /// transcription still in flight from it lands nowhere — above all after+ /// Close, where words arriving late would reopen what was put away.+ int _take = 0;++ /// Whether the panel is up, as its own listenable: the terminal page watches+ /// THIS, not the controller, so the panel's own changes repaint the panel and+ /// never rebuild the terminal above it.+ ValueListenable<bool> get openState => _open;+ bool get isOpen => _open.value;+ bool get isSending => _isSending;+ VoiceInputStatus get status => _status;+ String get transcript => _heard;+ String? get notice => _notice;++ /// A code from [voiceLanguages].+ String get language => _language;++ /// Opens the panel already recording — what a tap on the terminal does.+ Future<void> open() {+ _open.value = true;+ return startListening();+ }++ /// Closes the panel, discarding anything not sent.+ void close() {+ _open.value = false;+ clear();+ }++ void clear() {+ _abandonTake();+ _heard = '';+ _setStatus(VoiceInputStatus.idle);+ }++ Future<void> toggleListening() => switch (_status) {+ VoiceInputStatus.starting || VoiceInputStatus.listening => stopListening(),+ VoiceInputStatus.transcribing => Future.value(),+ VoiceInputStatus.idle || VoiceInputStatus.unavailable => startListening(),+ };++ Future<void> startListening() async {+ if (_isSending || _disposed) return;+ if (_status != VoiceInputStatus.idle &&+ _status != VoiceInputStatus.unavailable) {+ return;+ }+ final take = ++_take;+ _setStatus(VoiceInputStatus.starting);+ if (!await _micAllowed()) {+ if (take != _take) return;+ _setStatus(VoiceInputStatus.unavailable, notice: VoiceNotice.unavailable);+ return;+ }+ // Closed, cleared or stopped while the permission prompt was up.+ if (take != _take) return;+ try {+ await _recorder.start();+ } on Exception {+ if (take != _take) return;+ _setStatus(VoiceInputStatus.idle, notice: VoiceNotice.couldNotStart);+ return;+ }+ if (take != _take) {+ unawaited(_recorder.cancel());+ return;+ }+ _takeLimit = Timer(maxTake, () => unawaited(stopListening()));+ _setStatus(VoiceInputStatus.listening);+ }++ /// Ends the take and transcribes it.+ Future<void> stopListening() async {+ if (_status == VoiceInputStatus.starting) {+ _abandonTake();+ _setStatus(VoiceInputStatus.idle);+ return;+ }+ if (_status == VoiceInputStatus.listening) await _transcribeTake();+ }++ /// Sends everything heard, and empties the panel once it is sent — kept when+ /// delivery fails, so nothing said has to be said twice.+ ///+ /// Send while still talking ends the take first: one tap finishes the+ /// sentence and sends it. A take that comes back as nothing sends nothing,+ /// rather than the half of the message that was heard before it.+ Future<void> submit(Future<bool> Function(String text) deliver) async {+ if (_isSending || _status == VoiceInputStatus.transcribing) return;+ if (_status == VoiceInputStatus.listening && !await _transcribeTake()) {+ return;+ }+ final text = transcript.trim();+ if (text.isEmpty || _isSending) return;+ _isSending = true;+ _setStatus(VoiceInputStatus.idle);+ var sent = false;+ try {+ sent = await deliver(text);+ } on Exception {+ // Reported below exactly like a refusal: the words stay, Send stays live.+ }+ _isSending = false;+ if (sent) _heard = '';+ _setStatus(+ VoiceInputStatus.idle,+ notice: sent ? null : VoiceNotice.notSent,+ );+ }++ /// Everything heard — the take still being recorded included, once it is+ /// transcribed — emptied out of the panel, for the keyboard to carry on from.+ Future<String> takeTranscript() async {+ if (_status == VoiceInputStatus.listening) await _transcribeTake();+ final text = transcript;+ clear();+ return text;+ }++ /// Transcribes in [code] from now on — the take being recorded included —+ /// on this phone and in later pagers too.+ Future<void> selectLanguage(String code) async {+ if (!isVoiceLanguage(code)) return;+ _language = code;+ _languageChosen = true;+ _notify();+ try {+ await _storage.write(_languageKey, code);+ } on Exception {+ // Still used for this pager; only remembering it failed.+ }+ }++ @override+ void dispose() {+ _abandonTake();+ _disposed = true;+ _open.dispose();+ unawaited(_recorder.dispose());+ super.dispose();+ }++ /// True when the take's words, if any, joined the transcript.+ Future<bool> _transcribeTake() async {+ final take = _take;+ _takeLimit?.cancel();+ _setStatus(VoiceInputStatus.transcribing);+ try {+ final recording = await _recorder.stop();+ if (take != _take) return false;+ appLog.info(+ 'voice',+ recording == null+ ? 'take: no audio captured'+ : 'take: ${recording.length.inMilliseconds}ms '+ '${recording.wav.length}B peak=${recording.peak}',+ );+ if (recording == null || recording.peak < silencePeak) {+ _setStatus(VoiceInputStatus.idle, notice: VoiceNotice.noSound);+ return false;+ }+ final words = await transcriber(recording.wav, _language);+ // The count, never the words: a transcript is what someone said.+ appLog.info('voice', 'stt[$_language]: ${words.length} chars');+ if (take != _take) return false;+ _heard = _joinWords(_heard, words);+ _setStatus(+ VoiceInputStatus.idle,+ notice: words.isEmpty ? VoiceNotice.nothingHeard : null,+ );+ return words.isNotEmpty;+ } on Exception catch (error) {+ appLog.warn('voice', 'stt[$_language] failed', error: error);+ if (take == _take) {+ _setStatus(VoiceInputStatus.idle, notice: VoiceNotice.notTranscribed);+ }+ return false;+ }+ }++ Future<bool> _micAllowed() async {+ try {+ return await _recorder.allowed();+ } on Exception {+ return false;+ }+ }++ Future<void> _loadLanguage() async {+ try {+ final saved = await _storage.read(_languageKey);+ // A choice made while this was loading is newer than the saved one.+ if (_languageChosen || _disposed || !isVoiceLanguage(saved)) return;+ _language = saved!;+ _notify();+ } on Exception {+ // The phone's own language still works; only the memory is missing.+ }+ }++ void _abandonTake() {+ _take++;+ _takeLimit?.cancel();+ if (_status == VoiceInputStatus.starting ||+ _status == VoiceInputStatus.listening) {+ unawaited(_recorder.cancel());+ }+ }++ void _setStatus(VoiceInputStatus status, {String? notice}) {+ _status = status;+ _notice = notice;+ _notify();+ }++ void _notify() {+ if (!_disposed) notifyListeners();+ }+}++String _joinWords(String first, String second) =>+ [first.trim(), second.trim()].where((part) => part.isNotEmpty).join(' ');diff --git a/mobile/lib/phone/voice_input_panel.dart b/mobile/lib/phone/voice_input_panel.dartnew file mode 100644index 000000000..6b0e6c682--- /dev/null+++ b/mobile/lib/phone/voice_input_panel.dart@@ -0,0 +1,211 @@+import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/shared/theme/app_theme.dart';++import 'voice_input_controller.dart';+import 'voice_language.dart';+import 'voice_mic_button.dart';+import 'voice_panel_parts.dart';++/// What a tap on the terminal opens: talk to the agent, read back what was+/// heard, send it — or hand over to the keyboard.+///+/// Words arrive when a take ENDS, not while it is being spoken: they come from+/// the backend's `/api/voice/stt`, which transcribes a finished recording. Send+/// works mid-take for that reason — it ends the take and sends what it heard.+///+/// It sits where the keyboard would, alone: [TerminalKeyBar] belongs to the+/// keyboard, so this panel carries its own `⌄`.+///+/// ⚠️ **One fixed height, whatever it says.** The transcript scrolls inside a+/// box of its own rather than growing the panel: this panel's top edge is the+/// terminal's bottom edge, so a panel that grew by a line per sentence would+/// resize the remote shell once per sentence.+class VoiceInputPanel extends StatelessWidget {+ const VoiceInputPanel({+ super.key,+ required this.voice,+ required this.canSend,+ required this.onSend,+ required this.onUseKeyboard,+ required this.onDismiss,+ });++ final VoiceInputController voice;++ /// False while the stream is not accepting input. Recording still works —+ /// what was said waits for Send.+ final bool canSend;+ final VoidCallback onSend;++ /// Closes this panel for the keyboard, carrying what was heard with it.+ final VoidCallback onUseKeyboard;++ /// Puts the panel away, and what was not sent with it.+ final VoidCallback onDismiss;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return ListenableBuilder(+ listenable: voice,+ builder: (context, _) {+ final status = voice.status;+ final hasWords = voice.transcript.isNotEmpty;+ final canFinish = hasWords || status == VoiceInputStatus.listening;+ return ExcludeFocus(+ // Same reason as the key bar's: nothing here may take focus from the+ // terminal the keyboard button is about to hand it to.+ child: DecoratedBox(+ decoration: BoxDecoration(+ color: AppPalette.panelBg,+ border: Border(top: BorderSide(color: AppGlass.hair)),+ ),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(12, 8, 12, 10),+ child: MediaQuery.withNoTextScaling(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ _StatusRow(voice: voice, onDismiss: onDismiss),+ _Transcript(voice: voice),+ const SizedBox(height: 6),+ Row(+ children: [+ VoicePanelAction(+ key: const ValueKey('voice-keyboard'),+ icon: LucideIcons.keyboard300,+ label: 'Keyboard',+ onTap: onUseKeyboard,+ ),+ const Spacer(),+ VoiceMicButton(+ status: status,+ onPressed: voice.toggleListening,+ ),+ const Spacer(),+ VoicePanelAction(+ key: const ValueKey('voice-send'),+ icon: LucideIcons.arrowUp300,+ label: 'Send',+ emphasized: true,+ onTap:+ canSend &&+ canFinish &&+ !voice.isSending &&+ status != VoiceInputStatus.transcribing+ ? onSend+ : null,+ ),+ ],+ ),+ ],+ ),+ ),+ ),+ ),+ );+ },+ );+ }+}++/// Language, what the recognizer is doing, the way to start over and the way+/// out.+class _StatusRow extends StatelessWidget {+ const _StatusRow({required this.voice, required this.onDismiss});++ final VoiceInputController voice;+ final VoidCallback onDismiss;++ String get _label => switch (voice.status) {+ VoiceInputStatus.starting => 'Starting…',+ VoiceInputStatus.listening => 'Listening…',+ VoiceInputStatus.transcribing => 'Transcribing…',+ VoiceInputStatus.unavailable => 'Voice input is off',+ VoiceInputStatus.idle when voice.isSending => 'Sending…',+ VoiceInputStatus.idle => 'Tap the mic to talk',+ };++ @override+ Widget build(BuildContext context) {+ // With words on screen the transcript box has no room for a notice, so a+ // failed Send says so here instead.+ final notice = voice.transcript.isNotEmpty ? voice.notice : null;+ return SizedBox(+ height: 28,+ child: Row(+ children: [+ VoiceLanguageChip(+ label: voice.language.toUpperCase(),+ onTap: () => showVoiceLanguagePicker(+ context,+ current: voice.language,+ onSelected: voice.selectLanguage,+ ),+ ),+ const SizedBox(width: 8),+ Expanded(+ child: Text(+ notice ?? _label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontSize: 12,+ color: notice != null+ ? AppPalette.warn+ : AppPalette.textSecondary,+ ),+ ),+ ),+ if (voice.transcript.isNotEmpty)+ VoicePanelIconButton(+ key: const ValueKey('voice-clear'),+ icon: LucideIcons.x300,+ semanticLabel: 'Clear',+ onTap: voice.clear,+ ),+ VoicePanelIconButton(+ key: const ValueKey('voice-hide'),+ icon: LucideIcons.chevronDown300,+ semanticLabel: 'Hide voice input',+ onTap: onDismiss,+ ),+ ],+ ),+ );+ }+}++/// What was heard, newest words kept in view; the notice when there are none.+class _Transcript extends StatelessWidget {+ const _Transcript({required this.voice});++ final VoiceInputController voice;++ static const double _height = 58;++ @override+ Widget build(BuildContext context) {+ final words = voice.transcript;+ final notice = voice.notice;+ final showsWords = words.isNotEmpty;+ return SizedBox(+ height: _height,+ width: double.infinity,+ child: SingleChildScrollView(+ // Reversed so the latest words are the ones on screen as they arrive.+ reverse: true,+ child: Text(+ showsWords ? words : notice ?? '',+ style: TextStyle(+ fontSize: showsWords ? 16 : 13,+ height: 1.35,+ color: showsWords ? AppPalette.textPrimary : AppPalette.warn,+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/lib/phone/voice_language.dart b/mobile/lib/phone/voice_language.dartnew file mode 100644index 000000000..d8796fb10--- /dev/null+++ b/mobile/lib/phone/voice_language.dart@@ -0,0 +1,51 @@+import 'package:flutter/widgets.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'phone_sheet.dart';++typedef VoiceLanguage = ({String code, String name});++/// The languages `/api/voice/stt` transcribes, each named in itself.+///+/// ⚠️ A twin of `VOICE_WAV_LANGS` in the backend's `lib/deepgramWav.ts`. A code+/// the backend does not serve is not refused there — it is silently transcribed+/// as English — so a language added on one side belongs on the other.+const voiceLanguages = <VoiceLanguage>[+ (code: 'en', name: 'English'),+ (code: 'vi', name: 'Tiếng Việt'),+ (code: 'es', name: 'Español'),+ (code: 'fr', name: 'Français'),+ (code: 'ja', name: '日本語'),+ (code: 'it', name: 'Italiano'),+];++bool isVoiceLanguage(String? code) =>+ voiceLanguages.any((language) => language.code == code);++/// The first of the phone's own languages the backend serves, or English.+String defaultVoiceLanguage(List<Locale> preferred) {+ for (final locale in preferred) {+ if (isVoiceLanguage(locale.languageCode)) return locale.languageCode;+ }+ return 'en';+}++/// Picks the language voice input is transcribed in.+Future<void> showVoiceLanguagePicker(+ BuildContext context, {+ required String current,+ required ValueChanged<String> onSelected,+}) => showPhoneSheet(+ context,+ title: 'Voice input language',+ actions: [+ for (final language in voiceLanguages)+ PhoneSheetAction(+ icon: language.code == current+ ? LucideIcons.check300+ : LucideIcons.languages300,+ label: language.name,+ onTap: () => onSelected(language.code),+ ),+ ],+);diff --git a/mobile/lib/phone/voice_mic_button.dart b/mobile/lib/phone/voice_mic_button.dartnew file mode 100644index 000000000..67c6a4ece--- /dev/null+++ b/mobile/lib/phone/voice_mic_button.dart@@ -0,0 +1,188 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/shared/theme/app_theme.dart';++import 'voice_input_controller.dart';++/// The round button voice input is started and stopped with.+///+/// While listening it breathes — a glow and a ring that swell and fade — so it+/// reads as hearing from across the screen, which is where the eyes are: on the+/// terminal, not on this button.+///+/// ⚠️ The swell is painted, never laid out. The button sits in a fixed square+/// with room for the ring already in it: a panel whose height moved with the+/// animation would resize the terminal above it, and every resize is a+/// SIGWINCH on the far machine.+class VoiceMicButton extends StatefulWidget {+ const VoiceMicButton({+ super.key,+ required this.status,+ required this.onPressed,+ });++ final VoiceInputStatus status;+ final VoidCallback onPressed;++ static const double _extent = 72;+ static const double _core = 56;++ @override+ State<VoiceMicButton> createState() => _VoiceMicButtonState();+}++class _VoiceMicButtonState extends State<VoiceMicButton>+ with SingleTickerProviderStateMixin {+ late final AnimationController _breath = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 1400),+ );++ bool get _listening => widget.status == VoiceInputStatus.listening;++ @override+ void initState() {+ super.initState();+ _syncBreath();+ }++ @override+ void didUpdateWidget(VoiceMicButton oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.status != widget.status) _syncBreath();+ }++ @override+ void dispose() {+ _breath.dispose();+ super.dispose();+ }++ void _syncBreath() {+ if (_listening) {+ _breath.repeat();+ return;+ }+ _breath+ ..stop()+ ..value = 0;+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final status = widget.status;+ final lit =+ status == VoiceInputStatus.listening ||+ status == VoiceInputStatus.starting;+ final off = status == VoiceInputStatus.unavailable;+ final transcribing = status == VoiceInputStatus.transcribing;+ return Semantics(+ button: true,+ label: transcribing+ ? 'Transcribing'+ : lit+ ? 'Stop listening'+ : 'Start listening',+ child: GestureDetector(+ key: const ValueKey('voice-mic'),+ behavior: HitTestBehavior.opaque,+ onTap: () {+ HapticFeedback.lightImpact();+ widget.onPressed();+ },+ child: SizedBox.square(+ dimension: VoiceMicButton._extent,+ child: Stack(+ alignment: Alignment.center,+ children: [+ if (_listening) _Ring(breath: _breath),+ AnimatedContainer(+ duration: const Duration(milliseconds: 220),+ curve: Curves.easeOutCubic,+ width: VoiceMicButton._core,+ height: VoiceMicButton._core,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ gradient: lit+ ? LinearGradient(+ begin: Alignment.topLeft,+ end: Alignment.bottomRight,+ colors: [+ Color.lerp(AppPalette.accent, Colors.white, 0.18)!,+ AppPalette.accent,+ ],+ )+ : null,+ color: lit ? null : AppGlass.surfaceFill,+ border: Border.all(+ color: lit+ ? Colors.white.withValues(alpha: 0.28)+ : AppGlass.lift,+ ),+ boxShadow: lit+ ? [+ BoxShadow(+ color: AppPalette.accent.withValues(alpha: 0.45),+ blurRadius: 18,+ ),+ ]+ : null,+ ),+ // The words are with the backend: nothing to start or stop+ // until they are back, and the button says it is busy.+ child: transcribing+ ? Center(+ child: SizedBox.square(+ dimension: 22,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ color: AppPalette.accent,+ ),+ ),+ )+ : Icon(+ off ? LucideIcons.micOff300 : LucideIcons.mic300,+ size: 24,+ color: lit+ ? Colors.white+ : off+ ? AppPalette.textFaint+ : AppPalette.textPrimary,+ ),+ ),+ ],+ ),+ ),+ ),+ );+ }+}++/// The ring that leaves the button while it listens.+class _Ring extends StatelessWidget {+ const _Ring({required this.breath});++ final Animation<double> breath;++ @override+ Widget build(BuildContext context) => AnimatedBuilder(+ animation: breath,+ builder: (context, _) {+ final t = Curves.easeOut.transform(breath.value);+ return Transform.scale(+ scale: 1 + 0.28 * t,+ child: Container(+ width: VoiceMicButton._core,+ height: VoiceMicButton._core,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: AppPalette.accent.withValues(alpha: 0.35 * (1 - t)),+ ),+ ),+ );+ },+ );+}diff --git a/mobile/lib/phone/voice_notice.dart b/mobile/lib/phone/voice_notice.dartnew file mode 100644index 000000000..cd278fcfe--- /dev/null+++ b/mobile/lib/phone/voice_notice.dart@@ -0,0 +1,22 @@+/// The one line voice input shows when it cannot do what was asked.+abstract final class VoiceNotice {+ static const unavailable =+ 'Voice input is off. Allow Harness the microphone in Settings, or use the keyboard.';++ static const couldNotStart =+ "The microphone couldn't start. Tap the mic to try again.";++ static const nothingHeard = "Didn't catch that. Tap the mic to try again.";++ /// The microphone opened but delivered silence — a muted input, or a+ /// simulator the Mac has not given its microphone to. Speaking again will not+ /// help, so the notice does not suggest it.+ static const noSound =+ 'No sound reached the microphone. Check the input Harness is using.';++ static const notTranscribed =+ "Couldn't turn that into text. Tap the mic to try again.";++ static const notSent =+ "Not sent — this terminal isn't taking input right now.";+}diff --git a/mobile/lib/phone/voice_panel_parts.dart b/mobile/lib/phone/voice_panel_parts.dartnew file mode 100644index 000000000..12b290a07--- /dev/null+++ b/mobile/lib/phone/voice_panel_parts.dart@@ -0,0 +1,135 @@+import 'package:flutter/material.dart';++import 'package:harness_mobile/shared/theme/app_theme.dart';++/// The language voice input is transcribed in, as a two-letter chip.+class VoiceLanguageChip extends StatelessWidget {+ const VoiceLanguageChip({+ super.key,+ required this.label,+ required this.onTap,+ });++ final String label;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) => Semantics(+ button: true,+ label: 'Voice input language, $label',+ child: GestureDetector(+ key: const ValueKey('voice-language'),+ onTap: onTap,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),+ decoration: BoxDecoration(+ color: AppGlass.surfaceFill,+ borderRadius: BorderRadius.circular(6),+ border: Border.all(color: AppGlass.lift),+ ),+ child: Text(+ label,+ style: TextStyle(+ fontSize: 11,+ fontWeight: FontWeight.w600,+ color: AppPalette.textPrimary,+ ),+ ),+ ),+ ),+ );+}++/// A pill beside the mic. Null [onTap] draws it dimmed and dead.+class VoicePanelAction extends StatelessWidget {+ const VoicePanelAction({+ super.key,+ required this.icon,+ required this.label,+ required this.onTap,+ this.emphasized = false,+ });++ final IconData icon;+ final String label;+ final VoidCallback? onTap;+ final bool emphasized;++ @override+ Widget build(BuildContext context) {+ final live = onTap != null;+ final filled = emphasized && live;+ final foreground = filled+ ? Colors.white+ : live+ ? AppPalette.textPrimary+ : AppPalette.textFaint;+ return Semantics(+ button: true,+ enabled: live,+ label: label,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: onTap,+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 160),+ curve: Curves.easeOut,+ height: 40,+ padding: const EdgeInsets.symmetric(horizontal: 14),+ decoration: BoxDecoration(+ color: filled ? AppPalette.accent : AppGlass.surfaceFill,+ borderRadius: BorderRadius.circular(20),+ border: Border.all(+ color: filled+ ? Colors.white.withValues(alpha: 0.2)+ : AppGlass.lift,+ ),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(icon, size: 16, color: foreground),+ const SizedBox(width: 6),+ Text(+ label,+ style: TextStyle(+ fontSize: 14,+ fontWeight: FontWeight.w600,+ color: foreground,+ ),+ ),+ ],+ ),+ ),+ ),+ );+ }+}++/// A bare icon in the panel's status row: Clear, and `⌄`.+class VoicePanelIconButton extends StatelessWidget {+ const VoicePanelIconButton({+ super.key,+ required this.icon,+ required this.semanticLabel,+ required this.onTap,+ });++ final IconData icon;+ final String semanticLabel;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) => Semantics(+ button: true,+ label: semanticLabel,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: onTap,+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),+ child: Icon(icon, size: 18, color: AppPalette.textSecondary),+ ),+ ),+ );+}diff --git a/mobile/lib/phone/voice_recorder.dart b/mobile/lib/phone/voice_recorder.dartnew file mode 100644index 000000000..330f93db3--- /dev/null+++ b/mobile/lib/phone/voice_recorder.dart@@ -0,0 +1,121 @@+import 'dart:async';+import 'dart:typed_data';++import 'package:record/record.dart';++import 'voice_wav.dart';++/// One finished recording: the WAV to upload, how long it ran, and the loudest+/// sample in it — which is what tells "nobody spoke" apart from "no sound ever+/// reached the microphone".+typedef VoiceTake = ({Uint8List wav, Duration length, int peak});++/// The microphone behind [VoiceInputController], as the four things voice+/// input asks of it. Words are not its business: it hands back a WAV, and the+/// backend turns that into text.+///+/// A seam rather than `AudioRecorder` itself: the plugin is a platform channel,+/// and a widget test that reached it would hang on a call no recorder answers.+abstract interface class VoiceRecorder {+ /// Asks for the microphone the first time it runs. False once refused.+ Future<bool> allowed();++ /// Starts a recording. Throws when the microphone cannot be opened.+ Future<void> start();++ /// Ends the recording, or returns null when not one buffer was captured.+ Future<VoiceTake?> stop();++ /// Ends the recording and throws it away.+ Future<void> cancel();++ Future<void> dispose();+}++/// [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 {+ /// 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(+ encoder: AudioEncoder.pcm16bits,+ sampleRate: 16000,+ numChannels: 1,+ );++ final AudioRecorder _recorder = AudioRecorder();+ final BytesBuilder _pcm = BytesBuilder(copy: false);+ StreamSubscription<Uint8List>? _subscription;+ Completer<void>? _drained;++ /// What the platform actually records at. ⚠️ Not always [_requested]: a+ /// device may refuse 16 kHz and say so through `setOnConfigChanged`, and a+ /// WAV header stating the wrong rate plays back — and transcribes — at the+ /// wrong speed.+ int _sampleRate = _requested.sampleRate;+ int _channels = _requested.numChannels;++ @override+ Future<bool> allowed() => _recorder.hasPermission();++ @override+ Future<void> start() async {+ await _discardTake();+ _sampleRate = _requested.sampleRate;+ _channels = _requested.numChannels;+ await _recorder.setOnConfigChanged((config) {+ _sampleRate = config.sampleRate;+ _channels = config.numChannels;+ });+ final stream = await _recorder.startStream(_requested);+ final drained = _drained = Completer<void>();+ void finish([Object? _]) {+ if (!drained.isCompleted) drained.complete();+ }++ _subscription = stream.listen(_pcm.add, onDone: finish, onError: finish);+ }++ @override+ Future<VoiceTake?> stop() async {+ final drained = _drained;+ if (drained == null) return null;+ await _recorder.stop();+ // The plugin's own rule: the last buffer arrives with the stream's close,+ // not with `stop()`, so the take is only whole once the stream is done.+ await drained.future.timeout(const Duration(seconds: 2), onTimeout: () {});+ _subscription = null;+ _drained = null;+ final pcm = _pcm.takeBytes();+ if (pcm.isEmpty) return null;+ final samples = pcm.length ~/ (2 * _channels);+ return (+ wav: wavFromPcm16(pcm, sampleRate: _sampleRate, channels: _channels),+ length: Duration(microseconds: samples * 1000000 ~/ _sampleRate),+ peak: pcm16Peak(pcm),+ );+ }++ @override+ Future<void> cancel() async {+ if (_drained == null) return;+ await _recorder.cancel();+ await _discardTake();+ }++ @override+ Future<void> dispose() async {+ await _discardTake();+ await _recorder.dispose();+ }++ Future<void> _discardTake() async {+ await _subscription?.cancel();+ _subscription = null;+ _drained = null;+ _pcm.clear();+ }+}diff --git a/mobile/lib/phone/voice_wav.dart b/mobile/lib/phone/voice_wav.dartnew file mode 100644index 000000000..882edffab--- /dev/null+++ b/mobile/lib/phone/voice_wav.dart@@ -0,0 +1,47 @@+import 'dart:typed_data';++/// The loudest sample in 16-bit little-endian PCM, as a magnitude.+int pcm16Peak(Uint8List pcm) {+ final data = ByteData.sublistView(pcm);+ var peak = 0;+ for (var offset = 0; offset + 1 < pcm.length; offset += 2) {+ final sample = data.getInt16(offset, Endian.little).abs();+ if (sample > peak) peak = sample;+ }+ return peak;+}++/// Wraps raw 16-bit little-endian PCM in a 44-byte WAV header.+///+/// A self-describing container rather than bare samples, and the backend+/// depends on it: `/api/voice/stt` forwards the file under its own+/// Content-Type with NO rate or encoding hints, so the header is the only+/// place the sample rate is stated. Headerless PCM would be read as if its+/// first 44 bytes were a header. The twin of `wav()` in the CLI's+/// `cable/cableHost.ts`, which does the same for the dial's recordings.+Uint8List wavFromPcm16(+ Uint8List pcm, {+ required int sampleRate,+ required int channels,+}) {+ const headerLength = 44;+ final blockAlign = channels * 2;+ final header = ByteData(headerLength)+ ..setUint32(0, 0x52494646) // "RIFF"+ ..setUint32(4, 36 + pcm.length, Endian.little)+ ..setUint32(8, 0x57415645) // "WAVE"+ ..setUint32(12, 0x666d7420) // "fmt "+ ..setUint32(16, 16, Endian.little) // fmt chunk size+ ..setUint16(20, 1, Endian.little) // PCM+ ..setUint16(22, channels, Endian.little)+ ..setUint32(24, sampleRate, Endian.little)+ ..setUint32(28, sampleRate * blockAlign, Endian.little)+ ..setUint16(32, blockAlign, Endian.little)+ ..setUint16(34, 16, Endian.little) // bits per sample+ ..setUint32(36, 0x64617461) // "data"+ ..setUint32(40, pcm.length, Endian.little);+ return (BytesBuilder(copy: false)+ ..add(header.buffer.asUint8List())+ ..add(pcm))+ .takeBytes();+}diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dartindex 19928c0d5..4da04fb95 100644--- a/mobile/lib/widgets/terminal_panel.dart+++ b/mobile/lib/widgets/terminal_panel.dart@@ -89,6 +89,16 @@ class TerminalPanel extends StatefulWidget {final bool showHeader;final int focusRequest;+ /// Takes over the tap that would raise the software keyboard. Null leaves it+ /// to xterm, which is what every desktop tile does.+ ///+ /// Set on the phone, where that tap opens voice input instead+ /// (`phone/terminal_page.dart`). Claimed on tap DOWN — xterm then neither+ /// raises the keyboard nor reports the click to a mouse-tracking program —+ /// but run on tap UP, so a scroll that began as a press opens nothing. A tap+ /// that clears a selection, or opens a link, is still exactly that.+ final VoidCallback? onInputTap;+/// Whether this tile's composer textbox is showing. Only consulted for a remote machine.final bool composerVisible;final bool readOnly;@@ -118,6 +128,7 @@ class TerminalPanel extends StatefulWidget {this.compactHeader = false,this.showHeader = true,this.focusRequest = 0,+ this.onInputTap,this.composerVisible = false,this.readOnly = false,this.notice,@@ -193,6 +204,9 @@ class _TerminalPanelState extends State<TerminalPanel>null,);String? _pressedLink;++ /// Whether the tap in progress was claimed for [TerminalPanel.onInputTap].+ bool _inputTapClaimed = false;bool _openingLink = false;bool _linkRefreshPending = false;bool _followTail = true;@@ -1153,6 +1167,24 @@ class _TerminalPanelState extends State<TerminalPanel>_hoveredLink.value = target;}+ bool _onTerminalTapDown(TapDownDetails details, CellOffset cell) {+ _inputTapClaimed = false;+ if (_onLinkTapDown(details, cell)) return true;+ if (widget.onInputTap == null || _controller.selection != null) {+ return false;+ }+ return _inputTapClaimed = true;+ }++ void _onTerminalTapUp(TapUpDetails details, CellOffset cell) {+ if (!_inputTapClaimed) {+ _onLinkTapUp(details, cell);+ return;+ }+ _inputTapClaimed = false;+ widget.onInputTap?.call();+ }+bool _onLinkTapDown(TapDownDetails details, CellOffset cell) {_pressedLink = _linkModifierPressed? _linkAtPointer(details.globalPosition)@@ -1374,8 +1406,8 @@ class _TerminalPanelState extends State<TerminalPanel>allowedMimeTypes: const ['image/png'],onContentInserted: _onContentInserted,onKeyEvent: _onTerminalKey,- onTapDown: _onLinkTapDown,- onTapUp: _onLinkTapUp,+ onTapDown: _onTerminalTapDown,+ onTapUp: _onTerminalTapUp,// Constant on purpose. The click cursor is applied by// [_LinkTooltip]'s own MouseRegion, which repaints// without rebuilding this view.diff --git a/mobile/pubspec.lock b/mobile/pubspec.lockindex 04143c677..4b44c6439 100644--- a/mobile/pubspec.lock+++ b/mobile/pubspec.lock@@ -552,6 +552,54 @@ packages:url: "https://pub.dev"source: hostedversion: "3.2.2"+ record:+ dependency: "direct main"+ description:+ name: record+ sha256: "82539d1372e23cf51375fdfcba084f39912bcbf9a953b75d56596691f8f11c0f"+ url: "https://pub.dev"+ source: hosted+ version: "7.1.1"+ record_android:+ dependency: transitive+ description:+ name: record_android+ sha256: f5080279259c4ad769590f1c165762eaa4e414178adc2e2fab137103228e07ac+ url: "https://pub.dev"+ source: hosted+ version: "2.2.0"+ record_ios:+ dependency: transitive+ description:+ name: record_ios+ sha256: "21d189f49a598af4697dac4cc9e48389ac0a1fb3e916622b5504a58d9b96313e"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.1"+ record_linux:+ dependency: transitive+ description:+ name: record_linux+ sha256: b7484fdaf1f6d291543b9cf615e78096662b02df68d7a4728b13f352bde58d27+ url: "https://pub.dev"+ source: hosted+ version: "2.1.1"+ record_macos:+ dependency: transitive+ description:+ name: record_macos+ sha256: ced7495abf3d683e8a7dbe8fc96df8ea5722837a26f922b7cb7c5de11661bb46+ url: "https://pub.dev"+ source: hosted+ version: "2.1.1"+ record_platform_interface:+ dependency: transitive+ description:+ name: record_platform_interface+ sha256: d94b37cadb8fe203e64b0e9893271c0b71b34f2550ee7fb0c6105d650e00c1f5+ url: "https://pub.dev"+ source: hosted+ version: "2.1.0"record_use:dependency: transitivedescription:@@ -560,6 +608,22 @@ packages:url: "https://pub.dev"source: hostedversion: "0.6.0"+ record_web:+ dependency: transitive+ description:+ name: record_web+ sha256: "7f6950be87abacb05cf77eb6ca200b60f2c2a6af5d50236b5f4baf53f92e755e"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.3"+ record_windows:+ dependency: transitive+ description:+ name: record_windows+ sha256: "8195489a47b5e8246985d6213ff65aae1b14e32a0ca45dc5f680e8d503296e1b"+ url: "https://pub.dev"+ source: hosted+ version: "2.3.0"riverpod:dependency: transitivedescription:diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yamlindex 35f122b81..118552897 100644--- a/mobile/pubspec.yaml+++ b/mobile/pubspec.yaml@@ -59,6 +59,13 @@ dependencies:# for why the whole pipe past this point accepts nothing else.image_picker: ^1.2.3+ # Talking to an agent: tapping the terminal opens voice input before the+ # keyboard (`phone/voice_input_panel.dart`). This only RECORDS — 16 kHz mono+ # PCM, wrapped as WAV here — and the words come from the Harness backend's+ # `/api/voice/stt`, the same endpoint the dial's recordings go to. The OS+ # recognizer was tried first and misheard Vietnamese badly.+ record: ^7.1.1+dev_dependencies:flutter_test:sdk: flutterdiff --git a/mobile/test/terminal_input_dock_test.dart b/mobile/test/terminal_input_dock_test.dartnew file mode 100644index 000000000..7c4984594--- /dev/null+++ b/mobile/test/terminal_input_dock_test.dart@@ -0,0 +1,191 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/phone/terminal_input_dock.dart';+import 'package:harness_mobile/phone/terminal_key_bar.dart';+import 'package:harness_mobile/phone/voice_input_controller.dart';+import 'package:harness_mobile/phone/voice_input_panel.dart';+import 'package:harness_mobile/terminal/terminal_session.dart';++import 'voice_fakes.dart';++void main() {+ late FakeVoiceRecorder recorder;+ late FakeTranscriber backend;+ late VoiceInputController voice;+ late TerminalSession session;+ late List<(String, Map<String, dynamic>)> frames;+ late int dismissals;+ late int keyboardRequests;++ setUp(() {+ recorder = FakeVoiceRecorder();+ backend = FakeTranscriber();+ voice = VoiceInputController(+ transcriber: backend.call,+ recorder: recorder,+ storage: MemoryKeyValueStore(),+ preferredLocales: const [],+ );+ frames = [];+ dismissals = 0;+ keyboardRequests = 0;+ session =+ TerminalSession(+ machineId: 'm',+ agentId: 'a',+ agentName: 'Agent',+ engineId: 'claude',+ send: (type, payload) async {+ frames.add((type, payload));+ return true;+ },+ sendBinary: (_) async => true,+ )+ ..status = TerminalSessionStatus.controlling+ ..streamId = 's';+ });++ tearDown(() {+ voice.dispose();+ session.dispose();+ });++ Future<void> pumpDock(WidgetTester tester, {bool keyboardUp = false}) =>+ tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Align(+ alignment: Alignment.bottomCenter,+ child: TerminalInputDock(+ session: session,+ voice: voice,+ keyboardUp: keyboardUp,+ onDismiss: () => dismissals++,+ onUseKeyboard: () => keyboardRequests++,+ ),+ ),+ ),+ ),+ );++ testWidgets('nothing is drawn while no input is up', (tester) async {+ await pumpDock(tester);++ expect(find.byType(TerminalKeyBar), findsNothing);+ expect(find.byType(VoiceInputPanel), findsNothing);+ });++ testWidgets('the keyboard gets the key bar alone', (tester) async {+ await pumpDock(tester, keyboardUp: true);++ expect(find.byType(TerminalKeyBar), findsOneWidget);+ expect(find.byType(VoiceInputPanel), findsNothing);+ });++ testWidgets('voice input takes the key bar\'s place, and Send makes a turn', (+ tester,+ ) async {+ await pumpDock(tester);+ await voice.open();+ await tester.pump();++ expect(find.byType(TerminalKeyBar), findsNothing);+ expect(find.byType(VoiceInputPanel), findsOneWidget);+ expect(find.text('Listening…'), findsOneWidget);++ backend.replies.add('summarise the diff');+ await tester.tap(find.byKey(const ValueKey('voice-mic')));+ await tester.pump();+ expect(find.text('summarise the diff'), findsOneWidget);++ await tester.tap(find.byKey(const ValueKey('voice-send')));+ await tester.pumpAndSettle();++ // The composer's frame, not typed bytes — the machine owns the Enter.+ expect(frames, hasLength(1));+ expect(frames.single.$1, 'message');+ expect(frames.single.$2['content'], 'summarise the diff');+ expect(find.text('summarise the diff'), findsNothing);+ });++ testWidgets('Send is dead while the terminal takes no input', (tester) async {+ session.status = TerminalSessionStatus.takenOver;+ await pumpDock(tester);+ backend.replies.add('hello');+ await voice.open();+ await voice.stopListening();+ await tester.pump();++ await tester.tap(find.byKey(const ValueKey('voice-send')));+ await tester.pump();++ expect(frames, isEmpty);+ expect(voice.transcript, 'hello');+ });++ testWidgets('Keyboard and ⌄ hand back to the page', (tester) async {+ await pumpDock(tester);+ await voice.open();+ await tester.pump();++ await tester.tap(find.byKey(const ValueKey('voice-keyboard')));+ await tester.tap(find.byKey(const ValueKey('voice-hide')));++ expect(keyboardRequests, 1);+ expect(dismissals, 1);+ // The page is what closes it; this dock only reports the taps.+ voice.close();+ });++ testWidgets('Send mid-sentence finishes the take and sends it', (+ tester,+ ) async {+ backend.replies.add('ship it');+ await pumpDock(tester);+ await voice.open();+ await tester.pump();++ await tester.tap(find.byKey(const ValueKey('voice-send')));+ await tester.pumpAndSettle();++ expect(recorder.stops, 1);+ expect(frames.single.$2['content'], 'ship it');+ });++ testWidgets('the language chip names the language takes are sent in', (+ tester,+ ) async {+ await pumpDock(tester);+ await voice.open();+ await tester.pump();+ expect(find.text('EN'), findsOneWidget);++ await tester.tap(find.byKey(const ValueKey('voice-language')));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Tiếng Việt'));+ await tester.pumpAndSettle();++ expect(find.text('VI'), findsOneWidget);+ expect(voice.language, 'vi');+ voice.close();+ await tester.pumpAndSettle();+ });++ testWidgets('the mic stops a take and starts the next', (tester) async {+ await pumpDock(tester);+ await voice.open();+ await tester.pump();++ await tester.tap(find.byKey(const ValueKey('voice-mic')));+ await tester.pump();+ expect(voice.status, VoiceInputStatus.idle);+ expect(recorder.stops, 1);++ await tester.tap(find.byKey(const ValueKey('voice-mic')));+ await tester.pump();+ expect(voice.status, VoiceInputStatus.listening);+ // Stopped here, not left breathing: the ring repeats forever.+ voice.close();+ await tester.pumpAndSettle();+ });+}diff --git a/mobile/test/terminal_panel_input_tap_test.dart b/mobile/test/terminal_panel_input_tap_test.dartnew file mode 100644index 000000000..9e228a63c--- /dev/null+++ b/mobile/test/terminal_panel_input_tap_test.dart@@ -0,0 +1,109 @@+import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/terminal/terminal_session.dart';+import 'package:harness_mobile/widgets/terminal_panel.dart';+import 'package:xterm/xterm.dart';++/// On the phone a tap on the terminal opens voice input, and the keyboard is+/// only ever what voice input hands over to. The panel is where that tap is+/// taken: xterm would otherwise raise the keyboard itself before anyone else+/// could say otherwise.+void main() {+ late AppNotifier notifier;+ late TerminalSession session;+ late int inputTaps;++ setUp(() {+ notifier = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ );+ session = TerminalSession(+ machineId: 'm',+ agentId: 'a',+ agentName: 'Agent',+ engineId: 'claude',+ send: (_, _) async => true,+ sendBinary: (_) async => true,+ );+ session.status = TerminalSessionStatus.controlling;+ session.streamId = 's';+ inputTaps = 0;+ });++ tearDown(() {+ session.dispose();+ notifier.dispose();+ });++ Future<void> pumpPanel(+ WidgetTester tester, {+ VoidCallback? onInputTap,+ }) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SizedBox(+ width: 400,+ height: 320,+ child: TerminalPanel(+ notifier: notifier,+ session: session,+ focused: false,+ showHeader: false,+ onInputTap: onInputTap,+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ }++ testWidgets('a taken tap raises no keyboard, and runs the host instead', (+ tester,+ ) async {+ await pumpPanel(tester, onInputTap: () => inputTaps++);++ await tester.tap(find.byType(TerminalView));+ // Past the double-tap window, which is what holds a single tap back.+ await tester.pump(kDoubleTapTimeout);++ expect(inputTaps, 1);+ expect(tester.testTextInput.hasAnyClients, isFalse);+ });++ testWidgets('without a host the tap is still xterm\'s, keyboard and all', (+ tester,+ ) async {+ await pumpPanel(tester);++ await tester.tap(find.byType(TerminalView));+ // Past the double-tap window, which is what holds a single tap back.+ await tester.pump(kDoubleTapTimeout);++ expect(tester.testTextInput.hasAnyClients, isTrue);+ });++ testWidgets('a scroll that began as a press opens nothing', (tester) async {+ await pumpPanel(tester, onInputTap: () => inputTaps++);++ final gesture = await tester.startGesture(+ tester.getCenter(find.byType(TerminalView)),+ );+ // Held past the press timeout, so the tap recognizer has already reported+ // tap DOWN before the finger moves.+ await tester.pump(const Duration(milliseconds: 200));+ await gesture.moveBy(const Offset(0, -120));+ await gesture.up();+ await tester.pump();++ expect(inputTaps, 0);+ expect(tester.testTextInput.hasAnyClients, isFalse);+ });+}diff --git a/mobile/test/voice_encoding_test.dart b/mobile/test/voice_encoding_test.dartnew file mode 100644index 000000000..b13c508a6--- /dev/null+++ b/mobile/test/voice_encoding_test.dart@@ -0,0 +1,65 @@+import 'dart:convert';+import 'dart:typed_data';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/api/multipart_body.dart';+import 'package:harness_mobile/phone/voice_language.dart';+import 'package:harness_mobile/phone/voice_wav.dart';++void main() {+ test('a WAV header states the rate the audio was actually recorded at', () {+ final pcm = Uint8List.fromList(List.filled(320, 7));++ final wav = wavFromPcm16(pcm, sampleRate: 16000, channels: 1);+ final header = ByteData.sublistView(wav, 0, 44);++ expect(ascii.decode(wav.sublist(0, 4)), 'RIFF');+ expect(ascii.decode(wav.sublist(8, 16)), 'WAVEfmt ');+ expect(header.getUint32(4, Endian.little), 36 + 320);+ expect(header.getUint16(22, Endian.little), 1);+ expect(header.getUint32(24, Endian.little), 16000);+ expect(header.getUint32(28, Endian.little), 32000);+ expect(header.getUint16(34, Endian.little), 16);+ expect(ascii.decode(wav.sublist(36, 40)), 'data');+ expect(header.getUint32(40, Endian.little), 320);+ expect(wav.sublist(44), pcm);+ });++ test('the peak is the loudest sample, whichever its sign', () {+ final pcm = ByteData(6)+ ..setInt16(0, 120, Endian.little)+ ..setInt16(2, -3000, Endian.little)+ ..setInt16(4, 2999, Endian.little);++ expect(pcm16Peak(pcm.buffer.asUint8List()), 3000);+ expect(pcm16Peak(Uint8List(8)), 0);+ });++ test('the upload is one file part the backend reads as `file`', () {+ final body = multipartFileBody(+ field: 'file',+ filename: 'voice.wav',+ fileContentType: 'audio/wav',+ file: Uint8List.fromList([1, 2, 3]),+ boundary: 'b0',+ );++ expect(body.contentType, 'multipart/form-data; boundary=b0');+ final text = latin1.decode(body.bytes);+ expect(+ text,+ '--b0\r\n'+ 'Content-Disposition: form-data; name="file"; filename="voice.wav"\r\n'+ 'Content-Type: audio/wav\r\n\r\n'+ '\x01\x02\x03\r\n--b0--\r\n',+ );+ });++ test('the languages offered are exactly the ones the backend serves', () {+ // `VOICE_WAV_LANGS` in backend/src/lib/deepgramWav.ts.+ expect(+ [for (final language in voiceLanguages) language.code],+ ['en', 'vi', 'es', 'fr', 'ja', 'it'],+ );+ });+}diff --git a/mobile/test/voice_fakes.dart b/mobile/test/voice_fakes.dartnew file mode 100644index 000000000..50bc494f4--- /dev/null+++ b/mobile/test/voice_fakes.dart@@ -0,0 +1,79 @@+import 'dart:async';+import 'dart:typed_data';++import 'package:harness_mobile/core/local_key_value_store.dart';+import 'package:harness_mobile/phone/voice_recorder.dart';++/// A microphone the test talks into: [captured] is what the next [stop] hands+/// back — speech-loud unless a test says otherwise — and [pendingPermission]+/// holds a permission prompt open.+class FakeVoiceRecorder implements VoiceRecorder {+ bool permitted = true;+ Completer<bool>? pendingPermission;+ VoiceTake? captured = (+ wav: Uint8List.fromList([1, 2, 3, 4]),+ length: const Duration(seconds: 2),+ peak: 9000,+ );++ int starts = 0;+ int stops = 0;+ int cancels = 0;+ bool recording = false;++ @override+ Future<bool> allowed() =>+ pendingPermission?.future ?? Future.value(permitted);++ @override+ Future<void> start() async {+ starts++;+ recording = true;+ }++ @override+ Future<VoiceTake?> stop() async {+ stops++;+ recording = false;+ return captured;+ }++ @override+ Future<void> cancel() async {+ cancels++;+ recording = false;+ }++ @override+ Future<void> dispose() async {}+}++/// The backend's `/api/voice/stt`: answers each recording with the next of+/// [replies], or with [pending] held open until the test completes it.+class FakeTranscriber {+ final List<String> replies = [];+ final List<({int bytes, String lang})> calls = [];+ Completer<String>? pending;+ bool fails = false;++ Future<String> call(Uint8List wav, String lang) async {+ calls.add((bytes: wav.length, lang: lang));+ if (fails) throw Exception('HTTP 502');+ final held = pending;+ if (held != null) return held.future;+ return replies.isEmpty ? '' : replies.removeAt(0);+ }+}++class MemoryKeyValueStore implements LocalKeyValueStore {+ final Map<String, String> values = {};++ @override+ Future<String?> read(String key) async => values[key];++ @override+ Future<void> write(String key, String value) async => values[key] = value;++ @override+ Future<void> delete(String key) async => values.remove(key);+}diff --git a/mobile/test/voice_input_controller_test.dart b/mobile/test/voice_input_controller_test.dartnew file mode 100644index 000000000..8fdb9a720--- /dev/null+++ b/mobile/test/voice_input_controller_test.dart@@ -0,0 +1,277 @@+import 'dart:async';+import 'dart:typed_data';+import 'dart:ui';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/phone/voice_input_controller.dart';+import 'package:harness_mobile/phone/voice_notice.dart';++import 'voice_fakes.dart';++void main() {+ late FakeVoiceRecorder recorder;+ late FakeTranscriber backend;+ late MemoryKeyValueStore storage;+ late VoiceInputController voice;++ VoiceInputController controller({List<Locale> locales = const []}) =>+ VoiceInputController(+ transcriber: backend.call,+ recorder: recorder,+ storage: storage,+ preferredLocales: locales,+ );++ setUp(() {+ recorder = FakeVoiceRecorder();+ backend = FakeTranscriber();+ storage = MemoryKeyValueStore();+ voice = controller();+ });++ tearDown(() => voice.dispose());++ test('opening is recording: the panel is up and the mic is on', () async {+ await voice.open();++ expect(voice.isOpen, isTrue);+ expect(voice.status, VoiceInputStatus.listening);+ expect(recorder.recording, isTrue);+ });++ test('stopping sends the take to the backend and keeps its words', () async {+ backend.replies.add('fix the failing test');+ await voice.open();++ await voice.stopListening();++ expect(backend.calls.single.lang, 'en');+ expect(voice.transcript, 'fix the failing test');+ expect(voice.status, VoiceInputStatus.idle);+ });++ test(+ 'the words wait for the backend: nothing shows mid-transcription',+ () async {+ backend.pending = Completer<String>();+ await voice.open();++ final stopping = voice.stopListening();+ await Future<void>.delayed(Duration.zero);+ expect(voice.status, VoiceInputStatus.transcribing);+ expect(voice.transcript, isEmpty);++ backend.pending!.complete('run the tests');+ await stopping;+ expect(voice.transcript, 'run the tests');+ },+ );++ test('a second take adds to what the first one heard', () async {+ backend.replies.addAll(['run the tests', 'then commit']);+ await voice.open();+ await voice.toggleListening();++ await voice.toggleListening();+ await voice.toggleListening();++ expect(voice.transcript, 'run the tests then commit');+ });++ test('a refused microphone says so, and the next open asks again', () async {+ recorder.permitted = false;+ await voice.open();++ expect(voice.status, VoiceInputStatus.unavailable);+ expect(voice.notice, VoiceNotice.unavailable);++ recorder.permitted = true;+ voice.close();+ await voice.open();+ expect(voice.status, VoiceInputStatus.listening);+ });++ test('closing while the permission prompt is up records nothing', () async {+ recorder.pendingPermission = Completer<bool>();+ final opening = voice.open();+ expect(voice.status, VoiceInputStatus.starting);++ voice.close();+ recorder.pendingPermission!.complete(true);+ await opening;++ expect(recorder.starts, 0);+ expect(voice.status, VoiceInputStatus.idle);+ });++ test('a failed transcription says so and adds nothing', () async {+ backend.fails = true;+ await voice.open();++ await voice.stopListening();++ expect(voice.transcript, isEmpty);+ expect(voice.notice, VoiceNotice.notTranscribed);+ });++ test('an empty transcript comes back as a notice, not a message', () async {+ await voice.open();++ await voice.stopListening();++ expect(voice.transcript, isEmpty);+ expect(voice.notice, VoiceNotice.nothingHeard);+ });++ test('a silent microphone is said so, and nothing is uploaded', () async {+ recorder.captured = (+ wav: Uint8List(44),+ length: const Duration(seconds: 3),+ peak: 0,+ );+ await voice.open();++ await voice.stopListening();++ expect(backend.calls, isEmpty);+ expect(voice.notice, VoiceNotice.noSound);+ });++ test('a take with no audio at all is said so too', () async {+ recorder.captured = null;+ await voice.open();++ await voice.stopListening();++ expect(backend.calls, isEmpty);+ expect(voice.notice, VoiceNotice.noSound);+ });++ test('send hands over everything heard and empties the panel', () async {+ backend.replies.add('open a PR');+ await voice.open();+ await voice.stopListening();++ final delivered = <String>[];+ await voice.submit((text) async {+ delivered.add(text);+ return true;+ });++ expect(delivered, ['open a PR']);+ expect(voice.transcript, isEmpty);+ });++ test('send mid-sentence ends the take and sends it with the rest', () async {+ backend.replies.addAll(['open a PR', 'for this branch']);+ await voice.open();+ await voice.stopListening();+ await voice.startListening();++ final delivered = <String>[];+ await voice.submit((text) async {+ delivered.add(text);+ return true;+ });++ expect(recorder.stops, 2);+ expect(delivered, ['open a PR for this branch']);+ });++ test('a take that fails mid-send sends none of the message', () async {+ backend.replies.add('delete the');+ await voice.open();+ await voice.stopListening();+ await voice.startListening();+ backend.fails = true;++ var delivered = false;+ await voice.submit((_) async => delivered = true);++ expect(delivered, isFalse);+ expect(voice.transcript, 'delete the');+ expect(voice.notice, VoiceNotice.notTranscribed);+ });++ test('a send that fails keeps the words for another try', () async {+ backend.replies.add('deploy');+ await voice.open();+ await voice.stopListening();++ await voice.submit((_) async => false);++ expect(voice.transcript, 'deploy');+ expect(voice.notice, VoiceNotice.notSent);+ expect(voice.isSending, isFalse);+ });++ test('closing mid-transcription drops the words when they arrive', () async {+ backend.pending = Completer<String>();+ await voice.open();+ final stopping = voice.stopListening();+ await Future<void>.delayed(Duration.zero);++ voice.close();+ backend.pending!.complete('never mind');+ await stopping;++ expect(voice.isOpen, isFalse);+ expect(voice.transcript, isEmpty);+ });++ test('closing while recording throws the recording away', () async {+ await voice.open();++ voice.close();++ expect(recorder.cancels, 1);+ expect(backend.calls, isEmpty);+ });++ test(+ 'handing over to the keyboard transcribes the take in progress',+ () async {+ backend.replies.addAll(['rename the', 'module']);+ await voice.open();+ await voice.stopListening();+ await voice.startListening();++ expect(await voice.takeTranscript(), 'rename the module');+ expect(voice.transcript, isEmpty);+ },+ );++ test("the phone's language is the default, when the backend serves it", () {+ final vietnamese = controller(locales: const [Locale('vi', 'VN')]);+ final german = controller(locales: const [Locale('de'), Locale('fr')]);+ addTearDown(vietnamese.dispose);+ addTearDown(german.dispose);++ expect(vietnamese.language, 'vi');+ expect(german.language, 'fr');+ });++ test(+ 'a chosen language is used, remembered, and restored next time',+ () async {+ await voice.selectLanguage('vi');+ backend.replies.add('xin chào');+ await voice.open();+ await voice.stopListening();++ expect(backend.calls.single.lang, 'vi');+ expect(storage.values['voice_input_language'], 'vi');++ final later = controller();+ addTearDown(later.dispose);+ await Future<void>.delayed(Duration.zero);+ expect(later.language, 'vi');+ },+ );++ test('a language the backend does not serve is refused', () async {+ await voice.selectLanguage('de');++ expect(voice.language, 'en');+ });+}