Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

feat(macos): add actionable paste permission recovery (#2318)

Joshua6578aa89a2c6
diff --git a/src/components/dictation/DictationErrorCard.tsx b/src/components/dictation/DictationErrorCard.tsx
index 50784f02a..72e58af20 100644
--- a/src/components/dictation/DictationErrorCard.tsx
+++ b/src/components/dictation/DictationErrorCard.tsx
@@ -1,5 +1,6 @@
-import { useLayoutEffect, useRef } from "react";
-import { RotateCcw, ScrollText } from "../icons";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { RotateCcw, ScrollText, Settings, Copy, Check, X } from "../icons";
import { ASSISTANT_PANEL_SIZE_LIMITS } from "../../helpers/voiceSurfaceGeometry.mjs";
import { cn } from "../lib/utils";
import type { ToastActionConfig } from "../ui/useToast";
@@ -7,8 +8,10 @@ import type { ToastActionConfig } from "../ui/useToast";
interface DictationErrorCardProps {
title?: string;
description?: string;
+ descriptionHotkey?: string;
+ onDismiss?: () => void;
actions: ToastActionConfig[];
- onAction: (action: ToastActionConfig) => void;
+ onAction: (action: ToastActionConfig) => ReturnType<ToastActionConfig["onClick"]>;
onPreferredHeightChange?: (height: number) => void;
progressDuration?: number;
progressPaused?: boolean;
@@ -18,12 +21,120 @@ interface DictationErrorCardProps {
const ACTION_ICONS = {
retry: RotateCcw,
transcript: ScrollText,
+ settings: Settings,
+ copy: Copy,
};
+function ErrorAction({
+ action,
+ primary,
+ onAction,
+}: {
+ action: ToastActionConfig;
+ primary: boolean;
+ onAction: DictationErrorCardProps["onAction"];
+}) {
+ const [pending, setPending] = useState(false);
+ const [result, setResult] = useState<boolean | undefined>();
+ const pendingRef = useRef(false);
+ const mountedRef = useRef(true);
+ const resetTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ clearTimeout(resetTimer.current);
+ };
+ }, []);
+
+ const handleClick = async () => {
+ if (!action.feedback) {
+ return onAction(action);
+ }
+ if (pendingRef.current) return;
+ pendingRef.current = true;
+ setPending(true);
+ setResult(undefined);
+ clearTimeout(resetTimer.current);
+ let outcome: void | boolean;
+ try {
+ outcome = await onAction(action);
+ } catch {
+ outcome = false;
+ } finally {
+ pendingRef.current = false;
+ if (mountedRef.current) setPending(false);
+ }
+ if (!mountedRef.current || typeof outcome !== "boolean") return;
+ setResult(outcome);
+ resetTimer.current = setTimeout(() => setResult(undefined), 1800);
+ };
+
+ const Icon = result === true ? Check : action.icon ? ACTION_ICONS[action.icon] : null;
+ const label =
+ result === true
+ ? action.feedback?.successLabel
+ : result === false
+ ? action.feedback?.failureLabel
+ : action.label;
+ return (
+ <button
+ type="button"
+ onClick={() => void handleClick()}
+ disabled={pending}
+ className={cn(
+ "inline-flex h-8 min-w-0 shrink-0 items-center justify-center gap-1.5 rounded-full px-4",
+ "text-sm font-medium transition-[background-color,color,transform] duration-150",
+ "focus:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 active:scale-[0.98] disabled:cursor-wait",
+ primary
+ ? "bg-foreground text-background hover:bg-foreground/90"
+ : "bg-foreground/15 text-foreground hover:bg-foreground/20"
+ )}
+ >
+ {Icon && <Icon className="size-3.5 shrink-0" aria-hidden="true" />}
+ <span className="truncate" aria-live={action.feedback ? "polite" : undefined}>
+ {label}
+ </span>
+ </button>
+ );
+}
+
+function ErrorDescription({ text, hotkey }: { text: string; hotkey?: string }) {
+ const start = hotkey ? text.indexOf(hotkey) : -1;
+ if (!hotkey || start < 0) return text;
+ return (
+ <>
+ {text.slice(0, start)}
+ <span
+ dir="ltr"
+ role="img"
+ aria-label={hotkey}
+ className="inline-flex items-center gap-1 whitespace-nowrap align-baseline"
+ >
+ {hotkey.split("+").map((key, index) => (
+ <span
+ key={`${key}-${index}`}
+ aria-hidden="true"
+ className="inline-flex items-center gap-1"
+ >
+ {index > 0 && <span className="text-xs">+</span>}
+ <kbd className="inline-flex h-5 min-w-5 items-center justify-center rounded border border-border bg-surface-raised px-1 font-sans text-[11px] font-medium text-foreground shadow-sm">
+ {key === "Cmd" ? "⌘" : key}
+ </kbd>
+ </span>
+ ))}
+ </span>
+ {text.slice(start + hotkey.length)}
+ </>
+ );
+}
+
/** Shared one/two-action error surface for the floating dictation window. */
export function DictationErrorCard({
title,
description,
+ descriptionHotkey,
+ onDismiss,
actions,
onAction,
onPreferredHeightChange,
@@ -31,6 +142,7 @@ export function DictationErrorCard({
progressPaused = false,
ready = true,
}: DictationErrorCardProps) {
+ const { t } = useTranslation();
const cardRef = useRef<HTMLElement | null>(null);
const lastPreferredHeightRef = useRef(0);
const hasSecondaryAction = actions.length > 1;
@@ -84,38 +196,29 @@ export function DictationErrorCard({
const text = (
<div className="min-w-0 flex-1 break-words px-2 py-1">
- {title && <p className="text-base font-normal leading-snug text-foreground">{title}</p>}
+ {title && (
+ <p
+ className={cn("text-base font-normal leading-snug text-foreground", onDismiss && "pe-7")}
+ >
+ {title}
+ </p>
+ )}
{description && (
<p className="mt-1 whitespace-pre-wrap text-sm leading-snug text-muted-foreground">
- {description}
+ <ErrorDescription text={description} hotkey={descriptionHotkey} />
</p>
)}
</div>
);
- const renderAction = (action: ToastActionConfig, index: number) => {
- const Icon = action.icon ? ACTION_ICONS[action.icon] : null;
- const primary = index === 0;
-
- return (
- <button
- key={`${action.label}-${index}`}
- type="button"
- onClick={() => onAction(action)}
- className={cn(
- "inline-flex h-8 min-w-0 shrink-0 items-center justify-center gap-1.5 rounded-full px-4",
- "text-sm font-medium transition-[background-color,color,transform] duration-150",
- "focus:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 active:scale-[0.98]",
- primary
- ? "bg-foreground text-background hover:bg-foreground/90"
- : "bg-foreground/15 text-foreground hover:bg-foreground/20"
- )}
- >
- {Icon && <Icon className="size-3.5 shrink-0" aria-hidden="true" />}
- <span className="truncate">{action.label}</span>
- </button>
- );
- };
+ const renderAction = (action: ToastActionConfig, index: number) => (
+ <ErrorAction
+ key={`${action.label}-${index}`}
+ action={action}
+ primary={index === 0}
+ onAction={onAction}
+ />
+ );
return (
<section
@@ -152,6 +255,16 @@ export function DictationErrorCard({
/>
</svg>
)}
+ {onDismiss && (
+ <button
+ type="button"
+ onClick={onDismiss}
+ aria-label={t("common.close")}
+ className="absolute end-2 top-2 z-10 flex size-7 items-center justify-center rounded-md text-muted-foreground hover:bg-foreground/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
+ >
+ <X className="size-3.5" aria-hidden="true" />
+ </button>
+ )}
{hasSecondaryAction ? (
<div className="px-2 py-3">
{text}
diff --git a/src/components/ui/Toast.tsx b/src/components/ui/Toast.tsx
index c2a6668f9..5329a15ec 100644
--- a/src/components/ui/Toast.tsx
+++ b/src/components/ui/Toast.tsx
@@ -231,7 +231,13 @@ const ToastViewport: React.FC<{
<Toast
key={toast.id}
{...toast}
- onClose={() => onDismiss(toast.id)}
+ onClose={() => {
+ try {
+ toast.onClose?.();
+ } finally {
+ onDismiss(toast.id);
+ }
+ }}
onPauseTimer={() => onPauseTimer(toast.id)}
onResumeTimer={(remaining) => onResumeTimer(toast.id, remaining)}
/>
@@ -264,6 +270,8 @@ const Toast: React.FC<
> = ({
title,
description,
+ descriptionHotkey,
+ dismissible,
secondaryDescription,
copyCommand,
technicalDetails,
@@ -306,7 +314,7 @@ const Toast: React.FC<
const handleStructuredAction = (structuredAction: ToastActionConfig) => {
if (structuredAction.dismissOnClick !== false) onClose?.();
- void structuredAction.onClick();
+ return structuredAction.onClick();
};
const handleErrorHeightChange = React.useCallback(async (height: number) => {
@@ -357,6 +365,8 @@ const Toast: React.FC<
<DictationErrorCard
title={title}
description={description}
+ descriptionHotkey={descriptionHotkey}
+ onDismiss={dismissible ? onClose : undefined}
actions={actions ?? []}
onAction={handleStructuredAction}
onPreferredHeightChange={handleErrorHeightChange}
diff --git a/src/components/ui/useToast.ts b/src/components/ui/useToast.ts
index 3d3935fe4..966e066cc 100644
--- a/src/components/ui/useToast.ts
+++ b/src/components/ui/useToast.ts
@@ -11,8 +11,9 @@ export interface TechnicalErrorDetailsData {
export interface ToastActionConfig {
label: string;
- icon?: "retry" | "transcript";
- onClick: () => void | Promise<void>;
+ icon?: "retry" | "transcript" | "settings" | "copy";
+ onClick: () => void | boolean | Promise<void | boolean>;
+ feedback?: { successLabel: string; failureLabel: string };
dismissOnClick?: boolean;
}
@@ -20,6 +21,7 @@ export interface ToastProps {
id?: string;
title?: string;
description?: string;
+ descriptionHotkey?: string;
secondaryDescription?: string;
copyCommand?: string;
technicalDetails?: TechnicalErrorDetailsData;
@@ -29,6 +31,7 @@ export interface ToastProps {
variant?: "default" | "destructive" | "success";
duration?: number;
onClose?: () => void;
+ dismissible?: boolean;
}
export interface ToastContextType {
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 9ebf28a9e..a62ee7577 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -4007,6 +4007,19 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
async safePaste(text, options = {}) {
try {
const result = await window.electronAPI.pasteText(text, options);
+ if (
+ result?.success === false &&
+ result.code === "ACCESSIBILITY_PERMISSION_REQUIRED" &&
+ result.clipboardCopied === true
+ ) {
+ this.onError?.({
+ title: "Paste Error",
+ code: result.code,
+ clipboardCopied: true,
+ transcript: text,
+ });
+ return false;
+ }
return result?.pasted === true;
} catch (error) {
const message =
@@ -4014,7 +4027,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
(typeof error?.toString === "function" ? error.toString() : String(error));
this.onError?.({
title: "Paste Error",
- description: `Failed to paste text. Please check accessibility permissions. ${message}`,
+ code: "PASTE_FAILED",
+ // Keep the platform's guidance, without Electron's IPC wrapper around it.
+ description: message.replace(/^Error invoking remote method '[^']+': (?:\w*Error: )?/, ""),
});
return false;
}
diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.js
index 8a365ce7b..7b1a8a342 100644
--- a/src/helpers/clipboard.js
+++ b/src/helpers/clipboard.js
@@ -907,7 +907,9 @@ class ClipboardManager {
if (platform === "darwin") {
method = this.resolveFastPasteBinary() ? "cgevent" : "applescript";
this.safeLog("🔍 Checking accessibility permissions for paste operation...");
- const hasPermissions = await this.checkAccessibilityPermissions(allowClipboardFallback);
+ const hasPermissions = await this.checkAccessibilityPermissions(
+ allowClipboardFallback || options.silentAccessibilityCheck === true
+ );
if (!hasPermissions) {
this.safeLog("⚠️ No accessibility permissions - text copied to clipboard only");
@@ -917,7 +919,10 @@ class ClipboardManager {
}
const errorMsg =
"Accessibility permissions required for automatic pasting. Text has been copied to clipboard - please paste manually with Cmd+V.";
- throw new Error(errorMsg);
+ throw Object.assign(new Error(errorMsg), {
+ code: "ACCESSIBILITY_PERMISSION_REQUIRED",
+ clipboardCopied: true,
+ });
}
this.safeLog("✅ Permissions granted, attempting to paste...");
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index f58c127d7..d39a6694b 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -3064,11 +3064,25 @@ class IPCHandlers {
? winTarget.id
: null;
- const pasteResult = await this.clipboardManager.pasteText(textToPaste, {
- ...options,
- webContents: event.sender,
- targetWindow,
- });
+ let pasteResult;
+ try {
+ pasteResult = await this.clipboardManager.pasteText(textToPaste, {
+ ...options,
+ webContents: event.sender,
+ targetWindow,
+ silentAccessibilityCheck: true,
+ });
+ } catch (error) {
+ if (error?.code !== "ACCESSIBILITY_PERMISSION_REQUIRED" || error.clipboardCopied !== true) {
+ throw error;
+ }
+ return {
+ success: false,
+ pasted: false,
+ code: "ACCESSIBILITY_PERMISSION_REQUIRED",
+ clipboardCopied: true,
+ };
+ }
const pasted = pasteResult?.pasted !== false;
debugLogger.debug("[AutoLearn] Paste completed", {
autoLearnEnabled: this._autoLearnEnabled,
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
index 0837f1cab..536d64e5a 100644
--- a/src/hooks/useAudioRecording.js
+++ b/src/hooks/useAudioRecording.js
@@ -53,6 +53,7 @@ export const useAudioRecording = (toast, options = {}) => {
const pushForceStoppedRef = useRef(false);
const stopLockRef = useRef(false);
const preparationGenerationRef = useRef(0);
+ const dictationErrorGenerationRef = useRef(0);
const wasRecordingRef = useRef(false);
const wasMicUnavailableRef = useRef(false);
const demoKindRef = useRef("dictation");
@@ -74,6 +75,13 @@ export const useAudioRecording = (toast, options = {}) => {
assistantOpenRef,
} = options;
+ useEffect(
+ () => () => {
+ dictationErrorGenerationRef.current += 1;
+ },
+ []
+ );
+
useEffect(() => {
onDemoEventRef.current = onDemoEvent;
}, [onDemoEvent]);
@@ -219,7 +227,10 @@ export const useAudioRecording = (toast, options = {}) => {
? await audioManagerRef.current.startStreamingRecording()
: await audioManagerRef.current.startRecording();
recordingStarted = didStart;
- if (didStart) dismissDictationError?.();
+ if (didStart) {
+ dictationErrorGenerationRef.current += 1;
+ dismissDictationError?.();
+ }
// A stop that landed while the start was still awaiting the mic open was
// dropped (isRecording was still false), leaving a runaway recording
@@ -329,9 +340,97 @@ export const useAudioRecording = (toast, options = {}) => {
audioManagerRef.current?.streamingPartialText
).trim() || fallback.trim();
- const showDictationError = ({ title, description, transcript = "", duration }) => {
+ const showDictationError = ({
+ title,
+ description,
+ transcript = "",
+ duration,
+ code,
+ settingsLaunchFailed = false,
+ }) => {
+ const errorGeneration = ++dictationErrorGenerationRef.current;
const recoverAssistant = Boolean(audioManagerRef.current?.voiceAgentRequested);
onDictationError?.({ recoverAssistant });
+ if (code === "ACCESSIBILITY_PERMISSION_REQUIRED") {
+ let settingsOpening = false;
+ const isCurrent = () => errorGeneration === dictationErrorGenerationRef.current;
+ const actions = [
+ {
+ label: t("hooks.audioRecording.pastePermission.openSettings"),
+ icon: "settings",
+ dismissOnClick: false,
+ onClick: async () => {
+ if (settingsOpening || !isCurrent()) return;
+ settingsOpening = true;
+ let opened = false;
+ try {
+ const result = await window.electronAPI?.openAccessibilitySettings?.();
+ opened = result?.success === true;
+ } catch {
+ // Keep the manual path available if System Settings cannot open.
+ } finally {
+ settingsOpening = false;
+ }
+ // A recording that is starting owns the pill; re-showing the card now would
+ // dismiss that recording's live transcript.
+ if (!opened && isCurrent() && !startLockRef.current) {
+ showDictationError({
+ title,
+ description,
+ transcript,
+ code,
+ settingsLaunchFailed: true,
+ });
+ }
+ },
+ },
+ ];
+ if (transcript.trim()) {
+ actions.push({
+ label: t("hooks.audioRecording.pastePermission.copyToClipboard"),
+ icon: "copy",
+ dismissOnClick: false,
+ feedback: {
+ successLabel: t("common.copied"),
+ failureLabel: t("hooks.audioRecording.pastePermission.copyFailed"),
+ },
+ onClick: async () => {
+ if (!isCurrent()) return;
+ let copied = false;
+ try {
+ const result = await window.electronAPI?.writeClipboard?.(transcript);
+ copied = result?.success === true;
+ } catch {
+ copied = false;
+ }
+ if (isCurrent()) return copied;
+ },
+ });
+ }
+ toast({
+ title,
+ description: [
+ settingsLaunchFailed
+ ? t("hooks.audioRecording.pastePermission.settingsFailed")
+ : description,
+ transcript.trim()
+ ? t("hooks.audioRecording.pastePermission.manualPaste", { shortcut: "Cmd+V" })
+ : "",
+ ]
+ .filter(Boolean)
+ .join(" "),
+ descriptionHotkey: transcript.trim() ? "Cmd+V" : undefined,
+ variant: "destructive",
+ presentation: "dictation-error",
+ duration: 0,
+ dismissible: true,
+ onClose: () => {
+ if (isCurrent()) dictationErrorGenerationRef.current += 1;
+ },
+ actions,
+ });
+ return;
+ }
const recoverableTranscript = getRecoverableTranscript(transcript);
const actions = [
{
@@ -435,6 +534,8 @@ export const useAudioRecording = (toast, options = {}) => {
title,
description,
duration: error?.code === "AUTH_EXPIRED" ? 8000 : undefined,
+ code: error?.code,
+ transcript: error?.transcript,
});
}
if (getSettings().pauseMediaOnDictation) {
@@ -483,6 +584,7 @@ export const useAudioRecording = (toast, options = {}) => {
},
onTranscriptionComplete: async (result) => {
if (result.success) {
+ dictationErrorGenerationRef.current += 1;
dismissDictationError?.();
const transcribedText = result.text?.trim();
diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.json
index e38416876..a73c58c89 100644
--- a/src/locales/ar/translation.json
+++ b/src/locales/ar/translation.json
@@ -69,6 +69,18 @@
"title": "لم يتم لصق النص المفرَّغ",
"description": "توقف الإملاء بينما كان مفتاح الاختصار لا يزال مضغوطًا، لذلك لم يتم لصق النص. نصك المفرَّغ موجود في الحافظة.",
"descriptionClipboardFailed": "توقف الإملاء بينما كان مفتاح الاختصار لا يزال مضغوطًا، لذلك لم يتم لصق النص، ولم يمكن نسخه إلى الحافظة أيضًا."
+ },
+ "pastePermission": {
+ "title": "السماح باللصق التلقائي",
+ "description": "فعّل OpenWhispr في إعدادات النظام ← الخصوصية والأمن ← تسهيلات الاستخدام.",
+ "settingsFailed": "تعذّر فتح الإعدادات. افتح إعدادات النظام ← الخصوصية والأمن ← تسهيلات الاستخدام وفعّل OpenWhispr.",
+ "manualPaste": "انسخ النص أدناه، ثم اضغط على {{shortcut}} للصقه.",
+ "openSettings": "فتح الإعدادات",
+ "copyToClipboard": "نسخ إلى الحافظة",
+ "copyFailed": "تعذّر النسخ"
+ },
+ "pasteFailed": {
+ "title": "تعذّر اللصق تلقائيًا"
}
},
"clipboard": {
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index be6a7b5ee..889d0cb0c 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -940,6 +940,18 @@
"unavailable": "OpenWhispr konnte den ausgewählten Text nicht sicher lesen. Prüfe die Bedienungshilfen oder Eingabeautomatisierung.",
"tooLarge": "Die Auswahl ist zu groß. Wähle höchstens 6.000 Zeichen aus.",
"reasoningFailed": "Die KI konnte die Auswahlbearbeitung nicht abschließen. Dein ursprünglicher Text wurde nicht geändert."
+ },
+ "pastePermission": {
+ "title": "Automatisches Einfügen erlauben",
+ "description": "Aktiviere OpenWhispr unter Systemeinstellungen → Datenschutz & Sicherheit → Bedienungshilfen.",
+ "settingsFailed": "Die Einstellungen konnten nicht geöffnet werden. Öffne Systemeinstellungen → Datenschutz & Sicherheit → Bedienungshilfen und aktiviere OpenWhispr.",
+ "manualPaste": "Kopiere deinen Text unten und drücke dann {{shortcut}}, um ihn einzufügen.",
+ "openSettings": "Einstellungen öffnen",
+ "copyToClipboard": "Text kopieren",
+ "copyFailed": "Kopieren fehlgeschlagen"
+ },
+ "pasteFailed": {
+ "title": "Automatisches Einfügen fehlgeschlagen"
}
},
"clipboard": {
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 744f76607..71452abd2 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -940,6 +940,18 @@
"unavailable": "OpenWhispr could not safely read the selected text. Check accessibility or input automation permissions and try again.",
"tooLarge": "The selection is too large to edit safely. Select 6,000 characters or fewer.",
"reasoningFailed": "The AI could not complete the selection edit. Your original text was not changed."
+ },
+ "pastePermission": {
+ "title": "Allow automatic pasting",
+ "description": "Enable OpenWhispr in System Settings → Privacy & Security → Accessibility.",
+ "settingsFailed": "Couldn't open Settings. Open System Settings → Privacy & Security → Accessibility and enable OpenWhispr.",
+ "manualPaste": "Copy your text below, then press {{shortcut}} to paste it.",
+ "openSettings": "Open Settings",
+ "copyToClipboard": "Copy to clipboard",
+ "copyFailed": "Copy failed"
+ },
+ "pasteFailed": {
+ "title": "Couldn't paste automatically"
}
},
"clipboard": {
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 1cf3638e7..a543f8061 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -940,6 +940,18 @@
"unavailable": "OpenWhispr no pudo leer de forma segura el texto seleccionado. Revisa los permisos de accesibilidad o automatización.",
"tooLarge": "La selección es demasiado grande. Selecciona 6.000 caracteres o menos.",
"reasoningFailed": "La IA no pudo completar la edición. El texto original no se modificó."
+ },
+ "pastePermission": {
+ "title": "Permitir el pegado automático",
+ "description": "Activa OpenWhispr en Ajustes del Sistema → Privacidad y seguridad → Accesibilidad.",
+ "settingsFailed": "No se pudieron abrir los ajustes. Abre Ajustes del Sistema → Privacidad y seguridad → Accesibilidad y activa OpenWhispr.",
+ "manualPaste": "Copia tu texto abajo y pulsa {{shortcut}} para pegarlo.",
+ "openSettings": "Abrir ajustes",
+ "copyToClipboard": "Copiar al portapapeles",
+ "copyFailed": "Error al copiar"
+ },
+ "pasteFailed": {
+ "title": "No se pudo pegar automáticamente"
}
},
"clipboard": {
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 5bb9ede62..b1ffcbebe 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -940,6 +940,18 @@
"unavailable": "OpenWhispr n’a pas pu lire la sélection en toute sécurité. Vérifiez les autorisations d’accessibilité ou d’automatisation.",
"tooLarge": "La sélection est trop grande. Sélectionnez au maximum 6 000 caractères.",
"reasoningFailed": "L’IA n’a pas pu terminer la modification. Le texte d’origine n’a pas été modifié."
+ },
+ "pastePermission": {
+ "title": "Autoriser le collage automatique",
+ "description": "Activez OpenWhispr dans Réglages Système → Confidentialité et sécurité → Accessibilité.",
+ "settingsFailed": "Impossible d’ouvrir les réglages. Ouvrez Réglages Système → Confidentialité et sécurité → Accessibilité et activez OpenWhispr.",
+ "manualPaste": "Copiez votre texte ci-dessous, puis appuyez sur {{shortcut}} pour le coller.",
+ "openSettings": "Ouvrir les réglages",
+ "copyToClipboard": "Copier le texte",
+ "copyFailed": "Échec de la copie"
+ },
+ "pasteFailed": {
+ "title": "Collage automatique impossible"
}
},
"clipboard": {
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 97859077f..711887afb 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -940,6 +940,18 @@
"unavailable": "OpenWhispr non ha potuto leggere in sicurezza il testo selezionato. Controlla i permessi di accessibilità o automazione.",
"tooLarge": "La selezione è troppo grande. Seleziona al massimo 6.000 caratteri.",
"reasoningFailed": "L’IA non ha potuto completare la modifica. Il testo originale non è stato cambiato."
+ },
+ "pastePermission": {
+ "title": "Consenti di incollare automaticamente",
+ "description": "Abilita OpenWhispr in Impostazioni di Sistema → Privacy e sicurezza → Accessibilità.",
+ "settingsFailed": "Impossibile aprire le impostazioni. Apri Impostazioni di Sistema → Privacy e sicurezza → Accessibilità e abilita OpenWhispr.",
+ "manualPaste": "Copia il testo qui sotto, poi premi {{shortcut}} per incollarlo.",
+ "openSettings": "Apri impostazioni",
+ "copyToClipboard": "Copia negli appunti",
+ "copyFailed": "Copia non riuscita"
+ },
+ "pasteFailed": {
+ "title": "Impossibile incollare automaticamente"
}
},
"clipboard": {
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 56d0a6c09..75ed3c7b6 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -940,6 +940,18 @@
"unavailable": "OpenWhispr は選択したテキストを安全に読み取れませんでした。アクセシビリティまたは入力自動化の権限を確認してください。",
"tooLarge": "選択範囲が大きすぎます。6,000文字以内を選択してください。",
"reasoningFailed": "AI は選択範囲の編集を完了できませんでした。元のテキストは変更されていません。"
+ },
+ "pastePermission": {
+ "title": "自動貼り付けを許可",
+ "description": "システム設定 → プライバシーとセキュリティ → アクセシビリティでOpenWhisprを有効にしてください。",
+ "settingsFailed": "設定を開けませんでした。システム設定 → プライバシーとセキュリティ → アクセシビリティを開き、OpenWhisprを有効にしてください。",
+ "manualPaste": "下のボタンでテキストをコピーし、{{shortcut}}を押して貼り付けてください。",
+ "openSettings": "設定を開く",
+ "copyToClipboard": "テキストをコピー",
+ "copyFailed": "コピーに失敗しました"
+ },
+ "pasteFailed": {
+ "title": "自動貼り付けに失敗しました"
}
},
"clipboard": {
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index ed7acef46..f6ae5444e 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -919,6 +919,18 @@
"unavailable": "O OpenWhispr não conseguiu ler o texto selecionado com segurança. Verifique as permissões de acessibilidade ou automação.",
"tooLarge": "A seleção é muito grande. Selecione no máximo 6.000 caracteres.",
"reasoningFailed": "A IA não conseguiu concluir a edição. O texto original não foi alterado."
+ },
+ "pastePermission": {
+ "title": "Permitir colagem automática",
+ "description": "Ative o OpenWhispr em Ajustes do Sistema → Privacidade e Segurança → Acessibilidade.",
+ "settingsFailed": "Não foi possível abrir os ajustes. Abra Ajustes do Sistema → Privacidade e Segurança → Acessibilidade e ative o OpenWhispr.",
+ "manualPaste": "Copie o texto abaixo e pressione {{shortcut}} para colá-lo.",
+ "openSettings": "Abrir ajustes",
+ "copyToClipboard": "Copiar texto",
+ "copyFailed": "Falha ao copiar"
+ },
+ "pasteFailed": {
+ "title": "Não foi possível colar automaticamente"
}
},
"clipboard": {
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 8c9370f06..5249c88e6 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -940,6 +940,18 @@
"unavailable": "OpenWhispr не смог безопасно прочитать выделенный текст. Проверьте разрешения специальных возможностей или автоматизации ввода.",
"tooLarge": "Выделение слишком большое. Выберите не более 6 000 символов.",
"reasoningFailed": "ИИ не смог завершить изменение. Исходный текст не был изменён."
+ },
+ "pastePermission": {
+ "title": "Разрешите автоматическую вставку",
+ "description": "Включите OpenWhispr в Системных настройках → Конфиденциальность и безопасность → Универсальный доступ.",
+ "settingsFailed": "Не удалось открыть настройки. Откройте Системные настройки → Конфиденциальность и безопасность → Универсальный доступ и включите OpenWhispr.",
+ "manualPaste": "Скопируйте текст ниже, затем нажмите {{shortcut}}, чтобы вставить его.",
+ "openSettings": "Открыть настройки",
+ "copyToClipboard": "Скопировать текст",
+ "copyFailed": "Не удалось скопировать"
+ },
+ "pasteFailed": {
+ "title": "Не удалось вставить автоматически"
}
},
"clipboard": {
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index a768c63ec..b0829fd4f 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -940,6 +940,18 @@
"unavailable": "OpenWhispr 无法安全读取选中的文本。请检查辅助功能或输入自动化权限。",
"tooLarge": "选中的内容过长。请选择不超过 6,000 个字符。",
"reasoningFailed": "AI 无法完成选中文本编辑。原始文本未被更改。"
+ },
+ "pastePermission": {
+ "title": "允许自动粘贴",
+ "description": "请在系统设置 → 隐私与安全性 → 辅助功能中启用 OpenWhispr。",
+ "settingsFailed": "无法打开设置。请打开系统设置 → 隐私与安全性 → 辅助功能,并启用 OpenWhispr。",
+ "manualPaste": "点击下方按钮复制文本,然后按 {{shortcut}} 粘贴。",
+ "openSettings": "打开设置",
+ "copyToClipboard": "复制到剪贴板",
+ "copyFailed": "复制失败"
+ },
+ "pasteFailed": {
+ "title": "无法自动粘贴"
}
},
"clipboard": {
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 5c540e299..05fef41f4 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -940,6 +940,18 @@
"unavailable": "OpenWhispr 無法安全讀取選取的文字。請檢查輔助使用或輸入自動化權限。",
"tooLarge": "選取內容過長。請選取不超過 6,000 個字元。",
"reasoningFailed": "AI 無法完成選取文字編輯。原始文字未被變更。"
+ },
+ "pastePermission": {
+ "title": "允許自動貼上",
+ "description": "請在系統設定 → 隱私權與安全性 → 輔助使用中啟用 OpenWhispr。",
+ "settingsFailed": "無法開啟設定。請開啟系統設定 → 隱私權與安全性 → 輔助使用,並啟用 OpenWhispr。",
+ "manualPaste": "點擊下方按鈕複製文字,然後按 {{shortcut}} 貼上。",
+ "openSettings": "開啟設定",
+ "copyToClipboard": "複製到剪貼板",
+ "copyFailed": "複製失敗"
+ },
+ "pasteFailed": {
+ "title": "無法自動貼上"
}
},
"clipboard": {
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 9c74aef6a..a82f859d1 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1104,7 +1104,15 @@ declare global {
restoreClipboard?: boolean;
allowClipboardFallback?: boolean;
}
- ) => Promise<{ success: true; pasted: boolean }>;
+ ) => Promise<
+ | { success: true; pasted: boolean }
+ | {
+ success: false;
+ pasted: false;
+ code: "ACCESSIBILITY_PERMISSION_REQUIRED";
+ clipboardCopied: true;
+ }
+ >;
captureSelectedText?: (options?: { probeEditable?: boolean }) => Promise<
| {
status: "selected";
diff --git a/src/utils/recordingErrors.ts b/src/utils/recordingErrors.ts
index f19e2a613..b71ca9118 100644
--- a/src/utils/recordingErrors.ts
+++ b/src/utils/recordingErrors.ts
@@ -10,6 +10,10 @@ type RecordingError = {
};
export function getRecordingErrorTitle(error: RecordingError, t: TFunction): string {
+ if (error.code === "ACCESSIBILITY_PERMISSION_REQUIRED") {
+ return t("hooks.audioRecording.pastePermission.title");
+ }
+ if (error.code === "PASTE_FAILED") return t("hooks.audioRecording.pasteFailed.title");
if (error.code?.startsWith("SELECTION_EDIT_")) {
return t("hooks.audioRecording.selectionEditing.notAppliedTitle");
}
@@ -32,6 +36,9 @@ export function getRecordingErrorTitle(error: RecordingError, t: TFunction): str
}
export function getRecordingErrorDescription(error: RecordingError, t: TFunction): string {
+ if (error.code === "ACCESSIBILITY_PERMISSION_REQUIRED") {
+ return t("hooks.audioRecording.pastePermission.description");
+ }
if (error.messageKey) return t(error.messageKey);
return error.description ?? "";
}
diff --git a/test/helpers/assistantPanel.test.js b/test/helpers/assistantPanel.test.js
index ece5dff3b..15c0ea486 100644
--- a/test/helpers/assistantPanel.test.js
+++ b/test/helpers/assistantPanel.test.js
@@ -8,229 +8,7 @@ const { createRendererServer, installBrowserGlobals } = require("../lib/renderer
const noop = () => {};
-function installInteractiveDom(t) {
- const originalDocument = globalThis.document;
- const originalNode = globalThis.Node;
- const originalElement = globalThis.Element;
- const originalHTMLElement = globalThis.HTMLElement;
- const originalHTMLIFrameElement = globalThis.HTMLIFrameElement;
- const originalActEnvironment = globalThis.IS_REACT_ACT_ENVIRONMENT;
- const originalRequestAnimationFrame = globalThis.requestAnimationFrame;
- const originalCancelAnimationFrame = globalThis.cancelAnimationFrame;
-
- class FakeNode {
- constructor(nodeType, nodeName, ownerDocument) {
- this.nodeType = nodeType;
- this.nodeName = nodeName;
- this.ownerDocument = ownerDocument;
- this.parentNode = null;
- this.childNodes = [];
- }
-
- appendChild(child) {
- return this.insertBefore(child, null);
- }
-
- insertBefore(child, before) {
- if (child.parentNode) child.parentNode.removeChild(child);
- const index = before === null ? this.childNodes.length : this.childNodes.indexOf(before);
- this.childNodes.splice(index < 0 ? this.childNodes.length : index, 0, child);
- child.parentNode = this;
- return child;
- }
-
- removeChild(child) {
- const index = this.childNodes.indexOf(child);
- if (index >= 0) this.childNodes.splice(index, 1);
- child.parentNode = null;
- return child;
- }
-
- contains(candidate) {
- for (let current = candidate; current; current = current.parentNode) {
- if (current === this) return true;
- }
- return false;
- }
-
- get firstChild() {
- return this.childNodes[0] ?? null;
- }
-
- get lastChild() {
- return this.childNodes.at(-1) ?? null;
- }
-
- get nextSibling() {
- if (!this.parentNode) return null;
- const index = this.parentNode.childNodes.indexOf(this);
- return this.parentNode.childNodes[index + 1] ?? null;
- }
-
- get textContent() {
- return this.childNodes.map((child) => child.textContent).join("");
- }
-
- set textContent(value) {
- for (const child of this.childNodes) child.parentNode = null;
- this.childNodes = [];
- if (value !== "") this.appendChild(this.ownerDocument.createTextNode(String(value)));
- }
- }
-
- class Element extends FakeNode {}
- class HTMLElement extends Element {}
- class HTMLIFrameElement extends HTMLElement {}
-
- class FakeText extends FakeNode {
- constructor(value, ownerDocument) {
- super(3, "#text", ownerDocument);
- this.nodeValue = value;
- }
-
- get textContent() {
- return this.nodeValue;
- }
-
- set textContent(value) {
- this.nodeValue = String(value);
- }
- }
-
- class FakeElement extends HTMLElement {
- constructor(tagName, ownerDocument, namespaceURI = "http://www.w3.org/1999/xhtml") {
- super(1, tagName.toUpperCase(), ownerDocument);
- this.tagName = tagName.toUpperCase();
- this.namespaceURI = namespaceURI;
- this.attributes = new Map();
- this.listeners = new Map();
- this.style = {
- setProperty: (name, value) => {
- this.style[name] = value;
- },
- removeProperty: (name) => {
- delete this.style[name];
- },
- };
- }
-
- setAttribute(name, value) {
- this.attributes.set(name, String(value));
- }
-
- getAttribute(name) {
- return this.attributes.get(name) ?? null;
- }
-
- removeAttribute(name) {
- this.attributes.delete(name);
- }
-
- addEventListener(type, listener) {
- const listeners = this.listeners.get(type) ?? new Set();
- listeners.add(listener);
- this.listeners.set(type, listeners);
- }
-
- removeEventListener(type, listener) {
- this.listeners.get(type)?.delete(listener);
- }
-
- dispatchEvent(event) {
- if (!event.target) event.target = this;
- for (let current = this; current; current = event.bubbles ? current.parentNode : null) {
- event.currentTarget = current;
- for (const listener of current.listeners?.get(event.type) ?? []) listener(event);
- if (event.cancelBubble) break;
- }
- return !event.defaultPrevented;
- }
-
- focus() {
- this.ownerDocument.activeElement = this;
- }
- }
-
- const documentListeners = new Map();
- const document = {
- nodeType: 9,
- nodeName: "#document",
- activeElement: null,
- createElement: (tagName) => new FakeElement(tagName, document),
- createElementNS: (namespaceURI, tagName) => new FakeElement(tagName, document, namespaceURI),
- createTextNode: (value) => new FakeText(String(value), document),
- createComment: (value) => {
- const comment = new FakeNode(8, "#comment", document);
- comment.nodeValue = String(value);
- return comment;
- },
- addEventListener(type, listener) {
- const listeners = documentListeners.get(type) ?? new Set();
- listeners.add(listener);
- documentListeners.set(type, listeners);
- },
- removeEventListener(type, listener) {
- documentListeners.get(type)?.delete(listener);
- },
- };
- const container = new FakeElement("div", document);
- document.documentElement = container;
- document.body = container;
- document.defaultView = globalThis.window;
- Object.assign(globalThis.window, {
- Node: FakeNode,
- Element,
- HTMLElement,
- HTMLIFrameElement,
- document,
- getSelection: () => ({
- isCollapsed: true,
- rangeCount: 0,
- removeAllRanges() {},
- }),
- });
- globalThis.document = document;
- globalThis.Node = FakeNode;
- globalThis.Element = Element;
- globalThis.HTMLElement = HTMLElement;
- globalThis.HTMLIFrameElement = HTMLIFrameElement;
- globalThis.IS_REACT_ACT_ENVIRONMENT = true;
- globalThis.requestAnimationFrame = (callback) => {
- callback();
- return 1;
- };
- globalThis.cancelAnimationFrame = noop;
-
- t.after(() => {
- if (originalDocument === undefined) delete globalThis.document;
- else globalThis.document = originalDocument;
- if (originalNode === undefined) delete globalThis.Node;
- else globalThis.Node = originalNode;
- if (originalElement === undefined) delete globalThis.Element;
- else globalThis.Element = originalElement;
- if (originalHTMLElement === undefined) delete globalThis.HTMLElement;
- else globalThis.HTMLElement = originalHTMLElement;
- if (originalHTMLIFrameElement === undefined) delete globalThis.HTMLIFrameElement;
- else globalThis.HTMLIFrameElement = originalHTMLIFrameElement;
- if (originalActEnvironment === undefined) delete globalThis.IS_REACT_ACT_ENVIRONMENT;
- else globalThis.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment;
- if (originalRequestAnimationFrame === undefined) delete globalThis.requestAnimationFrame;
- else globalThis.requestAnimationFrame = originalRequestAnimationFrame;
- if (originalCancelAnimationFrame === undefined) delete globalThis.cancelAnimationFrame;
- else globalThis.cancelAnimationFrame = originalCancelAnimationFrame;
- });
-
- return container;
-}
-
-function findElement(root, predicate) {
- if (root.nodeType === 1 && predicate(root)) return root;
- for (const child of root.childNodes) {
- const match = findElement(child, predicate);
- if (match) return match;
- }
- return null;
-}
+const { installInteractiveDom, findElement } = require("../lib/interactiveDom");
async function renderAssistantPanel(
t,
@@ -891,13 +669,23 @@ test("a follow-up into an open panel strips caret delivery and stays panel-first
assistant.openRef.current = true;
await React.act(async () => {
- assistant.handleCommand({ text: "draft a reply", attachment: null, selectedContext: null, delivery });
+ assistant.handleCommand({
+ text: "draft a reply",
+ attachment: null,
+ selectedContext: null,
+ delivery,
+ });
});
assert.equal(assistant.pendingCommand.delivery, null);
assistant.openRef.current = false;
await React.act(async () => {
- assistant.handleCommand({ text: "draft a reply", attachment: null, selectedContext: null, delivery });
+ assistant.handleCommand({
+ text: "draft a reply",
+ attachment: null,
+ selectedContext: null,
+ delivery,
+ });
});
assert.deepEqual(assistant.pendingCommand.delivery, delivery);
});
diff --git a/test/helpers/audioManagerPasteRecovery.test.js b/test/helpers/audioManagerPasteRecovery.test.js
new file mode 100644
index 000000000..6b63a8cf3
--- /dev/null
+++ b/test/helpers/audioManagerPasteRecovery.test.js
@@ -0,0 +1,70 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { loadAudioManager } = require("./harness/audioManager");
+
+test("safePaste preserves exact final text only for confirmed permission recovery", async (t) => {
+ const { window, createManager } = await loadAudioManager(t, {
+ cachePrefix: "openwhispr-paste-recovery-",
+ settingsKey: "__pasteRecoverySettings",
+ });
+ const errors = [];
+ const manager = createManager({
+ onError: (error) => errors.push(error),
+ streamingFinalText: "raw text",
+ });
+ const text = " Final translated text\nwith spacing ";
+ const options = { restoreClipboard: false };
+ const calls = [];
+ window.electronAPI.pasteText = async (...args) => {
+ calls.push(args);
+ return {
+ success: false,
+ pasted: false,
+ code: "ACCESSIBILITY_PERMISSION_REQUIRED",
+ clipboardCopied: true,
+ };
+ };
+ assert.equal(await manager.safePaste(text, options), false);
+ assert.deepEqual(calls, [[text, options]]);
+ assert.deepEqual(errors, [
+ {
+ title: "Paste Error",
+ code: "ACCESSIBILITY_PERMISSION_REQUIRED",
+ clipboardCopied: true,
+ transcript: text,
+ },
+ ]);
+
+ for (const pasted of [true, false]) {
+ errors.length = 0;
+ window.electronAPI.pasteText = async () => ({ success: true, pasted });
+ assert.equal(await manager.safePaste(text), pasted);
+ assert.deepEqual(errors, []);
+ }
+ window.electronAPI.pasteText = async () => {
+ throw new Error("accessibility in an unrelated error");
+ };
+ assert.equal(await manager.safePaste(text), false);
+ assert.deepEqual(errors, [
+ {
+ title: "Paste Error",
+ code: "PASTE_FAILED",
+ description: "accessibility in an unrelated error",
+ },
+ ]);
+
+ errors.length = 0;
+ window.electronAPI.pasteText = async () => {
+ throw new Error(
+ "Error invoking remote method 'paste-text': Error: Please install xdotool or paste manually with Ctrl+V."
+ );
+ };
+ assert.equal(await manager.safePaste(text), false);
+ assert.equal(errors[0].description, "Please install xdotool or paste manually with Ctrl+V.");
+
+ window.electronAPI.pasteText = async () => {
+ throw new Error("Error invoking remote method 'paste-text': TypeError: bad input");
+ };
+ await manager.safePaste(text);
+ assert.equal(errors[1].description, "bad input");
+});
diff --git a/test/helpers/clipboardRestore.test.js b/test/helpers/clipboardRestore.test.js
index 512136ae9..d82a17648 100644
--- a/test/helpers/clipboardRestore.test.js
+++ b/test/helpers/clipboardRestore.test.js
@@ -63,7 +63,7 @@ const clipboardModulePath = require.resolve("../../src/helpers/clipboard");
const originalLoad = Module._load;
-function loadClipboardManager({ spawn } = {}) {
+function loadClipboardManager({ spawn, accessibility = true } = {}) {
delete require.cache[clipboardModulePath];
Module._load = function loadWithMocks(request, parent, isMain) {
@@ -71,7 +71,7 @@ function loadClipboardManager({ spawn } = {}) {
return {
clipboard: fakeClipboard,
systemPreferences: {
- isTrustedAccessibilityClient: () => true,
+ isTrustedAccessibilityClient: () => accessibility,
},
};
}
@@ -842,3 +842,60 @@ test("terminal detection matches window classes and macOS app names alike", () =
assert.equal(manager.isLinuxTerminalWindowClass("org.mozilla.firefox"), false);
assert.equal(manager.isLinuxTerminalWindowClass(null), false);
});
+
+for (const silent of [true, false]) {
+ test(`macOS denial preserves text and owns the dialog only when silent=${silent}`, async (t) => {
+ const platform = Object.getOwnPropertyDescriptor(process, "platform");
+ Object.defineProperty(process, "platform", { value: "darwin" });
+ t.after(() => Object.defineProperty(process, "platform", platform));
+ const Manager = loadClipboardManager({ accessibility: false });
+ const manager = new Manager();
+ manager.resolveFastPasteBinary = () => null;
+ let dialogs = 0;
+ manager.showAccessibilityDialog = () => {
+ dialogs += 1;
+ };
+ resetClipboard({ text: "previous" });
+ await assert.rejects(
+ manager._pasteText(" final text\n", { silentAccessibilityCheck: silent }),
+ (error) => {
+ assert.equal(error.code, "ACCESSIBILITY_PERMISSION_REQUIRED");
+ assert.equal(error.clipboardCopied, true);
+ return true;
+ }
+ );
+ assert.equal(fakeClipboard.text, " final text\n");
+ assert.equal(dialogs, silent ? 0 : 1);
+ });
+}
+
+test("intentional macOS clipboard fallback stays silent and does not throw", async (t) => {
+ const platform = Object.getOwnPropertyDescriptor(process, "platform");
+ Object.defineProperty(process, "platform", { value: "darwin" });
+ t.after(() => Object.defineProperty(process, "platform", platform));
+ const Manager = loadClipboardManager({ accessibility: false });
+ const manager = new Manager();
+ manager.resolveFastPasteBinary = () => null;
+ manager.showAccessibilityDialog = () => assert.fail("unexpected dialog");
+ resetClipboard();
+ const result = await manager._pasteText("manual text", { allowClipboardFallback: true });
+ assert.equal(result.pasted, false);
+ assert.equal(fakeClipboard.text, "manual text");
+});
+
+test("clipboard write failure is never classified as an Accessibility denial", async (t) => {
+ const write = fakeClipboard.writeText;
+ fakeClipboard.writeText = () => {
+ throw new Error("clipboard unavailable");
+ };
+ t.after(() => {
+ fakeClipboard.writeText = write;
+ });
+ const manager = new ClipboardManager();
+ await assert.rejects(manager._pasteText("final text"), (error) => {
+ assert.equal(error.message, "clipboard unavailable");
+ assert.equal(error.code, undefined);
+ assert.equal(error.clipboardCopied, undefined);
+ return true;
+ });
+});
diff --git a/test/helpers/ipcPasteOutcome.test.js b/test/helpers/ipcPasteOutcome.test.js
index 88494bf43..29074b42c 100644
--- a/test/helpers/ipcPasteOutcome.test.js
+++ b/test/helpers/ipcPasteOutcome.test.js
@@ -156,3 +156,86 @@ test("paste-text does not schedule AutoLearn monitoring after a clipboard-only f
assert.deepEqual(result, { success: true, pasted: false });
assert.deepEqual(monitored, []);
});
+
+test("paste-text serializes only a copied Accessibility denial and skips AutoLearn", async (t) => {
+ const originalTimeout = global.setTimeout;
+ t.after(() => {
+ global.setTimeout = originalTimeout;
+ target._autoLearnEnabled = false;
+ target.textEditMonitor = null;
+ });
+ let scheduled = 0;
+ global.setTimeout = () => {
+ scheduled += 1;
+ return 1;
+ };
+ target._autoLearnEnabled = true;
+ target.textEditMonitor = {
+ activateTargetPid: async () => true,
+ startMonitoring: () => assert.fail("must not monitor denial"),
+ };
+ target.windowManager = { isOnboardingDemoActive: () => false };
+ target.clipboardManager = {
+ pasteText: async (_text, options) => {
+ assert.equal(options.silentAccessibilityCheck, true);
+ throw Object.assign(new Error("internal detail"), {
+ code: "ACCESSIBILITY_PERMISSION_REQUIRED",
+ clipboardCopied: true,
+ });
+ },
+ };
+ assert.deepEqual(
+ await handlers.get("paste-text")({ sender: {} }, "final text", {
+ silentAccessibilityCheck: false,
+ }),
+ {
+ success: false,
+ pasted: false,
+ code: "ACCESSIBILITY_PERMISSION_REQUIRED",
+ clipboardCopied: true,
+ }
+ );
+ assert.equal(scheduled, 0);
+});
+
+test("paste-text preserves rejection for generic errors and unconfirmed clipboard writes", async () => {
+ target.windowManager = { isOnboardingDemoActive: () => false };
+ for (const error of [
+ new Error("accessibility mentioned in an unrelated failure"),
+ Object.assign(new Error("not copied"), { code: "ACCESSIBILITY_PERMISSION_REQUIRED" }),
+ ]) {
+ target.clipboardManager = {
+ pasteText: async () => {
+ throw error;
+ },
+ };
+ await assert.rejects(
+ handlers.get("paste-text")({ sender: {} }, "text"),
+ (thrown) => thrown === error
+ );
+ }
+});
+
+test("Accessibility settings opens the macOS system pane and reports launch failure", async (t) => {
+ const platform = Object.getOwnPropertyDescriptor(process, "platform");
+ Object.defineProperty(process, "platform", { value: "darwin" });
+ t.after(() => {
+ Object.defineProperty(process, "platform", platform);
+ delete electronStub.shell.openExternal;
+ });
+ const urls = [];
+ electronStub.shell.openExternal = async (url) => {
+ urls.push(url);
+ };
+ assert.deepEqual(await handlers.get("open-accessibility-settings")(), { success: true });
+ assert.deepEqual(urls, [
+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",
+ ]);
+ electronStub.shell.openExternal = async () => {
+ throw new Error("launch failed");
+ };
+ assert.deepEqual(await handlers.get("open-accessibility-settings")(), {
+ success: false,
+ error: "launch failed",
+ });
+});
diff --git a/test/helpers/pastePermissionToast.test.js b/test/helpers/pastePermissionToast.test.js
new file mode 100644
index 000000000..841f66f5b
--- /dev/null
+++ b/test/helpers/pastePermissionToast.test.js
@@ -0,0 +1,193 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRoot } = require("react-dom/client");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+const { installInteractiveDom, findElement } = require("../lib/interactiveDom");
+const translations = require("../../src/locales/en/translation.json");
+const click = (button) => button.dispatchEvent({ type: "click", bubbles: true, button: 0 });
+
+async function setup(t, mockModules = {}) {
+ let root;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ delete globalThis.__recoveryCardProps;
+ });
+ installBrowserGlobals(t, { window: { location: { search: "", pathname: "/" } } });
+ const container = installInteractiveDom(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-recovery-card-",
+ mockModules,
+ });
+ const [{ default: i18n }, { initReactI18next }] = await Promise.all([
+ vite.ssrLoadModule("i18next"),
+ vite.ssrLoadModule("react-i18next"),
+ ]);
+ await i18n.use(initReactI18next).init({
+ lng: "en",
+ resources: { en: { translation: translations } },
+ interpolation: { escapeValue: false },
+ });
+ root = createRoot(container);
+ return {
+ container,
+ vite,
+ render: async (element) => React.act(async () => root.render(element)),
+ unmount: async () => {
+ await React.act(async () => root.unmount());
+ root = null;
+ },
+ };
+}
+
+test("permission toasts persist through actions and compose close with provider dismissal", async (t) => {
+ const h = await setup(t, {
+ "/dictation/DictationErrorCard": `export function DictationErrorCard(props) { globalThis.__recoveryCardProps=props; return null; }`,
+ });
+ const { ToastProvider } = await h.vite.ssrLoadModule("/components/ui/Toast.tsx");
+ const { useToast } = await h.vite.ssrLoadModule("/components/ui/useToast.ts");
+ let context;
+ function Probe() {
+ context = useToast();
+ return null;
+ }
+ await h.render(React.createElement(ToastProvider, null, React.createElement(Probe)));
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const events = [];
+ for (const title of ["Permission needed", "Settings could not open"]) {
+ await React.act(async () =>
+ context.toast({
+ title,
+ presentation: "dictation-error",
+ duration: 0,
+ dismissible: true,
+ onClose: () => events.push("closed"),
+ actions: [
+ {
+ label: "Settings",
+ dismissOnClick: false,
+ onClick: async () => events.push("settings"),
+ },
+ { label: "Copy", dismissOnClick: false, onClick: async () => true },
+ ],
+ })
+ );
+ let card = globalThis.__recoveryCardProps;
+ assert.equal(card.progressDuration, 0);
+ await React.act(async () => card.onAction(card.actions[0]));
+ assert.equal(await card.onAction(card.actions[1]), true, "Toast forwards Copy result");
+ await React.act(async () => t.mock.timers.tick(60001));
+ assert.equal(context.toastCount, 1);
+ card = globalThis.__recoveryCardProps;
+ assert.equal(typeof card.onDismiss, "function");
+ await React.act(async () => card.onDismiss());
+ await React.act(async () => t.mock.timers.tick(201));
+ assert.equal(context.toastCount, 0);
+ }
+ assert.deepEqual(events, ["settings", "closed", "settings", "closed"]);
+ await React.act(async () =>
+ context.toast({ title: "Short", presentation: "dictation-error", actions: [] })
+ );
+ assert.equal(globalThis.__recoveryCardProps.onDismiss, undefined);
+ await React.act(async () => t.mock.timers.tick(3001));
+ await React.act(async () => t.mock.timers.tick(201));
+ assert.equal(context.toastCount, 0, "generic timer unchanged");
+ await React.act(async () =>
+ context.toast({
+ title: "Transcript",
+ presentation: "dictation-error",
+ onClose: () => events.push("before"),
+ actions: [{ label: "View transcript", onClick: () => events.push("view") }],
+ })
+ );
+ const card = globalThis.__recoveryCardProps;
+ await React.act(async () => card.onAction(card.actions[0]));
+ assert.deepEqual(events.slice(-2), ["before", "view"]);
+});
+
+test("real card keeps copy local, guards pending clicks, resets feedback and renders shortcut keycaps", async (t) => {
+ const h = await setup(t);
+ const { DictationErrorCard } = await h.vite.ssrLoadModule(
+ "/components/dictation/DictationErrorCard.tsx"
+ );
+ let resolveCopy,
+ calls = 0,
+ closed = 0;
+ const action = {
+ label: "Copy to clipboard",
+ icon: "copy",
+ dismissOnClick: false,
+ feedback: { successLabel: "Copied", failureLabel: "Copy failed" },
+ onClick: () => {
+ calls += 1;
+ return new Promise((resolve) => {
+ resolveCopy = resolve;
+ });
+ },
+ };
+ const props = {
+ title: "Allow automatic pasting",
+ description: "Paste with Cmd+V.",
+ descriptionHotkey: "Cmd+V",
+ actions: [action],
+ onAction: (value) => value.onClick(),
+ onDismiss: () => {
+ closed += 1;
+ },
+ };
+ await h.render(React.createElement(DictationErrorCard, props));
+ const getCopy = () =>
+ findElement(
+ h.container,
+ (e) =>
+ e.tagName === "BUTTON" && e.textContent !== "" && e.getAttribute("aria-label") !== "Close"
+ );
+ assert.ok(findElement(h.container, (e) => e.tagName === "KBD" && e.textContent === "⌘"));
+ assert.ok(findElement(h.container, (e) => e.tagName === "KBD" && e.textContent === "V"));
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ for (const [result, label] of [
+ [true, "Copied"],
+ [false, "Copy failed"],
+ [undefined, "Copy to clipboard"],
+ ]) {
+ const previousCalls = calls;
+ await React.act(async () => {
+ click(getCopy());
+ click(getCopy());
+ });
+ assert.equal(calls, previousCalls + 1);
+ assert.notEqual(getCopy().getAttribute("disabled"), null);
+ await React.act(async () => resolveCopy(result));
+ assert.equal(getCopy().textContent.trim(), label);
+ assert.equal(closed, 0);
+ await React.act(async () => t.mock.timers.tick(1801));
+ assert.equal(getCopy().textContent.trim(), "Copy to clipboard");
+ }
+ action.onClick = async () => {
+ throw new Error("copy rejected");
+ };
+ await React.act(async () => click(getCopy()));
+ assert.equal(getCopy().textContent.trim(), "Copy failed");
+ action.onClick = () =>
+ new Promise((resolve) => {
+ resolveCopy = resolve;
+ });
+ await React.act(async () => click(getCopy()));
+ const oldCopy = resolveCopy;
+ await h.render(React.createElement(DictationErrorCard, { ...props, key: "new card" }));
+ await React.act(async () => oldCopy(true));
+ assert.equal(
+ getCopy().textContent.trim(),
+ "Copy to clipboard",
+ "old results do not affect a new card"
+ );
+ const closeButton = findElement(h.container, (e) => e.getAttribute("aria-label") === "Close");
+ assert.ok(closeButton);
+ await React.act(async () => click(closeButton));
+ assert.equal(closed, 1);
+ await React.act(async () => click(getCopy()));
+ await h.unmount();
+ await React.act(async () => resolveCopy(true));
+ await React.act(async () => t.mock.timers.tick(1801));
+ assert.equal(h.container.textContent, "");
+});
diff --git a/test/helpers/useAudioRecordingPasteRecovery.test.js b/test/helpers/useAudioRecordingPasteRecovery.test.js
new file mode 100644
index 000000000..909b61606
--- /dev/null
+++ b/test/helpers/useAudioRecordingPasteRecovery.test.js
@@ -0,0 +1,345 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRoot } = require("react-dom/client");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installHookDom,
+} = require("../lib/rendererTestHarness");
+const permission = {
+ title: "Paste Error",
+ code: "ACCESSIBILITY_PERMISSION_REQUIRED",
+ clipboardCopied: true,
+};
+const finalText = " Final translated text\nwith spacing ";
+
+function deferred() {
+ let resolve, reject;
+ const promise = new Promise((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve, reject };
+}
+
+async function mount(t) {
+ let root;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ delete globalThis.__pasteRecoveryManager;
+ });
+ const toasts = [],
+ writes = [],
+ shown = [],
+ hidden = [],
+ dismissed = [];
+ let settingsCalls = 0;
+ const noopDispose = () => () => {};
+ const { window } = installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ onToggleDictation: noopDispose,
+ onToggleVoiceAgent: noopDispose,
+ onToggleTranslation: noopDispose,
+ onStartDictation: noopDispose,
+ onStopDictation: noopDispose,
+ hideDictationPreview: async () => hidden.push(true),
+ completeDictationPreview: async () => {},
+ dictationLifecycleStateChanged: () => {},
+ openAccessibilitySettings: async () => {
+ settingsCalls += 1;
+ return { success: true };
+ },
+ writeClipboard: async (text) => {
+ writes.push(text);
+ return { success: true };
+ },
+ },
+ },
+ });
+ const container = installHookDom(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-paste-recovery-hook-",
+ mockModules: {
+ "/utils/logger": "export default { debug() {}, info() {}, warn() {}, error() {} };",
+ "/utils/visualFrame": "export async function waitForVisualFrames() {}",
+ "/helpers/audioManager": `export default class FakeAudioManager {
+ constructor() { this.voiceAgentRequested=false; this.sttConfig={success:true}; this.streamingFinalText="raw words"; this.starts=0; this.saves=0; globalThis.__pasteRecoveryManager=this; }
+ setCallbacks(callbacks) { this.callbacks=callbacks; }
+ getState() { return { isRecording:false, isProcessing:false }; }
+ shouldUseStreaming() { return false; }
+ setVoiceAgentRequested(value) { this.voiceAgentRequested=value; }
+ setAssistantSelectionContext() {}
+ setTranslationRequested() {}
+ async startRecording() { this.starts+=1; return true; }
+ async safePaste(text) { this.callbacks.onError({title:"Paste Error",code:"ACCESSIBILITY_PERMISSION_REQUIRED",clipboardCopied:true,transcript:text}); return false; }
+ async saveTranscription() { this.saves+=1; return true; }
+ cleanup() {}
+ }`,
+ },
+ });
+ const { useAudioRecording } = await vite.ssrLoadModule("/hooks/useAudioRecording.js");
+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");
+ const { default: i18n } = await vite.ssrLoadModule("/i18n.ts");
+ await i18n.changeLanguage("en");
+ useSettingsStore.setState({
+ autoPasteEnabled: false,
+ keepTranscriptionInClipboard: false,
+ snippets: [],
+ useLocalWhisper: true,
+ pauseMediaOnDictation: false,
+ });
+ let recording;
+ const toast = (value) => toasts.push(value);
+ const options = {
+ onShowTranscript: (value) => shown.push(value),
+ dismissDictationError: () => dismissed.push(true),
+ };
+ function Harness() {
+ recording = useAudioRecording(toast, options);
+ return null;
+ }
+ root = createRoot(container);
+ await React.act(async () => root.render(React.createElement(Harness)));
+ const manager = globalThis.__pasteRecoveryManager;
+ return {
+ toasts,
+ writes,
+ shown,
+ hidden,
+ dismissed,
+ manager,
+ settings: useSettingsStore,
+ api: window.electronAPI,
+ recording: () => recording,
+ settingsCalls: () => settingsCalls,
+ changeLanguage: async (language) => React.act(async () => i18n.changeLanguage(language)),
+ error: async (error = { ...permission, transcript: finalText }) =>
+ React.act(async () => manager.callbacks.onError(error)),
+ unmount: async () => {
+ await React.act(async () => root.unmount());
+ root = null;
+ },
+ };
+}
+
+test("permission recovery preserves final text and keeps Settings and Copy on the same card", async (t) => {
+ const h = await mount(t);
+ await h.error();
+ const card = h.toasts.at(-1);
+ assert.equal(card.duration, 0);
+ assert.equal(card.dismissible, true);
+ assert.equal(card.presentation, "dictation-error");
+ assert.equal(card.actions[0].icon, "settings");
+ assert.equal(card.actions[1].icon, "copy");
+ assert.equal(card.actions[0].dismissOnClick, false);
+ assert.equal(card.actions[1].dismissOnClick, false);
+ await card.actions[0].onClick();
+ assert.equal(h.settingsCalls(), 1);
+ assert.equal(await card.actions[1].onClick(), true);
+ assert.deepEqual(h.writes, [finalText]);
+ assert.equal(h.toasts.length, 1);
+ assert.equal(h.manager.starts, 0);
+ assert.deepEqual(h.shown, []);
+ assert.deepEqual(h.hidden, []);
+});
+
+test("a visible permission card keeps its actions working after changing the app language", async (t) => {
+ const h = await mount(t);
+ await h.error();
+ const card = h.toasts.at(-1);
+ const copy = deferred();
+ h.api.writeClipboard = async (text) => {
+ h.writes.push(text);
+ return copy.promise;
+ };
+ const pendingCopy = card.actions[1].onClick();
+ await h.changeLanguage("de");
+ copy.resolve({ success: true });
+ assert.equal(await pendingCopy, true);
+ assert.equal(h.toasts.length, 1);
+ await card.actions[0].onClick();
+ assert.equal(h.settingsCalls(), 1);
+ assert.equal(await card.actions[1].onClick(), true);
+ assert.deepEqual(h.writes, [finalText, finalText]);
+});
+
+test("copy reports only strict bridge success and never falls back or replaces the card", async (t) => {
+ const h = await mount(t);
+ await h.error();
+ const copy = h.toasts.at(-1).actions[1];
+ for (const result of [true, false, undefined, "reject", "absent"]) {
+ h.api.writeClipboard =
+ result === "absent"
+ ? undefined
+ : async () => {
+ if (result === "reject") throw new Error("locked");
+ return result === undefined ? undefined : { success: result };
+ };
+ assert.equal(await copy.onClick(), result === true);
+ }
+ assert.equal(h.toasts.length, 1);
+ assert.equal(h.settingsCalls(), 0);
+ assert.equal(h.manager.starts, 0);
+ for (const transcript of ["", " \n "]) {
+ await h.error({ ...permission, transcript });
+ assert.equal(h.toasts.at(-1).actions.length, 1);
+ assert.doesNotMatch(h.toasts.at(-1).description, /Copy your text/);
+ assert.equal(h.toasts.at(-1).descriptionHotkey, undefined);
+ }
+});
+
+test("Settings failures retain a persistent manual path and exact-text copy", async (t) => {
+ const h = await mount(t);
+ for (const result of [false, undefined, "reject", "absent"]) {
+ h.api.openAccessibilitySettings =
+ result === "absent"
+ ? undefined
+ : async () => {
+ if (result === "reject") throw new Error("unavailable");
+ return result === undefined ? undefined : { success: result };
+ };
+ await h.error();
+ await h.toasts.at(-1).actions[0].onClick();
+ const fallback = h.toasts.at(-1);
+ assert.match(fallback.description, /Couldn't open Settings/);
+ assert.match(fallback.description, /System Settings.*Accessibility/);
+ assert.equal(fallback.duration, 0);
+ assert.equal(fallback.dismissible, true);
+ assert.equal(await fallback.actions[1].onClick(), true);
+ assert.equal(h.writes.at(-1), finalText);
+ }
+ h.api.openAccessibilitySettings = async () => ({ success: true });
+ const count = h.toasts.length;
+ await h.toasts.at(-1).actions[0].onClick();
+ assert.equal(h.toasts.length, count, "fallback action remains usable");
+});
+
+test("a start that does not begin recording leaves the permission card working", async (t) => {
+ const h = await mount(t);
+ await h.error();
+ const card = h.toasts.at(-1);
+ h.manager.startRecording = async () => false;
+ await React.act(async () => assert.equal(await h.recording().startRecording(), false));
+ assert.deepEqual(h.dismissed, []);
+ await card.actions[0].onClick();
+ assert.equal(h.settingsCalls(), 1);
+ assert.equal(await card.actions[1].onClick(), true);
+ assert.deepEqual(h.writes, [finalText]);
+});
+
+test("a Settings failure during a recording start does not re-show the card", async (t) => {
+ const h = await mount(t);
+ await h.error();
+ const card = h.toasts.at(-1);
+ const started = deferred();
+ h.manager.startRecording = () => started.promise;
+ h.api.openAccessibilitySettings = async () => ({ success: false });
+ let starting;
+ await React.act(async () => {
+ starting = h.recording().startRecording();
+ });
+ await card.actions[0].onClick();
+ assert.equal(h.toasts.length, 1);
+ await React.act(async () => {
+ started.resolve(true);
+ await starting;
+ });
+ assert.equal(h.dismissed.length, 1);
+});
+
+for (const transition of ["close", "newer error", "start", "complete", "unmount"]) {
+ test(`late Settings and Copy results cannot survive ${transition}`, async (t) => {
+ const h = await mount(t);
+ await h.error();
+ const old = h.toasts.at(-1);
+ const settings = deferred(),
+ copy = deferred();
+ let launches = 0,
+ writes = 0;
+ h.api.openAccessibilitySettings = () => {
+ launches += 1;
+ return settings.promise;
+ };
+ h.api.writeClipboard = () => {
+ writes += 1;
+ return copy.promise;
+ };
+ const pendingSettings = old.actions[0].onClick();
+ await old.actions[0].onClick();
+ assert.equal(launches, 1);
+ const pendingCopy = old.actions[1].onClick();
+ if (transition === "close") old.onClose();
+ if (transition === "newer error") {
+ await h.error({ ...permission, transcript: "new final text" });
+ old.onClose();
+ }
+ if (transition === "start") {
+ await React.act(async () => assert.equal(await h.recording().startRecording(), true));
+ assert.equal(h.manager.starts, 1);
+ }
+ if (transition === "complete") {
+ await React.act(async () =>
+ h.manager.callbacks.onTranscriptionComplete({
+ success: true,
+ text: "new text",
+ source: "local",
+ })
+ );
+ assert.equal(h.dismissed.length, 1);
+ }
+ if (transition === "unmount") await h.unmount();
+ const count = h.toasts.length;
+ settings.reject(new Error("late"));
+ copy.resolve({ success: true });
+ await pendingSettings;
+ assert.equal(await pendingCopy, undefined);
+ await old.actions[1].onClick();
+ assert.equal(writes, 1, "already stale copy does not dispatch");
+ assert.equal(h.toasts.length, count);
+ if (transition === "newer error") {
+ const actual = [];
+ h.api.writeClipboard = async (text) => {
+ actual.push(text);
+ return { success: true };
+ };
+ assert.equal(await h.toasts.at(-1).actions[1].onClick(), true);
+ assert.deepEqual(actual, ["new final text"]);
+ }
+ });
+}
+
+test("generic errors retain Retry, transcript and the platform's paste guidance", async (t) => {
+ const h = await mount(t);
+ const guidance = "Please install xdotool or paste manually with Ctrl+V.";
+ await h.error({ title: "Paste Error", code: "PASTE_FAILED", description: guidance });
+ const card = h.toasts.at(-1);
+ assert.equal(card.title, "Couldn't paste automatically");
+ assert.equal(card.actions[0].icon, "retry");
+ assert.equal(card.actions[1].icon, "transcript");
+ assert.equal(card.description, guidance);
+ assert.equal(card.duration, undefined);
+ assert.equal(card.dismissible, undefined);
+ card.actions[1].onClick();
+ assert.deepEqual(h.shown, ["raw words"]);
+ await h.error({ title: "Other error", description: "details" });
+ assert.equal(h.hidden.length, 1);
+});
+
+test("completed batch and streaming dictations are saved when automatic paste is denied", async (t) => {
+ const h = await mount(t);
+ h.settings.setState({ autoPasteEnabled: true });
+ for (const source of ["local", "streaming"]) {
+ await React.act(async () =>
+ h.manager.callbacks.onTranscriptionComplete({
+ success: true,
+ text: "final result",
+ rawText: "raw input",
+ source,
+ })
+ );
+ assert.equal(h.toasts.at(-1).actions[1].icon, "copy");
+ }
+ assert.equal(h.manager.saves, 2);
+});
diff --git a/test/helpers/voiceSurfaceGeometry.test.js b/test/helpers/voiceSurfaceGeometry.test.js
index 21092f087..6db8fcec6 100644
--- a/test/helpers/voiceSurfaceGeometry.test.js
+++ b/test/helpers/voiceSurfaceGeometry.test.js
@@ -127,7 +127,12 @@ test("DictationErrorCard reports content height at the shared expected width", a
"/components/icons": `
export function RotateCcw() { return null; }
export function ScrollText() { return null; }
+ export function Settings() { return null; }
+ export function Copy() { return null; }
+ export function Check() { return null; }
+ export function X() { return null; }
`,
+ "react-i18next": `export function useTranslation() { return { t: (key) => key }; }`,
react: `
export function useLayoutEffect(effect) {
globalThis.__dictationErrorCardCleanup = effect();
diff --git a/test/lib/interactiveDom.js b/test/lib/interactiveDom.js
new file mode 100644
index 000000000..9e74891e7
--- /dev/null
+++ b/test/lib/interactiveDom.js
@@ -0,0 +1,228 @@
+// Shared minimal DOM for interactive React behavior tests; no layout emulation.
+const noop = () => {};
+
+function installInteractiveDom(t) {
+ const originalDocument = globalThis.document;
+ const originalNode = globalThis.Node;
+ const originalElement = globalThis.Element;
+ const originalHTMLElement = globalThis.HTMLElement;
+ const originalHTMLIFrameElement = globalThis.HTMLIFrameElement;
+ const originalActEnvironment = globalThis.IS_REACT_ACT_ENVIRONMENT;
+ const originalRequestAnimationFrame = globalThis.requestAnimationFrame;
+ const originalCancelAnimationFrame = globalThis.cancelAnimationFrame;
+
+ class FakeNode {
+ constructor(nodeType, nodeName, ownerDocument) {
+ this.nodeType = nodeType;
+ this.nodeName = nodeName;
+ this.ownerDocument = ownerDocument;
+ this.parentNode = null;
+ this.childNodes = [];
+ }
+
+ appendChild(child) {
+ return this.insertBefore(child, null);
+ }
+
+ insertBefore(child, before) {
+ if (child.parentNode) child.parentNode.removeChild(child);
+ const index = before === null ? this.childNodes.length : this.childNodes.indexOf(before);
+ this.childNodes.splice(index < 0 ? this.childNodes.length : index, 0, child);
+ child.parentNode = this;
+ return child;
+ }
+
+ removeChild(child) {
+ const index = this.childNodes.indexOf(child);
+ if (index >= 0) this.childNodes.splice(index, 1);
+ child.parentNode = null;
+ return child;
+ }
+
+ contains(candidate) {
+ for (let current = candidate; current; current = current.parentNode) {
+ if (current === this) return true;
+ }
+ return false;
+ }
+
+ get firstChild() {
+ return this.childNodes[0] ?? null;
+ }
+
+ get lastChild() {
+ return this.childNodes.at(-1) ?? null;
+ }
+
+ get nextSibling() {
+ if (!this.parentNode) return null;
+ const index = this.parentNode.childNodes.indexOf(this);
+ return this.parentNode.childNodes[index + 1] ?? null;
+ }
+
+ get textContent() {
+ return this.childNodes.map((child) => child.textContent).join("");
+ }
+
+ set textContent(value) {
+ for (const child of this.childNodes) child.parentNode = null;
+ this.childNodes = [];
+ if (value !== "") this.appendChild(this.ownerDocument.createTextNode(String(value)));
+ }
+ }
+
+ class Element extends FakeNode {}
+ class HTMLElement extends Element {}
+ class HTMLIFrameElement extends HTMLElement {}
+
+ class FakeText extends FakeNode {
+ constructor(value, ownerDocument) {
+ super(3, "#text", ownerDocument);
+ this.nodeValue = value;
+ }
+
+ get textContent() {
+ return this.nodeValue;
+ }
+
+ set textContent(value) {
+ this.nodeValue = String(value);
+ }
+ }
+
+ class FakeElement extends HTMLElement {
+ constructor(tagName, ownerDocument, namespaceURI = "http://www.w3.org/1999/xhtml") {
+ super(1, tagName.toUpperCase(), ownerDocument);
+ this.tagName = tagName.toUpperCase();
+ this.namespaceURI = namespaceURI;
+ this.attributes = new Map();
+ this.listeners = new Map();
+ this.style = {
+ setProperty: (name, value) => {
+ this.style[name] = value;
+ },
+ removeProperty: (name) => {
+ delete this.style[name];
+ },
+ };
+ }
+
+ setAttribute(name, value) {
+ this.attributes.set(name, String(value));
+ }
+
+ getAttribute(name) {
+ return this.attributes.get(name) ?? null;
+ }
+
+ removeAttribute(name) {
+ this.attributes.delete(name);
+ }
+
+ addEventListener(type, listener) {
+ const listeners = this.listeners.get(type) ?? new Set();
+ listeners.add(listener);
+ this.listeners.set(type, listeners);
+ }
+
+ removeEventListener(type, listener) {
+ this.listeners.get(type)?.delete(listener);
+ }
+
+ dispatchEvent(event) {
+ if (!event.target) event.target = this;
+ for (let current = this; current; current = event.bubbles ? current.parentNode : null) {
+ event.currentTarget = current;
+ for (const listener of current.listeners?.get(event.type) ?? []) listener(event);
+ if (event.cancelBubble) break;
+ }
+ return !event.defaultPrevented;
+ }
+
+ focus() {
+ this.ownerDocument.activeElement = this;
+ }
+ }
+
+ const documentListeners = new Map();
+ const document = {
+ nodeType: 9,
+ nodeName: "#document",
+ activeElement: null,
+ createElement: (tagName) => new FakeElement(tagName, document),
+ createElementNS: (namespaceURI, tagName) => new FakeElement(tagName, document, namespaceURI),
+ createTextNode: (value) => new FakeText(String(value), document),
+ createComment: (value) => {
+ const comment = new FakeNode(8, "#comment", document);
+ comment.nodeValue = String(value);
+ return comment;
+ },
+ addEventListener(type, listener) {
+ const listeners = documentListeners.get(type) ?? new Set();
+ listeners.add(listener);
+ documentListeners.set(type, listeners);
+ },
+ removeEventListener(type, listener) {
+ documentListeners.get(type)?.delete(listener);
+ },
+ };
+ const container = new FakeElement("div", document);
+ document.documentElement = container;
+ document.body = container;
+ document.defaultView = globalThis.window;
+ Object.assign(globalThis.window, {
+ Node: FakeNode,
+ Element,
+ HTMLElement,
+ HTMLIFrameElement,
+ document,
+ getSelection: () => ({
+ isCollapsed: true,
+ rangeCount: 0,
+ removeAllRanges() {},
+ }),
+ });
+ globalThis.document = document;
+ globalThis.Node = FakeNode;
+ globalThis.Element = Element;
+ globalThis.HTMLElement = HTMLElement;
+ globalThis.HTMLIFrameElement = HTMLIFrameElement;
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
+ globalThis.requestAnimationFrame = (callback) => {
+ callback();
+ return 1;
+ };
+ globalThis.cancelAnimationFrame = noop;
+
+ t.after(() => {
+ if (originalDocument === undefined) delete globalThis.document;
+ else globalThis.document = originalDocument;
+ if (originalNode === undefined) delete globalThis.Node;
+ else globalThis.Node = originalNode;
+ if (originalElement === undefined) delete globalThis.Element;
+ else globalThis.Element = originalElement;
+ if (originalHTMLElement === undefined) delete globalThis.HTMLElement;
+ else globalThis.HTMLElement = originalHTMLElement;
+ if (originalHTMLIFrameElement === undefined) delete globalThis.HTMLIFrameElement;
+ else globalThis.HTMLIFrameElement = originalHTMLIFrameElement;
+ if (originalActEnvironment === undefined) delete globalThis.IS_REACT_ACT_ENVIRONMENT;
+ else globalThis.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment;
+ if (originalRequestAnimationFrame === undefined) delete globalThis.requestAnimationFrame;
+ else globalThis.requestAnimationFrame = originalRequestAnimationFrame;
+ if (originalCancelAnimationFrame === undefined) delete globalThis.cancelAnimationFrame;
+ else globalThis.cancelAnimationFrame = originalCancelAnimationFrame;
+ });
+
+ return container;
+}
+
+function findElement(root, predicate) {
+ if (root.nodeType === 1 && predicate(root)) return root;
+ for (const child of root.childNodes) {
+ const match = findElement(child, predicate);
+ if (match) return match;
+ }
+ return null;
+}
+
+module.exports = { installInteractiveDom, findElement };