Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
Restore Voice Assistant auto-paste into focused inputs (#1859)
void5a0f9d906505
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 36ec893cc..66ed5bd8c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,7 @@ The chat agent and the voice agent become one Voice Assistant behind a redesigne### Voice Assistant- **One assistant, one entry point.** The separate always-on-top chat window is gone. The dictation pill is now the only surface: speak a standalone command and the answer streams into a floating panel with the chat's full toolset — notes search and editing, calendar, web search, clipboard, and memory when you're signed in — with conversations saved and resumable. Highlighted text is still edited in place. (#1597)+- **Answers return to the focused field.** With auto-paste enabled, standalone Voice Assistant answers now paste at a verified writable cursor. Without a writable cursor—or if the target changes while the answer is generated—the completed answer stays safely in the floating panel and is copied to the clipboard for manual paste; the existing Copy button confirms the automatic copy for six seconds. Empty or cancelled responses do not change the clipboard. (#1859)- **A pill that shows what it's doing.** An idle orb that grows into a recording capsule with a live, level-driven waveform and an in-capsule cancel, then a processing state that never changes shape mid-cycle. Dragging the pill no longer walks it across the screen as it resizes. (#1597)- **Your dictionary reaches the assistant.** Custom-dictionary words are injected into every assistant conversation, so replies come back using your names and jargon. (#1597)- **Follow-ups without reopening.** Type into the panel or press the hotkey again to speak into the same conversation; Esc collapses it and cancels anything in flight; Copy takes the answer in one click. (#1597)diff --git a/CLAUDE.md b/CLAUDE.mdindex 9ab951a8b..025e3949d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -652,15 +652,16 @@ Detects meetings via three independent sources, orchestrated by `MeetingDetectio### 17. Voice Assistant Hotkey-A dedicated global hotkey that starts a dictation whose transcript is sent straight to the voice assistant as a command — no wake word ("Hey [AgentName]") needed — and that always bypasses the cleanup model. Standalone commands never type at the cursor: the answer streams into a floating assistant panel attached to the dictation pill (there is no separate assistant window). The pill window is content-protected while the panel is open (the panel never appears in screen shares).+A dedicated global hotkey that starts a dictation whose transcript is sent straight to the voice assistant as a command — no wake word ("Hey [AgentName]") needed — and that always bypasses the cleanup model. Standalone commands never type at an unverified cursor: with auto-paste enabled and a writable caret verified at capture time (an opaque `caret` session in `selectionManager.js`, revalidated before pasting; terminals and fields with a live selection excluded — the native probes check the focused element's own selection state, closing the clipboard-capture blind spots), the completed answer pastes at that caret and the pill returns to idle. Otherwise the answer streams into a floating assistant panel attached to the dictation pill (there is no separate assistant window) and, with auto-paste enabled, is also copied to the clipboard for manual paste (the Copy button confirms for six seconds). The pill window is content-protected while the panel is open (the panel never appears in screen shares).**Flow**:1. Hotkey pressed → `voiceAgent` slot callback in `main.js` → `windowManager.sendToggleVoiceAgent()` → `toggle-voice-agent` IPC to the main window → recording capsule appears2. `useAudioRecording.js` starts a recording with `audioManager.setVoiceAgentRequested(true)` (any other start resets it to `false`)3. On transcription, `resolveReasoningRoute` consults `resolveDictationRouteKind()` (`src/helpers/dictationRouting.js`): a voice assistant recording always takes the agent route and never falls back to cleanup. The dictation agent's reachability only gates selection edits — a selection with the dictation agent unconfigured routes to the panel with the selected text quoted instead of editing in place-4. Standalone commands (no text selected) stream into the assistant panel (`src/components/dictation/AssistantPanel.tsx`) through the chat pipeline: chat tools (notes search/create/update, calendar, web search, clipboard), RAG memory, and the custom dictionary injected into the system prompt. Conversations persist in the `agent_conversations` table and are browsable from the ControlPanel chat-5. Selection edits are unchanged: highlighted text goes through the `dictationAgent` scope and is safely replaced in place — it never opens the panel+4. Standalone commands (no text selected) run through the chat pipeline (`src/components/dictation/AssistantPanel.tsx`): chat tools (notes search/create/update, calendar, web search, clipboard), RAG memory, and the custom dictionary injected into the system prompt. Conversations persist in the `agent_conversations` table and are browsable from the ControlPanel chat+5. Response delivery: a capture with `status: "editable"` (a focused writable non-terminal field with no selection) plus auto-paste banks a `deliverySessionId`; the completed answer is pasted via `paste-at-captured-target`, which revalidates the target and fails closed to the panel + clipboard on any change (`assistantResponseDelivery.ts`, `pasteAtCapturedTarget` in `selectionManager.js`). A follow-up spoken while the panel is already open stays panel-first. Cancelled or empty responses never paste and never touch the clipboard+6. Selection edits are unchanged: highlighted text goes through the `dictationAgent` scope and is safely replaced in place — it never opens the panel**Storage & IPC**:diff --git a/README.md b/README.mdindex 11859bec0..beeddae19 100644--- a/README.md+++ b/README.md@@ -45,7 +45,7 @@ OpenWhispr turns your voice into text, notes, and actions from your desktop. Pre- **Voice dictation** — global hotkey to dictate into any app with automatic pasting- **Dictation translation** — dedicated hotkey to dictate in one language and paste the text in another- **AI agent** — talk to GPT-5, Claude, Gemini, Groq, Tinfoil, OpenRouter, or local models with a named voice assistant-- **Voice Assistant hotkey** — dedicated hotkey that sends what you say straight to your AI assistant as a command, no wake word needed and no cleanup pass; the answer streams into a floating assistant panel, highlighted text is edited in place, and you can opt in to sending a screenshot of your current screen as context+- **Voice Assistant hotkey** — dedicated hotkey that sends what you say straight to your AI assistant as a command, no wake word needed and no cleanup pass; highlighted text is edited in place. With auto-paste enabled, answers paste at a focused text cursor or stream into a floating panel and copy to the clipboard when no writable cursor is available. You can also opt in to sending a screenshot of your current screen as context- **Meeting transcription** — auto-detect Zoom, Teams, and FaceTime calls with live speaker diarization, voice fingerprinting, and Google, Microsoft, or Apple Calendar integration- **Local speaker diarization** — on-device speaker labelling with voice fingerprint recognition across meetings, no cloud required- **Notes** — create, organize, and search notes with folders, semantic search, cloud sync, and AI actionsdiff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.mdindex ae285b159..aeab9c41a 100644--- a/TROUBLESHOOTING.md+++ b/TROUBLESHOOTING.md@@ -174,7 +174,7 @@ On GNOME and KDE, the first automatic paste can show a remote-interaction permis1. Check your chat model under Settings → AI Models → Chat (the panel runs on the chat scope); the Voice Assistant toggle only gates in-place selection edits2. Check that you have a valid API key for your selected provider3. Verify the Voice Assistant hotkey doesn't conflict with other global shortcuts-4. Remember there is no separate assistant window — answers open in a floating panel attached to the dictation pill. Press the Voice Assistant hotkey (or use the pill) and speak; if text is highlighted it is edited in place instead of opening the panel+4. Remember there is no separate assistant window. Press the Voice Assistant hotkey (or use the pill) and speak: highlighted text is edited in place; with auto-paste enabled, an answer pastes at a focused writable cursor. Without a writable cursor—or if the target changes while the answer is generated—OpenWhispr leaves the field untouched, opens the floating panel attached to the dictation pill, and copies the completed answer to the clipboard for manual paste5. For local models: ensure the model is downloaded and llama-server is running6. For Metal OOM on macOS: try a smaller local modeldiff --git a/preload.js b/preload.jsindex fd5df000f..3fdd2ebca 100644--- a/preload.js+++ b/preload.js@@ -73,9 +73,11 @@ contextBridge.exposeInMainWorld("electronAPI", {),testProviderConnection: (config) => ipcRenderer.invoke("test-provider-connection", config),pasteText: (text, options) => ipcRenderer.invoke("paste-text", text, options),- captureSelectedText: () => ipcRenderer.invoke("capture-selected-text"),+ captureSelectedText: (options) => ipcRenderer.invoke("capture-selected-text", options),replaceSelectedText: (sessionId, text, options) =>ipcRenderer.invoke("replace-selected-text", sessionId, text, options),+ pasteAtCapturedTarget: (sessionId, text, options) =>+ ipcRenderer.invoke("paste-at-captured-target", sessionId, text, options),hideWindow: () => ipcRenderer.invoke("hide-window"),showDictationPanel: () => ipcRenderer.invoke("show-dictation-panel"),captureDictationTarget: () => ipcRenderer.invoke("capture-dictation-target"),diff --git a/resources/linux-text-monitor.c b/resources/linux-text-monitor.cindex ac73c62f6..472e874d5 100644--- a/resources/linux-text-monitor.c+++ b/resources/linux-text-monitor.c@@ -10,6 +10,8 @@* INITIAL_VALUE_B64:<base64> - Initial text field value (multiline)* CHANGED:<text> - Text field value after a change* CHANGED_B64:<base64> - Text field value after a change (multiline)+ * EDITABLE - Focused element is writable with no live selection (--probe-editable)+ * NOT_EDITABLE - Focused element is not safely writable* NO_ELEMENT - Could not get focused element* NO_VALUE - Focused element has no text value*@@ -148,13 +150,15 @@ static char *read_text_value(AtspiText *text_iface) {return value;}-int main(void) {+int main(int argc, char **argv) {signal(SIGTERM, signal_handler);signal(SIGINT, signal_handler);+ int probe_editable = argc >= 2 && strcmp(argv[1], "--probe-editable") == 0;+/* Read original text from stdin (consume but don't use) */char stdin_buf[4096];- if (fgets(stdin_buf, sizeof(stdin_buf), stdin)) {+ if (!probe_editable && fgets(stdin_buf, sizeof(stdin_buf), stdin)) {/* consumed */}@@ -203,6 +207,45 @@ int main(void) {return 1;}+ if (probe_editable) {+ AtspiStateSet *states = atspi_accessible_get_state_set(focused);+ int editable = states &&+ atspi_state_set_contains(states, ATSPI_STATE_EDITABLE) &&+ atspi_state_set_contains(states, ATSPI_STATE_ENABLED) &&+ atspi_state_set_contains(states, ATSPI_STATE_FOCUSABLE) &&+ !atspi_state_set_contains(states, ATSPI_STATE_PROTECTED);+ if (states) g_object_unref(states);+ /* A shell prompt must never read as a writable caret: pasted newlines+ * execute. VTE and Qt terminals expose ATSPI_ROLE_TERMINAL; the caller+ * separately refuses terminals by executable name. */+ if (editable &&+ atspi_accessible_get_role(focused, NULL) == ATSPI_ROLE_TERMINAL) {+ editable = 0;+ }+ /* A live selection means an EDITABLE verdict would let generated text+ * paste over the user's highlighted text. This is the authoritative+ * check: the caller's clipboard-based capture cannot see a selection+ * whose text already matches the clipboard. */+ if (editable) {+ AtspiText *probe_text = atspi_accessible_get_text_iface(focused);+ if (probe_text) {+ gint n_selections = atspi_text_get_n_selections(probe_text, NULL);+ for (gint i = 0; i < n_selections && editable; i++) {+ AtspiRange *selection = atspi_text_get_selection(probe_text, i, NULL);+ if (selection) {+ if (selection->end_offset > selection->start_offset) editable = 0;+ g_free(selection);+ }+ }+ g_object_unref(probe_text);+ }+ }+ printf("%s\n", editable ? "EDITABLE" : "NOT_EDITABLE");+ fflush(stdout);+ g_object_unref(focused);+ return 0;+ }+/* Get the Text interface */AtspiText *text_iface = atspi_accessible_get_text_iface(focused);if (!text_iface) {diff --git a/resources/linux-text-monitor.py b/resources/linux-text-monitor.pyindex 82c36f575..2cfc1680f 100644--- a/resources/linux-text-monitor.py+++ b/resources/linux-text-monitor.py@@ -65,11 +65,14 @@ def _emit_text(prefix, value):def main():+ probe_editable = len(sys.argv) >= 2 and sys.argv[1] == "--probe-editable"+# Read original text from stdin (consume but don't use in this binary)- try:- sys.stdin.readline()- except Exception:- pass+ if not probe_editable:+ try:+ sys.stdin.readline()+ except Exception:+ passif not HAS_ATSPI:print("NO_ELEMENT", flush=True)@@ -97,6 +100,44 @@ def main():print("NO_ELEMENT", flush=True)sys.exit(1)+ if probe_editable:+ try:+ states = focused.get_state_set()+ editable = (+ states.contains(Atspi.StateType.EDITABLE)+ and states.contains(Atspi.StateType.ENABLED)+ and states.contains(Atspi.StateType.FOCUSABLE)+ and not states.contains(Atspi.StateType.PROTECTED)+ )+ except Exception:+ editable = False+ # A shell prompt must never read as a writable caret: pasted newlines+ # execute. VTE and Qt terminals expose the TERMINAL role; the caller+ # separately refuses terminals by executable name.+ if editable:+ try:+ if focused.get_role() == Atspi.Role.TERMINAL:+ editable = False+ except Exception:+ pass+ # A live selection means an EDITABLE verdict would let generated text+ # paste over the user's highlighted text. This is the authoritative+ # check: the caller's clipboard-based capture cannot see a selection+ # whose text already matches the clipboard.+ if editable:+ try:+ text_iface = focused.get_text_iface()+ if text_iface:+ for i in range(text_iface.get_n_selections()):+ selection = text_iface.get_selection(i)+ if selection and selection.end_offset > selection.start_offset:+ editable = False+ break+ except Exception:+ pass+ print("EDITABLE" if editable else "NOT_EDITABLE", flush=True)+ sys.exit(0)+# Check if the element supports the Text interfacetry:text_iface = focused.get_text_iface()diff --git a/resources/macos-text-monitor.swift b/resources/macos-text-monitor.swiftindex ca7f1dd4a..1048acdf3 100644--- a/resources/macos-text-monitor.swift+++ b/resources/macos-text-monitor.swift@@ -31,6 +31,65 @@ func writeTextOutput(_ prefix: String, _ value: String) {writeOutput("\(prefix):\(truncated)")}+func isEditableTextElement(_ element: AXUIElement) -> Bool {+ // A live selection means an editable verdict would let generated text+ // paste over the user's highlighted text (--editable-target mode probes+ // an element whose selection state the caller could not read itself).+ var selectedTextValue: AnyObject?+ if AXUIElementCopyAttributeValue(+ element,+ kAXSelectedTextAttribute as CFString,+ &selectedTextValue+ ) == .success, let selectedText = selectedTextValue as? String, !selectedText.isEmpty {+ return false+ }++ var enabledValue: AnyObject?+ if AXUIElementCopyAttributeValue(+ element,+ kAXEnabledAttribute as CFString,+ &enabledValue+ ) == .success, let enabled = enabledValue as? Bool, !enabled {+ return false+ }++ var subroleValue: AnyObject?+ if AXUIElementCopyAttributeValue(+ element,+ kAXSubroleAttribute as CFString,+ &subroleValue+ ) == .success, subroleValue as? String == "AXSecureTextField" {+ return false+ }++ var roleValue: AnyObject?+ guard AXUIElementCopyAttributeValue(+ element,+ kAXRoleAttribute as CFString,+ &roleValue+ ) == .success, let role = roleValue as? String,+ ["AXTextField", "AXTextArea", "AXComboBox"].contains(role)+ else {+ return false+ }++ var settable = DarwinBoolean(false)+ if AXUIElementIsAttributeSettable(+ element,+ kAXValueAttribute as CFString,+ &settable+ ) == .success, settable.boolValue {+ return true+ }++ settable = DarwinBoolean(false)+ return AXUIElementIsAttributeSettable(+ element,+ kAXSelectedTextAttribute as CFString,+ &settable+ ) == .success && settable.boolValue+}+func readCurrentValue() -> String? {guard let element = monitoredElement else { return nil }var value: AnyObject?@@ -52,17 +111,20 @@ func observerCallback(// Usage: macos-text-monitor <pid>// macos-text-monitor --selected-text <pid>+// macos-text-monitor --editable-target <pid>// macos-text-monitor --window-bounds <pid>let selectionReadMode = CommandLine.arguments.count >= 3 &&CommandLine.arguments[1] == "--selected-text"+let editableTargetMode = CommandLine.arguments.count >= 3 &&+ CommandLine.arguments[1] == "--editable-target"let windowBoundsMode = CommandLine.arguments.count >= 3 &&CommandLine.arguments[1] == "--window-bounds"-let pidArgumentIndex = selectionReadMode || windowBoundsMode ? 2 : 1+let pidArgumentIndex = selectionReadMode || editableTargetMode || windowBoundsMode ? 2 : 1guard CommandLine.arguments.count > pidArgumentIndex,let targetPid = Int32(CommandLine.arguments[pidArgumentIndex]),targetPid > 0 else {- writeError("Usage: macos-text-monitor [--selected-text|--window-bounds] <pid>")+ writeError("Usage: macos-text-monitor [--selected-text|--editable-target|--window-bounds] <pid>")writeOutput("NO_ELEMENT")exit(1)}@@ -106,7 +168,7 @@ if windowBoundsMode {// spawned via execFile, which keeps stdin open without writing — blocking on// readLine there would hang until the caller's timeout kills the process.var originalText = ""-if !selectionReadMode, let line = readLine(strippingNewline: true) {+if !selectionReadMode && !editableTargetMode, let line = readLine(strippingNewline: true) {originalText = line}@@ -144,6 +206,11 @@ guard let resolvedElement = focusedElement else {exit(1)}+if editableTargetMode {+ writeOutput(isEditableTextElement(resolvedElement) ? "EDITABLE" : "NOT_EDITABLE")+ exit(0)+}+// Selection capture is a short-lived, read-only mode used before an AI edit.// It deliberately uses the same AX client as the monitor so a packaged app's// trusted native helper does not need to rely on System Events automation.@@ -157,7 +224,7 @@ if selectionReadMode {if selectionResult == .success, let selection = selectionValue as? String {if selection.isEmpty {- writeOutput("NONE:")+ writeOutput(isEditableTextElement(resolvedElement) ? "EDITABLE_NONE:" : "NONE:")} else {writeTextOutput("SELECTED", selection)}diff --git a/resources/windows-text-monitor.c b/resources/windows-text-monitor.cindex 6f844b2e5..108093d0c 100644--- a/resources/windows-text-monitor.c+++ b/resources/windows-text-monitor.c@@ -10,6 +10,8 @@* INITIAL_VALUE_B64:<base64> - Initial text field value (multiline)* CHANGED:<text> - Text field value after a change* CHANGED_B64:<base64> - Text field value after a change (multiline)+ * EDITABLE - Focused element is writable with no live selection (--probe-editable)+ * NOT_EDITABLE - Focused element is not safely writable* NO_ELEMENT - Could not get focused element* NO_VALUE - Focused element has no text value*@@ -117,13 +119,72 @@ static BSTR read_text_pattern_value(IUIAutomationTextPattern *tp) {return text;}-int main(void) {+static int text_pattern_is_writable(IUIAutomationTextPattern *tp) {+ IUIAutomationTextRange *range = NULL;+ if (FAILED(IUIAutomationTextPattern_get_DocumentRange(tp, &range)) || !range) return 0;++ VARIANT read_only;+ VariantInit(&read_only);+ HRESULT hr = IUIAutomationTextRange_GetAttributeValue(+ range,+ UIA_IsReadOnlyAttributeId,+ &read_only+ );+ int writable = SUCCEEDED(hr) && read_only.vt == VT_BOOL &&+ read_only.boolVal == VARIANT_FALSE;+ VariantClear(&read_only);+ IUIAutomationTextRange_Release(range);+ return writable;+}++/* A live selection means an EDITABLE verdict would let generated text paste+ * over the user's highlighted text, so the probe must refuse it. This is the+ * authoritative check: the caller's clipboard-based capture cannot see a+ * selection whose text already matches the clipboard. */+static int text_pattern_has_selection(IUIAutomationTextPattern *tp) {+ IUIAutomationTextRangeArray *ranges = NULL;+ if (FAILED(IUIAutomationTextPattern_GetSelection(tp, &ranges)) || !ranges) return 0;++ int has_selection = 0;+ int length = 0;+ IUIAutomationTextRangeArray_get_Length(ranges, &length);+ for (int i = 0; i < length && !has_selection; i++) {+ IUIAutomationTextRange *range = NULL;+ if (FAILED(IUIAutomationTextRangeArray_GetElement(ranges, i, &range)) || !range) continue;+ BSTR text = NULL;+ if (SUCCEEDED(IUIAutomationTextRange_GetText(range, 1, &text)) && text) {+ has_selection = text[0] != L'\0';+ SysFreeString(text);+ }+ IUIAutomationTextRange_Release(range);+ }+ IUIAutomationTextRangeArray_Release(ranges);+ return has_selection;+}++/* An element without a Text pattern cannot report its selection; the verdict+ * stands because the copy-based capture works normally for those controls. */+static int focused_has_selection(IUIAutomationElement *focused) {+ IUIAutomationTextPattern *tp = NULL;+ HRESULT hr = IUIAutomationElement_GetCurrentPatternAs(+ focused, UIA_TextPatternId,+ &IID_IUIAutomationTextPattern, (void **)&tp+ );+ if (FAILED(hr) || !tp) return 0;+ int has_selection = text_pattern_has_selection(tp);+ IUIAutomationTextPattern_Release(tp);+ return has_selection;+}++int main(int argc, char **argv) {signal(SIGTERM, signal_handler);signal(SIGINT, signal_handler);+ int probe_editable = argc >= 2 && strcmp(argv[1], "--probe-editable") == 0;+/* Read original text from stdin (consume but don't use) */char stdin_buf[4096];- if (fgets(stdin_buf, sizeof(stdin_buf), stdin)) {+ if (!probe_editable && fgets(stdin_buf, sizeof(stdin_buf), stdin)) {/* consumed */}@@ -162,6 +223,15 @@ int main(void) {return 1;}+ BOOL isEnabled = FALSE;+ BOOL isKeyboardFocusable = FALSE;+ BOOL isPassword = TRUE;+ if (probe_editable) {+ IUIAutomationElement_get_CurrentIsEnabled(focused, &isEnabled);+ IUIAutomationElement_get_CurrentIsKeyboardFocusable(focused, &isKeyboardFocusable);+ IUIAutomationElement_get_CurrentIsPassword(focused, &isPassword);+ }+/* Try to get the Value pattern, then fall back to Text pattern */IUIAutomationValuePattern *valuePattern = NULL;IUIAutomationTextPattern *textPattern = NULL;@@ -171,6 +241,24 @@ int main(void) {&IID_IUIAutomationValuePattern, (void **)&valuePattern);+ if (probe_editable && SUCCEEDED(hr) && valuePattern) {+ BOOL isReadOnly = TRUE;+ HRESULT readOnlyResult = IUIAutomationValuePattern_get_CurrentIsReadOnly(+ valuePattern,+ &isReadOnly+ );+ int editable = isEnabled && isKeyboardFocusable && !isPassword &&+ SUCCEEDED(readOnlyResult) && !isReadOnly &&+ !focused_has_selection(focused);+ printf("%s\n", editable ? "EDITABLE" : "NOT_EDITABLE");+ fflush(stdout);+ IUIAutomationValuePattern_Release(valuePattern);+ IUIAutomationElement_Release(focused);+ IUIAutomation_Release(automation);+ CoUninitialize();+ return 0;+ }+BSTR lastValue = NULL;if (SUCCEEDED(hr) && valuePattern) {@@ -194,6 +282,22 @@ int main(void) {&IID_IUIAutomationTextPattern, (void **)&textPattern);if (SUCCEEDED(hr) && textPattern) {+ if (probe_editable) {+ CONTROLTYPEID controlType = 0;+ IUIAutomationElement_get_CurrentControlType(focused, &controlType);+ int editable = isEnabled && isKeyboardFocusable && !isPassword &&+ text_pattern_is_writable(textPattern) &&+ !text_pattern_has_selection(textPattern) &&+ (controlType == UIA_EditControlTypeId ||+ controlType == UIA_DocumentControlTypeId);+ printf("%s\n", editable ? "EDITABLE" : "NOT_EDITABLE");+ fflush(stdout);+ IUIAutomationTextPattern_Release(textPattern);+ IUIAutomationElement_Release(focused);+ IUIAutomation_Release(automation);+ CoUninitialize();+ return 0;+ }lastValue = read_text_pattern_value(textPattern);if (lastValue) {useTextPattern = 1;@@ -201,7 +305,7 @@ int main(void) {}}if (!useTextPattern) {- printf("NO_VALUE\n");+ printf("%s\n", probe_editable ? "NOT_EDITABLE" : "NO_VALUE");fflush(stdout);if (textPattern) IUIAutomationTextPattern_Release(textPattern);IUIAutomationElement_Release(focused);diff --git a/scripts/build-windows-text-monitor.js b/scripts/build-windows-text-monitor.jsindex 16845082d..dd25813e5 100644--- a/scripts/build-windows-text-monitor.js+++ b/scripts/build-windows-text-monitor.js@@ -2,11 +2,6 @@/*** Ensures the Windows text monitor binary is available.*- * Strategy:- * 1. If binary exists and is up-to-date, do nothing- * 2. Try to download prebuilt binary from GitHub releases- * 3. Fall back to local compilation if download fails- ** This allows developers without a C compiler to still build the app.*/@@ -161,13 +156,13 @@ async function main() {return;}- const downloaded = await tryDownload();- if (downloaded) {+ const compiled = tryCompile();+ if (compiled) {return;}- const compiled = tryCompile();- if (compiled) {+ const downloaded = await tryDownload();+ if (downloaded) {return;}diff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.tsindex 387301e00..b986cacf9 100644--- a/src/components/chat/useChatStreaming.ts+++ b/src/components/chat/useChatStreaming.ts@@ -79,6 +79,14 @@ export interface SendToAIOptions {attachment?: ChatImageAttachment;/** Agent-response selection attached to this request without changing chat history. */selectedContext?: AgentSelectionContext;+ /** Keeps a caret-destined voice response in the compact pill while it streams. */+ suppressResponseContent?: boolean;+ /** Per-request completion hook used to deliver a finished voice response. */+ onComplete?: (result: {+ assistantId: string;+ content: string;+ toolCalls?: ToolCallInfo[];+ }) => void | Promise<void>;}export interface ChatStreaming {@@ -184,8 +192,16 @@ export function useChatStreaming({}, [messages]);const sendGenerationRef = useRef(0);+ // Generation stamped by the most recent cancel issued while still mounted+ // (Esc, a Stop button). The unmount cleanup below flips mountedRef off+ // before routing through cancelStream, so it never stamps this — which is+ // how sendToAI tells a user's cancel from an unmount mid-stream.+ const explicitCancelGenerationRef = useRef(0);const cancelStream = useCallback(() => {sendGenerationRef.current += 1;+ if (mountedRef.current) {+ explicitCancelGenerationRef.current = sendGenerationRef.current;+ }ReasoningService.cancelActiveStream();setAgentState("idle");clearToolActivity();@@ -214,7 +230,7 @@ export function useChatStreaming({const announceResponse = () => {if (responseAnnounced) return;responseAnnounced = true;- onResponseContent?.();+ if (!options?.suppressResponseContent) onResponseContent?.();};const settings = getSettings();const chatConfig = selectResolvedLLMConfig(settings, "chatIntelligence");@@ -485,6 +501,26 @@ export function useChatStreaming({}}+ if (cancelled() || !mountedRef.current) {+ setMessages((prev) =>+ prev.map((message) =>+ message.id === assistantId ? { ...message, isStreaming: false } : message+ )+ );+ // An unmount mid-stream (page navigation) keeps the partial reply in+ // history so the saved conversation matches what the user last saw;+ // an explicit cancel drops it. The unmount cleanup cancels too, so+ // cancelled() alone cannot tell the two apart. Neither path may run+ // the per-request delivery hook.+ const explicitlyCancelled = explicitCancelGenerationRef.current > sendGeneration;+ if (!explicitlyCancelled && fullContent.trim().length > 0) {+ const finalMsg = messagesRef.current.find((m) => m.id === assistantId);+ onStreamComplete?.(assistantId, fullContent, finalMsg?.toolCalls);+ }+ return;+ }++ const hasDeliverableContent = fullContent.trim().length > 0;if (!responseAnnounced && !cancelled()) {// The stream ended without a visible token or tool call (think-only// local model, empty completion). Show that as a reply so every@@ -503,6 +539,13 @@ export function useChatStreaming({const finalMsg = messagesRef.current.find((m) => m.id === assistantId);onStreamComplete?.(assistantId, fullContent, finalMsg?.toolCalls);+ if (hasDeliverableContent) {+ await options?.onComplete?.({+ assistantId,+ content: fullContent,+ toolCalls: finalMsg?.toolCalls,+ });+ }} catch (error) {if (cancelled()) {setMessages((prev) =>diff --git a/src/components/dictation/AssistantPanel.tsx b/src/components/dictation/AssistantPanel.tsxindex 2db9173e9..de2d4735d 100644--- a/src/components/dictation/AssistantPanel.tsx+++ b/src/components/dictation/AssistantPanel.tsx@@ -33,23 +33,31 @@ import {resolveAssistantPanelBusy,restoreAssistantConversation,} from "../../helpers/assistantSessionState";+import {+ deliverAssistantResponse,+ type AssistantResponseDelivery,+} from "../../helpers/assistantResponseDelivery";export interface AssistantCommand {id: number;text: string;attachment: ChatImageAttachment | null;selectedContext: AgentSelectionContext | null;+ delivery: AssistantResponseDelivery | null;}type AssistantFooterPhase ="pill" | "pill-entering" | "pill-exiting" | "actions-entering" | "actions" | "actions-exiting";+const MANUAL_COPY_FEEDBACK_MS = 1800;+const AUTO_COPY_FEEDBACK_MS = 6000;+interface AssistantPanelProps {/** Voice command waiting to be sent into the conversation (consumed on mount and on change). */pendingCommand: AssistantCommand | null;onCommandConsumed: (id: number) => void;onCommandDiscarded: (id: number) => void;- onCommandSettled: (id: number) => void;+ onCommandSettled: (id: number, options?: { showPanel?: boolean }) => void;/** Conversation to resume when reopening the panel; null starts fresh on first message. */initialConversationId: number | null;onConversationIdChange: (id: number | null) => void;@@ -106,7 +114,7 @@ export function AssistantPanel({messages,setMessages,onStreamComplete: (_assistantId, content, toolCalls) => {- persistence.saveAssistantMessage(content, toolCalls);+ void persistence.saveAssistantMessage(content, toolCalls);},onResponseContent,});@@ -127,6 +135,17 @@ export function AssistantPanel({createConversation,onSendingChange: setSubmissionInFlight,});+ const latestAssistantMessage = [...messages]+ .reverse()+ .find((message) => message.role === "assistant");+ const responseContent = latestAssistantMessage?.content ?? "";+ const {+ copied,+ copy: handleCopy,+ confirmCopied,+ } = useCopyFeedback(responseContent, {+ resetMs: MANUAL_COPY_FEEDBACK_MS,+ });useEffect(() => {onConversationIdChange(persistence.conversationId);@@ -171,6 +190,9 @@ export function AssistantPanel({}consumedCommandIdRef.current = pendingCommand.id;const commandId = pendingCommand.id;+ const delivery = pendingCommand.delivery;+ const targetsCapturedInput = delivery?.mode === "paste";+ let responseDelivered = false;if (pendingCommand.selectedContext) {setSelectedContext(null);onSelectionContextChange(null);@@ -178,6 +200,14 @@ export function AssistantPanel({void sendMessage(pendingCommand.text, {attachment: pendingCommand.attachment ?? undefined,selectedContext: pendingCommand.selectedContext ?? undefined,+ suppressResponseContent: targetsCapturedInput,+ onComplete: delivery+ ? async ({ content }) => {+ const result = await deliverAssistantResponse(delivery, content);+ responseDelivered = result.pasted;+ if (result.copied) confirmCopied(content, AUTO_COPY_FEEDBACK_MS);+ }+ : undefined,}).then((sent) => {if (sent) {@@ -206,7 +236,7 @@ export function AssistantPanel({},]);})- .finally(() => onCommandSettled(commandId));+ .finally(() => onCommandSettled(commandId, { showPanel: !responseDelivered }));}, [historyReady,submissionInFlight,@@ -215,6 +245,7 @@ export function AssistantPanel({onCommandDiscarded,onCommandSettled,onSelectionContextChange,+ confirmCopied,sendMessage,setMessages,t,@@ -245,10 +276,6 @@ export function AssistantPanel({return () => onBusyChange(false);}, [isBusy, onBusyChange]);- const latestAssistantMessage = [...messages]- .reverse()- .find((message) => message.role === "assistant");- const responseContent = latestAssistantMessage?.content ?? "";const displayedResponseRef = useRef("");if (responseContent) displayedResponseRef.current = responseContent;const displayedResponse = responseContent || displayedResponseRef.current;@@ -263,7 +290,6 @@ export function AssistantPanel({voiceState,requestPending: thinking || pendingCommand != null,});- const { copied, copy: handleCopy } = useCopyFeedback(responseContent, { resetMs: 1800 });const responseSelectionRootRef = useRef<HTMLDivElement | null>(null);const [selectedContext, setSelectedContext] = useState<AgentSelectionContext | null>(null);diff --git a/src/helpers/assistantResponseDelivery.ts b/src/helpers/assistantResponseDelivery.tsnew file mode 100644index 000000000..a6b24f029--- /dev/null+++ b/src/helpers/assistantResponseDelivery.ts@@ -0,0 +1,90 @@+export type AssistantResponseDelivery =+ | {+ mode: "paste";+ sessionId: string;+ restoreClipboard: boolean;+ allowClipboardFallback: boolean;+ }+ | { mode: "clipboard" };++interface AssistantResponseDeliveryApi {+ pasteAtCapturedTarget?: (+ sessionId: string,+ text: string,+ options?: { restoreClipboard?: boolean; allowClipboardFallback?: boolean }+ ) => Promise<{ success: boolean }>;+ writeClipboard?: (text: string) => Promise<{ success: boolean }>;+}++interface ClipboardWriter {+ writeText: (text: string) => Promise<void>;+}++interface AssistantResponseDeliveryDependencies {+ electronAPI?: AssistantResponseDeliveryApi;+ clipboard?: ClipboardWriter;+}++export function createAssistantResponseDelivery({+ autoPasteEnabled,+ deliverySessionId,+ restoreClipboard,+ allowClipboardFallback,+}: {+ autoPasteEnabled: boolean;+ deliverySessionId?: string;+ restoreClipboard: boolean;+ allowClipboardFallback: boolean;+}): AssistantResponseDelivery | null {+ if (!autoPasteEnabled) return null;+ if (!deliverySessionId) return { mode: "clipboard" };++ return {+ mode: "paste",+ sessionId: deliverySessionId,+ restoreClipboard,+ allowClipboardFallback,+ };+}++async function copyAssistantResponse(+ content: string,+ electronAPI: AssistantResponseDeliveryApi | undefined,+ clipboard: ClipboardWriter | undefined+): Promise<boolean> {+ try {+ const result = await electronAPI?.writeClipboard?.(content);+ if (result?.success === true) return true;+ } catch {}++ try {+ await clipboard?.writeText(content);+ return Boolean(clipboard);+ } catch {+ return false;+ }+}++export async function deliverAssistantResponse(+ delivery: AssistantResponseDelivery,+ content: string,+ dependencies: AssistantResponseDeliveryDependencies = {}+): Promise<{ pasted: boolean; copied: boolean }> {+ const electronAPI = dependencies.electronAPI ?? window.electronAPI;+ const clipboard = dependencies.clipboard ?? navigator.clipboard;++ if (delivery.mode === "paste") {+ try {+ const result = await electronAPI?.pasteAtCapturedTarget?.(delivery.sessionId, content, {+ restoreClipboard: delivery.restoreClipboard,+ allowClipboardFallback: delivery.allowClipboardFallback,+ });+ if (result?.success === true) return { pasted: true, copied: false };+ } catch {}+ }++ return {+ pasted: false,+ copied: await copyAssistantResponse(content, electronAPI, clipboard),+ };+}diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex 65c84e70f..32c6c20e9 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -770,9 +770,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}// Kicked off at voice-agent recording start, alongside the screenshot, so the- // read resolves while the user is still speaking.+ // read resolves while the user is still speaking. The editable-caret probe+ // only matters when auto-paste could deliver to that caret, so the flag+ // spares the main process a binary spawn otherwise.beginSelectionCapture() {- this.selectionCapturePromise = window.electronAPI?.captureSelectedText?.() ?? null;+ this.selectionCapturePromise =+ window.electronAPI?.captureSelectedText?.({+ probeEditable: Boolean(getSettings().autoPasteEnabled),+ }) ?? null;// Marks the stored promise handled without consuming it: a failure nobody is// awaiting yet must not surface as an unhandled rejection, and the awaiting// caller must still see the original error.@@ -782,7 +787,12 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);consumeSelectionCapture() {const pending = this.selectionCapturePromise;this.selectionCapturePromise = null;- return pending ?? window.electronAPI?.captureSelectedText?.();+ return (+ pending ??+ window.electronAPI?.captureSelectedText?.({+ probeEditable: Boolean(getSettings().autoPasteEnabled),+ })+ );}async consumeScreenContext() {@@ -2356,8 +2366,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// the chat's tools and memory once transcription completes; nothing types// at the cursor. The transcript flows back as the result text so history// and previews stay truthful.- _bankAssistantDirective(transcript, config, selectedContext) {+ _bankAssistantDirective(transcript, config, options = {}) {if (!this.isProcessing) return;+ const { selectedContext, deliverySessionId } = options || {};this.pendingAssistantConversation = {transcript,// resolveReasoningRoute mirrors an attached screenContext into@@ -2366,6 +2377,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// the image (the panel re-decides against the chat scope's model).screenContext: config?.rawScreenContext ?? null,...(selectedContext ? { selectedContext } : {}),+ ...(deliverySessionId ? { deliverySessionId } : {}),};}@@ -2385,13 +2397,18 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// Panel-first commands skip the dictation-agent model, so the org policy// guard that protected that model must run here instead.- _bankPanelAgentCommand(text, agentName, config, selectedContext, selectedText) {+ _bankPanelAgentCommand(+ text,+ agentName,+ config,+ { selectedContext, selectedText, deliverySessionId } = {}+ ) {this.assertAgentAllowedByPolicy();const command = this.voiceAgentRequested? text: stripAgentAddress(text, agentName, resolveWakeWordLanguage(getSettings()));const transcript = selectedText === undefined ? command : `${command}\n\n"${selectedText}"`;- this._bankAssistantDirective(transcript, config, selectedContext);+ this._bankAssistantDirective(transcript, config, { selectedContext, deliverySessionId });return text;}@@ -2403,7 +2420,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// target. Keep it on the existing panel-first route and leave the// external selection replacement path completely untouched.this.selectionCapturePromise = null;- return this._bankPanelAgentCommand(text, agentName, config, assistantSelectionContext);+ return this._bankPanelAgentCommand(text, agentName, config, {+ selectedContext: assistantSelectionContext,+ });}let capture;@@ -2422,19 +2441,21 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);if (wasCancelled()) return text;const captureDisposition = getSelectionCaptureDisposition(capture);+ const deliverySessionId =+ captureDisposition === "caret" && getSettings().autoPasteEnabled+ ? capture.sessionId+ : undefined;if (!config?.selectionEditReachable) {// No in-place editor: the panel never types, so only a readable// selection is quoted; every other capture sends the plain command.- return this._bankPanelAgentCommand(- text,- agentName,- config,- undefined,- captureDisposition === "selection" && typeof capture?.text === "string"- ? capture.text- : undefined- );+ return this._bankPanelAgentCommand(text, agentName, config, {+ selectedText:+ captureDisposition === "selection" && typeof capture?.text === "string"+ ? capture.text+ : undefined,+ deliverySessionId,+ });}if (capture?.status === "too_large") {@@ -2450,8 +2471,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);throw error;}- if (captureDisposition === "standalone") {- return this._bankPanelAgentCommand(text, agentName, config);+ if (captureDisposition === "standalone" || captureDisposition === "caret") {+ return this._bankPanelAgentCommand(text, agentName, config, { deliverySessionId });}if (capture?.status !== "selected") {diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.jsindex 4a550243d..b07096f31 100644--- a/src/helpers/clipboard.js+++ b/src/helpers/clipboard.js@@ -913,7 +913,7 @@ class ClipboardManager {this.safeLog("⚠️ No accessibility permissions - text copied to clipboard only");if (allowClipboardFallback) {this.safeLog("✅ Clipboard fallback used (manual paste required)");- return { restoreComplete: Promise.resolve() };+ return { restoreComplete: Promise.resolve(), pasted: false };}const errorMsg ="Accessibility permissions required for automatic pasting. Text has been copied to clipboard - please paste manually with Cmd+V.";diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex c10cb38b0..e041cd0dc 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -2679,11 +2679,13 @@ class IPCHandlers {}});- ipcMain.handle("capture-selected-text", async () => {+ ipcMain.handle("capture-selected-text", async (event, options = {}) => {if (!this.selectionManager) {return { status: "unavailable", code: "selection_manager_unavailable" };}- return this.selectionManager.captureSelectedText();+ return this.selectionManager.captureSelectedText({+ probeEditable: options.probeEditable === true,+ });});ipcMain.handle("replace-selected-text", async (event, sessionId, text, options = {}) => {@@ -2697,6 +2699,17 @@ class IPCHandlers {});});+ ipcMain.handle("paste-at-captured-target", async (event, sessionId, text, options = {}) => {+ if (!this.selectionManager) {+ return { success: false, code: "selection_manager_unavailable" };+ }+ return this.selectionManager.pasteAtCapturedTarget(sessionId, text, {+ restoreClipboard: options.restoreClipboard !== false,+ allowClipboardFallback: options.allowClipboardFallback === true,+ webContents: event.sender,+ });+ });+ipcMain.handle("paste-text", async (event, text, options) => {// An onboarding demo already puts the transcript in its own textarea from// the demo event, and that textarea is what has focus — pasting on top ofdiff --git a/src/helpers/selectionEditing.js b/src/helpers/selectionEditing.jsindex 6e7bd7e89..f783b772a 100644--- a/src/helpers/selectionEditing.js+++ b/src/helpers/selectionEditing.js@@ -22,10 +22,6 @@ export function buildSelectionEditUserPrompt(spokenInstruction, selectedText) {});}-// Codes meaning "this target can never report a selection", as opposed to "a-// selection may exist and the read failed". They fall back to typing at the-// cursor — the Voice Agent's behavior before selection editing existed — because-// losing in-place editing is acceptable where losing the command is not.const STANDALONE_CAPTURE_CODES = new Set(["target_unavailable","copy_helper_unavailable",@@ -37,6 +33,7 @@ const STANDALONE_CAPTURE_CODES = new Set([]);export function getSelectionCaptureDisposition(capture) {+ if (capture?.status === "editable") return "caret";if (!capture || capture.status === "none") return "standalone";if (capture.status === "selected") return "selection";if (capture.status === "unavailable" && STANDALONE_CAPTURE_CODES.has(capture.code)) {diff --git a/src/helpers/selectionManager.js b/src/helpers/selectionManager.jsindex 603b184a5..0d80fe5f9 100644--- a/src/helpers/selectionManager.js+++ b/src/helpers/selectionManager.js@@ -9,10 +9,6 @@ const MAX_SELECTION_EDIT_CODE_POINTS = 6000;// re-verifying — the accepted cost of failing closed rather than pasting blind.const COPY_TIMEOUT_MS = 1200;const CLIPBOARD_POLL_MS = 20;-// The AT-SPI desktop scan takes ~600ms idle on KDE Wayland and over 1s under-// recording-start load or through Flatpak's xdg-dbus-proxy; a tighter timeout-// kills the probe with the target already on stdout and the capture falls-// back to standalone dictation, pasting over the selection.const ATSPI_TARGET_TIMEOUT_MS = 2000;// Editors that copy the whole current line when Ctrl+C (⌘C on macOS) lands with@@ -134,6 +130,7 @@ class SelectionManager {id: match[1],windowClass: result.stdout.match(/^WINDOW_CLASS (.+)$/m)?.[1]?.trim() || null,exeName: result.stdout.match(/^EXE_NAME (.+)$/m)?.[1]?.trim() || null,+ isTerminal: /^IS_TERMINAL true$/m.test(result.stdout),}: null;}@@ -154,7 +151,10 @@ class SelectionManager {return this.lastTarget?.kind === "win-hwnd" ? this.lastTarget.id : null;}- async captureSelectedText() {+ async captureSelectedText(options = {}) {+ // The caller knows whether a caret capture could ever be used (auto-paste+ // on); without it the probe's binary spawn would be pure waste.+ const probeEditable = options.probeEditable === true;return this.clipboardManager.runClipboardOperation(async () => {// captureTarget() fires on every toggle press, including stop. Fast// cloud transcription can get here before the stop-press probe lands@@ -172,7 +172,16 @@ class SelectionManager {if (!expectedTarget) {return { status: "unavailable", code: "target_unavailable" };}- const capture = await this._readCurrentSelection(expectedTarget);+ const capture = await this._readCurrentSelection(expectedTarget, { probeEditable });+ if (capture.status === "editable") {+ const sessionId = crypto.randomUUID();+ this.sessions.set(sessionId, {+ kind: "caret",+ target: capture.target,+ expiresAt: this.now() + SESSION_TTL_MS,+ });+ return { status: "editable", sessionId };+ }if (capture.status !== "selected") return capture;const characterCount = [...capture.text].length;@@ -186,6 +195,7 @@ class SelectionManager {const sessionId = crypto.randomUUID();this.sessions.set(sessionId, {+ kind: "selection",text: capture.text,target: capture.target,expiresAt: this.now() + SESSION_TTL_MS,@@ -208,7 +218,9 @@ class SelectionManager {this._pruneSessions();const session = this.sessions.get(sessionId);this.sessions.delete(sessionId);- if (!session) return { success: false, code: "session_expired" };+ if (!session || session.kind !== "selection") {+ return { success: false, code: "session_expired" };+ }const current = await this._readCurrentSelection(session.target, { activate: true });if (current.status === "target_changed") {@@ -227,6 +239,9 @@ class SelectionManager {restoreClipboard: options.restoreClipboard !== false,});await pasteResult?.restoreComplete;+ if (pasteResult?.pasted === false) {+ return { success: false, code: "paste_failed" };+ }return { success: true };} catch (error) {debugLogger.warn(@@ -239,6 +254,42 @@ class SelectionManager {});}+ async pasteAtCapturedTarget(sessionId, text, options = {}) {+ if (typeof text !== "string" || text.length === 0) {+ return { success: false, code: "invalid_replacement" };+ }++ return this.clipboardManager.runClipboardOperation(async () => {+ this._pruneSessions();+ const session = this.sessions.get(sessionId);+ this.sessions.delete(sessionId);+ if (!session || session.kind !== "caret") {+ return { success: false, code: "session_expired" };+ }++ const current = await this._readCurrentSelection(session.target, { probeEditable: true });+ if (current.status !== "editable") {+ return { success: false, code: "target_changed" };+ }++ try {+ const pasteResult = await this.clipboardManager._pasteText(text, {+ ...options,+ restoreClipboard: options.restoreClipboard !== false,+ ...(session.target?.kind === "win-hwnd" ? { targetWindow: session.target.id } : {}),+ });+ await pasteResult?.restoreComplete;+ if (pasteResult?.pasted === false) {+ return { success: false, code: "paste_failed" };+ }+ return { success: true };+ } catch (error) {+ debugLogger.warn("Assistant response paste failed", { error: error.message }, "clipboard");+ return { success: false, code: "paste_failed", error: error.message };+ }+ });+ }+_pruneSessions() {const now = this.now();for (const [id, session] of this.sessions) {@@ -251,15 +302,15 @@ class SelectionManager {return this._readMacSelection(expectedTarget, options);}if (this.platform === "win32") {- return this._readWindowsSelection(expectedTarget);+ return this._readWindowsSelection(expectedTarget, options);}if (this.platform === "linux") {- return this._readLinuxSelection(expectedTarget);+ return this._readLinuxSelection(expectedTarget, options);}return { status: "unavailable", code: "unsupported_platform" };}- async _readMacSelection(expectedTarget, { activate = false } = {}) {+ async _readMacSelection(expectedTarget, { activate = false, probeEditable = false } = {}) {const pid = expectedTarget?.pid || this.textEditMonitor?.lastTargetPid;if (!pid || !this.textEditMonitor?.getSelectedText) {return { status: "unavailable", code: "target_unavailable" };@@ -277,16 +328,20 @@ class SelectionManager {return { status: "selected", text: result.text, target: { kind: "mac-pid", pid } };}if (result.state === "none") {- return { status: "none", target: { kind: "mac-pid", pid } };+ const editable = probeEditable && result.editable && !(await this._isTerminalPid(pid));+ return {+ status: editable ? "editable" : "none",+ target: { kind: "mac-pid", pid },+ };}// Chromium browsers (and any app whose accessibility tree stays dormant)// never resolve a focused element, so the read above cannot tell a selection// from an empty field. A synthetic copy still can — the same route Windows// and Linux take by default.- return this._readMacSelectionViaClipboard(pid, expectedTarget);+ return this._readMacSelectionViaClipboard(pid, expectedTarget, probeEditable);}- async _readMacSelectionViaClipboard(pid, expectedTarget) {+ async _readMacSelectionViaClipboard(pid, expectedTarget, probeEditable) {const binary = this.clipboardManager.resolveFastPasteBinary?.();if (!binary) return { status: "unavailable", code: "accessibility_unavailable" };@@ -318,45 +373,54 @@ class SelectionManager {) {return { status: "none", target: capture.target };}- return capture;+ return this._markEditableCaret(capture, capture.target || expectedTarget, probeEditable);}_runCopyHelper(binary, args) {return runSpawn(binary, args, { timeout: COPY_TIMEOUT_MS });}- async _readWindowsSelection(expectedTarget) {+ async _readWindowsSelection(expectedTarget, { probeEditable = false } = {}) {const binary = this.clipboardManager.resolveWindowsFastPasteBinary();if (!binary) return { status: "unavailable", code: "copy_helper_unavailable" };- return this._captureViaClipboard(async () => {+ const capture = await this._captureViaClipboard(async () => {const result = await runSpawn(binary, ["--copy"], { timeout: COPY_TIMEOUT_MS });if (!result.success) return { success: false };const match = result.stdout.match(/COPY_OK\s+(\S+)/);return { success: !!match, target: match ? { kind: "win-hwnd", id: match[1] } : null };}, expectedTarget);+ // The copy reports only the HWND; a same-window expectedTarget (verified by+ // _captureViaClipboard) carries the exe/class identity the terminal and+ // line-copy checks need, so keep it on the target a caret session stores.+ const target =+ capture.target && expectedTarget+ ? { ...expectedTarget, ...capture.target }+ : capture.target || expectedTarget;+ return this._markEditableCaret(capture, target, probeEditable);}- async _readLinuxSelection(expectedTarget) {+ async _readLinuxSelection(expectedTarget, { probeEditable = false } = {}) {const target = await this._getLinuxTarget();if (!target) return { status: "unavailable", code: "target_unavailable" };if (expectedTarget && !this._sameTarget(target, expectedTarget)) {return { status: "target_changed" };}- // Replacement text typed into a shell executes on its embedded newlines,- // so a terminal selection reads as no selection and the command keeps the- // pre-selection-editing behavior of typing at the cursor. AT-SPI targets- // carry no window class here; the helper binary applies the same rule.if (this.clipboardManager.isLinuxTerminalWindowClass?.(target.windowClass)) {return { status: "none", target };}const binary = this.clipboardManager.resolveLinuxFastPasteBinary();if (target.kind === "atspi-pid") {- return this._readLinuxAtspiSelection(binary, expectedTarget || target);+ const capture = await this._readLinuxAtspiSelection(binary, expectedTarget || target);+ return this._markEditableCaret(+ capture,+ capture.target || expectedTarget || target,+ probeEditable+ );}- return this._captureViaClipboard(async () => {+ const capture = await this._captureViaClipboard(async () => {if (binary) {if (target.kind === "x11-window") {// The binary classifies the window itself via --window and picks@@ -416,6 +480,53 @@ class SelectionManager {}return { success: false };}, expectedTarget || target);+ return this._markEditableCaret(+ capture,+ capture.target || expectedTarget || target,+ probeEditable+ );+ }++ async _markEditableCaret(capture, target, probeEditable) {+ if (!probeEditable || capture.status !== "none" || !target) return capture;+ // Generated text pasted into a shell executes on its embedded newlines, so+ // a terminal target never becomes a caret destination — the same rule the+ // selection paths apply.+ if (this._isTerminalTarget(capture.target, target)) return capture;+ // AT-SPI targets carry only a pid — nothing for the signature check above+ // to match — so resolve the executable name before a Wayland terminal's+ // empty prompt can read as a writable caret.+ if (target.kind === "atspi-pid" && (await this._isTerminalPid(target.id))) return capture;+ const editable = await this.textEditMonitor?.isFocusedEditable?.(target);+ return editable ? { status: "editable", target } : capture;+ }++ _isTerminalTarget(...targets) {+ return targets.some(+ (target) =>+ target?.isTerminal === true ||+ this.clipboardManager.isTerminalSignature?.(this._targetSignature(target))+ );+ }++ // macOS AX and Linux AT-SPI targets carry only a pid; resolve the executable+ // so terminal apps can be recognized before their empty prompt reads as a+ // writable caret. macOS `ps` reports a full path, Linux the bare comm name —+ // the parsing below degrades to the bare name unchanged.+ async _isTerminalPid(pid) {+ if (!this.clipboardManager.isTerminalSignature) return false;+ const executablePath = await this._readExecutablePath(pid);+ if (!executablePath) return false;+ // Match the bundle and executable names, not the whole path — segments+ // like "/System/" would collide with short signatures such as "st".+ const bundleName = executablePath.match(/\/([^/]+)\.app\//)?.[1] ?? "";+ const executableName = executablePath.split("/").pop() ?? "";+ return this.clipboardManager.isTerminalSignature(`${bundleName} ${executableName}`);+ }++ async _readExecutablePath(pid) {+ const result = await runSpawn("ps", ["-p", String(pid), "-o", "comm="], { timeout: 500 });+ return result.success ? result.stdout.trim() : "";}async _readLinuxAtspiSelection(binary, expectedTarget) {@@ -517,8 +628,10 @@ class SelectionManager {// A clipboard side the sentinel write didn't reach (KDE desyncs X11 from// Wayland) still holds pre-copy content; snapshot it so stale text can't// be mistaken for the copied selection. Known limitation: a clipboard that- // already held exactly the selected text reads as "no selection", and the- // command falls back to standalone dictation.+ // already held exactly the selected text reads as "no selection". The+ // command then falls back to the Assistant panel — never to a caret paste,+ // because the editable probe reads the focused element's own selection+ // state and refuses a field with a live selection.const baseline = new Set([...beforeWrite, ...this.clipboardManager._readClipboardTextAll()]);const copyResult = await sendCopy();@@ -559,13 +672,15 @@ class SelectionManager {return { status: "selected", text: copiedText, target: copyResult.target };}+ _targetSignature(target) {+ return `${target?.exeName || ""} ${target?.windowClass || ""} ${target?.appName || ""}`.trim();+ }+// Windows and Linux name the app in the target captured before the copy;// macOS learns it from the copy helper's own report, so both are checked._isLineCopyEditor(...targets) {const signature = targets- .map((target) =>- `${target?.exeName || ""} ${target?.windowClass || ""} ${target?.appName || ""}`.trim()- )+ .map((target) => this._targetSignature(target)).join(" ").toLowerCase();if (!signature.trim()) return false;diff --git a/src/helpers/textEditMonitor.js b/src/helpers/textEditMonitor.jsindex eff9065db..a36d443dc 100644--- a/src/helpers/textEditMonitor.js+++ b/src/helpers/textEditMonitor.js@@ -218,6 +218,10 @@ class TextEditMonitor extends EventEmitter {{ timeout: timeoutMs },(error, stdout, stderr) => {const output = stdout.replace(/\n$/, "");+ if (output === "EDITABLE_NONE:") {+ resolve({ state: "none", editable: true });+ return;+ }if (output === "NONE:") {resolve({ state: "none" });return;@@ -278,6 +282,9 @@ class TextEditMonitor extends EventEmitter {return;}+ // The AppleScript never reports an editable caret (only the native+ // binary emits EDITABLE_NONE:), so this fallback can read selections+ // but never produce a caret delivery target — panel-first by design.const output = stdout.replace(/\n$/, "");if (output === "NONE:") {resolve({ state: "none" });@@ -290,6 +297,50 @@ class TextEditMonitor extends EventEmitter {);}+ async isFocusedEditable(target, timeoutMs = 1000) {+ const resolved = this.resolveBinary();+ if (!resolved) return false;++ let args;+ if (process.platform === "darwin") {+ const pid = target?.kind === "mac-pid" ? target.pid : this.lastTargetPid;+ if (!pid) return false;+ args = [...resolved.args, "--editable-target", String(pid)];+ } else {+ args = [...resolved.args, "--probe-editable"];+ }++ // The verdict is the first output line. A stale binary that predates the+ // probe flag falls into monitor mode instead: it blocks reading stdin,+ // then emits its monitor output and keeps running — closing stdin and+ // resolving on that first line keeps the stale case a fast "not editable"+ // rather than a hang until the timeout.+ return new Promise((resolve) => {+ const child = spawn(resolved.command, args, { stdio: ["pipe", "pipe", "ignore"] });+ let buffered = "";+ let settled = false;+ const settle = (verdict) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ try {+ child.kill();+ } catch {}+ resolve(verdict);+ };+ const timer = setTimeout(() => settle(false), timeoutMs);+ child.stdin.on("error", () => {});+ child.stdin.end();+ child.stdout.on("data", (data) => {+ buffered += data.toString();+ const newline = buffered.indexOf("\n");+ if (newline !== -1) settle(buffered.slice(0, newline).trim() === "EDITABLE");+ });+ child.on("error", () => settle(false));+ child.on("close", () => settle(buffered.trim() === "EDITABLE"));+ });+ }+/*** macOS: the target app's largest on-screen window rect, used to decide which* display the user is working on. Resolves to null when the app has nodiff --git a/src/hooks/useAssistantPanel.js b/src/hooks/useAssistantPanel.jsindex 44b525084..cfceb8834 100644--- a/src/hooks/useAssistantPanel.js+++ b/src/hooks/useAssistantPanel.js@@ -133,12 +133,17 @@ export function useAssistantPanel({const handleCommand = useCallback((command) => {commandIdRef.current += 1;+ // A follow-up spoken into an open panel stays panel-first: its answer is+ // already streaming into a visible conversation, and delivering it to+ // the external caret would snap that surface away mid-read.+ const delivery = openRef.current ? null : (command.delivery ?? null);beginThinking();setPendingCommand({id: commandIdRef.current,text: command.text,attachment: command.attachment ?? null,selectedContext: command.selectedContext ?? null,+ delivery,});},[beginThinking]@@ -169,15 +174,20 @@ export function useAssistantPanel({mountedRef.current = mounted;}, [mounted]);- // The chat reports content, an error, or nothing at all; whichever it is,- // the thinking flourish must end and the panel must be visible so the- // outcome can be seen and the main-process busy gate releases.const handleCommandSettled = useCallback(- (id) => {+ (id, { showPanel = true } = {}) => {if (id !== commandIdRef.current) return;if (!mountedRef.current || closingRef.current) return;setThinking(false);- void openPanel();+ if (showPanel) {+ void openPanel();+ return;+ }+ openRef.current = false;+ setOpen(false);+ setBusy(false);+ setResponseReady(false);+ setMounted(false);},[openPanel]);diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.jsindex 04eecf805..cf1e686e5 100644--- a/src/hooks/useAudioRecording.js+++ b/src/hooks/useAudioRecording.js@@ -20,6 +20,7 @@ import {} from "../utils/transcriptionPreview";import { canStartDictation } from "../utils/dictationReadiness";import { waitForVisualFrames } from "../utils/visualFrame";+import { createAssistantResponseDelivery } from "../helpers/assistantResponseDelivery";// Maps a failed selection-replacement code to its `selectionEditing.*` toast// detail key; unlisted codes fall back to the generic "unavailable" message.@@ -461,19 +462,22 @@ export const useAudioRecording = (toast, options = {}) => {if (localStorage.getItem("onboardingCompleted") !== "true") {window.electronAPI?.hideDictationPreview?.();} else {- // Panel-first: the command streams into the assistant panel;- // nothing types at the cursor and nothing lands in the clipboard.- // The directive's transcript is the command to send — it carries- // the quoted selection when the selection-without-editor fallback- // routed a highlighted passage here.window.electronAPI?.hideDictationPreview?.();- const { screenContext, transcript, selectedContext } = result.assistantConversation;+ const { screenContext, transcript, selectedContext, deliverySessionId } =+ result.assistantConversation;+ const { autoPasteEnabled, keepTranscriptionInClipboard } = getSettings();onAssistantCommandRef.current?.({text: expandSnippets(transcript, getSettings().snippets),attachment: screenContext? { image: screenContext.data, mediaType: screenContext.mediaType }: null,selectedContext: selectedContext ?? null,+ delivery: createAssistantResponseDelivery({+ autoPasteEnabled,+ deliverySessionId,+ restoreClipboard: !keepTranscriptionInClipboard,+ allowClipboardFallback: isAccessibilitySkipped(),+ }),});}} else {diff --git a/src/hooks/useCopyFeedback.ts b/src/hooks/useCopyFeedback.tsindex e33baafc9..afd251843 100644--- a/src/hooks/useCopyFeedback.ts+++ b/src/hooks/useCopyFeedback.ts@@ -1,18 +1,20 @@import { useCallback, useEffect, useRef, useState } from "react";-/**- * Copies `text` to the clipboard (native bridge first, web API fallback) and- * latches `copied` for `resetMs`. The latch clears immediately when the source- * text changes so stale feedback never survives a new answer.- */export function useCopyFeedback(text: string,{ resetMs = 1800 }: { resetMs?: number } = {}-): { copied: boolean; copy: () => Promise<void> } {+): {+ copied: boolean;+ copy: () => Promise<void>;+ confirmCopied: (copiedText: string, durationMs?: number) => void;+} {const [copied, setCopied] = useState(false);const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const confirmedTextRef = useRef<string | null>(null);useEffect(() => {+ if (confirmedTextRef.current === text) return;+ confirmedTextRef.current = null;setCopied(false);if (timerRef.current) clearTimeout(timerRef.current);}, [text]);@@ -24,6 +26,16 @@ export function useCopyFeedback([]);+ const confirmCopied = useCallback(+ (copiedText: string, durationMs = resetMs) => {+ confirmedTextRef.current = copiedText;+ setCopied(true);+ if (timerRef.current) clearTimeout(timerRef.current);+ timerRef.current = setTimeout(() => setCopied(false), durationMs);+ },+ [resetMs]+ );+const copy = useCallback(async () => {const textToCopy = text.trim();if (!textToCopy) return;@@ -40,10 +52,8 @@ export function useCopyFeedback(}}- setCopied(true);- if (timerRef.current) clearTimeout(timerRef.current);- timerRef.current = setTimeout(() => setCopied(false), resetMs);- }, [text, resetMs]);+ confirmCopied(text, resetMs);+ }, [confirmCopied, text, resetMs]);- return { copied, copy };+ return { copied, copy, confirmCopied };}diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 707cd8bb2..c8b71406f 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -478,7 +478,7 @@"title": "Sprachassistent-Einrichtung","description": "Sprechen Sie mit Ihrem KI-Assistenten per Tastendruck","hotkey": "Hotkey",- "howItWorks": "Drücken Sie die Taste und sagen Sie, was Sie möchten — zum Beispiel „schreibe eine kurze Dankesnachricht“. Ist Text markiert, bearbeitet und ersetzt {{agentName}} diese Auswahl; andernfalls öffnet sich die Antwort in einem schwebenden Panel. Sie müssen nicht zuerst „Hey {{agentName}}“ sagen.",+ "howItWorks": "Drücken Sie die Taste und sagen Sie, was Sie möchten — zum Beispiel „schreibe eine kurze Dankesnachricht“. Ist Text markiert, bearbeitet und ersetzt {{agentName}} ihn. Ist ein beschreibbares Textfeld fokussiert, wird die Antwort am Cursor eingefügt; andernfalls öffnet sie sich in einem schwebenden Panel. Sie müssen nicht zuerst „Hey {{agentName}}“ sagen.","test": "Ausprobieren","testInstruction": "Markiere unten den Beispieltext, drücke {{hotkey}} und sage „mach das kürzer“ — die Änderung landet direkt im Textfeld","testSetHotkey": "Lege oben einen Hotkey fest, um es auszuprobieren",@@ -1980,7 +1980,7 @@},"examplesTitle": "Beispiele","helper": "Wählen Sie etwas Kurzes und Natürliches zum Aussprechen",- "howItWorksDescription": "Wenn Sie 'Hey {{agentName}}' gefolgt von einer Anweisung sagen, öffnet sich die Antwort im schwebenden Assistenten-Panel. Ist Text markiert, wird dieser Text an Ihr konfiguriertes Sprachassistenten-Modell gesendet und sicher durch das Ergebnis ersetzt.",+ "howItWorksDescription": "Wenn Sie 'Hey {{agentName}}' gefolgt von einer Anweisung sagen, wird markierter Text sicher durch das Ergebnis ersetzt. Bei aktiviertem automatischen Einfügen landet die Antwort am Cursor eines fokussierten beschreibbaren Textfelds; andernfalls öffnet sie sich im schwebenden Assistenten-Panel.","howItWorksTitle": "So funktioniert es","instructionMode": "Anweisung","placeholder": "z. B. Jarvis, Nova, Atlas...",@@ -2144,7 +2144,7 @@},"voiceAgentHotkey": {"title": "Sprachassistent-Hotkey",- "description": "Sprechen Sie einen Befehl und der Assistent antwortet in einem schwebenden Panel — mit Ihren Notizen, Ihrem Kalender und Web-Tools. Markieren Sie zuerst Text, um ihn direkt zu bearbeiten."+ "description": "Sprechen Sie einen Befehl und der Assistent nutzt Ihre Notizen, Ihren Kalender und Web-Tools. Die Antwort wird am fokussierten beschreibbaren Cursor eingefügt, ersetzt markierten Text oder öffnet sich im schwebenden Panel."},"microphone": {"description": "Wählen Sie das Eingabegerät für das Diktat",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex d934396a4..4dfbdef91 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -478,7 +478,7 @@"title": "Voice Assistant Setup","description": "Talk to your AI assistant with a single keypress","hotkey": "Hotkey",- "howItWorks": "Press the key and say what you want — for example “write a short thank-you note”. If text is highlighted, {{agentName}} edits and replaces that selection; otherwise the answer opens in a floating panel. No need to say “Hey {{agentName}}” first.",+ "howItWorks": "Press the key and say what you want — for example “write a short thank-you note”. If text is highlighted, {{agentName}} edits and replaces it. If a writable text field is focused, the answer is pasted at the cursor; otherwise it opens in a floating panel. No need to say “Hey {{agentName}}” first.","test": "Try it","testInstruction": "Select the sample text below, then press {{hotkey}} and say “make this shorter” — the edit lands right in the text box","testSetHotkey": "Set a hotkey above to try it",@@ -1980,7 +1980,7 @@},"examplesTitle": "Examples","helper": "Pick something short and natural to say aloud",- "howItWorksDescription": "When you say \"Hey {{agentName}}\" followed by an instruction, the answer opens in the floating assistant panel. If text is highlighted, that text is sent to your configured Voice Assistant model and safely replaced with the result.",+ "howItWorksDescription": "When you say \"Hey {{agentName}}\" followed by an instruction, highlighted text is safely replaced with the result. With auto-paste enabled, an answer pastes at a focused writable cursor; otherwise it opens in the floating assistant panel.","howItWorksTitle": "How it works","instructionMode": "Instruction","placeholder": "e.g. Jarvis, Nova, Atlas...",@@ -2144,7 +2144,7 @@},"voiceAgentHotkey": {"title": "Voice Assistant Hotkey",- "description": "Speak a command and the assistant answers in a floating panel with your notes, calendar, and web tools. Select text first to edit it in place."+ "description": "Speak a command and the assistant uses your notes, calendar, and web tools. Its answer pastes at a focused writable cursor, replaces selected text, or opens in the floating panel."},"microphone": {"description": "Select which input device to use for dictation",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 35e4d302d..9a2dc0118 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -478,7 +478,7 @@"title": "Configuración del asistente de voz","description": "Habla con tu asistente de IA con una sola pulsación","hotkey": "Atajo",- "howItWorks": "Pulsa la tecla y di lo que quieres, por ejemplo «escribe una breve nota de agradecimiento». Si hay texto resaltado, {{agentName}} edita y reemplaza esa selección; si no, la respuesta se abre en un panel flotante. No hace falta decir «Hey {{agentName}}» antes.",+ "howItWorks": "Pulsa la tecla y di lo que quieres, por ejemplo «escribe una breve nota de agradecimiento». Si hay texto resaltado, {{agentName}} lo edita y reemplaza. Si un campo de texto editable tiene el foco, la respuesta se pega en el cursor; si no, se abre en un panel flotante. No hace falta decir «Hey {{agentName}}» antes.","test": "Pruébalo","testInstruction": "Selecciona el texto de ejemplo de abajo, pulsa {{hotkey}} y di «hazlo más corto»: la edición aparece directamente en el cuadro de texto","testSetHotkey": "Configura un atajo arriba para probarlo",@@ -1739,7 +1739,7 @@},"examplesTitle": "Ejemplos","helper": "Elige algo corto y natural para decir en voz alta",- "howItWorksDescription": "Cuando dices \"Hey {{agentName}}\" seguido de una instrucción, la respuesta se abre en el panel flotante del asistente. Si hay texto resaltado, ese texto se envía a tu modelo de Asistente de voz configurado y se reemplaza de forma segura por el resultado.",+ "howItWorksDescription": "Cuando dices \"Hey {{agentName}}\" seguido de una instrucción, el texto resaltado se reemplaza de forma segura por el resultado. Con el pegado automático activado, la respuesta se pega en el cursor de un campo editable con foco; si no, se abre en el panel flotante del asistente.","howItWorksTitle": "Cómo funciona","instructionMode": "Instrucción","placeholder": "p. ej. Jarvis, Nova, Atlas...",@@ -1903,7 +1903,7 @@},"voiceAgentHotkey": {"title": "Atajo del asistente de voz",- "description": "Di un comando y el asistente responde en un panel flotante con tus notas, calendario y herramientas web. Selecciona texto primero para editarlo en su lugar."+ "description": "Di un comando y el asistente usa tus notas, calendario y herramientas web. La respuesta se pega en un cursor editable con foco, reemplaza el texto seleccionado o se abre en el panel flotante."},"microphone": {"description": "Selecciona qué dispositivo de entrada usar para dictado",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex feba506f9..445259bf9 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -478,7 +478,7 @@"title": "Configuration de l'assistant vocal","description": "Parlez à votre assistant IA d'une simple touche","hotkey": "Raccourci",- "howItWorks": "Appuyez sur la touche et dites ce que vous voulez, par exemple « écris un petit mot de remerciement ». Si du texte est surligné, {{agentName}} modifie et remplace cette sélection ; sinon, la réponse s'ouvre dans un panneau flottant. Pas besoin de dire « Hey {{agentName}} » d'abord.",+ "howItWorks": "Appuyez sur la touche et dites ce que vous voulez, par exemple « écris un petit mot de remerciement ». Si du texte est surligné, {{agentName}} le modifie et le remplace. Si un champ de texte modifiable est actif, la réponse est collée au curseur ; sinon, elle s'ouvre dans un panneau flottant. Pas besoin de dire « Hey {{agentName}} » d'abord.","test": "Essayer","testInstruction": "Sélectionnez le texte d'exemple ci-dessous, appuyez sur {{hotkey}} et dites « raccourcis ce texte » — la modification apparaît directement dans la zone de texte","testSetHotkey": "Définissez un raccourci ci-dessus pour l'essayer",@@ -1980,7 +1980,7 @@},"examplesTitle": "Exemples","helper": "Choisissez un nom court et naturel à prononcer",- "howItWorksDescription": "Lorsque vous dites « Hey {{agentName}} » suivi d'une instruction, la réponse s'ouvre dans le panneau flottant de l'assistant. Si du texte est surligné, ce texte est envoyé à votre modèle d'Assistant vocal configuré et remplacé en toute sécurité par le résultat.",+ "howItWorksDescription": "Lorsque vous dites « Hey {{agentName}} » suivi d'une instruction, le texte surligné est remplacé en toute sécurité par le résultat. Si le collage automatique est activé, la réponse est collée au curseur d'un champ modifiable actif ; sinon, elle s'ouvre dans le panneau flottant de l'assistant.","howItWorksTitle": "Comment ça marche","instructionMode": "Instruction","placeholder": "ex. Jarvis, Nova, Atlas...",@@ -2144,7 +2144,7 @@},"voiceAgentHotkey": {"title": "Raccourci de l'assistant vocal",- "description": "Dites une commande et l'assistant répond dans un panneau flottant avec vos notes, votre calendrier et des outils web. Sélectionnez d'abord du texte pour le modifier sur place."+ "description": "Dites une commande et l'assistant utilise vos notes, votre calendrier et les outils web. La réponse est collée à un curseur modifiable actif, remplace le texte sélectionné ou s'ouvre dans le panneau flottant."},"microphone": {"description": "Sélectionnez le périphérique d'entrée à utiliser pour la dictée",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 498eb5c10..7cc638969 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -478,7 +478,7 @@"title": "Configurazione dell'assistente vocale","description": "Parla con il tuo assistente IA con un solo tasto","hotkey": "Scorciatoia",- "howItWorks": "Premi il tasto e di' cosa vuoi — ad esempio “scrivi un breve messaggio di ringraziamento”. Se c'è del testo evidenziato, {{agentName}} modifica e sostituisce quella selezione; altrimenti la risposta si apre in un pannello flottante. Non serve dire prima “Hey {{agentName}}”.",+ "howItWorks": "Premi il tasto e di' cosa vuoi — ad esempio “scrivi un breve messaggio di ringraziamento”. Se c'è del testo evidenziato, {{agentName}} lo modifica e sostituisce. Se è attivo un campo di testo modificabile, la risposta viene incollata al cursore; altrimenti si apre in un pannello flottante. Non serve dire prima “Hey {{agentName}}”.","test": "Provalo","testInstruction": "Seleziona il testo di esempio qui sotto, premi {{hotkey}} e di' «rendilo più corto» — la modifica arriva direttamente nella casella di testo","testSetHotkey": "Imposta una scorciatoia sopra per provarlo",@@ -1691,7 +1691,7 @@},"examplesTitle": "Esempi","helper": "Scegli qualcosa di breve e naturale da dire ad alta voce",- "howItWorksDescription": "Quando dici \"Ehi {{agentName}}\" seguito da un'istruzione, la risposta si apre nel pannello flottante dell'assistente. Se c'è del testo evidenziato, quel testo viene inviato al tuo modello di Assistente vocale configurato e sostituito in sicurezza con il risultato.",+ "howItWorksDescription": "Quando dici \"Ehi {{agentName}}\" seguito da un'istruzione, il testo evidenziato viene sostituito in sicurezza con il risultato. Con l'incolla automatico attivo, la risposta viene incollata al cursore di un campo modificabile attivo; altrimenti si apre nel pannello flottante dell'assistente.","howItWorksTitle": "Come funziona","instructionMode": "Istruzione","placeholder": "es. Jarvis, Nova, Atlas...",@@ -1855,7 +1855,7 @@},"voiceAgentHotkey": {"title": "Scorciatoia dell'assistente vocale",- "description": "Pronuncia un comando e l'assistente risponde in un pannello flottante con le tue note, il calendario e gli strumenti web. Seleziona prima del testo per modificarlo sul posto."+ "description": "Pronuncia un comando e l'assistente usa le tue note, il calendario e gli strumenti web. La risposta viene incollata a un cursore modificabile attivo, sostituisce il testo selezionato o si apre nel pannello flottante."},"microphone": {"description": "Seleziona il dispositivo di ingresso da usare per la dettatura",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 3a8aa2994..7de4cb9af 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -478,7 +478,7 @@"title": "音声アシスタント設定","description": "ワンキーでAIアシスタントに話しかけられます","hotkey": "ホットキー",- "howItWorks": "キーを押して、してほしいことを話すだけ。例えば「お礼のメッセージを書いて」と言えます。テキストが選択されていれば、{{agentName}}がその選択範囲を編集して置き換えます。選択がなければ、答えはフローティングパネルに表示されます。「Hey {{agentName}}」と言う必要はありません。",+ "howItWorks": "キーを押して、してほしいことを話すだけ。例えば「お礼のメッセージを書いて」と言えます。テキストが選択されていれば、{{agentName}}が編集して置き換えます。編集可能なテキスト欄にフォーカスがある場合、回答はカーソル位置に貼り付けられ、それ以外の場合はフローティングパネルに表示されます。「Hey {{agentName}}」と言う必要はありません。","test": "試す","testInstruction": "下のサンプルテキストを選択して {{hotkey}} を押し、「短くして」と話してください。編集結果がそのままテキストボックスに反映されます","testSetHotkey": "上でホットキーを設定すると試せます",@@ -1691,7 +1691,7 @@},"examplesTitle": "例","helper": "声に出して言いやすい短い名前を選びましょう",- "howItWorksDescription": "「ねぇ {{agentName}}」と呼びかけて指示を出すと、回答がフローティングのアシスタントパネルに表示されます。テキストが選択されている場合、そのテキストは設定済みの音声アシスタントモデルに送信され、結果で安全に置き換えられます。",+ "howItWorksDescription": "「ねぇ {{agentName}}」と呼びかけて指示を出すと、選択中のテキストは結果で安全に置き換えられます。自動貼り付けが有効で編集可能なテキスト欄にフォーカスがある場合、回答はカーソル位置に貼り付けられ、それ以外の場合はフローティングのアシスタントパネルに表示されます。","howItWorksTitle": "仕組み","instructionMode": "指示","placeholder": "例: ジャービス、ノヴァ、アトラス...",@@ -1855,7 +1855,7 @@},"voiceAgentHotkey": {"title": "音声アシスタントホットキー",- "description": "コマンドを話すと、アシスタントがノート・カレンダー・ウェブツールを使ってフローティングパネルで答えます。テキストを選択してから話すと、その場で編集されます。"+ "description": "コマンドを話すと、アシスタントがノート・カレンダー・ウェブツールを使います。回答はフォーカス中の編集可能なカーソル位置に貼り付けられるか、選択テキストを置き換えるか、フローティングパネルに表示されます。"},"microphone": {"description": "ディクテーションに使用する入力デバイスを選択",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 597608435..d79503277 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -457,7 +457,7 @@"title": "Configuração do assistente de voz","description": "Fale com seu assistente de IA com um único atalho","hotkey": "Atalho",- "howItWorks": "Pressione a tecla e diga o que quer — por exemplo, “escreva uma breve nota de agradecimento”. Se houver texto destacado, {{agentName}} edita e substitui essa seleção; caso contrário, a resposta abre em um painel flutuante. Não precisa dizer “Hey {{agentName}}” antes.",+ "howItWorks": "Pressione a tecla e diga o que quer — por exemplo, “escreva uma breve nota de agradecimento”. Se houver texto destacado, {{agentName}} o edita e substitui. Se um campo de texto editável estiver em foco, a resposta é colada no cursor; caso contrário, abre em um painel flutuante. Não precisa dizer “Hey {{agentName}}” antes.","test": "Experimente","testInstruction": "Selecione o texto de exemplo abaixo, pressione {{hotkey}} e diga “deixe isso mais curto” — a edição aparece direto na caixa de texto","testSetHotkey": "Defina um atalho acima para experimentar",@@ -1670,7 +1670,7 @@},"examplesTitle": "Exemplos","helper": "Escolha algo curto e natural de se dizer em voz alta",- "howItWorksDescription": "Quando você diz \"Ei {{agentName}}\" seguido de uma instrução, a resposta abre no painel flutuante do assistente. Se houver texto destacado, esse texto é enviado ao seu modelo de Assistente de voz configurado e substituído com segurança pelo resultado.",+ "howItWorksDescription": "Quando você diz \"Ei {{agentName}}\" seguido de uma instrução, o texto destacado é substituído com segurança pelo resultado. Com a colagem automática ativada, a resposta é colada no cursor de um campo editável em foco; caso contrário, abre no painel flutuante do assistente.","howItWorksTitle": "Como funciona","instructionMode": "Instrução","placeholder": "ex.: Jarvis, Nova, Atlas...",@@ -1834,7 +1834,7 @@},"voiceAgentHotkey": {"title": "Atalho do assistente de voz",- "description": "Diga um comando e o assistente responde em um painel flutuante com suas notas, calendário e ferramentas web. Selecione texto primeiro para editá-lo no lugar."+ "description": "Diga um comando e o assistente usa suas notas, calendário e ferramentas web. A resposta é colada em um cursor editável em foco, substitui o texto selecionado ou abre no painel flutuante."},"microphone": {"description": "Selecione qual dispositivo de entrada usar para ditado",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex a6f16c1de..448652a2f 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -478,7 +478,7 @@"title": "Настройка голосового помощника","description": "Обращайтесь к ИИ-помощнику одним нажатием","hotkey": "Горячая клавиша",- "howItWorks": "Нажмите клавишу и скажите, что вам нужно — например, «напиши короткую благодарственную записку». Если текст выделен, {{agentName}} отредактирует и заменит выделенное; иначе ответ откроется в плавающей панели. Говорить «Hey {{agentName}}» не нужно.",+ "howItWorks": "Нажмите клавишу и скажите, что вам нужно — например, «напиши короткую благодарственную записку». Если текст выделен, {{agentName}} отредактирует и заменит его. Если фокус находится в редактируемом текстовом поле, ответ вставится в позицию курсора; иначе он откроется в плавающей панели. Говорить «Hey {{agentName}}» не нужно.","test": "Попробуйте","testInstruction": "Выделите образец текста ниже, нажмите {{hotkey}} и скажите «сделай короче» — правка появится прямо в текстовом поле","testSetHotkey": "Задайте горячую клавишу выше, чтобы попробовать",@@ -1695,7 +1695,7 @@},"examplesTitle": "Примеры","helper": "Выберите что-то короткое и естественное для произношения",- "howItWorksDescription": "Когда вы говорите «Привет, {{agentName}}» и затем даёте инструкцию, ответ открывается в плавающей панели ассистента. Если текст выделен, он отправляется в настроенную модель голосового ассистента и безопасно заменяется результатом.",+ "howItWorksDescription": "Когда вы говорите «Привет, {{agentName}}» и затем даёте инструкцию, выделенный текст безопасно заменяется результатом. Если автовставка включена и фокус находится в редактируемом поле, ответ вставляется в позицию курсора; иначе он открывается в плавающей панели ассистента.","howItWorksTitle": "Как это работает","instructionMode": "Инструкция","placeholder": "например, Джарвис, Нова, Атлас...",@@ -1859,7 +1859,7 @@},"voiceAgentHotkey": {"title": "Горячая клавиша голосового помощника",- "description": "Скажите команду — помощник ответит в плавающей панели, используя ваши заметки, календарь и веб-инструменты. Сначала выделите текст, чтобы отредактировать его на месте."+ "description": "Скажите команду — помощник использует ваши заметки, календарь и веб-инструменты. Ответ вставляется в редактируемое поле с фокусом, заменяет выделенный текст или открывается в плавающей панели."},"microphone": {"description": "Выберите устройство ввода для диктовки",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 351e1792b..0da490f2b 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -478,7 +478,7 @@"title": "语音助手设置","description": "一键唤起你的 AI 助手","hotkey": "快捷键",- "howItWorks": "按下快捷键,说出你想要的内容,例如“写一段简短的感谢语”。如果有选中的文本,{{agentName}} 会编辑并替换所选内容;否则回答会在悬浮面板中打开。无需先说“Hey {{agentName}}”。",+ "howItWorks": "按下快捷键,说出你想要的内容,例如“写一段简短的感谢语”。如果有选中的文本,{{agentName}} 会编辑并替换它。如果可编辑文本框已获得焦点,回答会粘贴到光标处;否则会在悬浮面板中打开。无需先说“Hey {{agentName}}”。","test": "试一试","testInstruction": "选中下方的示例文本,按下 {{hotkey}} 并说“把它改短一点”——编辑结果会直接出现在文本框里","testSetHotkey": "在上方设置快捷键即可试用",@@ -1691,7 +1691,7 @@},"examplesTitle": "示例","helper": "选一个简短、说起来自然的名字",- "howItWorksDescription": "当你说“Hey {{agentName}}”并跟上指令时,回答会在悬浮助手面板中打开。如果有选中的文本,该文本会发送到你配置的语音助手模型,并安全地替换为结果。",+ "howItWorksDescription": "当你说“Hey {{agentName}}”并跟上指令时,选中的文本会安全地替换为结果。启用自动粘贴后,如果可编辑文本框已获得焦点,回答会粘贴到光标处;否则会在悬浮助手面板中打开。","howItWorksTitle": "工作原理","instructionMode": "指令","placeholder": "例如 Jarvis、Nova、Atlas...",@@ -1855,7 +1855,7 @@},"voiceAgentHotkey": {"title": "语音助手快捷键",- "description": "说出指令,助手会在悬浮面板中回答,并可使用你的笔记、日历和网页工具。先选中文本即可就地编辑。"+ "description": "说出指令,助手会使用你的笔记、日历和网页工具。回答会粘贴到已聚焦的可编辑光标处、替换选中文本,或在悬浮面板中打开。"},"microphone": {"description": "选择用于听写的输入设备",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 9a720b6b9..8823089b2 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -478,7 +478,7 @@"title": "語音助理設定","description": "一鍵喚起你的 AI 助理","hotkey": "快捷鍵",- "howItWorks": "按下快捷鍵,說出你想要的內容,例如「寫一段簡短的感謝語」。如果有選取的文字,{{agentName}} 會編輯並取代所選內容;否則回答會在懸浮面板中開啟。無需先說「Hey {{agentName}}」。",+ "howItWorks": "按下快捷鍵,說出你想要的內容,例如「寫一段簡短的感謝語」。如果有選取的文字,{{agentName}} 會編輯並取代它。如果可編輯文字欄位已取得焦點,回答會貼到游標處;否則會在懸浮面板中開啟。無需先說「Hey {{agentName}}」。","test": "試試看","testInstruction": "選取下方的範例文字,按下 {{hotkey}} 並說「把它改短一點」——編輯結果會直接出現在文字框裡","testSetHotkey": "在上方設定快捷鍵即可試用",@@ -1691,7 +1691,7 @@},"examplesTitle": "範例","helper": "選個簡短、自然、好說的名字",- "howItWorksDescription": "當你說「Hey {{agentName}}」加上一個指令時,回答會在浮動助理面板中開啟。如果有選取的文字,該文字會傳送到你設定的語音助理模型,並安全地取代為結果。",+ "howItWorksDescription": "當你說「Hey {{agentName}}」加上一個指令時,選取的文字會安全地取代為結果。啟用自動貼上後,如果可編輯文字欄位已取得焦點,回答會貼到游標處;否則會在浮動助理面板中開啟。","howItWorksTitle": "運作方式","instructionMode": "指令","placeholder": "例如 Jarvis、Nova、Atlas...",@@ -1855,7 +1855,7 @@},"voiceAgentHotkey": {"title": "語音助理快捷鍵",- "description": "說出指令,助理會在懸浮面板中回答,並可使用你的筆記、行事曆和網頁工具。先選取文字即可就地編輯。"+ "description": "說出指令,助理會使用你的筆記、行事曆和網頁工具。回答會貼到已聚焦的可編輯游標處、取代選取文字,或在懸浮面板中開啟。"},"microphone": {"description": "選擇用於語音輸入的輸入裝置",diff --git a/src/types/electron.ts b/src/types/electron.tsindex 7e1208b1a..d0c681ee5 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -925,13 +925,17 @@ declare global {allowClipboardFallback?: boolean;}) => Promise<void>;- captureSelectedText?: () => Promise<+ captureSelectedText?: (options?: { probeEditable?: boolean }) => Promise<| {status: "selected";sessionId: string;text: string;characterCount: number;}+ | {+ status: "editable";+ sessionId: string;+ }| {status: "none" | "unavailable" | "target_changed" | "too_large";code?: string;@@ -955,6 +959,20 @@ declare global {| "selection_manager_unavailable";error?: string;}>;+ pasteAtCapturedTarget?: (+ sessionId: string,+ text: string,+ options?: { restoreClipboard?: boolean; allowClipboardFallback?: boolean }+ ) => Promise<{+ success: boolean;+ code?:+ | "invalid_replacement"+ | "session_expired"+ | "target_changed"+ | "paste_failed"+ | "selection_manager_unavailable";+ error?: string;+ }>;hideWindow: () => Promise<void>;showDictationPanel: () => Promise<void>;captureDictationTarget?: () => Promise<{ success: boolean; pid: number | null }>;diff --git a/test/helpers/assistantPanel.test.js b/test/helpers/assistantPanel.test.jsindex fcef0ab96..25860e5be 100644--- a/test/helpers/assistantPanel.test.js+++ b/test/helpers/assistantPanel.test.js@@ -286,7 +286,9 @@ async function renderAssistantPanel(export function useWindowDrag() { return { handleMouseDown() {}, handleMouseUp() {} }; }`,"/hooks/useCopyFeedback": `- export function useCopyFeedback() { return { copied: false, async copy() {} }; }+ export function useCopyFeedback() {+ return { copied: false, async copy() {}, confirmCopied() {} };+ }`,"/stores/settingsStore": `const state = { voiceAgentKey: [] };@@ -448,7 +450,9 @@ test("starting a new conversation clears the displayed response and parent conteexport function useWindowDrag() { return { handleMouseDown() {}, handleMouseUp() {} }; }`,"/hooks/useCopyFeedback": `- export function useCopyFeedback() { return { copied: false, async copy() {} }; }+ export function useCopyFeedback() {+ return { copied: false, async copy() {}, confirmCopied() {} };+ }`,"/stores/settingsStore": `const state = { voiceAgentKey: [] };@@ -603,6 +607,40 @@ test("the Assistant uses its localized fallback for an unknown active tool", asyassert.doesNotMatch(markup, />Unregistered tool</);});+test("an automatic clipboard delivery keeps the shared Copy button confirmed for six seconds", async (t) => {+ let root = null;+ const originalSetTimeout = globalThis.setTimeout;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ globalThis.setTimeout = originalSetTimeout;+ });+ installBrowserGlobals(t);+ const container = installInteractiveDom(t);+ const scheduledDelays = [];+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-copy-feedback-test-",+ });+ const { useCopyFeedback } = await vite.ssrLoadModule("/hooks/useCopyFeedback.ts");+ const { createRoot } = require("react-dom/client");+ let copyFeedback;++ function Harness() {+ copyFeedback = useCopyFeedback("Agent answer");+ return React.createElement("button", null, copyFeedback.copied ? "Copied" : "Copy");+ }++ root = createRoot(container);+ await React.act(async () => root.render(React.createElement(Harness)));+ globalThis.setTimeout = (callback, delay, ...args) => {+ scheduledDelays.push(delay);+ return originalSetTimeout(callback, delay, ...args);+ };+ await React.act(async () => copyFeedback.confirmCopied("Agent answer", 6000));++ assert.equal(container.textContent, "Copied");+ assert.ok(scheduledDelays.includes(6000));+});+test("a failed Assistant resize releases its open claim so opening can retry", async (t) => {installBrowserGlobals(t);const vite = await createRendererServer(t, {@@ -664,3 +702,97 @@ test("a failed live-transcript resize releases its open claim so opening can retassert.equal(resizeCalls, 2);assert.equal(liveTranscript.openRef.current, false);});++test("a caret-delivered command returns the hidden Assistant to the idle pill", async (t) => {+ let root = null;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ });+ installBrowserGlobals(t);+ const container = installInteractiveDom(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-assistant-caret-settlement-test-",+ });+ const { useAssistantPanel } = await vite.ssrLoadModule("/hooks/useAssistantPanel.js");+ const { createRoot } = require("react-dom/client");+ let assistant;++ function Harness() {+ assistant = useAssistantPanel({+ requestMainWindowSize: async () => ({ success: true }),+ dictationErrorActionCount: 0,+ recordingControlsRef: { current: null },+ });+ return null;+ }++ root = createRoot(container);+ await React.act(async () => root.render(React.createElement(Harness)));+ await React.act(async () => {+ assistant.handleCommand({+ text: "draft a reply",+ attachment: null,+ selectedContext: null,+ delivery: {+ mode: "paste",+ sessionId: "caret-session",+ restoreClipboard: true,+ allowClipboardFallback: false,+ },+ });+ });+ assert.equal(assistant.mounted, true);+ assert.equal(assistant.open, false);++ await React.act(async () => {+ assistant.handleCommandSettled(1, { showPanel: false });+ });+ assert.equal(assistant.mounted, false);+ assert.equal(assistant.open, false);+ assert.equal(assistant.thinking, false);+});++test("a follow-up into an open panel strips caret delivery and stays panel-first", async (t) => {+ let root = null;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ });+ installBrowserGlobals(t);+ const container = installInteractiveDom(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-assistant-followup-delivery-test-",+ });+ const { useAssistantPanel } = await vite.ssrLoadModule("/hooks/useAssistantPanel.js");+ const { createRoot } = require("react-dom/client");+ let assistant;++ function Harness() {+ assistant = useAssistantPanel({+ requestMainWindowSize: async () => ({ success: true }),+ dictationErrorActionCount: 0,+ recordingControlsRef: { current: null },+ });+ return null;+ }++ root = createRoot(container);+ await React.act(async () => root.render(React.createElement(Harness)));+ const delivery = {+ mode: "paste",+ sessionId: "caret-session",+ restoreClipboard: true,+ allowClipboardFallback: false,+ };++ assistant.openRef.current = true;+ await React.act(async () => {+ 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 });+ });+ assert.deepEqual(assistant.pendingCommand.delivery, delivery);+});diff --git a/test/helpers/assistantResponseDelivery.test.js b/test/helpers/assistantResponseDelivery.test.jsnew file mode 100644index 000000000..d93f0b967--- /dev/null+++ b/test/helpers/assistantResponseDelivery.test.js@@ -0,0 +1,84 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const deliveryModule = import("../../src/helpers/assistantResponseDelivery.ts");+const RESPONSE = "Agent answer";+const PASTE_OPTIONS = {+ restoreClipboard: true,+ allowClipboardFallback: false,+};+const PASTE_DELIVERY = {+ mode: "paste",+ sessionId: "caret-session",+ ...PASTE_OPTIONS,+};++function createDeliveryHarness(pasteSuccess) {+ const pastes = [];+ const writes = [];++ return {+ pastes,+ writes,+ dependencies: {+ electronAPI: {+ async pasteAtCapturedTarget(sessionId, text, options) {+ pastes.push({ sessionId, text, options });+ return { success: pasteSuccess };+ },+ async writeClipboard(text) {+ writes.push(text);+ return { success: true };+ },+ },+ clipboard: { async writeText() {} },+ },+ };+}++test("Assistant delivery mode follows Auto-Paste and target state", async () => {+ const { createAssistantResponseDelivery } = await deliveryModule;+ const createDelivery = (autoPasteEnabled, deliverySessionId) =>+ createAssistantResponseDelivery({+ autoPasteEnabled,+ deliverySessionId,+ ...PASTE_OPTIONS,+ });++ assert.equal(createDelivery(false), null);+ assert.deepEqual(createDelivery(true), { mode: "clipboard" });+ assert.deepEqual(createDelivery(true, "caret-session"), PASTE_DELIVERY);+});++test("a captured Assistant target receives the response without replacing the clipboard", async () => {+ const { deliverAssistantResponse } = await deliveryModule;+ const { dependencies, pastes, writes } = createDeliveryHarness(true);++ assert.deepEqual(await deliverAssistantResponse(PASTE_DELIVERY, RESPONSE, dependencies), {+ pasted: true,+ copied: false,+ });+ assert.deepEqual(pastes, [+ {+ sessionId: "caret-session",+ text: RESPONSE,+ options: PASTE_OPTIONS,+ },+ ]);+ assert.deepEqual(writes, []);+});++test("no Assistant target and a lost target both copy the completed response", async () => {+ const { deliverAssistantResponse } = await deliveryModule;++ for (const delivery of [{ mode: "clipboard" }, PASTE_DELIVERY]) {+ const { dependencies, writes } = createDeliveryHarness(false);++ assert.deepEqual(+ await deliverAssistantResponse(delivery, RESPONSE, dependencies),+ { pasted: false, copied: true },+ delivery.mode+ );+ assert.deepEqual(writes, [RESPONSE], delivery.mode);+ }+});diff --git a/test/helpers/audioManagerAssistantDirective.test.js b/test/helpers/audioManagerAssistantDirective.test.jsindex 4e3b19b4f..06a92ed8d 100644--- a/test/helpers/audioManagerAssistantDirective.test.js+++ b/test/helpers/audioManagerAssistantDirective.test.js@@ -56,6 +56,57 @@ test("a standalone command banks a panel directive and returns the transcript",assert.equal(modelCalls.length, 0, "the dictation-agent model must not run");});+test("a verified caret banks targeted response delivery when auto-paste is enabled", async (t) => {+ const { createManager } = await loadAudioManagerHarness(t, {+ cachePrefix: "openwhispr-assistant-caret-delivery-",+ settingsKey: "__assistantCaretDeliverySettings",+ settings: { autoPasteEnabled: true },+ mockModules: {+ "/services/ReasoningService": 'export default { processText: async () => "" };',+ },+ });+ const { manager, modelCalls } = managerWithCapture(createManager, {+ status: "editable",+ sessionId: "caret-session",+ });++ const result = await manager.processAgentCommand("draft a reply", "gpt", "Aria", {+ selectionEditReachable: true,+ });++ assert.equal(result, "draft a reply");+ assert.deepEqual(manager.pendingAssistantConversation, {+ transcript: "draft a reply",+ screenContext: null,+ deliverySessionId: "caret-session",+ });+ assert.equal(modelCalls.length, 0, "caret delivery must retain the chat Agent route");+});++test("a verified caret stays panel-first when auto-paste is disabled", async (t) => {+ const { createManager } = await loadAudioManagerHarness(t, {+ cachePrefix: "openwhispr-assistant-caret-panel-",+ settingsKey: "__assistantCaretPanelSettings",+ settings: { autoPasteEnabled: false },+ mockModules: {+ "/services/ReasoningService": 'export default { processText: async () => "" };',+ },+ });+ const { manager } = managerWithCapture(createManager, {+ status: "editable",+ sessionId: "caret-session",+ });++ await manager.processAgentCommand("draft a reply", "gpt", "Aria", {+ selectionEditReachable: true,+ });++ assert.deepEqual(manager.pendingAssistantConversation, {+ transcript: "draft a reply",+ screenContext: null,+ });+});+test("a wake-word command is banked without the address", async (t) => {const { createManager } = await loadAudioManager(t, {cachePrefix: "openwhispr-assistant-wakeword-",@@ -188,7 +239,10 @@ test("a too-large selection with no dictation editor goes to the panel as a plaicachePrefix: "openwhispr-assistant-toolarge-",settingsKey: "__assistantTooLargeSettings",});- const { manager } = managerWithCapture(createManager, { status: "too_large", maxCharacters: 6000 });+ const { manager } = managerWithCapture(createManager, {+ status: "too_large",+ maxCharacters: 6000,+ });const result = await manager.processAgentCommand("summarize this", "gpt", "Aria", {selectionEditReachable: false,});diff --git a/test/helpers/audioManagerSelectionPrefetch.test.js b/test/helpers/audioManagerSelectionPrefetch.test.jsindex 7616de95d..2101a8e33 100644--- a/test/helpers/audioManagerSelectionPrefetch.test.js+++ b/test/helpers/audioManagerSelectionPrefetch.test.js@@ -40,8 +40,8 @@ async function loadAudioManager(t, { cachePrefix, settingsKey }) {function countingCapture(window) {const calls = [];- window.electronAPI.captureSelectedText = async () => {- calls.push(true);+ window.electronAPI.captureSelectedText = async (options) => {+ calls.push(options);return { status: "selected", text: "selected body", sessionId: `s${calls.length}` };};return calls;@@ -63,6 +63,24 @@ test("a prefetched selection is reused instead of read again", async (t) => {assert.equal(calls.length, 1, "consuming must reuse the prefetch");});+test("the caret probe request mirrors the auto-paste setting", async (t) => {+ const { window, createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-sel-probe-flag-test-",+ settingsKey: "__selProbeFlagSettings",+ });+ const calls = countingCapture(window);+ const manager = createManager();++ globalThis.__selProbeFlagSettings = { autoPasteEnabled: true };+ manager.beginSelectionCapture();+ await manager.consumeSelectionCapture();++ globalThis.__selProbeFlagSettings = { autoPasteEnabled: false };+ await manager.consumeSelectionCapture();++ assert.deepEqual(calls, [{ probeEditable: true }, { probeEditable: false }]);+});+test("consuming without a prefetch falls back to reading on demand", async (t) => {const { window, createManager } = await loadAudioManager(t, {cachePrefix: "openwhispr-sel-ondemand-test-",diff --git a/test/helpers/selectionEditing.test.js b/test/helpers/selectionEditing.test.jsindex bda7a9a11..22e4b5e9b 100644--- a/test/helpers/selectionEditing.test.js+++ b/test/helpers/selectionEditing.test.js@@ -30,6 +30,7 @@ test("builds a structured prompt that keeps instruction and selection separate",assert.equal(extractSelectionEditReplacement(`Improved text${marker}`, marker), "Improved text");assert.throws(() => extractSelectionEditReplacement("Truncated text", marker), /incomplete/);+ assert.equal(getSelectionCaptureDisposition({ status: "editable" }), "caret");assert.equal(getSelectionCaptureDisposition({ status: "none" }), "standalone");assert.equal(getSelectionCaptureDisposition({ status: "unavailable", code: "copy_helper_unavailable" }),diff --git a/test/helpers/selectionManager.test.js b/test/helpers/selectionManager.test.jsindex 4dd367375..488d94241 100644--- a/test/helpers/selectionManager.test.js+++ b/test/helpers/selectionManager.test.js@@ -27,7 +27,11 @@ function loadSelectionManager({ spawn } = {}) {const SelectionManager = loadSelectionManager();-function makeHarness({ selections = ["original"], now = () => 1000 } = {}) {+function makeHarness({+ selections = ["original"],+ now = () => 1000,+ pasteResult = { restoreComplete: Promise.resolve() },+} = {}) {const reads = [...selections];const pastes = [];const textEditMonitor = {@@ -37,6 +41,7 @@ function makeHarness({ selections = ["original"], now = () => 1000 } = {}) {const value = reads.shift();if (value === undefined) return { state: "unavailable" };if (value === null) return { state: "none" };+ if (typeof value === "object") return value;return { state: "selected", text: value };},};@@ -44,7 +49,7 @@ function makeHarness({ selections = ["original"], now = () => 1000 } = {}) {runClipboardOperation: (operation) => operation(),_pasteText: async (text, options) => {pastes.push({ text, options });- return { restoreComplete: Promise.resolve() };+ return pasteResult;},};const manager = new SelectionManager({@@ -66,6 +71,157 @@ test("captures an exact selection in an opaque session", async () => {assert.ok(result.sessionId);});+test("captures a verified writable caret in an opaque delivery session", async () => {+ const { manager } = makeHarness({ selections: [{ state: "none", editable: true }] });+ const result = await manager.captureSelectedText({ probeEditable: true });++ assert.equal(result.status, "editable");+ assert.ok(result.sessionId);+});++test("the editable probe only runs when the capture requests it", async () => {+ const { manager } = makeHarness({ selections: [{ state: "none", editable: true }] });+ manager._isTerminalPid = async () => {+ throw new Error("must not resolve terminal identity without probeEditable");+ };++ assert.equal((await manager.captureSelectedText()).status, "none");+});++test("pastes an assistant response only while the captured caret target is still editable", async () => {+ const { manager, pastes } = makeHarness({+ selections: [+ { state: "none", editable: true },+ { state: "none", editable: true },+ ],+ });+ const capture = await manager.captureSelectedText({ probeEditable: true });+ const result = await manager.pasteAtCapturedTarget(capture.sessionId, "Agent response", {+ restoreClipboard: true,+ });++ assert.deepEqual(result, { success: true });+ assert.equal(pastes.length, 1);+ assert.equal(pastes[0].text, "Agent response");+ assert.equal(pastes[0].options.restoreClipboard, true);+});++test("does not paste an assistant response after the captured caret target changes", async () => {+ const { manager, pastes } = makeHarness({+ selections: [+ { state: "none", editable: true },+ { state: "selected", text: "new selection" },+ ],+ });+ const capture = await manager.captureSelectedText({ probeEditable: true });++ assert.deepEqual(await manager.pasteAtCapturedTarget(capture.sessionId, "Agent response"), {+ success: false,+ code: "target_changed",+ });+ assert.equal(pastes.length, 0);+});++// Generated text pasted into a shell executes on its embedded newlines, so a+// terminal's empty prompt must never read as a writable caret.+test("a macOS terminal's empty prompt never becomes a caret delivery target", async () => {+ const { manager } = makeHarness({ selections: [{ state: "none", editable: true }] });+ manager.clipboardManager.isTerminalSignature = (signature) =>+ signature.toLowerCase().includes("iterm");+ manager._readExecutablePath = async () => "/Applications/iTerm.app/Contents/MacOS/iTerm2";++ assert.equal((await manager.captureSelectedText({ probeEditable: true })).status, "none");+});++test("a terminal-flagged target is refused as a caret destination without probing", async () => {+ const probes = [];+ const manager = new SelectionManager({+ clipboardManager: {+ isTerminalSignature: (signature) => signature.toLowerCase().includes("terminal"),+ },+ textEditMonitor: {+ isFocusedEditable: async (target) => {+ probes.push(target);+ return true;+ },+ },+ platform: "win32",+ now: () => 1000,+ });+ const flagged = { kind: "win-hwnd", id: "1A", isTerminal: true };+ const byExeName = { kind: "win-hwnd", id: "2B", exeName: "WindowsTerminal.exe" };+ const editor = { kind: "win-hwnd", id: "3C", exeName: "notepad.exe" };++ assert.equal(+ (await manager._markEditableCaret({ status: "none", target: flagged }, flagged, true)).status,+ "none"+ );+ assert.equal(+ (await manager._markEditableCaret({ status: "none", target: byExeName }, byExeName, true))+ .status,+ "none"+ );+ assert.equal(probes.length, 0);+ assert.equal(+ (await manager._markEditableCaret({ status: "none", target: editor }, editor, true)).status,+ "editable"+ );+ assert.equal(probes.length, 1);+});++// AT-SPI targets carry only a pid — no window class or exe name for the+// signature check — so the executable name must be resolved before a Wayland+// terminal's empty prompt can read as a writable caret.+test("a Linux AT-SPI terminal pid never becomes a caret delivery target", async () => {+ const probes = [];+ const executableByPid = { 4321: "gnome-terminal-", 8765: "gedit" };+ const manager = new SelectionManager({+ clipboardManager: {+ isTerminalSignature: (signature) => signature.toLowerCase().includes("gnome-terminal"),+ },+ textEditMonitor: {+ isFocusedEditable: async (target) => {+ probes.push(target);+ return true;+ },+ },+ platform: "linux",+ now: () => 1000,+ });+ manager._readExecutablePath = async (pid) => executableByPid[pid] ?? "";+ const terminal = { kind: "atspi-pid", id: "4321" };+ const editor = { kind: "atspi-pid", id: "8765" };++ assert.equal(+ (await manager._markEditableCaret({ status: "none", target: terminal }, terminal, true))+ .status,+ "none"+ );+ assert.equal(probes.length, 0, "a terminal pid must be refused without probing");+ assert.equal(+ (await manager._markEditableCaret({ status: "none", target: editor }, editor, true)).status,+ "editable"+ );+ assert.equal(probes.length, 1);+});++test("treats a clipboard-only fallback as a failed targeted paste", async () => {+ const { manager, pastes } = makeHarness({+ selections: [+ { state: "none", editable: true },+ { state: "none", editable: true },+ ],+ pasteResult: { restoreComplete: Promise.resolve(), pasted: false },+ });+ const capture = await manager.captureSelectedText({ probeEditable: true });++ assert.deepEqual(await manager.pasteAtCapturedTarget(capture.sessionId, "Agent response"), {+ success: false,+ code: "paste_failed",+ });+ assert.equal(pastes.length, 1);+});+test("replaces only when target and exact selection still match", async () => {const { manager, pastes } = makeHarness({ selections: ["original", "original"] });const capture = await manager.captureSelectedText();@@ -370,6 +526,33 @@ test("getWinTargetHwnd is null without a capture or with a non-Windows target",assert.equal(await manager.getWinTargetHwnd(), null);});+test("caret delivery pins the captured Windows HWND into the paste helper", async () => {+ const pastes = [];+ const manager = new SelectionManager({+ clipboardManager: {+ runClipboardOperation: (operation) => operation(),+ _pasteText: async (text, options) => {+ pastes.push({ text, options });+ return { restoreComplete: Promise.resolve() };+ },+ },+ textEditMonitor: {},+ platform: "win32",+ now: () => 1000,+ });+ manager.sessions.set("caret-session", {+ kind: "caret",+ target: { kind: "win-hwnd", id: "00001A2B" },+ expiresAt: 2000,+ });+ manager._readCurrentSelection = async () => ({ status: "editable" });++ assert.deepEqual(await manager.pasteAtCapturedTarget("caret-session", "Agent response"), {+ success: true,+ });+ assert.equal(pastes[0].options.targetWindow, "00001A2B");+});+// Replacement text typed into a shell executes on its embedded newlines, so a// terminal target must read as no selection (standalone dictation), not as an// editable selection.@@ -380,7 +563,7 @@ test("a terminal target reads as no selection", async () => {};const manager = new SelectionManager({clipboardManager,- textEditMonitor: {},+ textEditMonitor: { isFocusedEditable: async () => true },platform: "linux",now: () => 1000,});diff --git a/test/helpers/textEditMonitorSelection.test.js b/test/helpers/textEditMonitorSelection.test.jsindex aec0b683d..d706d73c1 100644--- a/test/helpers/textEditMonitorSelection.test.js+++ b/test/helpers/textEditMonitorSelection.test.js@@ -92,6 +92,41 @@ test("getSelectedText skips the native binary for a cached PID", darwinOnly, asyassert.deepEqual(await m.getSelectedText(42), { state: "none" });});+test("getSelectedText identifies an empty writable field", darwinOnly, async () => {+ const m = new TextEditMonitor();+ m.resolveBinary = () => ({ command: "/bin/sh", args: ["-c", 'echo "EDITABLE_NONE:"'] });++ assert.deepEqual(await m.getSelectedText(42), { state: "none", editable: true });+});++test("isFocusedEditable accepts only an explicit native editable verdict", darwinOnly, async () => {+ const editable = new TextEditMonitor();+ editable.resolveBinary = () => ({ command: "/bin/sh", args: ["-c", 'echo "EDITABLE"'] });+ const readOnly = new TextEditMonitor();+ readOnly.resolveBinary = () => ({+ command: "/bin/sh",+ args: ["-c", 'echo "NOT_EDITABLE"'],+ });++ assert.equal(await editable.isFocusedEditable({ kind: "mac-pid", pid: 42 }), true);+ assert.equal(await readOnly.isFocusedEditable({ kind: "mac-pid", pid: 42 }), false);+});++test("isFocusedEditable answers from a stale binary's first monitor line", darwinOnly, async () => {+ const m = new TextEditMonitor();+ // A binary that predates the probe flag falls into monitor mode: one+ // initial-value line, then it keeps running. The probe must settle on that+ // first line instead of hanging until the timeout.+ m.resolveBinary = () => ({+ command: "/bin/sh",+ args: ["-c", 'echo "INITIAL_VALUE:stale"; sleep 2'],+ });++ const startedAt = Date.now();+ assert.equal(await m.isFocusedEditable({ kind: "mac-pid", pid: 42 }), false);+ assert.ok(Date.now() - startedAt < 900, "must resolve on the first output line");+});+test("a non--25212 native failure is not cached", darwinOnly, async () => {const m = new TextEditMonitor();m.resolveBinary = () => ({diff --git a/test/helpers/useChatStreamingCancellation.test.js b/test/helpers/useChatStreamingCancellation.test.jsindex 25c95e711..2908f9f3b 100644--- a/test/helpers/useChatStreamingCancellation.test.js+++ b/test/helpers/useChatStreamingCancellation.test.js@@ -4,7 +4,11 @@ const fs = require("node:fs");const path = require("node:path");const React = require("react");const { renderToStaticMarkup } = require("react-dom/server");-const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");+const {+ createRendererServer,+ installBrowserGlobals,+ installHookDom,+} = require("../lib/rendererTestHarness");// Real end-to-end coverage for useChatStreaming.ts's empty-response fallback// and its interaction with cancellation (Esc/Stop, or an unmount mid-stream).@@ -27,10 +31,10 @@ const { createRendererServer, installBrowserGlobals } = require("../lib/renderer// for its markup-only assertions), but this narrower technique — one// synchronous render, then calling the returned functions like any other// closures — does not need any of those. The one thing SSR genuinely cannot-// do is run `useEffect` bodies, so the unmount cleanup that also calls-// `cancelStream()` (see useChatStreaming.ts's mount/unmount effect) is-// exercised by code reading, not by this test: it is a single, unconditional-// call to the same `cancelStream` these tests already prove correct.+// do is run `useEffect` bodies, so the unmount-mid-stream test mounts the+// hook for real (installHookDom + createRoot) to drive the actual unmount+// cleanup, whose cancel must persist the partial reply rather than drop it+// the way an explicit Esc/Stop cancel does.function createOpenAiChunk(delta, finishReason = null) {return {id: "chatcmpl-cancellation-test",@@ -45,8 +49,12 @@ const EMPTY_RESPONSE_TEXT = JSON.parse(fs.readFileSync(path.join(__dirname, "../../src/locales/en/translation.json"), "utf8")).agentMode.chat.emptyResponse;-async function renderChatStreaming(t, { electronAPI = {}, settings = {} } = {}) {+async function renderChatStreaming(+ t,+ { electronAPI = {}, settings = {}, onStreamComplete, live = false } = {}+) {installBrowserGlobals(t, { window: { electronAPI } });+ const container = live ? installHookDom(t) : null;const vite = await createRendererServer(t, {cachePrefix: "openwhispr-chat-streaming-cancellation-test-",});@@ -99,18 +107,35 @@ async function renderChatStreaming(t, { electronAPI = {}, settings = {} } = {})captured = useChatStreaming({messages,setMessages,+ onStreamComplete,onResponseContent: () => {responseContentCalls += 1;},});return null;}- renderToStaticMarkup(React.createElement(Harness));++ let unmount;+ if (live) {+ const { createRoot } = require("react-dom/client");+ const root = createRoot(container);+ await React.act(async () => root.render(React.createElement(Harness)));+ let unmounted = false;+ unmount = async () => {+ if (unmounted) return;+ unmounted = true;+ await React.act(async () => root.unmount());+ };+ t.after(unmount);+ } else {+ renderToStaticMarkup(React.createElement(Harness));+ }return {captured,getMessages: () => messages,getResponseContentCalls: () => responseContentCalls,+ unmount,};}@@ -129,13 +154,49 @@ test("a genuine empty completion still shows the empty-response fallback", async});};+ let completionCalls = 0;const { captured, getMessages } = await renderChatStreaming(t);- await captured.sendToAI("hello", []);+ await captured.sendToAI("hello", [], {+ suppressResponseContent: true,+ onComplete: () => {+ completionCalls += 1;+ },+ });const [message] = getMessages();assert.equal(message.content, EMPTY_RESPONSE_TEXT);assert.equal(message.isStreaming, false);+ assert.equal(completionCalls, 0);+});++test("a completed response runs its request delivery hook without opening response content", async (t) => {+ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ globalThis.fetch = async () => {+ const contentEvent = `data: ${JSON.stringify(+ createOpenAiChunk({ content: "Agent answer" })+ )}\n\n`;+ const finishEvent = `data: ${JSON.stringify(createOpenAiChunk({}, "stop"))}\n\n`;+ return new Response(`${contentEvent}${finishEvent}data: [DONE]\n\n`, {+ status: 200,+ headers: { "content-type": "text/event-stream" },+ });+ };++ const completions = [];+ const { captured, getResponseContentCalls } = await renderChatStreaming(t);++ await captured.sendToAI("hello", [], {+ suppressResponseContent: true,+ onComplete: (result) => completions.push(result),+ });++ assert.equal(getResponseContentCalls(), 0);+ assert.equal(completions.length, 1);+ assert.equal(completions[0].content, "Agent answer");});test("cancelling during RAG setup does not start an assistant reply", async (t) => {@@ -199,9 +260,19 @@ test("cancelling before any token arrives never shows the empty-response fallbacreturn new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } });};- const { captured, getMessages } = await renderChatStreaming(t);+ let streamCompleteCalls = 0;+ const { captured, getMessages } = await renderChatStreaming(t, {+ onStreamComplete: () => {+ streamCompleteCalls += 1;+ },+ });- const sendPromise = captured.sendToAI("hello", []);+ let completionCalls = 0;+ const sendPromise = captured.sendToAI("hello", [], {+ onComplete: () => {+ completionCalls += 1;+ },+ });const waitForMicrotasks = () => new Promise((resolve) => setImmediate(resolve));for (let i = 0; i < 50 && !fetchStarted; i++) await waitForMicrotasks();@@ -219,6 +290,83 @@ test("cancelling before any token arrives never shows the empty-response fallbacassert.notEqual(message.content, EMPTY_RESPONSE_TEXT);assert.equal(message.content, "");assert.equal(message.isStreaming, false);+ assert.equal(completionCalls, 0, "a cancelled request must never deliver a response");+ assert.equal(streamCompleteCalls, 0, "a cancelled request must never persist a partial reply");+});++test("an unmount mid-stream persists the partial reply without delivering it", async (t) => {+ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });++ const encoder = new TextEncoder();+ let releaseTail;+ const tailGate = new Promise((resolve) => {+ releaseTail = resolve;+ });+ globalThis.fetch = async () =>+ new Response(+ new ReadableStream({+ async start(controller) {+ controller.enqueue(+ encoder.encode(+ `data: ${JSON.stringify(createOpenAiChunk({ content: "Partial reply" }))}\n\n`+ )+ );+ // Hold the stream open across the unmount so the tail arrives after+ // the cleanup's cancel, the way a page navigation interrupts a send.+ await tailGate;+ controller.enqueue(+ encoder.encode(`data: ${JSON.stringify(createOpenAiChunk({}, "stop"))}\n\n`)+ );+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));+ controller.close();+ },+ }),+ { status: 200, headers: { "content-type": "text/event-stream" } }+ );++ const persisted = [];+ const { captured, getMessages, unmount } = await renderChatStreaming(t, {+ live: true,+ onStreamComplete: (_id, content) => persisted.push(content),+ });++ let completionCalls = 0;+ let sendPromise;+ const waitForMicrotasks = () => new Promise((resolve) => setImmediate(resolve));+ await React.act(async () => {+ sendPromise = captured.sendToAI("hello", [], {+ onComplete: () => {+ completionCalls += 1;+ },+ });+ for (+ let i = 0;+ i < 50 && !getMessages().some((m) => m.content === "Partial reply");+ i+++ ) {+ await waitForMicrotasks();+ }+ });+ assert.ok(+ getMessages().some((m) => m.content === "Partial reply"),+ "the partial token must arrive before the unmount"+ );++ await unmount();+ releaseTail();+ await sendPromise;++ assert.deepEqual(+ persisted,+ ["Partial reply"],+ "an unmounted stream must keep its partial reply in history"+ );+ assert.equal(completionCalls, 0, "an unmounted request must never deliver a response");+ const assistantMessage = getMessages().find((m) => m.role === "assistant");+ assert.equal(assistantMessage.isStreaming, false);});test("cancelling a tool-ineligible raw stream after reading starts shows no error", async (t) => {diff --git a/test/helpers/windowsTextMonitorBuild.test.js b/test/helpers/windowsTextMonitorBuild.test.jsnew file mode 100644index 000000000..9c83312c9--- /dev/null+++ b/test/helpers/windowsTextMonitorBuild.test.js@@ -0,0 +1,18 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");++test("Windows text monitor builds current source before using a released fallback", () => {+ const source = fs.readFileSync(+ path.join(__dirname, "../../scripts/build-windows-text-monitor.js"),+ "utf8"+ );+ const main = source.slice(source.indexOf("async function main()"));+ const compileIndex = main.indexOf("tryCompile()");+ const downloadIndex = main.indexOf("tryDownload()");++ assert.notEqual(compileIndex, -1, "main() should try local compilation");+ assert.notEqual(downloadIndex, -1, "main() should retain the download fallback");+ assert.ok(compileIndex < downloadIndex, "local compilation should run first");+});