Skip to content

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

fix: voice-agent screen context, selection-edit retry, calendar tool, and AX read fixes (#1566)

Gabriel Steinba6ecd648a88
diff --git a/CLAUDE.md b/CLAUDE.md
index 9704f39d2..c0b7b5638 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -643,7 +643,7 @@ When "Share screen context" is enabled (Settings → AI Models → Voice Agent
- Image-wired clients: `openai` (Responses `input_image` / Chat `image_url`, also `custom`/`openrouter`), `anthropic` (base64 content block via `process-anthropic-reasoning`), `gemini` (`inlineData`), `openwhispr` (forwards `screenContext` + `promptMode: "agent"` to `/api/reason`; the server routes to its `REASONING_VISION_*` model chain)
- IPC: `capture-screen-context`, `check-screen-recording-access`, `request-screen-recording-access`, `open-screen-recording-settings`, `screen-context-set-enabled`
- Privacy: screenshots live only in renderer memory for one request — never written to disk, stored in history, or logged (loggers emit `hasScreenContext` booleans only)
-- Failure UX: a rejected screenshot is retried once text-only from `processWithReasoningModel()` (rebuilding the prompt without the screen-context suffix) and reported via a non-destructive `SCREEN_CONTEXT_SKIPPED` toast, so an image problem never costs the user their command. Only if that retry also fails does the "Agent Unavailable" toast (`AGENT_REASONING_FAILED`) fire and the raw transcript get pasted
+- Failure UX: a rejected screenshot is retried once text-only from `processWithReasoningModel()` (swapping in the pre-built `textOnlySystemPrompt`, so selection-edit instructions and the completion marker survive the retry) and reported via a non-destructive `SCREEN_CONTEXT_SKIPPED` toast, so an image problem never costs the user their command. Only if that retry also fails does the "Agent Unavailable" toast (`AGENT_REASONING_FAILED`) fire and the raw transcript get pasted
**Tests**: `test/helpers/dictationRouting.test.js`, `test/helpers/screenContextCapture.test.js` (run with `node --test`)
diff --git a/src/components/settings/DictationAgentSettings.tsx b/src/components/settings/DictationAgentSettings.tsx
index 1ed79db07..3f5c3f039 100644
--- a/src/components/settings/DictationAgentSettings.tsx
+++ b/src/components/settings/DictationAgentSettings.tsx
@@ -29,6 +29,7 @@ export default function DictationAgentSettings() {
isMacOS,
granted: screenGranted,
supported: screenSupported,
+ needsRelaunch: screenNeedsRelaunch,
request: requestScreenAccess,
} = useScreenRecordingPermission();
const agentAllowed = usePolicyStore(isAgentAllowed);
@@ -208,6 +209,11 @@ export default function DictationAgentSettings() {
buttonText={t("onboarding.permissions.grantAccess")}
/>
)}
+ {voiceAgentScreenContext && isMacOS && screenNeedsRelaunch && (
+ <p className="text-[11px] text-warning/80 leading-snug">
+ {t("dictationAgent.screenContext.relaunchHint")}
+ </p>
+ )}
{voiceAgentScreenContext && useDictationAgentVisionModel && (
<InferenceConfigEditor
scope="dictationAgentVision"
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 0543cd613..23e1f895c 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -161,6 +161,15 @@ function resolveReasoningRoute(
translationRequested,
translationReachable: translation.reachable,
});
+ logger.logReasoning("ROUTE_RESOLVED", {
+ kind,
+ voiceAgentRequested,
+ agentReachable: agent.reachable,
+ agentMode: settings.dictationAgentMode,
+ agentProvider: agent.displayProvider,
+ agentModel: agent.model,
+ hasScreenContext: !!screenContext,
+ });
if (translationRequested && kind !== "translation") {
logger.warn(
"Translation requested but unreachable, falling back",
@@ -205,6 +214,12 @@ function resolveReasoningRoute(
baseModelSupportsVision: !!getCloudModel(agent.model)?.supportsVision,
});
const target = useVisionOverride ? vision : agent;
+ logger.logReasoning("AGENT_IMAGE_TARGET", {
+ hasScreenContext: !!screenContext,
+ visionOverrideActive: vision.active,
+ attach,
+ useVisionOverride,
+ });
const systemPrompt = dictationAgentPrompt(settings, agentName);
@@ -216,7 +231,7 @@ function resolveReasoningRoute(
systemPrompt: attach
? appendScreenContextSuffix(systemPrompt, settings.uiLanguage)
: systemPrompt,
- ...(attach ? { screenContext } : {}),
+ ...(attach ? { screenContext, textOnlySystemPrompt: systemPrompt } : {}),
},
};
}
@@ -680,6 +695,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
setVoiceAgentRequested(requested) {
this.voiceAgentRequested = requested;
this.pendingSelectionEdit = null;
+ // No recording must ever see a stale capture (e.g. left over from a
+ // cancelled voice-agent recording, even after the setting was turned
+ // off). A live voice-agent start re-captures right after this call.
+ this.screenContextPromise = null;
}
setTranslationRequested(requested) {
@@ -694,9 +713,6 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
return settings.translationSourceLanguage || "auto";
}
return settings.preferredLanguage;
- // A non-voice-agent recording must never see a stale capture (e.g. left
- // over from a cancelled voice-agent recording).
- if (!requested) this.screenContextPromise = null;
}
// Kicked off at voice-agent recording start (so the screenshot reflects the
@@ -712,10 +728,12 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
try {
// Capture resolves in well under a second; the race only protects the
// paste path if the IPC ever hangs.
- return await Promise.race([
+ const image = await Promise.race([
pending,
new Promise((resolve) => setTimeout(() => resolve(null), 3000)),
]);
+ if (!image) logger.logReasoning("SCREEN_CONTEXT_UNAVAILABLE", {});
+ return image;
} catch {
return null;
}
@@ -2178,14 +2196,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
});
// A screenshot the model or transport rejects must not cost the user
- // their command — rerun it text-only. Only the agent route attaches one,
- // so rebuilding its prompt also drops the screen-context instructions
- // that would otherwise reference an image we are no longer sending.
+ // their command — rerun it text-only, swapping in the pre-built prompt
+ // that never had the screen-context suffix. Rebuilding from scratch
+ // would drop the selection-edit instructions and completion marker.
if (config?.screenContext) {
- const { screenContext, ...textOnlyConfig } = config;
+ const { screenContext, textOnlySystemPrompt, ...textOnlyConfig } = config;
const result = await ReasoningService.processText(text, model, agentName, {
...textOnlyConfig,
- systemPrompt: dictationAgentPrompt(getSettings(), agentName),
+ systemPrompt: textOnlySystemPrompt ?? dictationAgentPrompt(getSettings(), agentName),
});
this._notifyScreenContextSkipped();
return result;
@@ -2258,6 +2276,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
config?.systemPrompt,
completionMarker
);
+ if (selectionConfig.textOnlySystemPrompt) {
+ // The text-only retry prompt must carry the same selection-edit
+ // instructions and marker, or a rejected screenshot loses the command.
+ selectionConfig.textOnlySystemPrompt = buildSelectionEditSystemPrompt(
+ selectionConfig.textOnlySystemPrompt,
+ completionMarker
+ );
+ }
const userPrompt = buildSelectionEditUserPrompt(text, capture.text);
try {
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 5c95bce04..108cc7f30 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -4485,22 +4485,19 @@ class IPCHandlers {
ipcMain.handle("capture-screen-context", () => screenContextCapture.captureCursorDisplay());
- const buildScreenRecordingAccess = (status) => ({
- granted: status === "granted",
- status,
- supported: status !== "unsupported",
- });
+ // Snapshot the launch-time TCC status so a mid-session grant (which macOS
+ // only honors after a relaunch) is detectable even if the renderer never
+ // checked before the user granted.
+ screenContextCapture.getAccessStatus();
- ipcMain.handle("check-screen-recording-access", () =>
- buildScreenRecordingAccess(screenContextCapture.getAccessStatus())
- );
+ ipcMain.handle("check-screen-recording-access", () => screenContextCapture.getAccessResult());
ipcMain.handle("request-screen-recording-access", async () => {
const status = await screenContextCapture.requestAccess();
if (process.platform === "darwin" && status !== "granted") {
await openSystemSettings("screenRecording");
}
- return buildScreenRecordingAccess(status);
+ return screenContextCapture.getAccessResult();
});
// Keeps the dictation overlay out of its own screenshots (and screen
diff --git a/src/helpers/screenContextCapture.js b/src/helpers/screenContextCapture.js
index 41729cdea..b36ac02af 100644
--- a/src/helpers/screenContextCapture.js
+++ b/src/helpers/screenContextCapture.js
@@ -24,14 +24,33 @@ function isWaylandSession() {
);
}
+// macOS applies a Screen Recording grant only at process launch:
+// getMediaAccessStatus flips to "granted" the moment the user toggles System
+// Settings, but desktopCapturer keeps returning stale/blank frames until the
+// app relaunches. Snapshot the first reading to detect mid-session grants.
+let launchStatus = null;
+
function getAccessStatus() {
if (isWaylandSession()) return "unsupported";
if (process.platform === "darwin") {
- return systemPreferences.getMediaAccessStatus("screen");
+ const status = systemPreferences.getMediaAccessStatus("screen");
+ if (launchStatus === null) launchStatus = status;
+ return status;
}
return "granted";
}
+function getAccessResult() {
+ const status = getAccessStatus();
+ return {
+ granted: status === "granted",
+ status,
+ supported: status !== "unsupported",
+ needsRelaunch:
+ process.platform === "darwin" && status === "granted" && launchStatus !== "granted",
+ };
+}
+
// Encodes from the same source bitmap at each step, so lowering quality never
// compounds artifacts from an earlier pass.
function encodeWithinBudget(image) {
@@ -48,7 +67,11 @@ function encodeWithinBudget(image) {
// Returns null on any failure — a screenshot must never break the dictation
// it accompanies.
async function captureCursorDisplay() {
- if (getAccessStatus() !== "granted") return null;
+ const accessStatus = getAccessStatus();
+ if (accessStatus !== "granted") {
+ debugLogger.warn("Screen context capture skipped", { accessStatus }, "screenContext");
+ return null;
+ }
try {
const cursor = screen.getCursorScreenPoint();
@@ -62,7 +85,10 @@ async function captureCursorDisplay() {
const sources = await desktopCapturer.getSources({ types: ["screen"], thumbnailSize });
// display_id can be empty on some Linux setups — fall back to the first screen.
const source = sources.find((s) => s.display_id === String(display.id)) || sources[0];
- if (!source || source.thumbnail.isEmpty()) return null;
+ if (!source || source.thumbnail.isEmpty()) {
+ debugLogger.warn("Screen context capture found no screen source", {}, "screenContext");
+ return null;
+ }
const encoded = encodeWithinBudget(source.thumbnail);
if (!encoded) {
@@ -89,4 +115,4 @@ async function requestAccess() {
return getAccessStatus();
}
-module.exports = { getAccessStatus, captureCursorDisplay, requestAccess };
+module.exports = { getAccessStatus, getAccessResult, captureCursorDisplay, requestAccess };
diff --git a/src/helpers/textEditMonitor.js b/src/helpers/textEditMonitor.js
index 69503e03b..83a6c24a1 100644
--- a/src/helpers/textEditMonitor.js
+++ b/src/helpers/textEditMonitor.js
@@ -15,6 +15,19 @@ const ACTIVATE_CONFIRM_DELAY_MS = 25;
// across that burst. Kept short so back-to-back dictations in different apps
// still get a fresh capture.
const TARGET_CAPTURE_FRESHNESS_MS = 250;
+// AXError -25212 (kAXErrorNoValue) on the focused-element read is how
+// Chromium/Electron apps respond while their AX tree is dormant, making the
+// native binary's 5-attempt retry (~1.2s) dead time on every read. A single
+// -25212 line can also be transient (the tree may wake mid-run — the binary
+// then logs "Got focused element on attempt N"), so only a run where the
+// element never resolved and every attempt failed with -25212 marks the app
+// as unsupported for this session.
+function isPersistentAxNoValueFailure(stderr) {
+ const text = stderr || "";
+ if (text.includes("Got focused element")) return false;
+ const attemptCodes = text.match(/\(error: -?\d+\)/g) || [];
+ return attemptCodes.length > 0 && attemptCodes.every((code) => code === "(error: -25212)");
+}
// Monitoring is strictly read-only: never write AXEnhancedUserInterface (or any
// AX attribute) on the target app to force its accessibility tree. Flipping that
@@ -106,6 +119,10 @@ class TextEditMonitor extends EventEmitter {
this.lastTargetPid = null;
this._captureTargetPromise = null;
this._lastCaptureAt = 0;
+ // PIDs whose AX tree never yields a focused element (see
+ // isPersistentAxNoValueFailure). A recycled PID only costs a detour via
+ // AppleScript, which is still correct.
+ this._nativeSelectionUnsupportedPids = new Set();
}
/**
@@ -220,7 +237,7 @@ class TextEditMonitor extends EventEmitter {
}
const resolved = this.resolveBinary();
- if (resolved) {
+ if (resolved && !this._nativeSelectionUnsupportedPids.has(pid)) {
execFile(
resolved.command,
[...resolved.args, "--selected-text", String(pid)],
@@ -251,12 +268,19 @@ class TextEditMonitor extends EventEmitter {
return;
}
+ // A timeout-killed child never finished the retry ladder — the
+ // tree could have woken on a later attempt — so only a completed
+ // run's verdict counts (the untimed monitor path also teaches).
+ if (!error?.killed && isPersistentAxNoValueFailure(stderr || error?.message || "")) {
+ this._nativeSelectionUnsupportedPids.add(pid);
+ }
debugLogger.debug(
"[TextEditMonitor] Native selected-text read unavailable; trying AppleScript",
{
pid,
error: error?.message || null,
stderr: stderr?.trim() || null,
+ nativeSkippedNextTime: this._nativeSelectionUnsupportedPids.has(pid),
}
);
this._getSelectedTextViaAppleScript(pid, timeoutMs, resolve);
@@ -495,6 +519,17 @@ class TextEditMonitor extends EventEmitter {
return;
}
+ // The native monitor for these apps always burns its retries and ends in
+ // NO_ELEMENT -> stopMonitoring; skip the doomed child process entirely.
+ if (this._nativeSelectionUnsupportedPids.has(targetPid)) {
+ debugLogger.debug(
+ "[TextEditMonitor] macOS native: AX reads unsupported for target this session, skipping monitor",
+ { targetPid }
+ );
+ this.stopMonitoring();
+ return;
+ }
+
debugLogger.debug("[TextEditMonitor] macOS native: starting", {
targetPid,
textPreview: originalText.substring(0, 80),
@@ -516,6 +551,9 @@ class TextEditMonitor extends EventEmitter {
return;
}
+ // Per-child verdict state, so overlapping monitor runs can never cache
+ // each other's target.
+ const axRun = { stderr: "", noElement: false };
this.process = spawn(command, [...args, String(targetPid)], {
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
@@ -528,12 +566,14 @@ class TextEditMonitor extends EventEmitter {
this.process.stdout.setEncoding("utf8");
this.process.stdout.on("data", (chunk) => {
debugLogger.debug("[TextEditMonitor] stdout", { data: chunk.trim() });
+ if (chunk.includes("NO_ELEMENT")) axRun.noElement = true;
this._handleProcessStdoutChunk(chunk);
});
this.process.stderr.setEncoding("utf8");
this.process.stderr.on("data", (data) => {
debugLogger.debug("[TextEditMonitor] stderr", { data: data.trim() });
+ axRun.stderr += data;
});
this.process.on("error", (err) => {
@@ -550,6 +590,16 @@ class TextEditMonitor extends EventEmitter {
this.process = null;
});
+ // "close" fires after both stdio streams have flushed. The monitor child
+ // runs the full retry ladder with no exec timeout, so NO_ELEMENT after a
+ // uniform -25212 run is a terminal verdict — teach the cache so plain
+ // dictation stops spawning doomed monitors.
+ this.process.on("close", () => {
+ if (axRun.noElement && isPersistentAxNoValueFailure(axRun.stderr)) {
+ this._nativeSelectionUnsupportedPids.add(targetPid);
+ }
+ });
+
this.timeout = setTimeout(() => this.stopMonitoring(), timeoutMs);
}
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
index 668636b45..726ade9a6 100644
--- a/src/hooks/useAudioRecording.js
+++ b/src/hooks/useAudioRecording.js
@@ -66,6 +66,13 @@ export const useAudioRecording = (toast, options = {}) => {
audioManagerRef.current.setVoiceAgentRequested(voiceAgentRequested);
audioManagerRef.current.setTranslationRequested(translationRequested);
+ if (voiceAgentRequested) {
+ logger.info(
+ "Voice agent recording start",
+ { screenContextEnabled: !!getSettings().voiceAgentScreenContext },
+ "reasoning"
+ );
+ }
if (voiceAgentRequested && getSettings().voiceAgentScreenContext) {
audioManagerRef.current.beginScreenContextCapture();
}
diff --git a/src/hooks/useScreenRecordingPermission.ts b/src/hooks/useScreenRecordingPermission.ts
index 0d7b3d96e..9438ab864 100644
--- a/src/hooks/useScreenRecordingPermission.ts
+++ b/src/hooks/useScreenRecordingPermission.ts
@@ -51,6 +51,7 @@ export function useScreenRecordingPermission() {
return {
granted: access?.granted ?? false,
supported: access?.supported ?? true,
+ needsRelaunch: access?.needsRelaunch ?? false,
request,
isMacOS,
};
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 27bd6e99c..5a94cf248 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -3137,7 +3137,8 @@
"visionModel": "Separates Vision-Modell",
"visionModelDescription": "Leitet Befehle mit Screenshot an ein anderes Modell mit Bildverständnis weiter.",
"permissionTitle": "Bildschirmaufnahme",
- "permissionDescription": "macOS benötigt die Berechtigung zur Bildschirmaufnahme, um Ihren Bildschirm zu erfassen."
+ "permissionDescription": "macOS benötigt die Berechtigung zur Bildschirmaufnahme, um Ihren Bildschirm zu erfassen.",
+ "relaunchHint": "Die Bildschirmaufnahme wurde erteilt, während OpenWhispr lief. Beenden und öffnen Sie OpenWhispr erneut, um Screenshots aufzunehmen."
},
"modes": {
"openwhispr": "OpenWhispr Cloud",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index c5cfcee4c..deae51f72 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -3137,7 +3137,8 @@
"visionModel": "Separate vision model",
"visionModelDescription": "Route commands that include a screenshot to a different, vision-capable model.",
"permissionTitle": "Screen Recording",
- "permissionDescription": "macOS requires Screen Recording permission to capture your screen."
+ "permissionDescription": "macOS requires Screen Recording permission to capture your screen.",
+ "relaunchHint": "Screen Recording was granted while OpenWhispr was running. Quit and reopen OpenWhispr to start capturing screenshots."
},
"modes": {
"openwhispr": "OpenWhispr Cloud",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 209b9ca41..894bef97a 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -3020,7 +3020,8 @@
"visionModel": "Modelo de visión aparte",
"visionModelDescription": "Envía los comandos que incluyen una captura a otro modelo con capacidad de visión.",
"permissionTitle": "Grabación de pantalla",
- "permissionDescription": "macOS requiere permiso de grabación de pantalla para capturar tu pantalla."
+ "permissionDescription": "macOS requiere permiso de grabación de pantalla para capturar tu pantalla.",
+ "relaunchHint": "El permiso de grabación de pantalla se concedió mientras OpenWhispr estaba en ejecución. Cierra y vuelve a abrir OpenWhispr para empezar a capturar la pantalla."
},
"modes": {
"openwhispr": "OpenWhispr Cloud",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index f9c6cad31..2a35b49b2 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -3137,7 +3137,8 @@
"visionModel": "Modèle de vision distinct",
"visionModelDescription": "Envoie les commandes incluant une capture vers un autre modèle capable de vision.",
"permissionTitle": "Enregistrement de l'écran",
- "permissionDescription": "macOS exige l'autorisation d'enregistrement de l'écran pour capturer votre écran."
+ "permissionDescription": "macOS exige l'autorisation d'enregistrement de l'écran pour capturer votre écran.",
+ "relaunchHint": "L'enregistrement d'écran a été autorisé pendant qu'OpenWhispr était en cours d'exécution. Quittez et rouvrez OpenWhispr pour commencer à capturer des captures d'écran."
},
"modes": {
"openwhispr": "OpenWhispr Cloud",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index d9ed7f4e1..3ba303dbe 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -2972,7 +2972,8 @@
"visionModel": "Modello di visione separato",
"visionModelDescription": "Instrada i comandi che includono uno screenshot verso un altro modello con capacità di visione.",
"permissionTitle": "Registrazione schermo",
- "permissionDescription": "macOS richiede l'autorizzazione alla registrazione dello schermo per catturare lo schermo."
+ "permissionDescription": "macOS richiede l'autorizzazione alla registrazione dello schermo per catturare lo schermo.",
+ "relaunchHint": "La registrazione dello schermo è stata concessa mentre OpenWhispr era in esecuzione. Chiudi e riapri OpenWhispr per iniziare a catturare gli screenshot."
},
"modes": {
"openwhispr": "OpenWhispr Cloud",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 7c9c33b25..691df1510 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -2972,7 +2972,8 @@
"visionModel": "専用のビジョンモデル",
"visionModelDescription": "スクリーンショット付きのコマンドを、画像対応の別モデルに振り分けます。",
"permissionTitle": "画面収録",
- "permissionDescription": "画面をキャプチャするには macOS の画面収録の許可が必要です。"
+ "permissionDescription": "画面をキャプチャするには macOS の画面収録の許可が必要です。",
+ "relaunchHint": "画面収録の許可は OpenWhispr の実行中に付与されました。スクリーンショットのキャプチャを開始するには、OpenWhispr を終了して再度開いてください。"
},
"modes": {
"openwhispr": "OpenWhispr Cloud",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index c5d9f170b..e33325a99 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -2972,7 +2972,8 @@
"visionModel": "Modelo de visão separado",
"visionModelDescription": "Encaminha comandos que incluem captura de tela para outro modelo com visão.",
"permissionTitle": "Gravação de tela",
- "permissionDescription": "O macOS exige permissão de gravação de tela para capturar sua tela."
+ "permissionDescription": "O macOS exige permissão de gravação de tela para capturar sua tela.",
+ "relaunchHint": "A permissão de gravação de tela foi concedida enquanto o OpenWhispr estava em execução. Feche e reabra o OpenWhispr para começar a capturar a tela."
},
"modes": {
"openwhispr": "OpenWhispr Cloud",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 08cf3c21d..d7cd920d0 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -3000,7 +3000,8 @@
"visionModel": "Отдельная модель со зрением",
"visionModelDescription": "Направляет команды со снимком экрана в другую модель, поддерживающую изображения.",
"permissionTitle": "Запись экрана",
- "permissionDescription": "macOS требует разрешение на запись экрана для создания снимков."
+ "permissionDescription": "macOS требует разрешение на запись экрана для создания снимков.",
+ "relaunchHint": "Доступ к записи экрана был предоставлен, пока OpenWhispr был запущен. Закройте и снова откройте OpenWhispr, чтобы начать делать снимки экрана."
},
"modes": {
"openwhispr": "OpenWhispr Cloud",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index a84f25e3e..ea020f94d 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -2972,7 +2972,8 @@
"visionModel": "单独的视觉模型",
"visionModelDescription": "将带截图的命令转发给另一个支持图像的模型。",
"permissionTitle": "屏幕录制",
- "permissionDescription": "macOS 需要屏幕录制权限才能截取屏幕。"
+ "permissionDescription": "macOS 需要屏幕录制权限才能截取屏幕。",
+ "relaunchHint": "屏幕录制权限是在 OpenWhispr 运行期间授予的。请退出并重新打开 OpenWhispr 以开始捕获屏幕截图。"
},
"modes": {
"openwhispr": "OpenWhispr Cloud",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 53ddd2f73..efc3e4237 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -2972,7 +2972,8 @@
"visionModel": "獨立的視覺模型",
"visionModelDescription": "將附有截圖的指令改由另一個支援影像的模型處理。",
"permissionTitle": "螢幕錄製",
- "permissionDescription": "macOS 需要螢幕錄製權限才能擷取螢幕。"
+ "permissionDescription": "macOS 需要螢幕錄製權限才能擷取螢幕。",
+ "relaunchHint": "螢幕錄製權限是在 OpenWhispr 執行期間授予的。請結束並重新開啟 OpenWhispr 以開始擷取螢幕截圖。"
},
"modes": {
"openwhispr": "OpenWhispr Cloud",
diff --git a/src/services/BaseReasoningService.ts b/src/services/BaseReasoningService.ts
index 7be70e413..c06e224b3 100644
--- a/src/services/BaseReasoningService.ts
+++ b/src/services/BaseReasoningService.ts
@@ -17,6 +17,8 @@ export interface ReasoningConfig {
disableThinking?: boolean;
/** Screenshot attached to voice-agent requests when screen context is on. */
screenContext?: ScreenContextImage;
+ /** Suffix-free prompt used when a screenshot-carrying request is retried text-only. */
+ textOnlySystemPrompt?: string;
language?: string;
requireCompleteOutput?: boolean;
requiresAgent?: boolean;
diff --git a/src/services/tools/calendarTool.ts b/src/services/tools/calendarTool.ts
index 3333b3319..462becc0a 100644
--- a/src/services/tools/calendarTool.ts
+++ b/src/services/tools/calendarTool.ts
@@ -1,4 +1,5 @@
import type { ToolDefinition, ToolResult } from "./ToolRegistry";
+import { getMeetingJoinUrl } from "../../helpers/meetingJoinUrl";
type TimeRange = "today" | "tomorrow" | "week";
@@ -22,7 +23,7 @@ function getWindowMinutes(timeRange: TimeRange): number {
export const calendarTool: ToolDefinition = {
name: "get_calendar_events",
description:
- "Get upcoming events from the user's connected calendars for a given time range. Returns event summaries, times, and locations.",
+ "Get upcoming events from the user's connected calendars for a given time range. Returns event summaries, start/end times, and meeting join links.",
parameters: {
type: "object",
properties: {
@@ -52,11 +53,14 @@ export const calendarTool: ToolDefinition = {
};
}
+ // Rows come straight from the calendar_events table (start_time/end_time
+ // columns; there is no location column — the join link is what the DB
+ // actually has for "where").
const events = response.events.map((event: Record<string, unknown>) => ({
summary: event.summary || "(No title)",
- start: event.start,
- end: event.end,
- location: event.location || null,
+ start: event.start_time,
+ end: event.end_time,
+ joinUrl: getMeetingJoinUrl(event),
}));
if (events.length === 0) {
diff --git a/src/types/electron.ts b/src/types/electron.ts
index ce29e7d33..270e095a9 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -575,6 +575,8 @@ export interface ScreenRecordingAccessResult {
granted: boolean;
status: "granted" | "denied" | "not-determined" | "restricted" | "unknown" | "unsupported";
supported: boolean;
+ /** macOS only: granted mid-session, so capture stays broken until the app relaunches. */
+ needsRelaunch?: boolean;
}
export interface ScreenContextImage {
diff --git a/test/helpers/audioManagerScreenContextRetry.test.js b/test/helpers/audioManagerScreenContextRetry.test.js
new file mode 100644
index 000000000..a83ff88cc
--- /dev/null
+++ b/test/helpers/audioManagerScreenContextRetry.test.js
@@ -0,0 +1,161 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+const MARKER_RE = /__OPENWHISPR_SELECTION_COMPLETE_[0-9a-f-]+__/;
+
+// audioManager pulls in the whole renderer graph; ReasoningService is routed
+// through a globalThis slot so each test can script its responses.
+async function loadAudioManager(t, { cachePrefix, settingsKey, reasoningKey }) {
+ const { window } = installBrowserGlobals(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix,
+ mockModules: {
+ "/utils/logger":
+ "export default { debug() {}, info() {}, warn() {}, error() {}, logReasoning() {} };",
+ "/stores/settingsStore": `
+ export const getSettings = () => globalThis.${settingsKey};
+ export const getEffectiveCleanupModel = () => null;
+ export const isCloudCleanupMode = () => false;
+ export const isCloudDictationAgentMode = () => false;
+ export const isCloudTranslationMode = () => false;
+ `,
+ "/services/ReasoningService": `
+ export default { processText: (...args) => globalThis.${reasoningKey}(...args) };
+ `,
+ "/services/SyncService.js": "export const syncService = {};",
+ "/lib/auth": "export const withSessionRefresh = (fn) => fn();",
+ "/utils/permissions": "export const isAccessibilitySkipped = () => false;",
+ },
+ });
+ t.after(() => {
+ delete globalThis[settingsKey];
+ delete globalThis[reasoningKey];
+ });
+ globalThis[settingsKey] = {};
+
+ const AudioManager = (await vite.ssrLoadModule("/helpers/audioManager.js")).default;
+ return {
+ window,
+ setProcessText: (fn) => {
+ globalThis[reasoningKey] = fn;
+ },
+ // Prototype-only instance: the constructor wires up media devices we don't need.
+ createManager: (overrides = {}) =>
+ Object.assign(Object.create(AudioManager.prototype), overrides),
+ };
+}
+
+test("a selection edit survives a rejected screenshot via the text-only retry", async (t) => {
+ const { window, setProcessText, createManager } = await loadAudioManager(t, {
+ cachePrefix: "openwhispr-sc-retry-test-",
+ settingsKey: "__scRetrySettings",
+ reasoningKey: "__scRetryProcessText",
+ });
+
+ window.electronAPI.captureSelectedText = async () => ({
+ status: "selected",
+ text: "selected body",
+ sessionId: "s1",
+ });
+
+ const processTextCalls = [];
+ setProcessText(async (text, model, agentName, config) => {
+ processTextCalls.push({ text, config });
+ if (config.screenContext) {
+ throw new Error("model rejected the image");
+ }
+ const marker = config.systemPrompt.match(MARKER_RE)?.[0] ?? "";
+ return `shorter text${marker}`;
+ });
+
+ const notices = [];
+ const manager = createManager({ onError: (notice) => notices.push(notice) });
+
+ const replacement = await manager.processAgentCommand("make it shorter", "gpt-5", "Agent", {
+ systemPrompt: "BASE PROMPT SCREEN_SUFFIX_SENTINEL",
+ textOnlySystemPrompt: "BASE PROMPT",
+ screenContext: { mediaType: "image/jpeg", data: "x" },
+ });
+
+ assert.equal(replacement, "shorter text");
+ assert.equal(processTextCalls.length, 2);
+
+ const [first, retry] = processTextCalls;
+ // Both calls carry the same selection-edit user payload and marker.
+ assert.equal(retry.text, first.text);
+ const firstMarker = first.config.systemPrompt.match(MARKER_RE)?.[0];
+ const retryMarker = retry.config.systemPrompt.match(MARKER_RE)?.[0];
+ assert.ok(firstMarker, "primary prompt must carry the completion marker");
+ assert.equal(retryMarker, firstMarker);
+ // The retry drops the image and its prompt suffix, nothing else.
+ assert.equal(retry.config.screenContext, undefined);
+ assert.equal(retry.config.textOnlySystemPrompt, undefined);
+ assert.ok(retry.config.systemPrompt.includes("SELECTION EDITING MODE"));
+ assert.ok(!retry.config.systemPrompt.includes("SCREEN_SUFFIX_SENTINEL"));
+ assert.equal(retry.config.requireCompleteOutput, true);
+
+ assert.deepEqual(
+ notices.map((n) => n.code),
+ ["SCREEN_CONTEXT_SKIPPED"]
+ );
+});
+
+test("the text-only retry swaps in the pre-built prompt verbatim", async (t) => {
+ const { setProcessText, createManager } = await loadAudioManager(t, {
+ cachePrefix: "openwhispr-sc-retry-direct-test-",
+ settingsKey: "__scRetryDirectSettings",
+ reasoningKey: "__scRetryDirectProcessText",
+ });
+
+ const prompts = [];
+ setProcessText(async (text, model, agentName, config) => {
+ prompts.push(config.systemPrompt);
+ if (config.screenContext) throw new Error("image too large");
+ return "done";
+ });
+
+ const manager = createManager({ onError: () => {} });
+ const result = await manager.processWithReasoningModel("hello", "gpt-5", "Agent", {
+ systemPrompt: "BASE PROMPT WITH SUFFIX",
+ textOnlySystemPrompt: "BASE PROMPT",
+ screenContext: { mediaType: "image/jpeg", data: "x" },
+ });
+
+ assert.equal(result, "done");
+ assert.deepEqual(prompts, ["BASE PROMPT WITH SUFFIX", "BASE PROMPT"]);
+});
+
+test("a non-voice-agent recording clears a stale screen capture", async (t) => {
+ const { createManager } = await loadAudioManager(t, {
+ cachePrefix: "openwhispr-sc-stale-test-",
+ settingsKey: "__scStaleSettings",
+ reasoningKey: "__scStaleProcessText",
+ });
+
+ const manager = createManager();
+ const stale = Promise.resolve({ mediaType: "image/jpeg", data: "stale" });
+
+ manager.screenContextPromise = stale;
+ manager.setVoiceAgentRequested(false);
+ assert.equal(manager.screenContextPromise, null);
+ assert.equal(await manager.consumeScreenContext(), null);
+
+ // A capture left by a cancelled recording never rides into the next
+ // voice-agent start either — begin() re-captures after the reset.
+ manager.screenContextPromise = stale;
+ manager.setVoiceAgentRequested(true);
+ assert.equal(manager.screenContextPromise, null);
+
+ // A fresh capture set after the start (as beginScreenContextCapture does)
+ // is consumed normally.
+ manager.screenContextPromise = Promise.resolve({ mediaType: "image/jpeg", data: "fresh" });
+ assert.deepEqual(await manager.consumeScreenContext(), {
+ mediaType: "image/jpeg",
+ data: "fresh",
+ });
+
+ // Guards the dead-code removal in getEffectiveSttLanguage.
+ manager.translationRequested = false;
+ assert.equal(manager.getEffectiveSttLanguage({ preferredLanguage: "en" }), "en");
+});
diff --git a/test/helpers/screenContextCapture.test.js b/test/helpers/screenContextCapture.test.js
index e9a175d3d..74059f284 100644
--- a/test/helpers/screenContextCapture.test.js
+++ b/test/helpers/screenContextCapture.test.js
@@ -30,7 +30,14 @@ function fakeImage(bytesAtQuality, { edge = 1568, resizes = [] } = {}) {
// branch is skipped on Linux CI and every status looks granted.
function loadCapture(t, { image, platform = "darwin", accessStatus = "granted" }) {
delete require.cache[modulePath];
- const calls = { thumbnailSizes: [] };
+ let currentAccessStatus = accessStatus;
+ const calls = {
+ thumbnailSizes: [],
+ warns: [],
+ setAccessStatus: (status) => {
+ currentAccessStatus = status;
+ },
+ };
const originalPlatform = process.platform;
Object.defineProperty(process, "platform", { value: platform, configurable: true });
@@ -55,7 +62,14 @@ function loadCapture(t, { image, platform = "darwin", accessStatus = "granted" }
return [{ display_id: "1", thumbnail: image }];
},
},
- systemPreferences: { getMediaAccessStatus: () => accessStatus },
+ systemPreferences: { getMediaAccessStatus: () => currentAccessStatus },
+ };
+ }
+ if (request.endsWith("debugLogger")) {
+ return {
+ warn: (message, meta, category) => calls.warns.push({ message, meta, category }),
+ debug: () => {},
+ info: () => {},
};
}
return originalLoad.call(this, request, parent, isMain);
@@ -115,6 +129,57 @@ test("capture is skipped when screen recording access is not granted", async (t)
assert.equal(await capture.captureCursorDisplay(), null);
assert.equal(calls.thumbnailSizes.length, 0);
+ // The skip must be diagnosable from the debug log, with the TCC status.
+ assert.deepEqual(calls.warns, [
+ {
+ message: "Screen context capture skipped",
+ meta: { accessStatus: "denied" },
+ category: "screenContext",
+ },
+ ]);
+});
+
+test("a grant made while the app is running is flagged as needing a relaunch", (t) => {
+ const { capture, calls } = loadCapture(t, {
+ image: fakeImage(() => 300_000),
+ accessStatus: "denied",
+ });
+
+ // Prime the launch-time snapshot, as ipcHandlers does at registration.
+ capture.getAccessStatus();
+ calls.setAccessStatus("granted");
+
+ assert.deepEqual(capture.getAccessResult(), {
+ granted: true,
+ status: "granted",
+ supported: true,
+ needsRelaunch: true,
+ });
+});
+
+test("a grant that predates launch never asks for a relaunch", (t) => {
+ const { capture } = loadCapture(t, { image: fakeImage(() => 300_000) });
+
+ assert.deepEqual(capture.getAccessResult(), {
+ granted: true,
+ status: "granted",
+ supported: true,
+ needsRelaunch: false,
+ });
+});
+
+test("non-macOS platforms never need a relaunch", (t) => {
+ const { capture } = loadCapture(t, {
+ image: fakeImage(() => 300_000),
+ platform: "win32",
+ });
+
+ assert.deepEqual(capture.getAccessResult(), {
+ granted: true,
+ status: "granted",
+ supported: true,
+ needsRelaunch: false,
+ });
});
test("the captured thumbnail is bounded to the vision-model edge", async (t) => {
diff --git a/test/helpers/textEditMonitorPrecedingChar.test.js b/test/helpers/textEditMonitorPrecedingChar.test.js
index 776d60620..b2bc68829 100644
--- a/test/helpers/textEditMonitorPrecedingChar.test.js
+++ b/test/helpers/textEditMonitorPrecedingChar.test.js
@@ -77,3 +77,119 @@ test(
assert.equal(m._pollInterval, null);
}
);
+
+// AXError -25212 (kAXErrorNoValue) marks apps whose AX tree never yields a
+// focused element to us (Chromium/Electron); the native binary's retry loop is
+// deterministic dead time there, so one failure routes the PID to AppleScript
+// for the rest of the session.
+test("getSelectedText caches a -25212 native failure per PID", darwinOnly, async () => {
+ const m = new TextEditMonitor();
+ m.resolveBinary = () => ({
+ command: "/bin/sh",
+ args: [
+ "-c",
+ 'echo "Attempt 1/5: Cannot get focused element for PID 42 (error: -25212)" >&2; echo "UNAVAILABLE:"; exit 1',
+ ],
+ });
+ m._getSelectedTextViaAppleScript = (pid, timeoutMs, resolve) => resolve({ state: "none" });
+
+ assert.deepEqual(await m.getSelectedText(42), { state: "none" });
+ assert.ok(m._nativeSelectionUnsupportedPids.has(42));
+});
+
+test("getSelectedText skips the native binary for a cached PID", darwinOnly, async () => {
+ const m = new TextEditMonitor();
+ // The trailing --selected-text args land in the -c script's $0/$1.
+ m.resolveBinary = () => ({ command: "/bin/sh", args: ["-c", 'echo "SELECTED:native"'] });
+ m._getSelectedTextViaAppleScript = (pid, timeoutMs, resolve) => resolve({ state: "none" });
+
+ assert.deepEqual(await m.getSelectedText(42), { state: "selected", text: "native" });
+
+ m._nativeSelectionUnsupportedPids.add(42);
+ assert.deepEqual(await m.getSelectedText(42), { state: "none" });
+});
+
+test("a non--25212 native failure is not cached", darwinOnly, async () => {
+ const m = new TextEditMonitor();
+ m.resolveBinary = () => ({
+ command: "/bin/sh",
+ args: [
+ "-c",
+ 'echo "Attempt 1/5: Cannot get focused element for PID 42 (error: -25204)" >&2; echo "UNAVAILABLE:"; exit 1',
+ ],
+ });
+ m._getSelectedTextViaAppleScript = (pid, timeoutMs, resolve) => resolve({ state: "none" });
+
+ assert.deepEqual(await m.getSelectedText(42), { state: "none" });
+ assert.equal(m._nativeSelectionUnsupportedPids.has(42), false);
+});
+
+test("a run where the AX tree woke mid-retry is not cached", darwinOnly, async () => {
+ const m = new TextEditMonitor();
+ // -25212 on attempt 1 was transient: the element resolved later, so the app
+ // must stay eligible for native reads even though this read failed.
+ m.resolveBinary = () => ({
+ command: "/bin/sh",
+ args: [
+ "-c",
+ 'echo "Attempt 1/5: Cannot get focused element for PID 42 (error: -25212)" >&2; echo "Got focused element on attempt 3" >&2; echo "UNAVAILABLE:"; exit 1',
+ ],
+ });
+ m._getSelectedTextViaAppleScript = (pid, timeoutMs, resolve) => resolve({ state: "none" });
+
+ assert.deepEqual(await m.getSelectedText(42), { state: "none" });
+ assert.equal(m._nativeSelectionUnsupportedPids.has(42), false);
+});
+
+test(
+ "a monitor run ending in NO_ELEMENT with uniform -25212 teaches the cache",
+ darwinOnly,
+ async () => {
+ const m = new TextEditMonitor();
+ m.resolveBinary = () => ({
+ command: "/bin/sh",
+ args: [
+ "-c",
+ 'echo "Attempt 5/5: Cannot get focused element for PID 4242 (error: -25212)" >&2; echo "NO_ELEMENT"',
+ ],
+ });
+
+ m.startMonitoring("pasted text", 4000, { targetPid: 4242 });
+ // The verdict lands on the child's "close" event, after monitoring stops.
+ const deadline = Date.now() + 6000;
+ while (!m._nativeSelectionUnsupportedPids.has(4242) && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 100));
+ }
+
+ assert.equal(m.currentOriginalText, null);
+ assert.ok(m._nativeSelectionUnsupportedPids.has(4242));
+ }
+);
+
+test("a timeout-killed selection read is not cached", darwinOnly, async () => {
+ const m = new TextEditMonitor();
+ // The child hangs after a -25212 line, so execFile kills it at the deadline
+ // — the ladder never completed and a later attempt might have succeeded.
+ m.resolveBinary = () => ({
+ command: "/bin/sh",
+ args: [
+ "-c",
+ 'echo "Attempt 1/5: Cannot get focused element for PID 42 (error: -25212)" >&2; sleep 5',
+ ],
+ });
+ m._getSelectedTextViaAppleScript = (pid, timeoutMs, resolve) => resolve({ state: "none" });
+
+ assert.deepEqual(await m.getSelectedText(42, 400), { state: "none" });
+ assert.equal(m._nativeSelectionUnsupportedPids.has(42), false);
+});
+
+test("startMonitoring skips the native monitor for a cached PID", darwinOnly, () => {
+ const m = new TextEditMonitor();
+ m.resolveBinary = () => ({ command: "/bin/echo", args: [] });
+ m._nativeSelectionUnsupportedPids.add(42);
+ m.startMonitoring("pasted text", 4000, { targetPid: 42 });
+ // The cache check runs before the initial settle delay, so monitoring ends
+ // synchronously — no doomed child process is ever spawned.
+ assert.equal(m.currentOriginalText, null);
+ assert.equal(m.process, null);
+});
diff --git a/test/services/calendarTool.test.js b/test/services/calendarTool.test.js
new file mode 100644
index 000000000..3cb84f6e4
--- /dev/null
+++ b/test/services/calendarTool.test.js
@@ -0,0 +1,97 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/services/tools/calendarTool.ts");
+
+// Rows shaped like the calendar_events table: start_time/end_time columns,
+// meeting links in hangout_link or conference_data — never start/end/location.
+function stubEvents(events, calls = []) {
+ global.window = {
+ electronAPI: {
+ gcalGetUpcomingEvents: async (windowMinutes) => {
+ calls.push(windowMinutes);
+ return { success: true, events };
+ },
+ },
+ };
+}
+
+test("events map the real DB columns and survive serialization", async () => {
+ const { calendarTool } = await load();
+ stubEvents([
+ {
+ summary: "Standup",
+ start_time: "2026-08-12 16:00:00",
+ end_time: "2026-08-12 16:15:00",
+ hangout_link: "https://meet.google.com/abc-defg-hij",
+ conference_data: null,
+ },
+ ]);
+
+ const result = await calendarTool.execute({ timeRange: "today" });
+
+ assert.equal(result.success, true);
+ const roundTripped = JSON.parse(JSON.stringify(result.data));
+ assert.deepEqual(roundTripped, [
+ {
+ summary: "Standup",
+ start: "2026-08-12 16:00:00",
+ end: "2026-08-12 16:15:00",
+ joinUrl: "https://meet.google.com/abc-defg-hij",
+ },
+ ]);
+});
+
+test("the join link falls back to conference_data when hangout_link is empty", async () => {
+ const { calendarTool } = await load();
+ stubEvents([
+ {
+ summary: "Design review",
+ start_time: "2026-08-12 17:00:00",
+ end_time: "2026-08-12 18:00:00",
+ hangout_link: null,
+ conference_data: JSON.stringify({
+ entryPoints: [{ entryPointType: "video", uri: "https://zoom.us/j/123456" }],
+ }),
+ },
+ ]);
+
+ const result = await calendarTool.execute({});
+
+ assert.equal(result.data[0].joinUrl, "https://zoom.us/j/123456");
+});
+
+test("no events yields an empty payload with a plain summary", async () => {
+ const { calendarTool } = await load();
+ stubEvents([]);
+
+ const result = await calendarTool.execute({ timeRange: "today" });
+
+ assert.deepEqual(result, {
+ success: true,
+ data: [],
+ displayText: "No events found for today",
+ });
+});
+
+test("an unsuccessful IPC response fails the tool call", async () => {
+ const { calendarTool } = await load();
+ global.window = {
+ electronAPI: { gcalGetUpcomingEvents: async () => ({ success: false }) },
+ };
+
+ const result = await calendarTool.execute({});
+
+ assert.equal(result.success, false);
+ assert.equal(result.displayText, "Failed to fetch calendar events");
+});
+
+test("the week range forwards a 7-day window", async () => {
+ const { calendarTool } = await load();
+ const calls = [];
+ stubEvents([], calls);
+
+ await calendarTool.execute({ timeRange: "week" });
+
+ assert.deepEqual(calls, [10080]);
+});