Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore: files changed app/src/assets/audio/README.md,app/src/assets/audio/ptt-close.wav,app/src/asset

Steven Enamakel796afb3c4a6d
diff --git a/app/src/assets/audio/README.md b/app/src/assets/audio/README.md
deleted file mode 100644
index 0f7583fcb6..0000000000
--- a/app/src/assets/audio/README.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# Audio assets
-
-Short UI chimes for the push-to-talk feature, driven by [`usePttHotkey.ts`](../../hooks/usePttHotkey.ts) and the [`tauri-plugin-ptt`](../../../../packages/tauri-plugin-ptt/README.md) plugin.
-
-| File | Purpose | Source | License |
-| ---------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------- | -------------------- |
-| [`ptt-open.wav`](./ptt-open.wav) | Mic opened (PTT key pressed). | Generated locally with Python `wave` + sine generator (800 to 1200 Hz sweep). | CC0 / Public Domain. |
-| [`ptt-close.wav`](./ptt-close.wav) | Mic closed (PTT key released). | Generated locally with Python `wave` + sine generator (1200 to 800 Hz sweep). | CC0 / Public Domain. |
-| [`ptt-error.wav`](./ptt-error.wav) | Session aborted (empty audio, mic permission denied, etc.). | Generated locally with Python `wave` + sine generator (250 Hz tone). | CC0 / Public Domain. |
-
-All clips are 80 to 120 ms long and LUFS-normalized to roughly match the in-app notification sound (about -16 LUFS). Replace freely with better-sounding equivalents. Just keep them under 200ms and CC0/MIT-equivalent.
diff --git a/app/src/assets/audio/ptt-close.wav b/app/src/assets/audio/ptt-close.wav
deleted file mode 100644
index 761d30766a..0000000000
Binary files a/app/src/assets/audio/ptt-close.wav and /dev/null differ
diff --git a/app/src/assets/audio/ptt-error.wav b/app/src/assets/audio/ptt-error.wav
deleted file mode 100644
index f6034a3e69..0000000000
Binary files a/app/src/assets/audio/ptt-error.wav and /dev/null differ
diff --git a/app/src/assets/audio/ptt-open.wav b/app/src/assets/audio/ptt-open.wav
deleted file mode 100644
index a4798b3ed3..0000000000
Binary files a/app/src/assets/audio/ptt-open.wav and /dev/null differ
diff --git a/app/src/components/DictationHotkeyManager.tsx b/app/src/components/DictationHotkeyManager.tsx
deleted file mode 100644
index eae3cf5d2c..0000000000
--- a/app/src/components/DictationHotkeyManager.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * DictationHotkeyManager
- *
- * Headless component that auto-registers the global dictation hotkey on mount
- * and logs toggle events. Mount inside the main app tree after the core host
- * has been initialized so core RPC is available when it starts up.
- */
-import { useEffect } from 'react';
-
-import { useDictationHotkey } from '../hooks/useDictationHotkey';
-
-export default function DictationHotkeyManager() {
- const { dictationEnabled, hotkeyRegistered, toggleCount, hotkey } = useDictationHotkey();
-
- useEffect(() => {
- if (toggleCount === 0) return;
- console.debug(`[dictation] toggle #${toggleCount} — dictation overlay should show/hide`);
- }, [toggleCount]);
-
- useEffect(() => {
- if (hotkeyRegistered) {
- console.debug(`[dictation] global hotkey active: ${hotkey}`);
- }
- }, [hotkeyRegistered, hotkey]);
-
- useEffect(() => {
- console.debug(`[dictation] enabled=${dictationEnabled}`);
- }, [dictationEnabled]);
-
- return null;
-}
diff --git a/app/src/components/PttHotkeyManager.tsx b/app/src/components/PttHotkeyManager.tsx
deleted file mode 100644
index 6340b2ae91..0000000000
--- a/app/src/components/PttHotkeyManager.tsx
+++ /dev/null
@@ -1,145 +0,0 @@
-/**
- * PttHotkeyManager
- *
- * Renderless boot-time wiring for the global push-to-talk feature:
- * 1. Registers the persisted PTT shortcut with the Tauri shell via
- * `usePttHotkey()`.
- * 2. Owns the singleton `pttService` state machine (built in T10), wired to
- * real audio capture (MediaRecorder), STT (voice_transcribe_bytes RPC),
- * chat send, thread resolution, chime playback, and overlay window
- * visibility.
- * 3. Subscribes to the Tauri events `ptt://start` / `ptt://stop` emitted by
- * the Rust shell when the global hotkey transitions edges, and forwards
- * them into the service.
- *
- * The service is constructed once for the AppShell's lifetime — multiple
- * mounts would create competing state machines fighting over the same mic.
- */
-import { listen, type UnlistenFn } from '@tauri-apps/api/event';
-import debug from 'debug';
-import { useEffect, useMemo, useRef } from 'react';
-import { useDispatch, useStore } from 'react-redux';
-
-import { cancelPttAudio, finalizePttAudio, startPttAudio } from '../features/voice/pttAudio';
-import { playPttChime } from '../features/voice/pttChimes';
-import { createNewVoiceThread, resolveActiveThreadId } from '../features/voice/pttThread';
-import { transcribePttAudio } from '../features/voice/pttTranscribe';
-import { usePttHotkey } from '../hooks/usePttHotkey';
-import { chatSend } from '../services/chatService';
-import { createPttService } from '../services/pttService';
-import type { RootState } from '../store';
-import { setIsHeld } from '../store/pttSlice';
-import { showPttOverlay } from '../utils/tauriCommands/ptt';
-
-const log = debug('app:ptt:manager');
-
-interface PttEventPayload {
- session_id: number;
-}
-
-// Stable monotonic clock for the pttService state machine. Defined at
-// module scope so the useMemo factory below doesn't reference an impure
-// function during render (react-hooks/purity).
-const monotonicNow = (): number => Date.now();
-
-export default function PttHotkeyManager(): null {
- // Register / unregister the configured hotkey with the Tauri shell.
- usePttHotkey();
-
- const dispatch = useDispatch();
- const store = useStore<RootState>();
- const unlistenRef = useRef<UnlistenFn[]>([]);
-
- const service = useMemo(
- () =>
- createPttService({
- audioCapture: { start: startPttAudio, finalize: finalizePttAudio, cancel: cancelPttAudio },
- transcribe: transcribePttAudio,
- sendMessage: async ({ threadId, body, speakReply, metadata }) => {
- await chatSend({
- threadId,
- message: body,
- speakReply,
- source: metadata.source,
- sessionId: metadata.session_id,
- });
- },
- resolveActiveThreadId,
- createNewVoiceThread,
- playChime: playPttChime,
- showOverlay: async (active, sessionId) => {
- // Respect the user's "show overlay" preference for the start edge,
- // but always tear it down on stop so a mid-session toggle can't leave
- // the overlay stuck visible.
- if (!active || store.getState().ptt.showOverlay) {
- await showPttOverlay(active, sessionId);
- }
- },
- getSettings: () => {
- const ptt = store.getState().ptt;
- return { speakReplies: ptt.speakReplies, showOverlay: ptt.showOverlay };
- },
- now: monotonicNow,
- // 10 s ceiling on a single PTT recording — matches the spec; if the
- // user holds the key longer the watchdog finalises so we don't keep
- // an open mic forever.
- watchdogMs: 10_000,
- // Recordings shorter than this are treated as accidental taps.
- minAudioMs: 250,
- logger: {
- debug: (msg, meta) => log(msg, meta ?? {}),
- info: (msg, meta) => log(msg, meta ?? {}),
- warn: (msg, meta) => log(msg, meta ?? {}),
- },
- }),
- // The service holds an internal state machine — recreating it across
- // store updates would orphan in-flight sessions. The closures above read
- // the latest store state on every call, so a stable identity is correct.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- []
- );
-
- useEffect(() => {
- let mounted = true;
- const subscribe = async () => {
- try {
- const offStart = await listen<PttEventPayload>('ptt://start', e => {
- dispatch(setIsHeld(true));
- service.onStart(e.payload.session_id).catch(err => {
- log('onStart failed', { sessionId: e.payload.session_id, err: String(err) });
- });
- });
- const offStop = await listen<PttEventPayload>('ptt://stop', e => {
- dispatch(setIsHeld(false));
- service.onStop(e.payload.session_id).catch(err => {
- log('onStop failed', { sessionId: e.payload.session_id, err: String(err) });
- });
- });
- if (!mounted) {
- offStart();
- offStop();
- return;
- }
- unlistenRef.current.push(offStart, offStop);
- log('PttHotkeyManager: listeners attached');
- } catch (err) {
- log('PttHotkeyManager: failed to attach listeners', err);
- }
- };
- void subscribe();
- return () => {
- mounted = false;
- const offs = unlistenRef.current;
- unlistenRef.current = [];
- for (const off of offs) {
- try {
- off();
- } catch (err) {
- log('PttHotkeyManager: unlisten threw', err);
- }
- }
- };
- }, [dispatch, service]);
-
- return null;
-}
diff --git a/app/src/components/settings/settingsRouteRegistry.ts b/app/src/components/settings/settingsRouteRegistry.ts
index 144a4b23d0..8d0b08f3cf 100644
--- a/app/src/components/settings/settingsRouteRegistry.ts
+++ b/app/src/components/settings/settingsRouteRegistry.ts
@@ -357,7 +357,7 @@ export const SETTINGS_ROUTE_REGISTRY: SettingsRegistryEntry[] = [
titleKey: 'pages.settings.ai.voice',
descriptionKey: 'pages.settings.ai.voiceDesc',
section: 'ai',
- searchKeywords: ['tts', 'stt', 'speech', 'dictation', 'audio'],
+ searchKeywords: ['tts', 'stt', 'speech', 'audio'],
// Surfaced on the Connections page (Intelligence group); route kept for
// deep-link compatibility but no longer in the settings sidebar.
},
diff --git a/app/src/components/skills/VoiceSetupModal.tsx b/app/src/components/skills/VoiceSetupModal.tsx
deleted file mode 100644
index b73409d3f0..0000000000
--- a/app/src/components/skills/VoiceSetupModal.tsx
+++ /dev/null
@@ -1,175 +0,0 @@
-/**
- * Voice Intelligence setup/enable modal.
- *
- * Two-step flow: if no speech-to-text engine is configured, directs to Voice
- * settings. Otherwise, starts the voice server and shows success.
- * Speech-to-text is hosted; nothing is downloaded.
- */
-import { useState } from 'react';
-import { useNavigate } from 'react-router-dom';
-
-import type { VoiceSkillStatus } from '../../features/voice/useVoiceSkillStatus';
-import { useT } from '../../lib/i18n/I18nContext';
-import {
- openhumanUpdateVoiceServerSettings,
- openhumanVoiceServerStart,
-} from '../../utils/tauriCommands/voice';
-import { CheckIcon, WarningIcon } from '../ui';
-import Button from '../ui/Button';
-import {
- SetupNotice,
- SetupSettingRow,
- SetupSuccess,
- SkillSetupModalShell,
-} from './SkillSetupPrimitives';
-
-type Step = 'setup' | 'enable' | 'success';
-
-interface Props {
- onClose: () => void;
- skillStatus: VoiceSkillStatus;
-}
-
-export default function VoiceSetupModal({ onClose, skillStatus }: Props) {
- const navigate = useNavigate();
- const { t } = useT();
- const { sttModelMissing, serverStatus } = skillStatus;
-
- const [step, setStep] = useState<Step>(sttModelMissing ? 'setup' : 'enable');
- const [isEnabling, setIsEnabling] = useState(false);
- const [enableError, setEnableError] = useState<string | null>(null);
-
- const handleEnable = async () => {
- setIsEnabling(true);
- setEnableError(null);
- try {
- // Enable auto-start in settings
- await openhumanUpdateVoiceServerSettings({ auto_start: true });
- // Start the voice server
- await openhumanVoiceServerStart();
- setStep('success');
- } catch (error) {
- setEnableError(error instanceof Error ? error.message : t('skills.setup.voice.startError'));
- } finally {
- setIsEnabling(false);
- }
- };
-
- const handleGoToVoiceSettings = () => {
- onClose();
- // The STT engine is picked on the Voice settings panel.
- navigate('/settings/voice');
- };
-
- const handleGoToSettings = () => {
- onClose();
- navigate('/settings/voice');
- };
-
- return (
- <SkillSetupModalShell
- onClose={onClose}
- title={t('skills.setup.voice.title')}
- titleId="voice-setup-title"
- subtitle={
- <>
- {step === 'setup' && t('skills.setup.voice.stepSetup')}
- {step === 'enable' && t('skills.setup.voice.stepEnable')}
- {step === 'success' && t('skills.setup.voice.stepSuccess')}
- </>
- }
- icon={
- <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={1.8}
- d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"
- />
- </svg>
- }>
- {/* ─── Setup step: STT model missing ─── */}
- {step === 'setup' && (
- <div className="space-y-4">
- <SetupNotice tone="amber" icon={<WarningIcon className="w-4 h-4 text-amber-500" />}>
- <div className="text-xs text-amber-700 leading-relaxed">
- <p className="font-medium">{t('skills.setup.voice.sttNotReady')}</p>
- <p className="mt-1">{t('skills.setup.voice.sttNotReadyDesc')}</p>
- </div>
- </SetupNotice>
-
- <p className="text-xs text-content-muted leading-relaxed">
- {t('skills.setup.voice.sttReturnHint')}
- </p>
-
- <div className="flex flex-col gap-2">
- <Button variant="primary" size="lg" onClick={handleGoToVoiceSettings} className="w-full">
- {t('skills.setup.voice.downloadSttBtn')}
- </Button>
- <Button variant="secondary" size="lg" onClick={onClose} className="w-full">
- {t('common.cancel')}
- </Button>
- </div>
- </div>
- )}
-
- {/* ─── Enable step ─── */}
- {step === 'enable' && (
- <div className="space-y-4">
- <SetupNotice tone="sage" icon={<CheckIcon className="w-4 h-4 text-sage-500" />}>
- {t('skills.setup.voice.sttReady')}
- </SetupNotice>
-
- <p className="text-xs text-content-muted leading-relaxed">
- {t('skills.setup.voice.enableDesc')}
- </p>
-
- <div className="space-y-2">
- <SetupSettingRow
- label={t('skills.setup.voice.hotkey')}
- value={serverStatus?.hotkey ?? 'Fn'}
- mono
- />
- <SetupSettingRow
- label={t('skills.setup.voice.activation')}
- value={
- serverStatus?.activation_mode === 'push'
- ? t('voice.pushToTalk')
- : t('voice.tapToToggle')
- }
- />
- </div>
-
- {enableError && <SetupNotice tone="coral">{enableError}</SetupNotice>}
-
- <Button
- variant="primary"
- size="lg"
- onClick={() => void handleEnable()}
- disabled={isEnabling}
- className="w-full">
- {isEnabling ? t('skills.setup.voice.starting') : t('skills.setup.voice.startBtn')}
- </Button>
- </div>
- )}
-
- {/* ─── Success step ─── */}
- {step === 'success' && (
- <SetupSuccess
- title={t('skills.setup.voice.activeTitle')}
- description={
- <>
- {t('skills.setup.voice.activeDescPrefix')}{' '}
- <span className="font-mono font-medium">{serverStatus?.hotkey ?? 'Fn'}</span>{' '}
- {t('skills.setup.voice.activeDescSuffix')}
- </>
- }
- settingsLabel={t('skills.setup.voice.customizeSettings')}
- finishLabel={t('common.finish')}
- onSettings={handleGoToSettings}
- onFinish={onClose}
- />
- )}
- </SkillSetupModalShell>
- );
-}
diff --git a/app/src/features/voice/pttAudio.ts b/app/src/features/voice/pttAudio.ts
deleted file mode 100644
index 62e4aabc20..0000000000
--- a/app/src/features/voice/pttAudio.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-/**
- * pttAudio — push-to-talk mic-capture adapter for pttService.
- *
- * Dictation's existing recorder lives in the Rust core (rdev-driven, fed by
- * the audio_capture domain) and surfaces results asynchronously over a
- * dedicated socket — it is not exposed as a reusable JS function that returns
- * a buffer. Rather than refactor that flow, we use a self-contained
- * MediaRecorder in the renderer. The captured audio is sent straight to the
- * existing `voice_transcribe_bytes` RPC (see `pttTranscribe.ts`), so we still
- * reuse the core's STT path; only the capture layer is renderer-owned.
- *
- * Module-level state is intentional — the singleton matches `pttService`'s
- * lifecycle (one active PTT session at a time, owned by `PttHotkeyManager`).
- * `cancel` is idempotent so the watchdog / preempt paths can call it freely.
- */
-import type { FinalizedAudio } from '../../services/pttService';
-
-interface Recorder {
- recorder: MediaRecorder;
- stream: MediaStream;
- chunks: Blob[];
- startedAt: number;
-}
-
-let active: Recorder | null = null;
-let lastMimeType: string | undefined;
-
-function pickMimeType(): string | undefined {
- // Prefer webm/opus — small, broadly supported, and accepted by every hosted
- // STT engine; the core's `extension` hint is "webm".
- const preferred = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', 'audio/mp4'];
- for (const mime of preferred) {
- if (typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported(mime)) {
- return mime;
- }
- }
- return undefined;
-}
-
-function stopTracks(stream: MediaStream): void {
- for (const track of stream.getTracks()) {
- try {
- track.stop();
- } catch {
- /* ignore */
- }
- }
-}
-
-export async function startPttAudio(opts: { sessionTag: string }): Promise<void> {
- // If a prior session was abandoned without a finalize/cancel, free it now
- // so we don't leak the mic.
- if (active) {
- console.debug('[ptt-audio] startPttAudio called with active recorder — cancelling first');
- await cancelPttAudio();
- }
-
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
- const mimeType = pickMimeType();
- const recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
- const chunks: Blob[] = [];
-
- recorder.addEventListener('dataavailable', (e: BlobEvent) => {
- if (e.data && e.data.size > 0) chunks.push(e.data);
- });
-
- active = { recorder, stream, chunks, startedAt: window.performance.now() };
- lastMimeType = mimeType ?? recorder.mimeType ?? undefined;
- recorder.start();
- console.debug('[ptt-audio] started', { sessionTag: opts.sessionTag, mimeType });
-}
-
-export async function finalizePttAudio(): Promise<FinalizedAudio> {
- if (!active) {
- throw new Error('[ptt-audio] finalize called with no active recorder');
- }
- const session = active;
- active = null;
-
- const done = new Promise<void>(resolve => {
- if (session.recorder.state === 'inactive') {
- resolve();
- return;
- }
- session.recorder.addEventListener('stop', () => resolve(), { once: true });
- });
- try {
- if (session.recorder.state !== 'inactive') session.recorder.stop();
- } catch (err) {
- console.warn('[ptt-audio] recorder.stop() threw', err);
- }
- await done;
- stopTracks(session.stream);
-
- const blob = new Blob(session.chunks, { type: session.recorder.mimeType || 'audio/webm' });
- const buffer = await blob.arrayBuffer();
- const durationMs = Math.round(window.performance.now() - session.startedAt);
- console.debug('[ptt-audio] finalized', { durationMs, bytes: buffer.byteLength });
- return { buffer, durationMs };
-}
-
-export async function cancelPttAudio(): Promise<void> {
- if (!active) return;
- const session = active;
- active = null;
- try {
- if (session.recorder.state !== 'inactive') session.recorder.stop();
- } catch {
- /* ignore */
- }
- stopTracks(session.stream);
- console.debug('[ptt-audio] cancelled');
-}
-
-/**
- * Maps the last-used MIME type to an extension string the core's
- * `voice_transcribe_bytes` RPC accepts. Persists across `finalizePttAudio`
- * (which clears `active`) so the transcribe step still gets the right hint.
- */
-export function lastRecordedExtension(): string {
- const mime = lastMimeType ?? '';
- if (mime.includes('webm')) return 'webm';
- if (mime.includes('ogg')) return 'ogg';
- if (mime.includes('mp4')) return 'm4a';
- return 'webm';
-}
diff --git a/app/src/features/voice/pttChimes.ts b/app/src/features/voice/pttChimes.ts
deleted file mode 100644
index db4a45a4c7..0000000000
--- a/app/src/features/voice/pttChimes.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * pttChimes — short audio cue playback for push-to-talk session boundaries.
- *
- * The three WAVs (open/close/error) live in `app/src/assets/audio/`. Vite
- * resolves binary assets imported with a string URL out-of-the-box, so a
- * standard `import openSrc from '...wav'` returns a URL the browser can fetch.
- *
- * HTMLAudioElement instances are cached per kind so repeat playback doesn't
- * re-decode the WAV on every press. `play()` may reject under the autoplay
- * policy (no user gesture yet) — we swallow that since PTT is triggered by
- * a global hotkey, not a click, and the chime is non-critical.
- */
-import closeSrc from '../../assets/audio/ptt-close.wav';
-import errorSrc from '../../assets/audio/ptt-error.wav';
-import openSrc from '../../assets/audio/ptt-open.wav';
-
-type ChimeKind = 'open' | 'close' | 'error';
-
-const sources: Record<ChimeKind, string> = { open: openSrc, close: closeSrc, error: errorSrc };
-
-const cache: Partial<Record<ChimeKind, HTMLAudioElement>> = {};
-
-function getElement(kind: ChimeKind): HTMLAudioElement {
- const cached = cache[kind];
- if (cached) return cached;
- const el = new window.Audio(sources[kind]);
- el.preload = 'auto';
- cache[kind] = el;
- return el;
-}
-
-export async function playPttChime(kind: ChimeKind): Promise<void> {
- try {
- const el = getElement(kind);
- el.currentTime = 0;
- await el.play();
- } catch (err) {
- // Autoplay policy can reject silently for the first chime if no gesture
- // has been observed. PTT is non-critical UX feedback so we just log.
- console.debug('[ptt-chime] play failed', { kind, err: String(err) });
- }
-}
diff --git a/app/src/features/voice/pttThread.ts b/app/src/features/voice/pttThread.ts
deleted file mode 100644
index 9b7c0a6409..0000000000
--- a/app/src/features/voice/pttThread.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * pttThread — thread-resolution adapter for pttService.
- *
- * Resolves which thread a PTT-captured message lands in:
- * 1. The currently-selected thread (state.thread.selectedThreadId) if any.
- * 2. Otherwise create a fresh thread via `threads_create_new`.
- *
- * Keeping this in its own module keeps `PttHotkeyManager` declarative — the
- * service interface only needs two thunks (`resolveActiveThreadId`,
- * `createNewVoiceThread`), and the redux access stays out of React render
- * scope.
- */
-import { threadApi } from '../../services/api/threadApi';
-import { store } from '../../store';
-
-export async function resolveActiveThreadId(): Promise<string | null> {
- const state = store.getState();
- return state.thread.selectedThreadId ?? null;
-}
-
-export async function createNewVoiceThread(): Promise<string> {
- // No special "voice" label yet — the core auto-generates a title from the
- // first user message, which gives a useful label for PTT sessions too.
- const thread = await threadApi.createNewThread();
- return thread.id;
-}
diff --git a/app/src/features/voice/pttTranscribe.ts b/app/src/features/voice/pttTranscribe.ts
deleted file mode 100644
index 9b5690c68e..0000000000
--- a/app/src/features/voice/pttTranscribe.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * pttTranscribe — speech-to-text adapter for pttService.
- *
- * Reuses the existing `openhuman.voice_transcribe_bytes` RPC (see
- * `crates/openhuman-core/src/voice/ops.rs`). The Rust side picks the hosted engine
- * routing based on the user's `stt_provider` setting and applies optional
- * LLM cleanup, so the renderer only needs to push raw bytes.
- *
- * The `extension` hint comes from `pttAudio.lastRecordedExtension()` —
- * MediaRecorder negotiates webm/opus on every modern desktop browser.
- */
-import { openhumanVoiceTranscribeBytes } from '../../utils/tauriCommands/voice';
-import { lastRecordedExtension } from './pttAudio';
-
-/**
- * Encode the buffer as a byte array for JSON-RPC transport. The wire format
- * expects `Vec<u8>` deserialized from a number array; serde-json doesn't
- * support binary natively over JSON-RPC.
- *
- * This is O(N) memory and CPU. For a 10s @ ~16 kbps opus blob (~20 KB) it's
- * cheap; if PTT recordings grow past ~5 MB we should swap to base64 or a
- * dedicated upload endpoint.
- */
-function bufferToByteArray(buf: ArrayBuffer): number[] {
- const view = new Uint8Array(buf);
- const out = new Array<number>(view.byteLength);
- for (let i = 0; i < view.byteLength; i++) {
- out[i] = view[i];
- }
- return out;
-}
-
-export async function transcribePttAudio(buf: ArrayBuffer): Promise<string> {
- if (buf.byteLength === 0) return '';
- const extension = lastRecordedExtension();
- const bytes = bufferToByteArray(buf);
- const result = await openhumanVoiceTranscribeBytes(
- bytes,
- extension,
- /* context */ undefined,
- /* skipCleanup */ false
- );
- // `result.text` is the cleaned-up version (LLM-polished when enabled);
- // `raw_text` is the unfiltered engine output. Prefer text but fall back.
- const text = (result?.text ?? result?.raw_text ?? '').trim();
- return text;
-}
diff --git a/app/src/features/voice/useVoiceSkillStatus.ts b/app/src/features/voice/useVoiceSkillStatus.ts
deleted file mode 100644
index d79ffdb957..0000000000
--- a/app/src/features/voice/useVoiceSkillStatus.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-/**
- * Derives a skill-card-friendly status for Voice Intelligence,
- * matching the state vocabulary used by third-party skills (Gmail, etc.).
- *
- * Speech-to-text is hosted, so the prerequisite is a *configured* engine
- * (`voice_server.stt_engine` resolving to a provider), not a downloaded model.
- */
-import { useCallback, useEffect, useMemo, useState } from 'react';
-
-import {
- openhumanVoiceServerStatus,
- openhumanVoiceStatus,
- type VoiceServerStatus,
- type VoiceStatus,
-} from '../../utils/tauriCommands/voice';
-import {
- activeStatus,
- errorStatus,
- offlineStatus,
- setupRequiredStatus,
- type SkillCardStatusDescriptor,
- transientStatus,
-} from '../skills/skillCardStatus';
-
-export interface VoiceSkillStatus extends SkillCardStatusDescriptor {
- /** True when the configured STT engine does not resolve to a provider —
- * i.e. the user picked a third-party engine with no credentials set up. */
- sttModelMissing: boolean;
- /** Voice system availability info (null before first fetch). */
- voiceStatus: VoiceStatus | null;
- /** Voice server runtime state (null before first fetch). */
- serverStatus: VoiceServerStatus | null;
-}
-
-export function useVoiceSkillStatus(): VoiceSkillStatus {
- const [voiceStatus, setVoiceStatus] = useState<VoiceStatus | null>(null);
- const [serverStatus, setServerStatus] = useState<VoiceServerStatus | null>(null);
-
- const fetchStatuses = useCallback(async () => {
- try {
- const [vs, ss] = await Promise.all([openhumanVoiceStatus(), openhumanVoiceServerStatus()]);
- setVoiceStatus(vs);
- setServerStatus(ss);
- } catch (err) {
- console.debug('[voice-skill-status] status fetch failed, will retry on next poll:', err);
- }
- }, []);
-
- // Poll voice status every 3s (lighter than the panel's 2s — just for card state)
- useEffect(() => {
- void fetchStatuses();
- const id = window.setInterval(() => void fetchStatuses(), 3000);
- return () => window.clearInterval(id);
- }, [fetchStatuses]);
-
- const sttReady = useMemo(() => {
- if (!voiceStatus) return false;
- // `stt_available` is the authoritative check: it asks whether the
- // configured hosted engine resolves to a provider at all. Nothing is
- // installed or downloaded for STT.
- return voiceStatus.stt_available;
- }, [voiceStatus]);
-
- return useMemo(() => {
- // No data yet
- if (!voiceStatus || !serverStatus) {
- return { ...offlineStatus(), sttModelMissing: false, voiceStatus, serverStatus };
- }
-
- // No usable STT engine — needs setup
- if (!sttReady) {
- return { ...setupRequiredStatus(), sttModelMissing: true, voiceStatus, serverStatus };
- }
-
- // Error
- if (serverStatus.last_error) {
- return { ...errorStatus(), sttModelMissing: false, voiceStatus, serverStatus };
- }
-
- // Active states: recording, transcribing, or idle (server running)
- if (serverStatus.state === 'recording' || serverStatus.state === 'transcribing') {
- return {
- ...transientStatus(serverStatus.state === 'recording' ? 'Recording' : 'Transcribing'),
- sttModelMissing: false,
- voiceStatus,
- serverStatus,
- };
- }
-
- if (serverStatus.state === 'idle') {
- return { ...activeStatus(), sttModelMissing: false, voiceStatus, serverStatus };
- }
-
- // Stopped
- return { ...offlineStatus('Stopped'), sttModelMissing: false, voiceStatus, serverStatus };
- }, [voiceStatus, serverStatus, sttReady]);
-}
diff --git a/app/src/hooks/__tests__/useDictationHotkey.test.tsx b/app/src/hooks/__tests__/useDictationHotkey.test.tsx
deleted file mode 100644
index bed2ea3cec..0000000000
--- a/app/src/hooks/__tests__/useDictationHotkey.test.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-// @vitest-environment jsdom
-import { renderHook, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { useDictationHotkey } from '../useDictationHotkey';
-
-const hoisted = vi.hoisted(() => {
- const handlers: Record<string, (...args: unknown[]) => void> = {};
- const mockSocket = {
- on: vi.fn((event: string, cb: (...args: unknown[]) => void) => {
- handlers[event] = cb;
- }),
- off: vi.fn(),
- disconnect: vi.fn(),
- id: 'mock-sid',
- };
- return {
- handlers,
- mockSocket,
- connectCoreSocketMock: vi
- .fn<() => Promise<typeof mockSocket | null>>()
- .mockResolvedValue(mockSocket),
- callCoreRpcMock: vi.fn<() => Promise<unknown>>(),
- getCoreHttpBaseUrlMock: vi.fn(async () => 'http://127.0.0.1:7788'),
- };
-});
-
-vi.mock('../../services/coreSocket', () => ({ connectCoreSocket: hoisted.connectCoreSocketMock }));
-vi.mock('../../services/coreRpcClient', () => ({
- callCoreRpc: hoisted.callCoreRpcMock,
- getCoreHttpBaseUrl: hoisted.getCoreHttpBaseUrlMock,
-}));
-
-describe('useDictationHotkey', () => {
- beforeEach(() => {
- hoisted.connectCoreSocketMock.mockClear();
- hoisted.connectCoreSocketMock.mockResolvedValue(hoisted.mockSocket);
- hoisted.callCoreRpcMock.mockClear();
- hoisted.callCoreRpcMock.mockResolvedValue({
- enabled: true,
- hotkey: 'F1',
- activationMode: 'toggle',
- });
- hoisted.mockSocket.on.mockClear();
- hoisted.mockSocket.off.mockClear();
- hoisted.mockSocket.disconnect.mockClear();
- Object.keys(hoisted.handlers).forEach(k => delete hoisted.handlers[k]);
- });
-
- it('opens a dedicated core socket on mount via connectCoreSocket', async () => {
- renderHook(() => useDictationHotkey());
-
- await waitFor(() => {
- expect(hoisted.connectCoreSocketMock).toHaveBeenCalledTimes(1);
- });
-
- const args = hoisted.connectCoreSocketMock.mock.calls[0] as unknown as [
- { getBaseUrl: () => Promise<string>; isDisposed: () => boolean },
- ];
- expect(typeof args[0].getBaseUrl).toBe('function');
- expect(typeof args[0].isDisposed).toBe('function');
- expect(args[0].isDisposed()).toBe(false);
- });
-
- it('disconnects the socket on unmount', async () => {
- const { unmount } = renderHook(() => useDictationHotkey());
- await waitFor(() => {
- expect(hoisted.connectCoreSocketMock).toHaveBeenCalled();
- });
- unmount();
- expect(hoisted.mockSocket.disconnect).toHaveBeenCalled();
- });
-
- it('short-circuits when connectCoreSocket returns null (disposed mid-await)', async () => {
- hoisted.connectCoreSocketMock.mockResolvedValueOnce(null);
- renderHook(() => useDictationHotkey());
- await waitFor(() => {
- expect(hoisted.connectCoreSocketMock).toHaveBeenCalled();
- });
- expect(hoisted.mockSocket.on).not.toHaveBeenCalled();
- });
-
- it('dispatches an autoSend insert-text event on transcription', async () => {
- renderHook(() => useDictationHotkey());
- await waitFor(() => {
- expect(hoisted.handlers['dictation:transcription']).toBeDefined();
- });
-
- const received: CustomEvent<{ text?: string; autoSend?: boolean }>[] = [];
- const listener = (e: Event) =>
- received.push(e as CustomEvent<{ text?: string; autoSend?: boolean }>);
- window.addEventListener('dictation://insert-text', listener);
- try {
- hoisted.handlers['dictation:transcription']({ text: ' hello world ' });
- } finally {
- window.removeEventListener('dictation://insert-text', listener);
- }
-
- expect(received).toHaveLength(1);
- // Trimmed text, and autoSend flag set so Conversations sends it straight to the agent.
- expect(received[0].detail).toEqual({ text: 'hello world', autoSend: true });
- });
-
- it('ignores blank transcription text (no event dispatched)', async () => {
- renderHook(() => useDictationHotkey());
- await waitFor(() => {
- expect(hoisted.handlers['dictation:transcription']).toBeDefined();
- });
-
- const received: Event[] = [];
- const listener = (e: Event) => received.push(e);
- window.addEventListener('dictation://insert-text', listener);
- try {
- hoisted.handlers['dictation:transcription']({ text: ' ' });
- } finally {
- window.removeEventListener('dictation://insert-text', listener);
- }
-
- expect(received).toHaveLength(0);
- });
-});
diff --git a/app/src/hooks/useDictationHotkey.ts b/app/src/hooks/useDictationHotkey.ts
deleted file mode 100644
index 01c49a6eed..0000000000
--- a/app/src/hooks/useDictationHotkey.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-/**
- * useDictationHotkey
- *
- * Fetches dictation config from the core RPC on mount and listens for
- * `dictation:toggle` Socket.IO events emitted by the Rust core when
- * the global hotkey is pressed. The hotkey listener runs in the core
- * process (via rdev), not in the Tauri shell.
- *
- * Dictation events are received over a **dedicated** Socket.IO
- * connection to the core process that does not require authentication.
- * This ensures dictation works regardless of whether the user is
- * logged in.
- *
- * Consumers receive:
- * - `dictationEnabled`: whether dictation is configured on
- * - `hotkeyRegistered`: true once the core confirms the hotkey is active
- * - `toggleCount`: increments each time the hotkey fires (use to trigger effects)
- * - `activationMode`: "toggle" or "push"
- * - `hotkey`: the configured hotkey string
- */
-import { useEffect, useRef, useState } from 'react';
-import { type Socket } from 'socket.io-client';
-
-import { callCoreRpc, getCoreHttpBaseUrl } from '../services/coreRpcClient';
-import { connectCoreSocket } from '../services/coreSocket';
-
-/** Resolve the core process base URL (without /rpc suffix) for Socket.IO.
- *
- * Delegates to `getCoreHttpBaseUrl` so the cloud-mode override set in the
- * BootCheckGate picker is honoured — previously this called
- * `invoke('core_rpc_url')` directly and would fall back to
- * `http://127.0.0.1:7788` whenever the user picked cloud mode (no local
- * sidecar to reply to the invoke), spamming `ERR_CONNECTION_REFUSED`.
- */
-async function resolveCoreSocketUrl(): Promise<string> {
- return getCoreHttpBaseUrl();
-}
-
-interface DictationSettings {
- enabled: boolean;
- hotkey: string;
- activation_mode: string;
- llm_refinement: boolean;
- streaming: boolean;
- streaming_interval_ms: number;
-}
-
-interface DictationHotkeyState {
- /** Whether dictation is enabled in the core config. */
- dictationEnabled: boolean;
- /** Whether the core hotkey listener is active. */
- hotkeyRegistered: boolean;
- /** Increments each time the hotkey is pressed (consumers can use as a trigger). */
- toggleCount: number;
- /** The configured activation mode ("toggle" or "push"). */
- activationMode: string;
- /** The configured hotkey string. */
- hotkey: string;
-}
-
-export function useDictationHotkey(): DictationHotkeyState {
- const [dictationEnabled, setDictationEnabled] = useState(false);
- const [hotkeyRegistered, setHotkeyRegistered] = useState(false);
- const [toggleCount, setToggleCount] = useState(0);
- const [activationMode, setActivationMode] = useState('toggle');
- const [hotkey, setHotkey] = useState('');
- const socketRef = useRef<Socket | null>(null);
-
- // Fetch config from core RPC on mount.
- useEffect(() => {
- let disposed = false;
-
- const init = async () => {
- try {
- const settings = await callCoreRpc<DictationSettings>({
- method: 'openhuman.config_get_dictation_settings',
- });
-
- if (disposed) return;
-
- if (!settings || typeof settings !== 'object') {
- console.debug('[dictation] no dictation settings from core');
- return;
- }
-
- // Handle Outcome wrapper — the result may be nested in .result
- const s = (
- 'result' in settings ? (settings as Record<string, unknown>).result : settings
- ) as DictationSettings;
-
- setDictationEnabled(s.enabled);
- setActivationMode(s.activation_mode ?? 'toggle');
- setHotkey(s.hotkey ?? '');
-
- if (s.enabled && s.hotkey) {
- // The core process registers the hotkey via rdev — we just note it.
- setHotkeyRegistered(true);
- console.debug(`[dictation] core hotkey active: ${s.hotkey}`);
- } else {
- console.debug('[dictation] dictation disabled or no hotkey configured');
- }
- } catch (err) {
- console.warn('[dictation] failed to fetch dictation settings', err);
- }
- };
-
- void init();
-
- return () => {
- disposed = true;
- };
- }, []);
-
- // Open a dedicated Socket.IO connection to the core for dictation
- // events. This is independent of the main socketService (which
- // requires auth) so dictation works even when not logged in.
- useEffect(() => {
- let socket: Socket | null = null;
- let disposed = false;
-
- const connect = async () => {
- try {
- socket = await connectCoreSocket({
- getBaseUrl: resolveCoreSocketUrl,
- isDisposed: () => disposed,
- });
- if (!socket) return;
- socketRef.current = socket;
-
- socket.on('connect', () => {
- console.debug('[dictation] dedicated socket connected', socket?.id);
- });
-
- socket.on('connect_error', (err: Error) => {
- console.debug('[dictation] socket connect error:', err.message);
- });
-
- // Hotkey toggle events.
- const handleToggle = () => {
- console.debug('[dictation] hotkey toggle event received');
- setToggleCount(c => c + 1);
- };
- socket.on('dictation:toggle', handleToggle);
- socket.on('dictation_toggle', handleToggle);
-
- // Transcription results — dispatch the custom DOM event that
- // Conversations.tsx uses to insert text into the chat input.
- socket.on('dictation:transcription', (data: { text?: string }) => {
- const text = data?.text?.trim();
- if (!text) return;
- console.debug(`[dictation] transcription received: ${text.length} chars — "${text}"`);
-
- window.dispatchEvent(
- new CustomEvent('dictation://insert-text', { detail: { text, autoSend: true } })
- );
- });
-
- socket.connect();
- } catch (err) {
- console.warn('[dictation] failed to open dedicated socket', err);
- }
- };
-
- void connect();
-
- return () => {
- disposed = true;
- if (socket) {
- socket.disconnect();
- socket = null;
- }
- socketRef.current = null;
- };
- }, []);
-
- return { dictationEnabled, hotkeyRegistered, toggleCount, activationMode, hotkey };
-}
diff --git a/app/src/hooks/usePttHotkey.ts b/app/src/hooks/usePttHotkey.ts
deleted file mode 100644
index be65d3e9e7..0000000000
--- a/app/src/hooks/usePttHotkey.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * usePttHotkey
- *
- * Subscribes the configured push-to-talk shortcut to the Tauri shell whenever
- * the persisted `shortcut` field on the `ptt` slice changes. Resets the
- * transient `isHeld` flag on mount so a stale rehydrated value (left over from
- * a crash mid-press) can never leave the UI thinking the PTT key is held.
- *
- * Wired into the renderer once via `PttHotkeyManager` (T11), mounted in
- * `App.tsx` alongside the dictation manager.
- */
-import { useEffect } from 'react';
-import { useDispatch, useSelector } from 'react-redux';
-
-import { selectPttShortcut, setIsHeld, setPttRegistrationError } from '../store/pttSlice';
-import { registerPttHotkey, unregisterPttHotkey } from '../utils/tauriCommands/ptt';
-
-export function usePttHotkey(): void {
- const dispatch = useDispatch();
- const shortcut = useSelector(selectPttShortcut);
-
- // Clear the transient isHeld flag on mount — a crash mid-press could
- // otherwise rehydrate to "held forever".
- useEffect(() => {
- dispatch(setIsHeld(false));
- }, [dispatch]);
-
- useEffect(() => {
- let cancelled = false;
- const apply = async () => {
- try {
- if (shortcut && shortcut.trim().length > 0) {
- await registerPttHotkey(shortcut);
- if (!cancelled) dispatch(setPttRegistrationError(null));
- } else {
- await unregisterPttHotkey();
- if (!cancelled) dispatch(setPttRegistrationError(null));
- }
- } catch (err) {
- if (!cancelled) {
- const msg = err instanceof Error ? err.message : String(err);
- console.warn('[ptt] hotkey (un)register failed', err);
- dispatch(setPttRegistrationError(msg));
- }
- }
- };
- void apply();
- return () => {
- cancelled = true;
- };
- }, [shortcut, dispatch]);
-}
diff --git a/app/src/overlay/OverlayApp.tsx b/app/src/overlay/OverlayApp.tsx
deleted file mode 100644
index 64e1c3ab4d..0000000000
--- a/app/src/overlay/OverlayApp.tsx
+++ /dev/null
@@ -1,651 +0,0 @@
-/**
- * OverlayApp
- *
- * Standalone React root rendered inside the Tauri `overlay` window (see
- * `crates/openhuman-app/tauri.conf.json`). The overlay lives in its own WebView
- * and cannot share Redux state with the main window, so it reacts to
- * signals from the Rust core over a dedicated, unauthenticated Socket.IO
- * connection (same pattern as `useDictationHotkey`).
- *
- * The overlay activates in two cases:
- *
- * 1. **STT / dictation** — when the user presses the dictation hotkey.
- * The core emits `dictation:toggle` with `{type: "pressed" | "released"}`
- * and `dictation:transcription` with `{text}`. "Pressed" opens the
- * overlay into STT mode; "released" (or the final transcription)
- * dismisses it.
- *
- * 2. **Attention message** — when the core (a scheduled cron job, a
- * proactive notification, …) publishes an `OverlayAttentionEvent` via
- * `openhuman::overlay::publish_attention(...)`. The bridge in
- * `openhuman_rpc::server::socketio` forwards this as an `overlay:attention` event.
- * The bubble auto-dismisses after its ttl.
- *
- * There is **no** demo loop — the overlay is entirely event-driven.
- */
-import {
- currentMonitor,
- getCurrentWindow,
- LogicalPosition,
- LogicalSize,
-} from '@tauri-apps/api/window';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { type Socket } from 'socket.io-client';
-
-import RotatingTetrahedronCanvas from '../components/RotatingTetrahedronCanvas';
-import { useT } from '../lib/i18n/I18nContext';
-import { callCoreRpc, getCoreHttpBaseUrl } from '../services/coreRpcClient';
-import { connectCoreSocket } from '../services/coreSocket';
-// `safeInvoke` (aliased to `invoke`) converts the CEF
-// `window.ipc.postMessage` synchronous throw — Sentry TAURI-REACT-7 /
-// TAURI-REACT-6 — into a rejected Promise so the existing `.catch(...)`
-// handler sees it as a normal IPC failure. The overlay window is the most
-// at-risk surface here because it boots into its own WebView where the
-// CEF IPC bridge can briefly be unwired.
-import { safeInvoke as invoke } from '../utils/tauriCommands/common';
-
-const OVERLAY_IDLE_WIDTH = 50;
-const OVERLAY_IDLE_HEIGHT = 50;
-const OVERLAY_ACTIVE_WIDTH = 224;
-const OVERLAY_ACTIVE_HEIGHT = 208;
-const OVERLAY_IDLE_MARGIN = 10;
-const OVERLAY_ACTIVE_MARGIN = 20;
-const OVERLAY_IDLE_OPACITY = 0.6;
-
-const OVERLAY_POSITION_KEY = 'overlay-position';
-
-/** Default auto-dismiss for an attention bubble when no ttl is supplied. */
-const DEFAULT_ATTENTION_TTL_MS = 6000;
-/** Grace period after STT `released` before returning to idle, giving the
- * final transcription time to arrive and the user a moment to read it. */
-const STT_RELEASE_LINGER_MS = 1500;
-/** Placeholder bubble text while waiting for the first transcription. */
-const STT_LISTENING_PLACEHOLDER = '"Listening…"';
-let lastPollDebugTs = 0;
-
-// ── State model ──────────────────────────────────────────────────────────
-
-type OverlayMode = 'idle' | 'stt' | 'attention';
-type BubbleTone = 'neutral' | 'accent' | 'success';
-
-interface OverlayBubble {
- id: string;
- text: string;
- tone: BubbleTone;
- compact?: boolean;
-}
-
-// ── Socket payload types ─────────────────────────────────────────────────
-
-interface DictationTogglePayload {
- type?: string;
- hotkey?: string;
- activation_mode?: string;
-}
-
-interface DictationTranscriptionPayload {
- text?: string;
-}
-
-interface OverlayAttentionPayload {
- id?: string;
- message?: string;
- tone?: BubbleTone;
- ttl_ms?: number;
- source?: string;
-}
-
-// ── Helpers ──────────────────────────────────────────────────────────────
-
-function bubbleToneClass(tone: BubbleTone) {
- switch (tone) {
- case 'accent':
- return 'bg-blue-700 text-white';
- case 'success':
- return 'bg-emerald-500 text-emerald-950';
- default:
- return 'bg-slate-700 text-white';
- }
-}
-
-/** Resolve the core process base URL (without /rpc suffix) for Socket.IO.
- * Mirrors `useDictationHotkey.resolveCoreSocketUrl`. Delegates to
- * `getCoreHttpBaseUrl` so cloud-mode overrides flow through. */
-async function resolveCoreSocketUrl(): Promise<string> {
- return getCoreHttpBaseUrl();
-}
-
-// ── Bubble chip with typewriter animation ────────────────────────────────
-
-function OverlayBubbleChip({ bubble }: { bubble: OverlayBubble }) {
- // Reset the typewriter on every new bubble identity via `key` at the
- // call site — that avoids a cascading setState inside this effect.
- const [displayedText, setDisplayedText] = useState('');
- const indexRef = useRef(0);
-
- useEffect(() => {
- if (!bubble.text) {
- return () => {
- indexRef.current = 0;
- };
- }
-
- const intervalId = window.setInterval(
- () => {
- indexRef.current += 1;
- setDisplayedText(bubble.text.slice(0, indexRef.current));
- if (indexRef.current >= bubble.text.length) {
- window.clearInterval(intervalId);
- }
- },
- bubble.compact ? 28 : 32
- );
-
- return () => {
- window.clearInterval(intervalId);
- indexRef.current = 0;
- };
- }, [bubble.compact, bubble.text]);
-
- return (
- <div
- className={`max-w-[184px] rounded-[18px] px-3 py-2 text-right transition-all duration-200 ${bubbleToneClass(bubble.tone)} ${bubble.compact ? 'text-[12px] leading-[1.35]' : 'text-[13px] leading-[1.45]'}`}>
- {displayedText || ' '}
- </div>
- );
-}
-
-// ── Main overlay root ────────────────────────────────────────────────────
-
-export default function OverlayApp() {
- const { t } = useT();
- const [mode, setMode] = useState<OverlayMode>('idle');
- const [bubble, setBubble] = useState<OverlayBubble | null>(null);
- const [isHovered, setIsHovered] = useState(false);
-
- /** Timer that returns the overlay to idle after a ttl (attention) or a
- * grace period (stt release). We clear it whenever the mode changes. */
- const dismissTimerRef = useRef<number | null>(null);
-
- const clearDismissTimer = useCallback(() => {
- if (dismissTimerRef.current !== null) {
- window.clearTimeout(dismissTimerRef.current);
- dismissTimerRef.current = null;
- }
- }, []);
-
- const scheduleDismiss = useCallback(
- (ms: number) => {
- clearDismissTimer();
- dismissTimerRef.current = window.setTimeout(() => {
- console.debug('[overlay] auto-dismiss → idle');
- setMode('idle');
- setBubble(null);
- dismissTimerRef.current = null;
- }, ms);
- },
- [clearDismissTimer]
- );
-
- const goIdle = useCallback(() => {
- clearDismissTimer();
- setMode('idle');
- setBubble(null);
- }, [clearDismissTimer]);
-
- /** Click handler for the orb: idle → bring main window to front; active → dismiss bubble. */
- const handleOrbClick = useCallback(() => {
- if (mode === 'idle') {
- console.debug('[overlay] orb clicked while idle — activating main window');
- invoke('activate_main_window').catch(err => {
- console.error('[overlay] failed to activate main window:', err);
- });
- } else {
- goIdle();
- }
- }, [mode, goIdle]);
-
- // ── Dictation: pressed / released ──────────────────────────────────────
- const handleDictationToggle = useCallback(
- (payload: DictationTogglePayload) => {
- const type = payload?.type ?? 'pressed';
- console.debug(`[overlay] dictation:toggle type=${type}`);
-
- if (type === 'pressed') {
- clearDismissTimer();
- setMode('stt');
- setBubble({
- id: `stt-${Date.now()}`,
- text: STT_LISTENING_PLACEHOLDER,
- tone: 'accent',
- compact: true,
- });
- return;
- }
-
- if (type === 'released') {
- // Linger briefly so any final transcription arriving shortly after
- // has a chance to land in the bubble before we go idle.
- scheduleDismiss(STT_RELEASE_LINGER_MS);
- }
- },
- [clearDismissTimer, scheduleDismiss]
- );
-
- // ── Dictation: final transcription text ────────────────────────────────
- const handleDictationTranscription = useCallback(
- (payload: DictationTranscriptionPayload) => {
- const text = payload?.text?.trim();
- if (!text) return;
- console.debug(`[overlay] dictation:transcription chars=${text.length}`);
-
- setMode('stt');
- setBubble({
- id: `stt-final-${Date.now()}`,
- text: `"${text}"`,
- tone: 'accent',
- compact: true,
- });
- // Show the result briefly then dismiss, regardless of hotkey state.
- scheduleDismiss(STT_RELEASE_LINGER_MS);
- },
- [scheduleDismiss]
- );
-
- // ── Attention from the core ─────────────────────────────────────────────
- const handleAttention = useCallback(
- (payload: OverlayAttentionPayload) => {
- const message = payload?.message?.trim();
- if (!message) {
- console.debug('[overlay] attention event with empty message — ignoring');
- return;
- }
- console.debug(
- `[overlay] attention source=${payload?.source ?? 'unknown'} tone=${payload?.tone ?? 'neutral'} chars=${message.length}`
- );
-
- const ttl =
- typeof payload?.ttl_ms === 'number' && payload.ttl_ms > 0
- ? payload.ttl_ms
- : DEFAULT_ATTENTION_TTL_MS;
-
- setMode('attention');
- setBubble({
- id: payload?.id ?? `attention-${Date.now()}`,
- text: `"${message}"`,
- // Match the Rust-side `OverlayAttentionTone::default()` (Neutral)
- // so missing/legacy payloads render as the neutral slate bubble.
- tone: payload?.tone ?? 'neutral',
- });
- scheduleDismiss(ttl);
- },
- [scheduleDismiss]
- );
-
- // ── Socket.IO subscription lifecycle ───────────────────────────────────
- useEffect(() => {
- let socket: Socket | null = null;
- let disposed = false;
-
- const connect = async () => {
- try {
- /* c8 ignore start — thin call site over the tested `connectCoreSocket` helper */
- console.debug('[overlay] connecting to core socket');
- socket = await connectCoreSocket({
- getBaseUrl: resolveCoreSocketUrl,
- isDisposed: () => disposed,
- });
- if (!socket) return;
- /* c8 ignore stop */
-
- socket.on('connect', () => {
- console.debug('[overlay] socket connected', socket?.id);
- });
-
- socket.on('connect_error', (err: Error) => {
- console.debug('[overlay] socket connect error:', err.message);
- });
-
- socket.on('disconnect', (reason: string) => {
- console.debug('[overlay] socket disconnected:', reason);
- });
-
- // Core emits each event under both colon and underscore forms
- // (see `emit_with_aliases` in `crates/openhuman-rpc/src/server/socketio.rs`). Subscribe
- // only to the canonical colon-delimited form so each signal fires
- // the handler exactly once.
- socket.on('dictation:toggle', handleDictationToggle);
- socket.on('dictation:transcription', handleDictationTranscription);
- socket.on('overlay:attention', handleAttention);
-
- socket.connect();
- } catch (err) {
- console.warn('[overlay] failed to open core socket', err);
- }
- };
-
- void connect();
-
- return () => {
- disposed = true;
- if (socket) {
- socket.disconnect();
- socket = null;
- }
- clearDismissTimer();
- };
- }, [clearDismissTimer, handleAttention, handleDictationToggle, handleDictationTranscription]);
-
- // ── Poll voice server status as fallback sync ─────────────────────────
- // Socket events are the primary state driver, but if an event is missed
- // (reconnect, brief disconnect) the overlay can get stuck. Polling the
- // actual server state every 2s corrects any drift.
- const modeRef = useRef(mode);
- useEffect(() => {
- modeRef.current = mode;
- }, [mode]);
-
- useEffect(() => {
- let disposed = false;
-
- const poll = async () => {
- try {
- const res = await callCoreRpc<{
- state: string;
- hotkey: string;
- activation_mode: string;
- transcription_count: number;
- last_error: string | null;
- }>({ method: 'openhuman.voice_server_status' });
-
- if (disposed) return;
-
- const serverState = res.state; // 'stopped' | 'idle' | 'recording' | 'transcribing'
- const currentMode = modeRef.current;
-
- // Server is actively recording/transcribing but overlay is idle → show stt
- if (
- (serverState === 'recording' || serverState === 'transcribing') &&
- currentMode !== 'stt'
- ) {
- console.debug(
- `[overlay] poll sync: server=${serverState}, overlay=${currentMode} → activating stt`
- );
- clearDismissTimer();
- setMode('stt');
- setBubble({
- id: `stt-poll-${Date.now()}`,
- text: serverState === 'transcribing' ? '"Transcribing…"' : STT_LISTENING_PLACEHOLDER,
- tone: 'accent',
- compact: true,
- });
- }
-
- // Server is idle/stopped but overlay thinks it's in stt → dismiss
- if ((serverState === 'idle' || serverState === 'stopped') && currentMode === 'stt') {
- console.debug(`[overlay] poll sync: server=${serverState}, overlay=stt → dismissing`);
- goIdle();
- }
- } catch (err) {
- if (process.env.NODE_ENV !== 'production') {
- const now = Date.now();
- if (now - lastPollDebugTs > 5000) {
- lastPollDebugTs = now;
- console.debug('[overlay] RPC poll failed', err);
- }
- }
- }
- };
-
- void poll();
- const id = window.setInterval(() => void poll(), 2000);
- return () => {
- disposed = true;
- window.clearInterval(id);
- };
- }, [clearDismissTimer, goIdle]);
-
- // ── Window framing: resize / reposition on mode change ────────────────
- const status: 'idle' | 'active' = mode === 'idle' ? 'idle' : 'active';
- const userDraggedRef = useRef(false);
-
- /** Save the current window position to localStorage after a drag. */
- const persistPosition = useCallback(async () => {
- try {
- const appWindow = getCurrentWindow();
- const pos = await appWindow.outerPosition();
- localStorage.setItem(OVERLAY_POSITION_KEY, JSON.stringify({ x: pos.x, y: pos.y }));
- userDraggedRef.current = true;
- } catch {
- // position read failed — ignore
- }
- }, []);
-
- /** Reset saved position so the overlay snaps back to the default corner. */
- const resetPosition = useCallback(() => {
- localStorage.removeItem(OVERLAY_POSITION_KEY);
- userDraggedRef.current = false;
- }, []);
-
- // NSPanel (non-activating overlay) doesn't deliver synthesized `click`
- // events to the webview, and calling `startDragging()` eagerly on
- // mouse-down blocks `mouseup` from firing. We instead arm the drag only
- // after the pointer moves past a small threshold, so a pure click fires
- // `mouseup` normally and we can activate the main window there.
- const pressRef = useRef<{ x: number; y: number; dragStarted: boolean } | null>(null);
- const CLICK_SLOP_PX = 4;
- /** Pending single-click, deferred so a follow-up double-click can cancel it. */
- const clickTimerRef = useRef<number | null>(null);
- const CLICK_DOUBLE_CLICK_DELAY_MS = 250;
-
- /** Record mouse-down position; defer drag until the pointer actually moves. */
- const handleDragStart = useCallback((e: React.MouseEvent) => {
- if (e.button !== 0) return;
- pressRef.current = { x: e.screenX, y: e.screenY, dragStarted: false };
- }, []);
-
- /** If pointer moves past the slop, escalate into a native window drag. */
- const handleMouseMove = useCallback(
- async (e: React.MouseEvent) => {
- const press = pressRef.current;
- if (!press) return;
- // If the primary button is no longer held, a prior mouseup was missed
- // (window-drag steals it, focus change, etc). Drop the stale press so
- // we don't spuriously start a drag on a hover.
- if ((e.buttons & 1) === 0) {
- pressRef.current = null;
- return;
- }
- if (press.dragStarted) return;
- const dx = Math.abs(e.screenX - press.x);
- const dy = Math.abs(e.screenY - press.y);
- if (dx <= CLICK_SLOP_PX && dy <= CLICK_SLOP_PX) return;
- press.dragStarted = true;
- try {
- const appWindow = getCurrentWindow();
- await appWindow.startDragging();
- void persistPosition();
- } catch {
- // startDragging can fail if not supported — fall through silently
- }
- },
- [persistPosition]
- );
-
- /**
- * On mouse-up, treat as a click if no drag was initiated. Emulates
- * `onClick` for the non-activating panel. The click is deferred briefly
- * so a follow-up `dblclick` (used to reset position) can cancel it.
- */
- const handleMouseUp = useCallback(
- (e: React.MouseEvent) => {
- const press = pressRef.current;
- pressRef.current = null;
- if (e.button !== 0 || !press) return;
- if (press.dragStarted) return;
- if (clickTimerRef.current !== null) {
- window.clearTimeout(clickTimerRef.current);
- }
- clickTimerRef.current = window.setTimeout(() => {
- clickTimerRef.current = null;
- console.debug('[overlay] orb mouseup → click');
- handleOrbClick();
- }, CLICK_DOUBLE_CLICK_DELAY_MS);
- },
- [handleOrbClick]
- );
-
- /** Double-click resets position — cancel any pending single-click first. */
- const handleDoubleClick = useCallback(() => {
- if (clickTimerRef.current !== null) {
- window.clearTimeout(clickTimerRef.current);
- clickTimerRef.current = null;
- }
- resetPosition();
- }, [resetPosition]);
-
- useEffect(() => {
- return () => {
- if (clickTimerRef.current !== null) {
- window.clearTimeout(clickTimerRef.current);
- clickTimerRef.current = null;
- }
- };
- }, []);
-
- useEffect(() => {
- const appWindow = getCurrentWindow();
- const isActive = status === 'active';
- const width = isActive ? OVERLAY_ACTIVE_WIDTH : OVERLAY_IDLE_WIDTH;
- const height = isActive ? OVERLAY_ACTIVE_HEIGHT : OVERLAY_IDLE_HEIGHT;
- const margin = isActive ? OVERLAY_ACTIVE_MARGIN : OVERLAY_IDLE_MARGIN;
- const size = new LogicalSize(width, height);
-
- const updateWindowFrame = async () => {
- // Remove all size constraints first, then set the new size, then
- // re-apply constraints. This avoids the ordering problem where the
- // old min/max clamps the new size.
- try {
- await appWindow.setMinSize(null);
- } catch {
- /* ignore */
- }
- try {
- await appWindow.setMaxSize(null);
- } catch {
- /* ignore */
- }
- try {
- await appWindow.setSize(size);
- } catch (error) {
- console.warn('[overlay] failed to resize overlay window', error);
- }
- console.debug(`[overlay] resized to ${width}x${height} (active=${isActive})`);
- // Lock to exact size so the user can't accidentally resize
- try {
- await appWindow.setMinSize(size);
- } catch {
- /* ignore */
- }
- try {
- await appWindow.setMaxSize(size);
- } catch {
- /* ignore */
- }
-
- // Restore saved position from a previous drag
- const saved = localStorage.getItem(OVERLAY_POSITION_KEY);
- if (saved) {
- try {
- const { x, y } = JSON.parse(saved) as { x: number; y: number };
- await appWindow.setPosition(new LogicalPosition(x, y));
- userDraggedRef.current = true;
- return;
- } catch {
- localStorage.removeItem(OVERLAY_POSITION_KEY);
- }
- }
-
- if (userDraggedRef.current) {
- return;
- }
-
- // Default: pin to bottom-right corner
- try {
- const monitor = await currentMonitor();
- if (!monitor) {
- console.warn('[overlay] could not resolve current monitor for positioning');
- return;
- }
-
- const x = monitor.workArea.position.x + monitor.workArea.size.width - width - margin;
- const y = monitor.workArea.position.y + monitor.workArea.size.height - height - margin;
- await appWindow.setPosition(new LogicalPosition(x, y));
- } catch (error) {
- console.warn('[overlay] failed to pin overlay bottom-right after resize', error);
- }
- };
-
- void updateWindowFrame();
- }, [status]);
-
- // ── Render ────────────────────────────────────────────────────────────
- const bubbles = useMemo<OverlayBubble[]>(() => (bubble ? [bubble] : []), [bubble]);
- const orbClassName = useMemo(() => {
- if (status === 'active') {
- return 'border-blue-950 bg-blue-700';
- }
- return 'border-slate-950 bg-slate-800';
- }, [status]);
- const tetrahedronInverted = status === 'active';
- const orbSizeClassName = status === 'active' ? 'h-[52px] w-[52px]' : 'h-[40px] w-[40px]';
- const orbCanvasClassName = status === 'active' ? 'h-[92%] w-[92%]' : 'h-[88%] w-[88%]';
- const orbStyle =
- status === 'idle' ? { opacity: isHovered ? 1 : OVERLAY_IDLE_OPACITY } : undefined;
-
- return (
- <div className="flex h-screen w-screen items-end justify-end bg-transparent px-0 py-0">
- <div
- className={`relative flex select-none flex-col items-end ${status === 'active' ? 'gap-3' : 'gap-0'}`}>
- <div
- className={`flex flex-col items-end gap-2 overflow-hidden transition-all duration-200 ${status === 'active' ? 'max-w-[184px] opacity-100' : 'max-w-0 opacity-0'}`}>
- {bubbles.map(b => (
- <div key={b.id} className="animate-[overlay-bubble-in_220ms_ease-out]">
- <OverlayBubbleChip key={b.id} bubble={b} />
- </div>
- ))}
- </div>
-
- <div className="relative">
- <button
- type="button"
- aria-label={
- mode === 'stt'
- ? t('overlay.ariaVoiceActive')
- : mode === 'attention'
- ? t('overlay.ariaAttention')
- : t('overlay.ariaOrb')
- }
- onMouseDown={handleDragStart}
- onMouseMove={handleMouseMove}
- onMouseUp={handleMouseUp}
- onDoubleClick={handleDoubleClick}
- onMouseEnter={() => {
- setIsHovered(true);
- }}
- onMouseLeave={() => {
- setIsHovered(false);
- }}
- className={`group relative flex cursor-grab items-center justify-center overflow-hidden rounded-full border transition-all duration-200 active:cursor-grabbing ${orbClassName} ${orbSizeClassName}`}
- style={orbStyle}
- title={t('overlay.orbTitle')}>
- <div
- className={`pointer-events-none opacity-95 transition-transform duration-300 group-hover:scale-105 ${orbCanvasClassName}`}>
- <RotatingTetrahedronCanvas inverted={tetrahedronInverted} />
- </div>
- </button>
- </div>
- </div>
- </div>
- );
-}
diff --git a/app/src/pages/PttOverlayPage.test.tsx b/app/src/pages/PttOverlayPage.test.tsx
deleted file mode 100644
index a3b8b7f7d0..0000000000
--- a/app/src/pages/PttOverlayPage.test.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { act, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { PttOverlayPage } from './PttOverlayPage';
-
-// Mock @tauri-apps/api/event's listen so we can dispatch fake events.
-vi.mock('@tauri-apps/api/event', () => {
- const handlers: Record<string, (e: { payload: unknown }) => void> = {};
- return {
- listen: vi.fn(async (name: string, handler: (e: { payload: unknown }) => void) => {
- handlers[name] = handler;
- return () => delete handlers[name];
- }),
- __dispatch: (name: string, payload: unknown) => handlers[name]?.({ payload }),
- };
-});
-
-describe('PttOverlayPage', () => {
- it('renders idle state by default', () => {
- render(<PttOverlayPage />);
- expect(screen.getByTestId('ptt-overlay-root')).toHaveAttribute('data-active', 'false');
- });
-
- it('flips to active when ptt-overlay://active fires with active=true', async () => {
- render(<PttOverlayPage />);
- const evt = await import('@tauri-apps/api/event');
- await act(async () => {
- (evt as unknown as { __dispatch: (n: string, p: unknown) => void }).__dispatch(
- 'ptt-overlay://active',
- { active: true, session_id: 1 }
- );
- });
- expect(screen.getByTestId('ptt-overlay-root')).toHaveAttribute('data-active', 'true');
- });
-});
diff --git a/app/src/pages/PttOverlayPage.tsx b/app/src/pages/PttOverlayPage.tsx
deleted file mode 100644
index ef9fd828f6..0000000000
--- a/app/src/pages/PttOverlayPage.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { listen, type UnlistenFn } from '@tauri-apps/api/event';
-import { useEffect, useState } from 'react';
-
-import { useT } from '../lib/i18n/I18nContext';
-
-export function PttOverlayPage() {
- const { t } = useT();
- const [active, setActive] = useState(false);
-
- useEffect(() => {
- let off: UnlistenFn | undefined;
- let cancelled = false;
- listen<{ active: boolean }>('ptt-overlay://active', e => {
- setActive(Boolean(e.payload?.active));
- })
- .then(fn => {
- if (cancelled) fn();
- else off = fn;
- })
- .catch(() => {});
- return () => {
- cancelled = true;
- off?.();
- };
- }, []);
-
- return (
- <div
- data-testid="ptt-overlay-root"
- data-active={active}
- style={{
- width: '160px',
- height: '56px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- gap: 8,
- background: 'rgba(20, 20, 24, 0.85)',
- borderRadius: 12,
- color: '#fff',
- fontFamily: 'Inter, system-ui, sans-serif',
- fontSize: 12,
- userSelect: 'none',
- pointerEvents: 'none',
- }}>
- <span
- aria-hidden
- style={{
- width: 10,
- height: 10,
- borderRadius: 999,
- background: active ? '#ff4d4f' : '#666',
- boxShadow: active ? '0 0 6px #ff4d4f' : undefined,
- transition: 'all 120ms ease',
- }}
- />
- {/* TODO(T13): i18n keys pttOverlay.listening / pttOverlay.idle added in T13 */}
- <span>{active ? t('pttOverlay.listening') : t('pttOverlay.idle')}</span>
- </div>
- );
-}
diff --git a/app/src/pages/__tests__/Skills.channels-grid.test.tsx b/app/src/pages/__tests__/Skills.channels-grid.test.tsx
index 684133d24f..21d12a01c6 100644
--- a/app/src/pages/__tests__/Skills.channels-grid.test.tsx
+++ b/app/src/pages/__tests__/Skills.channels-grid.test.tsx
@@ -1,7 +1,6 @@
import { fireEvent, screen, within } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import '../../test/mockDefaultSkillStatusHooks';
import { renderWithProviders } from '../../test/test-utils';
import type { ChannelDefinition } from '../../types/channels';
import Skills from '../Skills';
diff --git a/app/src/pages/__tests__/Skills.composio-catalog.test.tsx b/app/src/pages/__tests__/Skills.composio-catalog.test.tsx
index 8b63bff570..4af2b27d55 100644
--- a/app/src/pages/__tests__/Skills.composio-catalog.test.tsx
+++ b/app/src/pages/__tests__/Skills.composio-catalog.test.tsx
@@ -1,7 +1,6 @@
import { fireEvent, screen, waitFor, within } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import '../../test/mockDefaultSkillStatusHooks';
import { renderWithProviders } from '../../test/test-utils';
import Skills from '../Skills';
diff --git a/app/src/pages/__tests__/Skills.intelligence-tabs.test.tsx b/app/src/pages/__tests__/Skills.intelligence-tabs.test.tsx
index 863fc2a6b0..64994b9431 100644
--- a/app/src/pages/__tests__/Skills.intelligence-tabs.test.tsx
+++ b/app/src/pages/__tests__/Skills.intelligence-tabs.test.tsx
@@ -1,7 +1,6 @@
import { screen, waitFor, within } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
-import '../../test/mockDefaultSkillStatusHooks';
import { renderWithProviders } from '../../test/test-utils';
import Skills from '../Skills';
diff --git a/app/src/pages/__tests__/Skills.mcp-coming-soon.test.tsx b/app/src/pages/__tests__/Skills.mcp-coming-soon.test.tsx
index bff399d669..7655da4cc1 100644
--- a/app/src/pages/__tests__/Skills.mcp-coming-soon.test.tsx
+++ b/app/src/pages/__tests__/Skills.mcp-coming-soon.test.tsx
@@ -1,7 +1,6 @@
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
-import '../../test/mockDefaultSkillStatusHooks';
import { renderWithProviders } from '../../test/test-utils';
import Skills from '../Skills';
diff --git a/app/src/pages/__tests__/Skills.tab-resolution.test.tsx b/app/src/pages/__tests__/Skills.tab-resolution.test.tsx
index 051d665d35..c5209d3405 100644
--- a/app/src/pages/__tests__/Skills.tab-resolution.test.tsx
+++ b/app/src/pages/__tests__/Skills.tab-resolution.test.tsx
@@ -23,7 +23,6 @@
import { screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
-import '../../test/mockDefaultSkillStatusHooks';
import { renderWithProviders } from '../../test/test-utils';
import type { ChannelDefinition } from '../../types/channels';
import Skills from '../Skills';
diff --git a/app/src/pages/__tests__/Skills.third-party-gmail-sync.test.tsx b/app/src/pages/__tests__/Skills.third-party-gmail-sync.test.tsx
index 1f8d58eda3..11e6dd0af0 100644
--- a/app/src/pages/__tests__/Skills.third-party-gmail-sync.test.tsx
+++ b/app/src/pages/__tests__/Skills.third-party-gmail-sync.test.tsx
@@ -1,7 +1,6 @@
import { fireEvent, screen, within } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
-import '../../test/mockDefaultSkillStatusHooks';
import { renderWithProviders } from '../../test/test-utils';
import Skills from '../Skills';
diff --git a/app/src/pages/__tests__/Skills.third-party-notion-debug-tools.test.tsx b/app/src/pages/__tests__/Skills.third-party-notion-debug-tools.test.tsx
index d9eb701ee1..6a61ba27f1 100644
--- a/app/src/pages/__tests__/Skills.third-party-notion-debug-tools.test.tsx
+++ b/app/src/pages/__tests__/Skills.third-party-notion-debug-tools.test.tsx
@@ -1,7 +1,6 @@
import { fireEvent, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
-import '../../test/mockDefaultSkillStatusHooks';
import { renderWithProviders } from '../../test/test-utils';
import Skills from '../Skills';
diff --git a/app/src/pages/settings/voice/PttSettingsPanel.tsx b/app/src/pages/settings/voice/PttSettingsPanel.tsx
deleted file mode 100644
index 62fba0fcc0..0000000000
--- a/app/src/pages/settings/voice/PttSettingsPanel.tsx
+++ /dev/null
@@ -1,267 +0,0 @@
-/**
- * PttSettingsPanel — settings card for the global push-to-talk hotkey.
- *
- * Renders three controls bound to `pttSlice` (T8):
- * - A hotkey-capture input that writes the captured key into
- * `setPttShortcut` (null when cleared). Modifier-only presses are
- * rejected with an inline error since they don't make sense for PTT.
- * - A "Speak agent replies" switch bound to `setSpeakReplies`.
- * - A "Show overlay while held" switch bound to `setShowOverlay`.
- *
- * The hotkey registration side effect itself is handled by
- * `usePttHotkey` (T11) which subscribes to slice changes and forwards
- * to the Tauri shell — this panel only mutates Redux state and lets
- * the manager hook react. This separation keeps the settings UI
- * purely declarative and means the panel test does not need to mock
- * the Tauri command surface.
- *
- * The panel deliberately renders without a `SettingsHeader` since it's
- * intended to be embedded inside `VoicePanel` rather than mounted as a
- * standalone route. The "card" style matches the other sections inside
- * VoicePanel.
- *
- */
-import { Keyboard, X } from 'lucide-react';
-import { useCallback, useState } from 'react';
-
-import { Button, Card, Field, Switch } from '../../../components/ui';
-import { useT } from '../../../lib/i18n/I18nContext';
-import { useAppDispatch, useAppSelector } from '../../../store/hooks';
-import {
- selectPttRegistrationError,
- selectPttShortcut,
- selectShowOverlay,
- selectSpeakReplies,
- setPttShortcut,
- setShowOverlay,
- setSpeakReplies,
-} from '../../../store/pttSlice';
-
-/** Keys that are pure modifiers — a PTT binding made of only these makes
- * no sense (you can't "release" a modifier to send a sample without
- * already needing a non-modifier sentinel). We surface a typed error
- * instead of silently saving a useless binding. */
-const MODIFIER_KEYS = new Set([
- 'Shift',
- 'Control',
- 'Alt',
- 'Meta',
- 'OS',
- 'AltGraph',
- 'CapsLock',
- 'NumLock',
- 'ScrollLock',
-]);
-
-/**
- * Convert a KeyboardEvent into a stable shortcut string. Mirrors the
- * format the Tauri shell expects (e.g. `Ctrl+Alt+F13`). We use the
- * `key` field (and `code` for letters where `key` carries the layout's
- * uppercased value) to avoid layout drift across QWERTY / AZERTY / etc.
- */
-function eventToShortcut(e: React.KeyboardEvent): string | null {
- if (MODIFIER_KEYS.has(e.key)) return null;
- const parts: string[] = [];
- if (e.ctrlKey) parts.push('Ctrl');
- if (e.altKey) parts.push('Alt');
- if (e.shiftKey) parts.push('Shift');
- if (e.metaKey) parts.push('Meta');
- // Prefer e.key (already the localised label like "F13", "a", "Enter")
- // unless it's a single lowercase letter — for those we uppercase to
- // produce a consistent "Ctrl+A" form across capitalised / not.
- // Normalize Space (" ") to the display label "Space" so the saved
- // binding is readable (e.g. "Ctrl+Space" rather than "Ctrl+ ").
- let label = e.key === ' ' ? 'Space' : e.key;
- if (label.length === 1 && /[a-z]/.test(label)) {
- label = label.toUpperCase();
- }
- parts.push(label);
- return parts.join('+');
-}
-
-/**
- * Map a raw Tauri error string from `register_ptt_hotkey` to a localized
- * message. Pattern-matches on well-known substrings so the panel doesn't need
- * to depend on the exact Rust error wording; falls back to the raw string for
- * anything unrecognised (still useful to the user for diagnostics).
- */
-function localizedRegistrationError(raw: string | null, t: (key: string) => string): string | null {
- if (!raw) return null;
- const lower = raw.toLowerCase();
- if (lower.includes('conflict') && lower.includes('dictation')) {
- return t('pttSettings.errorConflictsWithDictation');
- }
- if (lower.includes('wayland')) {
- return t('pttSettings.errorUnsupportedWayland');
- }
- if (lower.includes('accessibility')) {
- return t('pttSettings.errorAccessibility');
- }
- if (lower.includes('in use') || lower.includes('shortcutinuse') || lower.includes('in_use')) {
- return t('pttSettings.errorShortcutInUse');
- }
- return raw;
-}
-
-const PttSettingsPanel = () => {
- const { t } = useT();
- const dispatch = useAppDispatch();
- const shortcut = useAppSelector(selectPttShortcut);
- const speakReplies = useAppSelector(selectSpeakReplies);
- const showOverlay = useAppSelector(selectShowOverlay);
- const registrationError = useAppSelector(selectPttRegistrationError);
-
- // Inline validation error for the capture input (e.g. modifier-only).
- // Cleared whenever the user retries or focuses the field. Server-side
- // errors (accessibility, in-use, Wayland) are emitted by the manager
- // hook via toast/snackbar in T11; we keep this panel-local state for
- // the capture-time failure modes.
- const [captureError, setCaptureError] = useState<string | null>(null);
-
- const handleShortcutKeyDown = useCallback(
- (e: React.KeyboardEvent<HTMLInputElement>) => {
- // Let Tab / Shift+Tab pass through so keyboard navigation within
- // the settings panel still works. All other keys are captured as
- // potential binding candidates and their default actions suppressed
- // so the input doesn't insert text.
- if (e.key === 'Tab') {
- return;
- }
- e.preventDefault();
- e.stopPropagation();
-
- // Allow Backspace / Delete / Escape to clear the binding so the
- // user can drop back to the "off" state without having to fight a
- // sticky F13.
- if (e.key === 'Backspace' || e.key === 'Delete' || e.key === 'Escape') {
- setCaptureError(null);
- dispatch(setPttShortcut(null));
- return;
- }
-
- if (MODIFIER_KEYS.has(e.key)) {
- setCaptureError(t('pttSettings.errorModifierOnly'));
- return;
- }
-
- const shortcutString = eventToShortcut(e);
- if (!shortcutString) {
- setCaptureError(t('pttSettings.errorEmpty'));
- return;
- }
-
- console.debug('[pttSettings] captured shortcut %s', shortcutString);
- setCaptureError(null);
- dispatch(setPttShortcut(shortcutString));
- },
- [dispatch, t]
- );
-
- const toggleSpeakReplies = useCallback(() => {
- dispatch(setSpeakReplies(!speakReplies));
- }, [dispatch, speakReplies]);
-
- const toggleShowOverlay = useCallback(() => {
- dispatch(setShowOverlay(!showOverlay));
- }, [dispatch, showOverlay]);
-
- return (
- <Card
- title={t('pttSettings.title')}
- description={t('pttSettings.description')}
- data-testid="ptt-settings-panel">
- {/* Hotkey capture: focus the field and press the key combination. */}
- <div className="space-y-2 px-4 py-3">
- <div className="flex items-center justify-between gap-4">
- <label htmlFor="ptt-shortcut-input" className="text-sm font-medium text-content">
- {t('pttSettings.shortcutLabel')}
- </label>
- <div className="flex items-center gap-2">
- <div className="relative">
- <Keyboard
- className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-content-faint"
- aria-hidden
- />
- <input
- id="ptt-shortcut-input"
- data-testid="ptt-shortcut-input"
- type="text"
- readOnly
- value={shortcut ?? ''}
- placeholder={t('pttSettings.shortcutPlaceholder')}
- aria-label={t('pttSettings.shortcutLabel')}
- onKeyDown={handleShortcutKeyDown}
- onFocus={() => setCaptureError(null)}
- className="h-8 w-56 rounded-md border border-line-strong bg-surface pl-8 pr-3 font-mono text-sm text-content placeholder:font-sans placeholder:text-content-faint focus:outline-hidden focus:ring-2 focus:ring-primary-500/25"
- />
- </div>
- {shortcut && (
- <Button
- type="button"
- variant="tertiary"
- size="sm"
- aria-label={t('pttSettings.clearShortcut')}
- leadingIcon={<X className="h-3.5 w-3.5" aria-hidden />}
- onClick={() => {
- setCaptureError(null);
- dispatch(setPttShortcut(null));
- }}>
- {t('pttSettings.clearShortcut')}
- </Button>
- )}
- </div>
- </div>
- {!shortcut && !captureError && (
- <p className="text-xs text-content-muted" data-testid="ptt-shortcut-unset-hint">
- {t('pttSettings.shortcutUnsetHint')}
- </p>
- )}
- {captureError && (
- <p
- className="text-xs text-coral-600 dark:text-coral-300"
- data-testid="ptt-shortcut-error">
- {captureError}
- </p>
- )}
- {!captureError && registrationError && (
- <p
- role="alert"
- className="text-xs text-coral-600 dark:text-coral-300"
- data-testid="ptt-registration-error">
- {localizedRegistrationError(registrationError, t)}
- </p>
- )}
- </div>
-
- <Field
- htmlFor="switch-speak-replies"
- label={t('pttSettings.speakRepliesLabel')}
- control={
- <Switch
- id="switch-speak-replies"
- checked={speakReplies}
- onCheckedChange={toggleSpeakReplies}
- aria-label={t('pttSettings.speakRepliesLabel')}
- data-testid="ptt-speak-replies-switch"
- />
- }
- />
-
- <Field
- htmlFor="switch-show-overlay"
- label={t('pttSettings.showOverlayLabel')}
- control={
- <Switch
- id="switch-show-overlay"
- checked={showOverlay}
- onCheckedChange={toggleShowOverlay}
- aria-label={t('pttSettings.showOverlayLabel')}
- data-testid="ptt-show-overlay-switch"
- />
- }
- />
- </Card>
- );
-};
-
-export default PttSettingsPanel;
diff --git a/app/src/pages/settings/voice/__tests__/PttSettingsPanel.test.tsx b/app/src/pages/settings/voice/__tests__/PttSettingsPanel.test.tsx
deleted file mode 100644
index 40dff8283e..0000000000
--- a/app/src/pages/settings/voice/__tests__/PttSettingsPanel.test.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import { fireEvent, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import { I18nProvider } from '../../../../lib/i18n/I18nContext';
-import { initialPttState, type PttState } from '../../../../store/pttSlice';
-import { renderWithProviders } from '../../../../test/test-utils';
-import PttSettingsPanel from '../PttSettingsPanel';
-
-/**
- * Render PttSettingsPanel with the given PTT slice state pre-seeded so
- * each test can assert against a known starting point. We wrap in the
- * real `I18nProvider` so the panel's labels resolve to the en.ts copy
- * — that lets tests query by their final rendered text without
- * hard-coding the message ids.
- */
-function renderPanel(pttOverrides: Partial<PttState> = {}) {
- const preloadedState = {
- locale: { current: 'en' as const },
- ptt: { ...initialPttState, ...pttOverrides },
- };
- return renderWithProviders(
- <I18nProvider>
- <PttSettingsPanel />
- </I18nProvider>,
- { preloadedState }
- );
-}
-
-describe('PttSettingsPanel', () => {
- it('renders the "not set" hint when no shortcut is bound', () => {
- renderPanel({ shortcut: null });
- expect(screen.getByText(/Push-to-talk is off: pick a hotkey to enable\./i)).toBeInTheDocument();
- });
-
- it('renders the bound shortcut when set', () => {
- renderPanel({ shortcut: 'F13' });
- expect(screen.getByTestId('ptt-shortcut-input')).toHaveValue('F13');
- // The unset hint should NOT show once a shortcut is bound.
- expect(
- screen.queryByText(/Push-to-talk is off: pick a hotkey to enable\./i)
- ).not.toBeInTheDocument();
- });
-
- it('toggles speakReplies via the switch', () => {
- const { store } = renderPanel({ shortcut: 'F13', speakReplies: true });
- const speakSwitch = screen.getByTestId('ptt-speak-replies-switch');
- expect(speakSwitch).toHaveAttribute('aria-checked', 'true');
-
- fireEvent.click(speakSwitch);
-
- const stateAfter = (store.getState() as { ptt: PttState }).ptt;
- expect(stateAfter.speakReplies).toBe(false);
- // And the aria-checked attribute should flip on the rendered switch.
- expect(screen.getByTestId('ptt-speak-replies-switch')).toHaveAttribute('aria-checked', 'false');
- });
-
- it('toggles showOverlay via the switch', () => {
- const { store } = renderPanel({ shortcut: 'F13', showOverlay: true });
- const overlaySwitch = screen.getByTestId('ptt-show-overlay-switch');
- expect(overlaySwitch).toHaveAttribute('aria-checked', 'true');
-
- fireEvent.click(overlaySwitch);
-
- const stateAfter = (store.getState() as { ptt: PttState }).ptt;
- expect(stateAfter.showOverlay).toBe(false);
- });
-
- it('updates the shortcut when a key is captured in the input', () => {
- const { store } = renderPanel({ shortcut: null });
- const input = screen.getByTestId('ptt-shortcut-input');
-
- // Simulate a real keyboard event — the panel listens for keydown on the
- // focused input and captures the key code (e.g. "F13"). Using fireEvent
- // because userEvent.keyboard treats F13 as a sequence.
- fireEvent.keyDown(input, { key: 'F13', code: 'F13' });
-
- const stateAfter = (store.getState() as { ptt: PttState }).ptt;
- expect(stateAfter.shortcut).toBe('F13');
- });
-
- it('shows the panel title and description from the en locale', () => {
- renderPanel({ shortcut: null });
- expect(screen.getByText('Push-to-talk')).toBeInTheDocument();
- expect(screen.getByText(/Hold a key to talk to OpenHuman/i)).toBeInTheDocument();
- });
-
- it('renders the localized registration error when the slice has a dictation conflict', () => {
- renderPanel({
- shortcut: 'F13',
- registrationError: "ptt shortcut 'F13' conflicts with the dictation hotkey",
- });
- const errEl = screen.getByTestId('ptt-registration-error');
- expect(errEl).toBeInTheDocument();
- expect(errEl).toHaveTextContent(/already used by dictation/i);
- });
-
- it('renders a localized Wayland error when the slice has one', () => {
- renderPanel({
- shortcut: 'F13',
- registrationError: 'global shortcuts are not supported in this Wayland session',
- });
- expect(screen.getByTestId('ptt-registration-error')).toHaveTextContent(/wayland/i);
- });
-
- it('renders the raw error string for unrecognised errors', () => {
- renderPanel({ shortcut: 'F13', registrationError: 'some unexpected Tauri error' });
- expect(screen.getByTestId('ptt-registration-error')).toHaveTextContent(
- 'some unexpected Tauri error'
- );
- });
-
- it('does not render a registration error when registrationError is null', () => {
- renderPanel({ shortcut: 'F13', registrationError: null });
- expect(screen.queryByTestId('ptt-registration-error')).not.toBeInTheDocument();
- });
-
- it('hides the registration error when a captureError (modifier-only) is also present', () => {
- // Both errors at once — captureError wins because it's more immediate.
- // Trigger captureError by pressing a modifier-only key.
- renderPanel({ shortcut: 'F13', registrationError: 'some unexpected Tauri error' });
- const input = screen.getByTestId('ptt-shortcut-input');
- fireEvent.keyDown(input, { key: 'Shift', code: 'ShiftLeft', shiftKey: true });
- // captureError is now set — registration error should be hidden.
- expect(screen.queryByTestId('ptt-registration-error')).not.toBeInTheDocument();
- expect(screen.getByTestId('ptt-shortcut-error')).toBeInTheDocument();
- });
-});
diff --git a/app/src/services/__tests__/pttService.test.ts b/app/src/services/__tests__/pttService.test.ts
deleted file mode 100644
index 55cb62346c..0000000000
--- a/app/src/services/__tests__/pttService.test.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { createPttService, type PttDeps } from '../pttService';
-
-function makeDeps(overrides: Partial<PttDeps> = {}): PttDeps {
- return {
- audioCapture: {
- start: vi.fn().mockResolvedValue(undefined),
- finalize: vi.fn().mockResolvedValue({ durationMs: 1500, buffer: new ArrayBuffer(0) }),
- cancel: vi.fn().mockResolvedValue(undefined),
- },
- transcribe: vi.fn().mockResolvedValue('hello world'),
- sendMessage: vi.fn().mockResolvedValue(undefined),
- resolveActiveThreadId: vi.fn().mockResolvedValue('thread-active'),
- createNewVoiceThread: vi.fn().mockResolvedValue('thread-new'),
- playChime: vi.fn().mockResolvedValue(undefined),
- showOverlay: vi.fn().mockResolvedValue(undefined),
- getSettings: () => ({ speakReplies: true, showOverlay: true }),
- now: () => 1_700_000_000_000,
- watchdogMs: 10_000,
- minAudioMs: 250,
- logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn() },
- ...overrides,
- };
-}
-
-describe('pttService state machine', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- });
-
- it('happy path: start → stop sends the transcript to the active thread with speakReply', async () => {
- const deps = makeDeps();
- const svc = createPttService(deps);
-
- await svc.onStart(1);
- expect(deps.audioCapture.start).toHaveBeenCalledWith({ sessionTag: 'ptt:1' });
- expect(deps.playChime).toHaveBeenCalledWith('open');
- expect(deps.showOverlay).toHaveBeenCalledWith(true, 1);
-
- await svc.onStop(1);
- expect(deps.audioCapture.finalize).toHaveBeenCalled();
- expect(deps.playChime).toHaveBeenCalledWith('close');
- expect(deps.showOverlay).toHaveBeenCalledWith(false, 1);
- expect(deps.transcribe).toHaveBeenCalled();
- expect(deps.sendMessage).toHaveBeenCalledWith({
- threadId: 'thread-active',
- body: 'hello world',
- metadata: { source: 'ptt', session_id: 1 },
- speakReply: true,
- });
- });
-
- it('falls back to a new "Voice" thread when no active thread exists', async () => {
- const deps = makeDeps({ resolveActiveThreadId: vi.fn().mockResolvedValue(null) });
- const svc = createPttService(deps);
-
- await svc.onStart(2);
- await svc.onStop(2);
-
- expect(deps.createNewVoiceThread).toHaveBeenCalled();
- expect(deps.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({ threadId: 'thread-new' })
- );
- });
-
- it('drops the session and plays the error chime when audio is shorter than minAudioMs', async () => {
- const deps = makeDeps({
- audioCapture: {
- start: vi.fn().mockResolvedValue(undefined),
- finalize: vi.fn().mockResolvedValue({ durationMs: 100, buffer: new ArrayBuffer(0) }),
- cancel: vi.fn().mockResolvedValue(undefined),
- },
- });
- const svc = createPttService(deps);
-
- await svc.onStart(3);
- await svc.onStop(3);
-
- expect(deps.transcribe).not.toHaveBeenCalled();
- expect(deps.sendMessage).not.toHaveBeenCalled();
- expect(deps.playChime).toHaveBeenCalledWith('error');
- });
-
- it('drops the session when the transcript is empty', async () => {
- const deps = makeDeps({ transcribe: vi.fn().mockResolvedValue(' ') });
- const svc = createPttService(deps);
-
- await svc.onStart(4);
- await svc.onStop(4);
-
- expect(deps.sendMessage).not.toHaveBeenCalled();
- expect(deps.playChime).toHaveBeenCalledWith('error');
- });
-
- it('watchdog finalises the session after watchdogMs even if onStop never arrives', async () => {
- const deps = makeDeps();
- const svc = createPttService(deps);
-
- await svc.onStart(5);
-
- // Advance fake time past the watchdog.
- await vi.advanceTimersByTimeAsync(11_000);
-
- expect(deps.audioCapture.finalize).toHaveBeenCalled();
- expect(deps.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({ metadata: expect.objectContaining({ session_id: 5 }) })
- );
- });
-
- it('second onStart while a session is active preempts the first', async () => {
- const deps = makeDeps();
- const svc = createPttService(deps);
-
- await svc.onStart(6);
- await svc.onStart(7);
-
- expect(deps.audioCapture.cancel).toHaveBeenCalled();
- expect(deps.audioCapture.start).toHaveBeenLastCalledWith({ sessionTag: 'ptt:7' });
- });
-
- it('honours the speakReplies setting when forwarding to sendMessage', async () => {
- const deps = makeDeps({ getSettings: () => ({ speakReplies: false, showOverlay: true }) });
- const svc = createPttService(deps);
-
- await svc.onStart(8);
- await svc.onStop(8);
-
- expect(deps.sendMessage).toHaveBeenCalledWith(expect.objectContaining({ speakReply: false }));
- });
-
- it('mismatched session_id on onStop is ignored', async () => {
- const deps = makeDeps();
- const svc = createPttService(deps);
-
- await svc.onStart(9);
- await svc.onStop(999); // stale stop event
-
- expect(deps.audioCapture.finalize).not.toHaveBeenCalled();
- });
-
- it('cancel("user_cancel") aborts an active session without sending a message', async () => {
- const deps = makeDeps();
- const svc = createPttService(deps);
-
- await svc.onStart(10);
- await svc.cancel('user_cancel');
-
- expect(deps.audioCapture.cancel).toHaveBeenCalled();
- expect(deps.playChime).toHaveBeenCalledWith('error');
- expect(deps.showOverlay).toHaveBeenLastCalledWith(false, 10);
- expect(deps.sendMessage).not.toHaveBeenCalled();
- });
-
- it('plays error chime and bails if audioCapture.start throws', async () => {
- const deps = makeDeps({
- audioCapture: {
- start: vi.fn().mockRejectedValue(new Error('mic denied')),
- finalize: vi.fn().mockResolvedValue({ durationMs: 1500, buffer: new ArrayBuffer(0) }),
- cancel: vi.fn().mockResolvedValue(undefined),
- },
- });
- const svc = createPttService(deps);
-
- await svc.onStart(11);
-
- expect(deps.playChime).toHaveBeenCalledWith('open');
- expect(deps.playChime).toHaveBeenCalledWith('error');
- expect(deps.showOverlay).toHaveBeenLastCalledWith(false, 11);
- // The session never armed — onStop should be a no-op.
- await svc.onStop(11);
- expect(deps.audioCapture.finalize).not.toHaveBeenCalled();
- expect(deps.sendMessage).not.toHaveBeenCalled();
- });
-
- it('posts a "[Voice — transcription failed]" breadcrumb when transcribe throws', async () => {
- const deps = makeDeps({ transcribe: vi.fn().mockRejectedValue(new Error('stt timeout')) });
- const svc = createPttService(deps);
-
- await svc.onStart(12);
- await svc.onStop(12);
-
- expect(deps.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- body: '[Voice — transcription failed]',
- metadata: { source: 'ptt', session_id: 12 },
- })
- );
- });
-});
diff --git a/app/src/services/pttService.ts b/app/src/services/pttService.ts
deleted file mode 100644
index 19342ee27a..0000000000
--- a/app/src/services/pttService.ts
+++ /dev/null
@@ -1,260 +0,0 @@
-/**
- * pttService — push-to-talk session state machine.
- *
- *
- * Dependency-injected so vitest can exercise the state machine with fake
- * audio capture / fake STT / fake sendMessage. Real wiring (subscribing to
- * `ptt://*` Tauri events, the real audio_capture, etc.) happens in
- * PttHotkeyManager.tsx (T11).
- */
-
-export type ChimeKind = 'open' | 'close' | 'error';
-
-export interface PttSettings {
- speakReplies: boolean;
- showOverlay: boolean;
-}
-
-export interface FinalizedAudio {
- durationMs: number;
- buffer: ArrayBuffer;
-}
-
-export interface PttDeps {
- audioCapture: {
- start(opts: { sessionTag: string }): Promise<void>;
- finalize(): Promise<FinalizedAudio>;
- cancel(): Promise<void>;
- };
- transcribe(buf: ArrayBuffer): Promise<string>;
- sendMessage(args: {
- threadId: string;
- body: string;
- metadata: { source: 'ptt'; session_id: number };
- speakReply: boolean;
- }): Promise<void>;
- resolveActiveThreadId(): Promise<string | null>;
- createNewVoiceThread(): Promise<string>;
- playChime(kind: ChimeKind): Promise<void>;
- showOverlay(active: boolean, sessionId: number): Promise<void>;
- getSettings(): PttSettings;
- now(): number;
- watchdogMs: number;
- minAudioMs: number;
- logger: {
- debug(msg: string, meta?: Record<string, unknown>): void;
- info(msg: string, meta?: Record<string, unknown>): void;
- warn(msg: string, meta?: Record<string, unknown>): void;
- };
-}
-
-interface PttService {
- onStart(sessionId: number): Promise<void>;
- onStop(sessionId: number): Promise<void>;
- cancel(reason: 'preempted' | 'mic_failure' | 'user_cancel'): Promise<void>;
-}
-
-interface ActiveSession {
- sessionId: number;
- startedAtMs: number;
- watchdogTimer: ReturnType<typeof setTimeout> | null;
- finalizedByWatchdog: boolean;
-}
-
-export function createPttService(deps: PttDeps): PttService {
- let active: ActiveSession | null = null;
-
- const armWatchdog = (sessionId: number) => {
- const timer = setTimeout(() => {
- if (active && active.sessionId === sessionId) {
- active.finalizedByWatchdog = true;
- deps.logger.warn('[ptt] watchdog fired — finalising session', { sessionId });
- // Fire-and-forget; the watchdog path is the same as a normal stop
- // except for the `finalizedByWatchdog` flag (used in logging only).
- void finaliseSession(sessionId, /* fromWatchdog */ true);
- }
- }, deps.watchdogMs);
- return timer;
- };
-
- const finaliseSession = async (sessionId: number, fromWatchdog: boolean) => {
- if (!active || active.sessionId !== sessionId) {
- // Stale finalisation — ignore.
- return;
- }
-
- if (active.watchdogTimer) {
- clearTimeout(active.watchdogTimer);
- active.watchdogTimer = null;
- }
-
- const settings = deps.getSettings();
- const session = active;
- active = null;
-
- let audio: FinalizedAudio;
- try {
- audio = await deps.audioCapture.finalize();
- } catch (err) {
- deps.logger.warn('[ptt] audio finalize failed', { sessionId, err: String(err) });
- await deps.playChime('error');
- await deps.showOverlay(false, sessionId);
- return;
- }
-
- await deps.playChime('close');
- await deps.showOverlay(false, sessionId);
-
- if (audio.durationMs < deps.minAudioMs) {
- deps.logger.info('[ptt] session dropped — audio shorter than minAudioMs', {
- sessionId,
- durationMs: audio.durationMs,
- });
- await deps.playChime('error');
- return;
- }
-
- let text = '';
- try {
- text = await deps.transcribe(audio.buffer);
- } catch (err) {
- deps.logger.warn('[ptt] transcription failed', { sessionId, err: String(err) });
- // Per spec: post the message anyway as a breadcrumb.
- text = '[Voice — transcription failed]';
- }
-
- const trimmed = text.trim();
-
- if (!trimmed) {
- deps.logger.info('[ptt] session dropped — empty transcript', { sessionId });
- await deps.playChime('error');
- return;
- }
-
- let threadId: string;
- try {
- const resolved = await deps.resolveActiveThreadId();
- if (!resolved) {
- threadId = await deps.createNewVoiceThread();
- } else {
- threadId = resolved;
- }
- } catch (err) {
- deps.logger.warn('[ptt] thread resolution failed — aborting commit', {
- sessionId,
- err: String(err),
- });
- await deps.playChime('error');
- return;
- }
-
- try {
- await deps.sendMessage({
- threadId,
- body: trimmed,
- metadata: { source: 'ptt', session_id: sessionId },
- speakReply: settings.speakReplies,
- });
- } catch (err) {
- deps.logger.warn('[ptt] sendMessage failed', { sessionId, threadId, err: String(err) });
- await deps.playChime('error');
- return;
- }
-
- deps.logger.info('[ptt] session committed', {
- sessionId,
- threadId,
- heldMs: deps.now() - session.startedAtMs,
- finalizedByWatchdog: fromWatchdog,
- transcriptLen: trimmed.length,
- });
- };
-
- return {
- async onStart(sessionId) {
- // Preempt: if another session is active, cancel it.
- if (active) {
- deps.logger.debug('[ptt] onStart while active — preempting', {
- old: active.sessionId,
- new: sessionId,
- });
- try {
- await deps.audioCapture.cancel();
- } catch (err) {
- deps.logger.warn('[ptt] cancel failed during preempt', { err: String(err) });
- }
- if (active.watchdogTimer) clearTimeout(active.watchdogTimer);
- active = null;
- }
-
- // Claim the slot BEFORE any awaits so concurrent onStart calls preempt
- // this in-progress session rather than racing with it.
- active = {
- sessionId,
- startedAtMs: deps.now(),
- watchdogTimer: null,
- finalizedByWatchdog: false,
- };
- const claimed = active;
-
- await deps.playChime('open');
- await deps.showOverlay(true, sessionId);
-
- // If a concurrent onStart preempted us during the awaits, our claim was
- // replaced. Stop here — the new claim owns the slot.
- if (active !== claimed) {
- return;
- }
-
- try {
- await deps.audioCapture.start({ sessionTag: `ptt:${sessionId}` });
- } catch (err) {
- deps.logger.warn('[ptt] audio start failed', { sessionId, err: String(err) });
- if (active === claimed) {
- active = null;
- }
- await deps.playChime('error');
- await deps.showOverlay(false, sessionId);
- return;
- }
-
- // Re-check after the audio.start await.
- if (active !== claimed) {
- // Concurrent preempt replaced our claim mid-flight; we already started
- // audio for an orphan session. Best-effort cancel and exit — cancellation
- // failure here is non-actionable (the orphan session is already detached).
- try {
- await deps.audioCapture.cancel();
- } catch (_) {
- // ignore: orphan-session cleanup is best-effort
- }
- return;
- }
-
- active.watchdogTimer = armWatchdog(sessionId);
- },
-
- async onStop(sessionId) {
- if (!active || active.sessionId !== sessionId) {
- deps.logger.debug('[ptt] stale onStop — ignored', { sessionId });
- return;
- }
- await finaliseSession(sessionId, /* fromWatchdog */ false);
- },
-
- async cancel(reason) {
- if (!active) return;
- deps.logger.info('[ptt] cancel', { sessionId: active.sessionId, reason });
- if (active.watchdogTimer) clearTimeout(active.watchdogTimer);
- const session = active;
- active = null;
- try {
- await deps.audioCapture.cancel();
- } catch (err) {
- deps.logger.warn('[ptt] cancel: audio cancel failed', { err: String(err) });
- }
- await deps.playChime('error');
- await deps.showOverlay(false, session.sessionId);
- },
- };
-}
diff --git a/app/src/store/__tests__/pttSlice.test.ts b/app/src/store/__tests__/pttSlice.test.ts
deleted file mode 100644
index 94ed95f244..0000000000
--- a/app/src/store/__tests__/pttSlice.test.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import {
- initialPttState,
- pttReducer,
- type PttState,
- setIsHeld,
- setPttRegistrationError,
- setPttShortcut,
- setShowOverlay,
- setSpeakReplies,
-} from '../pttSlice';
-import { resetUserScopedState } from '../resetActions';
-
-describe('ptt slice', () => {
- const initial: PttState = {
- shortcut: null,
- speakReplies: true,
- showOverlay: true,
- isHeld: false,
- registrationError: null,
- };
-
- it('has the documented default state', () => {
- expect(pttReducer(undefined, { type: '@@INIT' })).toEqual(initial);
- });
-
- it('setPttShortcut stores the shortcut string', () => {
- const next = pttReducer(initial, setPttShortcut('F13'));
- expect(next.shortcut).toBe('F13');
- });
-
- it('setPttShortcut with null clears the shortcut', () => {
- const withKey: PttState = { ...initial, shortcut: 'F13' };
- const next = pttReducer(withKey, setPttShortcut(null));
- expect(next.shortcut).toBeNull();
- });
-
- it('setSpeakReplies toggles the flag', () => {
- expect(pttReducer(initial, setSpeakReplies(false)).speakReplies).toBe(false);
- });
-
- it('setShowOverlay toggles the flag', () => {
- expect(pttReducer(initial, setShowOverlay(false)).showOverlay).toBe(false);
- });
-
- it('setIsHeld updates the runtime hold flag', () => {
- expect(pttReducer(initial, setIsHeld(true)).isHeld).toBe(true);
- });
-
- it('setPttRegistrationError stores the error string', () => {
- const next = pttReducer(initial, setPttRegistrationError('hotkey in use'));
- expect(next.registrationError).toBe('hotkey in use');
- });
-
- it('setPttRegistrationError with null clears the error', () => {
- const withErr: PttState = { ...initial, registrationError: 'some error' };
- const next = pttReducer(withErr, setPttRegistrationError(null));
- expect(next.registrationError).toBeNull();
- });
-
- it('resetUserScopedState returns the slice to initial state', () => {
- const dirty: PttState = {
- shortcut: 'F13',
- speakReplies: false,
- showOverlay: false,
- isHeld: true,
- registrationError: 'some error',
- };
- const next = pttReducer(dirty, resetUserScopedState());
- expect(next).toEqual(initialPttState);
- });
-});
diff --git a/app/src/store/pttSlice.ts b/app/src/store/pttSlice.ts
deleted file mode 100644
index ac5a89b2ed..0000000000
--- a/app/src/store/pttSlice.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { createSlice, type PayloadAction } from '@reduxjs/toolkit';
-
-import { resetUserScopedState } from './resetActions';
-
-/**
- * PTT (Push-to-Talk) slice — persisted hotkey binding + session settings,
- * plus non-persisted runtime flags:
- * - `isHeld`: tracks whether the PTT key is currently held. The boot hook
- * (Task 11) resets it to false on mount so a stale rehydrated value can
- * never leave the app stuck in "held" mode.
- * - `registrationError`: the most recent error from `register_ptt_hotkey`,
- * surfaced in PttSettingsPanel (T13). Cleared on successful register.
- * Transient — not persisted across sessions.
- */
-
-export interface PttState {
- /** Currently-bound PTT hotkey string (e.g. "F13" or "Ctrl+Alt+T"). null = unbound. */
- shortcut: string | null;
- /** When true, the agent's reply is spoken via TTS. */
- speakReplies: boolean;
- /** When true, the overlay window is shown during a PTT session. */
- showOverlay: boolean;
- /** Non-persisted runtime flag: is the PTT key currently held? */
- isHeld: boolean;
- /** Last error from register_ptt_hotkey, surfaced in PttSettingsPanel. Cleared on successful register. */
- registrationError: string | null;
-}
-
-export const initialPttState: PttState = {
- shortcut: null,
- speakReplies: true,
- showOverlay: true,
- isHeld: false,
- registrationError: null,
-};
-
-const pttSlice = createSlice({
- name: 'ptt',
- initialState: initialPttState,
- reducers: {
- setPttShortcut(state, action: PayloadAction<string | null>) {
- state.shortcut = action.payload;
- },
- setSpeakReplies(state, action: PayloadAction<boolean>) {
- state.speakReplies = action.payload;
- },
- setShowOverlay(state, action: PayloadAction<boolean>) {
- state.showOverlay = action.payload;
- },
- setIsHeld(state, action: PayloadAction<boolean>) {
- state.isHeld = action.payload;
- },
- setPttRegistrationError(state, action: PayloadAction<string | null>) {
- state.registrationError = action.payload;
- },
- },
- extraReducers: builder => {
- builder.addCase(resetUserScopedState, () => initialPttState);
- },
-});
-
-export const {
- setPttShortcut,
- setSpeakReplies,
- setShowOverlay,
- setIsHeld,
- setPttRegistrationError,
-} = pttSlice.actions;
-
-// ── Selectors ────────────────────────────────────────────────────────────────
-
-export const selectPttShortcut = (state: { ptt: PttState }): string | null => state.ptt.shortcut;
-
-export const selectSpeakReplies = (state: { ptt: PttState }): boolean => state.ptt.speakReplies;
-
-export const selectShowOverlay = (state: { ptt: PttState }): boolean => state.ptt.showOverlay;
-
-export const selectPttRegistrationError = (state: { ptt: PttState }): string | null =>
- state.ptt.registrationError;
-
-export const pttReducer = pttSlice.reducer;
diff --git a/app/src/test/mockDefaultSkillStatusHooks.ts b/app/src/test/mockDefaultSkillStatusHooks.ts
deleted file mode 100644
index 1dfc9966b5..0000000000
--- a/app/src/test/mockDefaultSkillStatusHooks.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- * Shared Vitest mocks for voice status hooks.
- * Import this module first in Skills page tests so `Skills` does not require `CoreStateProvider`.
- */
-import { vi } from 'vitest';
-
-/** Shared offline-shaped fields for skill status hook mocks (avoid drift across hooks). */
-const offlineStatusBase = {
- connectionStatus: 'offline' as const,
- statusDot: 'bg-stone-400',
- statusLabel: 'Offline',
- statusColor: 'text-content-muted',
- ctaLabel: 'Enable',
- ctaVariant: 'sage' as const,
-};
-
-vi.mock('../features/voice/useVoiceSkillStatus', () => ({
- useVoiceSkillStatus: () => ({
- ...offlineStatusBase,
- sttModelMissing: false,
- voiceStatus: null,
- serverStatus: null,
- }),
-}));
diff --git a/app/src/utils/tauriCommands/ptt.ts b/app/src/utils/tauriCommands/ptt.ts
deleted file mode 100644
index 981c56c9eb..0000000000
--- a/app/src/utils/tauriCommands/ptt.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * Push-to-talk (PTT) Tauri command wrappers.
- */
-import { invoke } from '@tauri-apps/api/core';
-
-import { isTauri } from './common';
-
-/**
- * Register (or re-register) the global push-to-talk hotkey.
- */
-export async function registerPttHotkey(shortcut: string): Promise<void> {
- if (!isTauri()) {
- console.debug('[ptt] registerPttHotkey: skipped — not running in Tauri');
- return;
- }
- console.debug('[ptt] registerPttHotkey: shortcut=%s', shortcut);
- await invoke<void>('register_ptt_hotkey', { shortcut });
- console.debug('[ptt] registerPttHotkey: done');
-}
-
-/**
- * Unregister the global push-to-talk hotkey.
- */
-export async function unregisterPttHotkey(): Promise<void> {
- if (!isTauri()) {
- console.debug('[ptt] unregisterPttHotkey: skipped — not running in Tauri');
- return;
- }
- console.debug('[ptt] unregisterPttHotkey: invoking');
- await invoke<void>('unregister_ptt_hotkey');
- console.debug('[ptt] unregisterPttHotkey: done');
-}
-
-/**
- * Show or hide the PTT overlay window.
- */
-export async function showPttOverlay(active: boolean, sessionId: number): Promise<void> {
- if (!isTauri()) {
- console.debug('[ptt] showPttOverlay: skipped — not running in Tauri');
- return;
- }
- console.debug('[ptt] showPttOverlay: active=%s sessionId=%d', active, sessionId);
- await invoke<void>('show_ptt_overlay', { active, sessionId });
-}
diff --git a/app/test/e2e/specs/ptt-flow.spec.ts b/app/test/e2e/specs/ptt-flow.spec.ts
deleted file mode 100644
index 1f34d20206..0000000000
--- a/app/test/e2e/specs/ptt-flow.spec.ts
+++ /dev/null
@@ -1,618 +0,0 @@
-// @ts-nocheck
-/**
- * E2E: global push-to-talk (PTT) end-to-end flow with mocked STT.
- *
- * What this spec exercises (top to bottom):
- *
- * UI:
- * 1. Navigate to /settings/voice → PttSettingsPanel mounts (data-testid
- * "ptt-settings-panel").
- * 2. Programmatically dispatch `setPttShortcut('F13')` against the exposed
- * Redux store to simulate the user binding a hotkey. Using a Redux
- * dispatch (rather than driving the readonly capture input via
- * chromedriver) sidesteps two fragile layers:
- * a. The keyboard-capture input intercepts native keydown events
- * that CDP would otherwise inject into the textarea.
- * b. F13 is reliably passable through chromedriver to a generic
- * input but the panel-level interception logic is unit-tested
- * elsewhere (PttSettingsPanel.test.tsx). We test the *binding
- * effect*, not the capture UX.
- * 3. Assert `usePttHotkey` reacts and Redux state settles with a non-null
- * shortcut. Registration may succeed (no error) or fail with a non-
- * empty error string on headless Linux runners with no real keyboard
- * — both are acceptable signals that the binding path was driven; we
- * log the failure for follow-up but don't make CI red on it.
- *
- * PTT session:
- * 4. Mock navigator.mediaDevices.getUserMedia + MediaRecorder so the
- * renderer-side audio capture (pttAudio.ts) can run without a real
- * microphone (headless CEF has no audio device).
- * 5. Configure the mock backend (audioTranscriptionText) so the core's
- * cloud STT path returns a known transcript "hello from PTT".
- * 6. Simulate the hotkey hold by emitting `ptt://start`/`ptt://stop` via
- * Tauri's internal event plugin (`__TAURI_INTERNALS__.invoke('plugin:
- * event|emit', ...)`). This is the same path `@tauri-apps/api/event`'s
- * `emit()` uses; we go through the internal because direct dynamic
- * imports of `@tauri-apps/api/event` don't resolve under Chromium-
- * driver (see core-rpc.ts).
- * 7. Wait long enough between start/stop (≥ 250 ms — pttService's
- * `minAudioMs`) so the recording isn't dropped as an accidental tap.
- *
- * Assertions:
- * 8. The overlay window is created (window-handle count went from 1 →
- * 2 when register_ptt_hotkey called ptt_overlay::ensure_window).
- * 9. The transcribed text appears as a user message in the chat thread.
- * 10. The core_rpc_relay invocation for `channel_web_chat` carried
- * `speak_reply: true` (the user's PTT setting was honoured on the
- * wire). We spy on `__TAURI_INTERNALS__.invoke` before the press to
- * capture the call payload.
- *
- *
- * Limitations / notes for follow-up sessions:
- * - The OS-level global-shortcut emit can't be triggered by the Chromium
- * driver (CDP injects events into the renderer, not the OS keyboard
- * subsystem). Step 6 above is the correct workaround in a unit-test
- * sense, but it does not exercise the rdev → tauri global-shortcut
- * pipeline on the way in. That layer is covered by Rust unit tests
- * in `ptt_hotkeys.rs` and integration coverage in PttHotkeyManager
- * tests.
- * - MediaRecorder availability under CEF headless: present but won't
- * produce real opus frames. We mock it entirely so the buffer reaches
- * the transcribe RPC as a zero-byte blob; the mock backend doesn't care
- * about the actual audio bytes (it just returns the configured
- * transcript text).
- */
-import { waitForApp } from '../helpers/app-helpers';
-import {
- chatMounted,
- getSelectedThreadId,
- waitForAssistantReplyContaining,
- waitForSocketConnected,
-} from '../helpers/chat-harness';
-import { callOpenhumanRpc } from '../helpers/core-rpc';
-import { resetApp } from '../helpers/reset-app';
-import { navigateViaHash } from '../helpers/shared-flows';
-import {
- clearRequestLog,
- getRequestLog,
- setMockBehavior,
- startMockServer,
- stopMockServer,
-} from '../mock-server';
-
-const USER_ID = 'e2e-ptt-flow';
-const SHORTCUT = 'F13';
-const STT_TRANSCRIPT = 'hello from PTT';
-
-const OVERLAY_WINDOW_LABEL = 'ptt-overlay';
-// pttService.minAudioMs is 250; we hold for 800 ms to be comfortably above the
-// floor and tolerant of slow CI scheduling.
-const HOLD_DURATION_MS = 800;
-
-describe('PTT — global push-to-talk flow', function () {
- before(function () {
- this.skip();
- });
- this.timeout(180_000);
-
- before(async function beforeSuite() {
- this.timeout(120_000);
- await startMockServer();
- await waitForApp();
- await resetApp(USER_ID);
-
- // The cloud STT path goes through /openai/v1/audio/transcriptions in the
- // mock backend; set the deterministic transcript before any PTT press.
- setMockBehavior('audioTranscriptionText', STT_TRANSCRIPT);
- });
-
- after(async () => {
- setMockBehavior('audioTranscriptionText', '');
- await stopMockServer();
- });
-
- // ---------------------------------------------------------------------------
- // Step 1: settings → voice → PttSettingsPanel.
- // ---------------------------------------------------------------------------
- it('renders the PTT settings panel under /settings/voice', async () => {
- await navigateViaHash('/settings/voice');
-
- // The panel may take a beat to mount as VoicePanel hydrates its providers.
- const panel = await browser.$('[data-testid="ptt-settings-panel"]');
- await panel.waitForExist({
- timeout: 20_000,
- timeoutMsg: 'ptt-settings-panel did not mount under /settings/voice',
- });
-
- // The hotkey input + the two switches must all be present (T13 contract).
- const shortcutInput = await browser.$('[data-testid="ptt-shortcut-input"]');
- await shortcutInput.waitForExist({ timeout: 5_000 });
- const speakSwitch = await browser.$('[data-testid="ptt-speak-replies-switch"]');
- await speakSwitch.waitForExist({ timeout: 5_000 });
- const overlaySwitch = await browser.$('[data-testid="ptt-show-overlay-switch"]');
- await overlaySwitch.waitForExist({ timeout: 5_000 });
- });
-
- // ---------------------------------------------------------------------------
- // Step 2 + 3: bind the shortcut, observe Redux + register_ptt_hotkey.
- //
- // We drive Redux directly. The shortcut-capture input is exhaustively
- // covered by PttSettingsPanel.test.tsx; here we test the *binding effect*
- // — that setting the shortcut triggers the manager hook which calls
- // register_ptt_hotkey in the Tauri shell.
- // ---------------------------------------------------------------------------
- it('binds the F13 hotkey via Redux + the manager hook forwards to the Tauri shell', async () => {
- // Sanity: store handle is exposed (gated on E2E build flag).
- const storePresent = await browser.execute(
- () =>
- typeof (window as unknown as { __OPENHUMAN_STORE__?: unknown }).__OPENHUMAN_STORE__ !==
- 'undefined'
- );
- expect(storePresent).toBe(true);
-
- // Speak replies must be true so the chat-send carries speak_reply: true.
- // showOverlay must be true so the manager invokes show_ptt_overlay on
- // the start edge (overlay window check below depends on it).
- await browser.execute(() => {
- const store = (
- window as unknown as {
- __OPENHUMAN_STORE__: { dispatch: (a: { type: string; payload: unknown }) => unknown };
- }
- ).__OPENHUMAN_STORE__;
- store.dispatch({ type: 'ptt/setSpeakReplies', payload: true });
- store.dispatch({ type: 'ptt/setShowOverlay', payload: true });
- });
-
- // Dispatch the binding.
- await browser.execute((shortcut: string) => {
- const store = (
- window as unknown as {
- __OPENHUMAN_STORE__: { dispatch: (a: { type: string; payload: string }) => unknown };
- }
- ).__OPENHUMAN_STORE__;
- store.dispatch({ type: 'ptt/setPttShortcut', payload: shortcut });
- }, SHORTCUT);
-
- // Wait until the slice settles with the bound shortcut.
- await browser.waitUntil(
- async () => {
- return (
- (await browser.execute(() => {
- const state = (
- window as unknown as {
- __OPENHUMAN_STORE__: { getState: () => { ptt?: { shortcut?: string | null } } };
- }
- ).__OPENHUMAN_STORE__.getState();
- return state.ptt?.shortcut ?? null;
- })) === SHORTCUT
- );
- },
- { timeout: 5_000, timeoutMsg: 'ptt.shortcut never settled to F13' }
- );
-
- // Give usePttHotkey a beat to call register_ptt_hotkey, then read the
- // registration-error slice. A null (or empty) error means the Tauri
- // shell registered the OS shortcut successfully. A non-null error is
- // acceptable in headless Linux containers where the global-shortcut
- // plugin can't talk to a real X11 / Wayland socket — we log and
- // continue rather than fail the spec on env-specific gaps.
- await browser.pause(2_000);
- const registrationError = await browser.execute(() => {
- const state = (
- window as unknown as {
- __OPENHUMAN_STORE__: { getState: () => { ptt?: { registrationError?: string | null } } };
- }
- ).__OPENHUMAN_STORE__.getState();
- return state.ptt?.registrationError ?? null;
- });
- if (registrationError) {
- console.warn(
- `[ptt-flow] register_ptt_hotkey returned error in this environment: ${registrationError}. ` +
- 'Continuing — the binding-side wiring was driven and the failure is the OS shortcut path.'
- );
- } else {
- console.log('[ptt-flow] register_ptt_hotkey succeeded — overlay window should now exist');
- }
- });
-
- // ---------------------------------------------------------------------------
- // Step 8: overlay window is created lazily by register_ptt_hotkey.
- //
- // We check getWindowHandles. The handle count goes from 1 (main app) →
- // 2 (main + ptt-overlay) once ensure_window has run. We tolerate either
- // outcome: if the OS shortcut failed earlier (headless container), the
- // overlay might still be created (ensure_window is best-effort and runs
- // before the shortcut registration), but we don't *require* it to assert
- // success.
- // ---------------------------------------------------------------------------
- it('lazy-creates the overlay webview window once the hotkey is bound', async () => {
- // Poll briefly — window creation is async after register_ptt_hotkey returns.
- const deadline = Date.now() + 10_000;
- let handles: string[] = [];
- while (Date.now() < deadline) {
- handles = await browser.getWindowHandles();
- if (handles.length >= 2) break;
- await browser.pause(300);
- }
- console.log(`[ptt-flow] window handles after bind: ${handles.length}`);
- if (handles.length < 2) {
- console.warn(
- '[ptt-flow] overlay window did not appear — likely register_ptt_hotkey failed on this OS ' +
- '(see registrationError log above). Skipping overlay-window assertion.'
- );
- return;
- }
- // Confirm at least one of the new handles loads the ptt-overlay route.
- const mainHandle = await browser.getWindowHandle();
- let foundOverlay = false;
- for (const handle of handles) {
- if (handle === mainHandle) continue;
- try {
- await browser.switchToWindow(handle);
- const url = await browser.getUrl();
- console.log(`[ptt-flow] inspecting non-main window: ${url}`);
- if (url.includes('ptt-overlay') || url.includes(OVERLAY_WINDOW_LABEL)) {
- foundOverlay = true;
- break;
- }
- } catch (err) {
- console.warn('[ptt-flow] switchToWindow threw — continuing', err);
- }
- }
- // Switch back to the main window before the next test runs.
- try {
- await browser.switchToWindow(mainHandle);
- } catch (err) {
- console.warn('[ptt-flow] could not switch back to main window', err);
- }
- expect(foundOverlay).toBe(true);
- });
-
- // ---------------------------------------------------------------------------
- // Step 4–7 + 9–10: simulate the hold, observe the commit.
- // ---------------------------------------------------------------------------
- it('simulates a PTT hold, captures audio, transcribes via mock, sends with speak_reply: true', async function () {
- this.timeout(120_000);
-
- // Make sure the user is signed in + the socket is connected so the
- // channel_web_chat RPC has a real client_id to route on.
- const socketReady = await waitForSocketConnected(30_000);
- if (!socketReady) {
- console.warn('[ptt-flow] socket did not connect within 30s — chat send may fail');
- }
-
- // Navigate to /chat so the chat runtime is hydrated and we land on a
- // resolvable thread. pttThread.ts will resolve the active thread or
- // create one as needed; this just makes the assertion at step 9
- // easier (we can read selectedThreadId and assert message presence).
- await navigateViaHash('/chat');
- await browser.waitUntil(async () => await chatMounted(), {
- timeout: 15_000,
- timeoutMsg: 'Conversations did not mount under /chat',
- });
-
- // -------------------------------------------------------------------------
- // 4a. Mock getUserMedia + MediaRecorder so pttAudio.ts succeeds.
- //
- // We replace getUserMedia with a fake that returns a MediaStream-shaped
- // object; we replace MediaRecorder with a minimal stub that fires
- // 'dataavailable' (empty Blob) and 'stop' synchronously when .stop() is
- // called. The audio buffer ends up zero-byte — the mock STT endpoint
- // returns the fixed transcript regardless.
- // -------------------------------------------------------------------------
- await browser.execute(() => {
- const w = window as unknown as Record<string, unknown>;
- w.__e2e_ptt_real_gum = navigator.mediaDevices?.getUserMedia?.bind(navigator.mediaDevices);
- w.__e2e_ptt_real_mr = (window as unknown as { MediaRecorder?: unknown }).MediaRecorder;
-
- class FakeMediaRecorder {
- public state: 'inactive' | 'recording' = 'inactive';
- public mimeType: string;
- private listeners = new Map<string, Set<(e: unknown) => void>>();
- constructor(_stream: unknown, opts?: { mimeType?: string }) {
- this.mimeType = opts?.mimeType || 'audio/webm;codecs=opus';
- }
- static isTypeSupported(_mime: string): boolean {
- return true;
- }
- addEventListener(type: string, fn: (e: unknown) => void): void {
- if (!this.listeners.has(type)) this.listeners.set(type, new Set());
- this.listeners.get(type)!.add(fn);
- }
- removeEventListener(type: string, fn: (e: unknown) => void): void {
- this.listeners.get(type)?.delete(fn);
- }
- dispatchEvent(type: string, payload: unknown): void {
- const set = this.listeners.get(type);
- if (!set) return;
- for (const fn of set) {
- try {
- fn(payload);
- } catch (err) {
- // swallow — listener failures shouldn't break the test
- console.warn('[e2e-ptt-mock] listener threw', err);
- }
- }
- }
- start(): void {
- this.state = 'recording';
- }
- stop(): void {
- // Emit a tiny synthetic chunk + a stop event. pttAudio expects
- // dataavailable with .data:Blob and then stop.
- const blob = new Blob([new Uint8Array(8)], { type: this.mimeType });
- this.dispatchEvent('dataavailable', { data: blob });
- this.state = 'inactive';
- this.dispatchEvent('stop', new Event('stop'));
- }
- }
-
- const fakeStream = {
- getTracks: () => [
- {
- stop() {
- /* noop */
- },
- kind: 'audio' as const,
- },
- ],
- };
-
- Object.defineProperty(navigator, 'mediaDevices', {
- configurable: true,
- value: {
- ...(navigator.mediaDevices || {}),
- getUserMedia: () => Promise.resolve(fakeStream as unknown as MediaStream),
- },
- });
- (window as unknown as { MediaRecorder: unknown }).MediaRecorder =
- FakeMediaRecorder as unknown;
- });
-
- // -------------------------------------------------------------------------
- // 10a. Spy on Tauri invocations so we can capture the channel_web_chat
- // payload and assert speak_reply: true was forwarded on the wire.
- //
- // __TAURI_INTERNALS__.invoke is the underlying channel every Tauri
- // command (and `core_rpc_relay`) flows through. We wrap it to push
- // relay calls into a module-window-scoped list.
- // -------------------------------------------------------------------------
- await browser.execute(() => {
- const w = window as unknown as {
- __TAURI_INTERNALS__?: {
- invoke?: (...args: unknown[]) => Promise<unknown>;
- [k: string]: unknown;
- };
- __e2e_ptt_relay_calls?: Array<{ cmd: string; args: unknown }>;
- __e2e_ptt_real_invoke?: (...args: unknown[]) => Promise<unknown>;
- };
- if (!w.__TAURI_INTERNALS__ || typeof w.__TAURI_INTERNALS__.invoke !== 'function') {
- console.warn('[e2e-ptt-spy] __TAURI_INTERNALS__.invoke missing — spy not installed');
- return;
- }
- w.__e2e_ptt_relay_calls = [];
- w.__e2e_ptt_real_invoke = w.__TAURI_INTERNALS__.invoke;
- const original = w.__e2e_ptt_real_invoke;
- w.__TAURI_INTERNALS__.invoke = async function spied(
- cmd: string,
- args?: unknown,
- ...rest: unknown[]
- ): Promise<unknown> {
- try {
- if (cmd === 'core_rpc_relay') {
- w.__e2e_ptt_relay_calls!.push({ cmd, args });
- }
- } catch {
- /* ignore */
- }
- // Forward to the original implementation, preserving binding.
- return (original as Function).call(w.__TAURI_INTERNALS__, cmd, args, ...rest);
- };
- });
-
- clearRequestLog();
- const threadIdBefore = await getSelectedThreadId();
- console.log(`[ptt-flow] selectedThreadId before press: ${threadIdBefore}`);
-
- // -------------------------------------------------------------------------
- // 6. Simulate the hotkey hold by emitting ptt://start and ptt://stop
- // via Tauri's internal event plugin. PttHotkeyManager's listen()
- // handlers pick these up and drive pttService through onStart/onStop.
- // -------------------------------------------------------------------------
- const sessionId = 1;
- const emitOk = await browser.execute(
- async ({ event, payloadJson }) => {
- const w = window as unknown as {
- __TAURI_INTERNALS__?: { invoke?: (...args: unknown[]) => Promise<unknown> };
- };
- const invoke = w.__TAURI_INTERNALS__?.invoke;
- if (!invoke) return { ok: false, err: 'no __TAURI_INTERNALS__.invoke' };
- try {
- // plugin:event|emit accepts a JSON-string payload for arbitrary
- // event types (the listener side is generic-typed).
- await invoke('plugin:event|emit', { event, payload: payloadJson });
- return { ok: true };
- } catch (e) {
- return { ok: false, err: e instanceof Error ? e.message : String(e) };
- }
- },
- { event: 'ptt://start', payloadJson: JSON.stringify({ session_id: sessionId }) }
- );
- if (!emitOk?.ok) {
- console.warn(`[ptt-flow] emit ptt://start failed: ${emitOk?.err}`);
- }
-
- // Hold for HOLD_DURATION_MS so the recording isn't dropped as a tap.
- await browser.pause(HOLD_DURATION_MS);
-
- const stopOk = await browser.execute(
- async ({ event, payloadJson }) => {
- const w = window as unknown as {
- __TAURI_INTERNALS__?: { invoke?: (...args: unknown[]) => Promise<unknown> };
- };
- const invoke = w.__TAURI_INTERNALS__?.invoke;
- if (!invoke) return { ok: false, err: 'no __TAURI_INTERNALS__.invoke' };
- try {
- await invoke('plugin:event|emit', { event, payload: payloadJson });
- return { ok: true };
- } catch (e) {
- return { ok: false, err: e instanceof Error ? e.message : String(e) };
- }
- },
- { event: 'ptt://stop', payloadJson: JSON.stringify({ session_id: sessionId }) }
- );
- if (!stopOk?.ok) {
- console.warn(`[ptt-flow] emit ptt://stop failed: ${stopOk?.err}`);
- }
-
- // -------------------------------------------------------------------------
- // 9. The transcript should appear as a user message in the chat thread.
- // -------------------------------------------------------------------------
- const sawTranscript = await waitForAssistantReplyContaining(STT_TRANSCRIPT, {
- timeoutMs: 30_000,
- logPrefix: '[ptt-flow]',
- });
- if (!sawTranscript) {
- console.warn(
- `[ptt-flow] transcript "${STT_TRANSCRIPT}" did not appear in DOM — ` +
- 'this is often caused by getUserMedia mock injection failing under headless CEF, ' +
- 'or by register_ptt_hotkey having failed earlier so pttService never received ptt://start.'
- );
- }
-
- // -------------------------------------------------------------------------
- // 10b. Assert at least one core_rpc_relay invocation included
- // method: 'openhuman.channel_web_chat' with speak_reply: true.
- // -------------------------------------------------------------------------
- const relayCalls = (await browser.execute(() => {
- return (window as unknown as { __e2e_ptt_relay_calls?: unknown[] }).__e2e_ptt_relay_calls;
- })) as Array<{ cmd: string; args: unknown }> | undefined;
- console.log(`[ptt-flow] captured ${relayCalls?.length ?? 0} core_rpc_relay invocations`);
-
- let sawSpeakReplyChat = false;
- for (const call of relayCalls ?? []) {
- try {
- // Tauri's invoke signature is (cmd, args) where args is a record.
- // For core_rpc_relay the renderer passes either a record like
- // { method, params, body } or a single string — we coerce robustly.
- const args = call.args as Record<string, unknown> | undefined;
- const payload = args && typeof args === 'object' ? JSON.stringify(args) : String(args);
- if (
- payload.includes('openhuman.channel_web_chat') &&
- payload.includes('"speak_reply":true')
- ) {
- sawSpeakReplyChat = true;
- break;
- }
- } catch {
- /* ignore non-stringifiable payloads */
- }
- }
- if (!sawSpeakReplyChat) {
- console.warn(
- '[ptt-flow] did not observe a channel_web_chat call with speak_reply:true. ' +
- 'Dumping the captured payloads for diagnosis:\n' +
- JSON.stringify(relayCalls ?? [], null, 2).slice(0, 4_000)
- );
- }
-
- // Restore the spy + getUserMedia/MediaRecorder so any later spec in the
- // session sees a clean window.
- await browser.execute(() => {
- const w = window as unknown as {
- __TAURI_INTERNALS__?: { invoke?: unknown };
- __e2e_ptt_real_invoke?: unknown;
- __e2e_ptt_real_gum?: unknown;
- __e2e_ptt_real_mr?: unknown;
- };
- if (w.__TAURI_INTERNALS__ && w.__e2e_ptt_real_invoke) {
- w.__TAURI_INTERNALS__.invoke = w.__e2e_ptt_real_invoke;
- }
- if (w.__e2e_ptt_real_gum && navigator.mediaDevices) {
- Object.defineProperty(navigator.mediaDevices, 'getUserMedia', {
- configurable: true,
- value: w.__e2e_ptt_real_gum,
- });
- }
- if (w.__e2e_ptt_real_mr) {
- (window as unknown as { MediaRecorder: unknown }).MediaRecorder = w.__e2e_ptt_real_mr;
- }
- delete (w as Record<string, unknown>).__e2e_ptt_relay_calls;
- delete (w as Record<string, unknown>).__e2e_ptt_real_invoke;
- delete (w as Record<string, unknown>).__e2e_ptt_real_gum;
- delete (w as Record<string, unknown>).__e2e_ptt_real_mr;
- });
-
- // Soft-assert: in a fully green environment both flags are true. We
- // expect both, but the warnings above explain the env paths where one
- // might come back false. Asserting hard would gate CI on shaky pieces.
- expect(sawTranscript).toBe(true);
- expect(sawSpeakReplyChat).toBe(true);
- });
-
- // ---------------------------------------------------------------------------
- // Step 5 corroboration: the mock STT endpoint was hit.
- //
- // We assert the request log contains a POST to
- // /openai/v1/audio/transcriptions. This is independent of the spy above —
- // it confirms the audio bytes actually traversed the Rust STT pipeline
- // (voice_transcribe_bytes RPC → cloud provider → mock).
- // ---------------------------------------------------------------------------
- it('the mock backend received the audio-transcriptions request', async () => {
- const log = getRequestLog() as Array<{ method: string; url: string }>;
- const sttCalls = log.filter(
- r => r.method === 'POST' && r.url.includes('/openai/v1/audio/transcriptions')
- );
- console.log(`[ptt-flow] /openai/v1/audio/transcriptions calls observed: ${sttCalls.length}`);
- // The earlier "PTT session" test logs a warning rather than failing if the
- // OS shortcut couldn't register. In that case the audio path may never
- // have triggered — log and move on rather than make CI red on env gaps.
- if (sttCalls.length === 0) {
- console.warn(
- '[ptt-flow] no audio-transcriptions calls observed. ' +
- 'Most likely cause: the renderer-side audio capture mock or the ptt://start emit ' +
- 'did not fully exercise the pttService path. The earlier in-flight steps log ' +
- 'their specific failures.'
- );
- }
- expect(sttCalls.length).toBeGreaterThan(0);
- });
-
- // ---------------------------------------------------------------------------
- // Optional sanity: the conversation persists with the transcript text.
- //
- // Uses the same test_support_read_workspace_file mechanism as the chat-
- // harness specs (see chat-harness-send-stream.spec.ts).
- // ---------------------------------------------------------------------------
- it('the chat thread JSONL contains the transcribed text on disk', async () => {
- const threadId = await getSelectedThreadId();
- if (typeof threadId !== 'string' || threadId.length === 0) {
- console.warn('[ptt-flow] no selectedThreadId after press — skipping JSONL check');
- return;
- }
- const hex = Array.from(new TextEncoder().encode(threadId))
- .map(b => b.toString(16).padStart(2, '0'))
- .join('');
- const relPath = `memory/conversations/threads/${hex}.jsonl`;
- let content = '';
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- const read = await callOpenhumanRpc<{ result: { content_utf8: string } }>(
- 'openhuman.test_support_read_workspace_file',
- { rel_path: relPath, max_bytes: 65_536 }
- );
- if (read.ok && read.result?.result?.content_utf8) {
- content = read.result.result.content_utf8;
- if (content.includes(STT_TRANSCRIPT)) break;
- }
- await browser.pause(300);
- }
- if (!content.includes(STT_TRANSCRIPT)) {
- console.warn(
- `[ptt-flow] thread JSONL did not contain "${STT_TRANSCRIPT}". This corroborates ` +
- 'an earlier failure in the press path; the earlier `it` logs the specific cause.'
- );
- }
- expect(content).toContain(STT_TRANSCRIPT);
- });
-});
diff --git a/app/test/e2e/specs/voice-mode.spec.ts b/app/test/e2e/specs/voice-mode.spec.ts
index 25271931e9..d2e8851ba7 100644
--- a/app/test/e2e/specs/voice-mode.spec.ts
+++ b/app/test/e2e/specs/voice-mode.spec.ts
@@ -305,8 +305,7 @@ describe.skip('Voice mode — Human tab capture & error mapping (#1610)', () =>
// ---------------------------------------------------------------------------
// 6.1 — Human tab renders with MicComposer in idle state.
//
- // Checks that the Human tab mounts, shows the "Push to Talk" label in the
- // mascot header, and the MicComposer idle button (aria-label="Start recording"
+ // Checks that the Human tab mounts the MicComposer idle button (aria-label="Start recording"
// / visible label "Tap and speak") is present.
// ---------------------------------------------------------------------------
it('6.1 — Human tab renders with MicComposer in idle state', async () => {
@@ -318,17 +317,6 @@ describe.skip('Voice mode — Human tab capture & error mapping (#1610)', () =>
await navigateToHumanTab();
- // The Human page renders a "Push to Talk" checkbox in the mascot header.
- const hasPushToTalk = await textExists('Push to Talk');
- if (!hasPushToTalk) {
- const tree = await dumpAccessibilityTree();
- console.log(
- '[HumanTabE2E:6.1] Push-to-Talk not found. Accessibility tree:\n',
- tree.slice(0, 4_000)
- );
- }
- expect(hasPushToTalk).toBe(true);
-
// The MicComposer is embedded via the sidebar Conversations with
// composer="mic-cloud". The idle button label is "Tap and speak".
const hasMicLabel = await textExists('Tap and speak');