Skip to content

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

38.6 KB
Raw Blame
const test = require("node:test");
const assert = require("node:assert/strict");
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 noop = () => {};

const { installInteractiveDom, findElement } = require("../lib/interactiveDom");

// Loads the real AssistantPanel with its heavier dependencies mocked, and real
// i18n so translated text (not keys) renders.
async function setupAssistantPanel(
  t,
  messages,
  {
    initialConversationId = null,
    agentState = "idle",
    activeToolName = null,
    locale = "en",
    approvals = {},
    realMarkdown = false,
  } = {}
) {
  installBrowserGlobals(t);
  globalThis.__assistantPanelMessages = messages;
  globalThis.__assistantPanelAgentState = agentState;
  globalThis.__assistantPanelActiveToolName = activeToolName;
  globalThis.__assistantPanelApprovals = approvals;
  t.after(() => {
    delete globalThis.__assistantPanelMessages;
    delete globalThis.__assistantPanelAgentState;
    delete globalThis.__assistantPanelActiveToolName;
    delete globalThis.__assistantPanelApprovals;
    delete globalThis.__assistantPanelStreamingOptions;
    delete globalThis.__assistantPanelCopyText;
    delete globalThis.__assistantPanelCopyFeedbackText;
  });

  const vite = await createRendererServer(t, {
    cachePrefix: "openwhispr-assistant-panel-test-",
    mockModules: {
      "/chat/useChatPersistence": `
        export function useChatPersistence() {
          return {
            messages: globalThis.__assistantPanelMessages,
            setMessages() {},
            conversationId: null,
            async createConversation() { return 1; },
            async loadConversation() {},
            saveUserMessage() {},
            saveAssistantMessage() {},
            handleNewChat() {},
          };
        }
      `,
      "/chat/useChatStreaming": `
        export function useChatStreaming(options) {
          globalThis.__assistantPanelStreamingOptions = options;
          return {
            agentState: globalThis.__assistantPanelAgentState,
            activeToolName: globalThis.__assistantPanelActiveToolName,
            toolStatus: "",
            cancelStream() {},
          };
        }
      `,
      "/chat/useChatMessageSender": `
        export function useChatMessageSender() { return () => {}; }
      `,
      useVoiceDraft: `
        export function useVoiceDraft() {
          return { status: "idle", elapsed: 0, readLevel: () => 0, start() {}, stop() {}, cancel() {} };
        }
      `,
      "/hooks/useWindowDrag": `
        export function useWindowDrag() { return { handleMouseDown() {}, handleMouseUp() {} }; }
      `,
      "/hooks/useCopyFeedback": `
        export function useCopyFeedback(text) {
          globalThis.__assistantPanelCopyFeedbackText = text;
          return {
            copied: false,
            async copy() {},
            async copyText(copied) {
              globalThis.__assistantPanelCopyText = copied;
              return true;
            },
            confirmCopied() {},
          };
        }
      `,
      "/stores/settingsStore": `
        const state = { voiceAgentKey: [] };
        export function useSettingsStore(selector) { return selector(state); }
      `,
      "/utils/hotkeys": `
        export function formatHotkeyListLabel() { return ""; }
      `,
      ...(realMarkdown
        ? {}
        : {
            "/ui/MarkdownRenderer": `
          import React from "react";
          export function MarkdownRenderer({ content, className }) {
            return React.createElement("div", { className }, content);
          }
        `,
          }),
      "/ui/useToast": `
        export function useToast() { return { toast() {} }; }
      `,
      "/stores/connectorApprovalStore": `
        export function useConnectorApprovalStore(selector) {
          return selector({ entries: globalThis.__assistantPanelApprovals || {} });
        }
        export function approvalKey(messageId, toolCallId) {
          return messageId + "::" + toolCallId;
        }
      `,
      "/chat/ApprovalCard": `
        import React from "react";
        export function ApprovalCard({ entry }) {
          return React.createElement("div", { "data-approval-card": entry.toolCallId, "data-state": entry.state });
        }
      `,
    },
  });
  const [{ default: viteI18next }, { initReactI18next }] = await Promise.all([
    vite.ssrLoadModule("i18next"),
    vite.ssrLoadModule("react-i18next"),
  ]);
  const translation = JSON.parse(
    fs.readFileSync(path.join(__dirname, `../../src/locales/${locale}/translation.json`), "utf8")
  );
  await viteI18next.use(initReactI18next).init({
    lng: locale,
    resources: { [locale]: { translation } },
    interpolation: { escapeValue: false },
  });
  const { AssistantPanel } = await vite.ssrLoadModule("/components/dictation/AssistantPanel.tsx");
  const props = {
    pendingCommand: null,
    onCommandConsumed: noop,
    onCommandDiscarded: noop,
    initialConversationId,
    onConversationIdChange: noop,
    voiceState: "idle",
    thinking: false,
    open: true,
    footerPhase: "pill",
    horizontalDirection: "right",
    onClose: noop,
    onBusyChange: noop,
    onResponseReadyChange: noop,
    onResponseContent: noop,
    onConversationReset: noop,
    onSelectionContextChange: noop,
  };
  return { AssistantPanel, props };
}

async function renderAssistantPanel(t, messages, options) {
  const { AssistantPanel, props } = await setupAssistantPanel(t, messages, options);
  return renderToStaticMarkup(React.createElement(AssistantPanel, props));
}

test("an empty idle Assistant shows typed input and generic suggestions", async (t) => {
  const markup = await renderAssistantPanel(t, []);

  assert.match(markup, /<textarea\b[^>]*dir="auto"/);
  assert.match(markup, /Summarize my recent notes/);
  assert.match(markup, /What is on my calendar\?/);
  assert.match(markup, /Help me draft something/);
});

test("a populated Assistant keeps typed input without empty-state suggestions", async (t) => {
  const markup = await renderAssistantPanel(t, [
    { id: "assistant-1", role: "assistant", content: "Existing answer", isStreaming: false },
  ]);

  assert.match(markup, /Existing answer/);
  assert.match(markup, /<textarea\b[^>]*dir="auto"/);
  assert.doesNotMatch(markup, /Summarize my recent notes/);
});

test("starting a new conversation clears the displayed response and parent content ownership", async (t) => {
  let root = null;
  t.after(async () => {
    if (root) await React.act(async () => root.unmount());
  });
  installBrowserGlobals(t);
  const container = installInteractiveDom(t);
  const lifecycleEvents = [];
  globalThis.__assistantPanelLifecycleEvents = lifecycleEvents;
  t.after(() => {
    delete globalThis.__assistantPanelLifecycleEvents;
  });

  const vite = await createRendererServer(t, {
    cachePrefix: "openwhispr-assistant-panel-reset-test-",
    mockModules: {
      "/components/icons": `
        import React from "react";
        const Icon = () => React.createElement("span");
        export const Check = Icon;
        export const Copy = Icon;
        export const Plus = Icon;
        export const X = Icon;
      `,
      "/chat/useChatPersistence": `
        import { useCallback, useState } from "react";
        const initialMessages = [
          { id: "assistant-1", role: "assistant", content: "Prior rendered response", isStreaming: false },
        ];
        export function useChatPersistence() {
          const [messages, setMessages] = useState(initialMessages);
          const [conversationId, setConversationId] = useState(42);
          const handleNewChat = useCallback(() => {
            globalThis.__assistantPanelLifecycleEvents.push("persistence-reset");
            setMessages([]);
            setConversationId(null);
          }, []);
          return {
            messages,
            setMessages,
            conversationId,
            async createConversation() { return 1; },
            async loadConversation() {},
            saveUserMessage() {},
            saveAssistantMessage() {},
            handleNewChat,
          };
        }
      `,
      "/chat/useChatStreaming": `
        import { useEffect } from "react";
        export function useChatStreaming({ onResponseContent }) {
          useEffect(() => onResponseContent(), [onResponseContent]);
          return {
            agentState: "idle",
            activeToolName: null,
            toolStatus: "",
            cancelStream() {},
          };
        }
      `,
      "/chat/useChatMessageSender": `
        export function useChatMessageSender() { return async () => true; }
      `,
      "/chat/ChatInput": `
        import React from "react";
        export function ChatInput() { return React.createElement("input"); }
      `,
      "/dictation/AssistantEmptyState": `
        import React from "react";
        export function AssistantEmptyState() { return React.createElement("div", null, "Empty state"); }
      `,
      "/dictation/BrandMarkIcon": `
        import React from "react";
        export function BrandMarkIcon() { return React.createElement("span"); }
      `,
      "/ui/MarkdownRenderer": `
        import React from "react";
        export function MarkdownRenderer({ content }) { return React.createElement("div", null, content); }
      `,
      "/ui/button": `
        import React from "react";
        export function Button(props) { return React.createElement("button", props); }
      `,
      "/hooks/useWindowDrag": `
        export function useWindowDrag() { return { handleMouseDown() {}, handleMouseUp() {} }; }
      `,
      "/hooks/useCopyFeedback": `
        export function useCopyFeedback() {
          return { copied: false, async copy() {}, confirmCopied() {} };
        }
      `,
      "/stores/settingsStore": `
        const state = { voiceAgentKey: [] };
        export function useSettingsStore(selector) { return selector(state); }
      `,
      "/utils/hotkeys": `
        export function formatHotkeyListLabel() { return ""; }
      `,
      "/ui/useToast": `
        export function useToast() { return { toast() {} }; }
      `,
    },
  });
  const [{ default: viteI18next }, { initReactI18next }] = await Promise.all([
    vite.ssrLoadModule("i18next"),
    vite.ssrLoadModule("react-i18next"),
  ]);
  const translation = JSON.parse(
    fs.readFileSync(path.join(__dirname, "../../src/locales/en/translation.json"), "utf8")
  );
  await viteI18next.use(initReactI18next).init({
    lng: "en",
    resources: { en: { translation } },
    interpolation: { escapeValue: false },
  });
  const [{ AssistantPanel }, { useAssistantPanel }] = await Promise.all([
    vite.ssrLoadModule("/components/dictation/AssistantPanel.tsx"),
    vite.ssrLoadModule("/hooks/useAssistantPanel.js"),
  ]);
  const { createRoot } = require("react-dom/client");
  let dictationErrorActionCount = 0;
  let assistant;
  const requestMainWindowSize = async () => ({ success: true });
  const recordingControlsRef = { current: null };

  function Harness() {
    assistant = useAssistantPanel({
      requestMainWindowSize,
      dictationErrorActionCount,
      recordingControlsRef,
    });
    return React.createElement(AssistantPanel, {
      pendingCommand: null,
      onCommandConsumed: noop,
      onCommandDiscarded: noop,
      onCommandSettled: noop,
      initialConversationId: 42,
      onConversationIdChange: (conversationId) => {
        lifecycleEvents.push(`conversation:${conversationId}`);
        assistant.setConversationId(conversationId);
      },
      voiceState: "idle",
      thinking: false,
      open: true,
      footerPhase: "pill",
      horizontalDirection: "right",
      onClose: noop,
      onBusyChange: assistant.setBusy,
      onResponseReadyChange: assistant.setResponseReady,
      onResponseContent: assistant.handleResponseContent,
      onConversationReset: () => {
        lifecycleEvents.push("content-reset");
        assistant.handleConversationReset();
      },
      onSelectionContextChange: (context) => lifecycleEvents.push(`selection:${context}`),
    });
  }

  root = createRoot(container);
  await React.act(async () => root.render(React.createElement(Harness)));
  assert.match(container.textContent, /Prior rendered response/);
  assert.equal(assistant.openRef.current, true);

  lifecycleEvents.length = 0;
  const newConversationButton = findElement(
    container,
    (element) => element.getAttribute("aria-label") === "New conversation"
  );
  assert.ok(newConversationButton, "fixture setup: populated Assistant exposes reset control");
  await React.act(async () => {
    newConversationButton.dispatchEvent({
      type: "click",
      bubbles: true,
      button: 0,
      defaultPrevented: false,
      cancelBubble: false,
      preventDefault() {
        this.defaultPrevented = true;
      },
      stopPropagation() {
        this.cancelBubble = true;
      },
    });
  });

  assert.doesNotMatch(container.textContent, /Prior rendered response/);
  assert.deepEqual(lifecycleEvents.slice(0, 4), [
    "persistence-reset",
    "conversation:null",
    "selection:null",
    "content-reset",
  ]);

  await React.act(async () => assistant.noteDictationError({ recoverAssistant: true }));
  dictationErrorActionCount = 1;
  await React.act(async () => root.render(React.createElement(Harness)));
  assert.equal(assistant.closing, true);
  await React.act(async () => assistant.completeContentFade());
  assert.equal(assistant.openRef.current, false);
});

test("the Assistant exposes an accessible new-conversation control only after messages exist", async (t) => {
  const populatedMarkup = await renderAssistantPanel(t, [
    { id: "assistant-1", role: "assistant", content: "Existing answer", isStreaming: false },
  ]);
  const emptyMarkup = await renderAssistantPanel(t, []);

  assert.match(populatedMarkup, /<button[^>]*aria-label="New conversation"/);
  assert.doesNotMatch(emptyMarkup, /<button[^>]*aria-label="New conversation"/);
});

test("a reopened Assistant blocks typed actions until retained history finishes loading", async (t) => {
  const markup = await renderAssistantPanel(t, [], { initialConversationId: 42 });

  assert.match(markup, /<textarea\b[^>]*readOnly=""/);
  assert.doesNotMatch(markup, /Summarize my recent notes/);
});

test("the Assistant response cancel control has an accessible name", async (t) => {
  const markup = await renderAssistantPanel(t, [], { agentState: "streaming" });

  assert.match(markup, /<button[^>]*aria-label="Cancel"[^>]*title="Cancel"/);
});

test("the Assistant localizes the active registered tool name", async (t) => {
  const markup = await renderAssistantPanel(t, [], {
    activeToolName: "search_notes",
    locale: "es",
  });

  assert.match(markup, />Buscar notas</);
  assert.doesNotMatch(markup, />Search notes</);
});

test("the Assistant uses its localized fallback for an unknown active tool", async (t) => {
  const markup = await renderAssistantPanel(t, [], {
    activeToolName: "unregistered_tool",
    locale: "es",
  });

  assert.match(markup, />Herramienta</);
  assert.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("Assistant selection copy preserves the selected text without claiming Copied", async (t) => {
  let root = null;
  t.after(async () => {
    if (root) await React.act(async () => root.unmount());
  });
  installBrowserGlobals(t);
  const container = installInteractiveDom(t);
  const writes = [];
  const originalElectronAPI = globalThis.window.electronAPI;
  t.after(() => {
    globalThis.window.electronAPI = originalElectronAPI;
  });
  globalThis.window.electronAPI = {
    writeClipboard: async (text) => {
      writes.push(text);
      return { success: true };
    },
  };

  const vite = await createRendererServer(t, {
    cachePrefix: "openwhispr-selection-copy-feedback-test-",
  });
  const { useCopyFeedback } = await vite.ssrLoadModule("/hooks/useCopyFeedback.ts");
  const { createRoot } = require("react-dom/client");
  let copyFeedback;

  function Harness() {
    copyFeedback = useCopyFeedback("Full Agent answer");
    return React.createElement("button");
  }

  root = createRoot(container);
  await React.act(async () => root.render(React.createElement(Harness)));
  await React.act(async () => copyFeedback.copyText(" selected answer "));
  assert.equal(copyFeedback.copied, false, "a partial copy never shows the Copied state");
  await React.act(async () => copyFeedback.copy());
  assert.equal(copyFeedback.copied, true);

  assert.deepEqual(writes, [" selected answer ", "Full Agent answer"]);
});

test("Assistant selection must stay entirely inside the response root", async (t) => {
  installBrowserGlobals(t);
  const vite = await createRendererServer(t, {
    cachePrefix: "openwhispr-assistant-selection-test-",
  });
  const { getSelectionForCopyShortcut, getSelectionInside } = await vite.ssrLoadModule(
    "/utils/assistantSelection.ts"
  );
  const insideStart = {};
  const insideEnd = {};
  const outside = {};
  const responseRoot = {
    contains: (node) => node === insideStart || node === insideEnd,
  };
  const originalGetSelection = globalThis.window.getSelection;
  t.after(() => {
    globalThis.window.getSelection = originalGetSelection;
  });

  globalThis.window.getSelection = () => ({
    isCollapsed: false,
    rangeCount: 1,
    getRangeAt: () => ({ startContainer: insideStart, endContainer: insideEnd }),
    toString: () => "selected answer",
  });
  assert.equal(getSelectionInside(responseRoot), "selected answer");
  assert.equal(
    getSelectionForCopyShortcut(
      { key: "c", ctrlKey: true, metaKey: false, altKey: false },
      responseRoot
    ),
    "selected answer"
  );
  assert.equal(
    getSelectionForCopyShortcut(
      { key: "c", ctrlKey: false, metaKey: true, altKey: false },
      responseRoot
    ),
    "selected answer"
  );
  assert.equal(
    getSelectionForCopyShortcut(
      { key: "c", ctrlKey: true, metaKey: false, altKey: true },
      responseRoot
    ),
    null
  );
  assert.equal(
    getSelectionForCopyShortcut(
      { key: "c", ctrlKey: true, metaKey: false, altKey: false, target: { tagName: "TEXTAREA" } },
      responseRoot
    ),
    null
  );

  globalThis.window.getSelection = () => ({
    isCollapsed: false,
    rangeCount: 1,
    getRangeAt: () => ({ startContainer: insideStart, endContainer: outside }),
    toString: () => "mixed selection",
  });
  assert.equal(getSelectionInside(responseRoot), null);
});

// The Open Settings link and technical details must never ride along in a
// drag-select + copy over the response, or the clipboard would pick up UI
// chrome instead of just the answer.
test("Cmd+C copies a selection in a classified error's answer, but not one running into its Open Settings or details", async (t) => {
  let root = null;
  t.after(async () => {
    if (root) await React.act(async () => root.unmount());
  });
  installBrowserGlobals(t);
  const container = installInteractiveDom(t);
  t.mock.method(globalThis.document, "addEventListener");

  const { AssistantPanel, props } = await setupAssistantPanel(t, [
    {
      id: "assistant-1",
      role: "assistant",
      content: "Error: OpenAI rejected your API key.",
      isStreaming: false,
      error: { settingsTarget: "llms", technicalDetails: { provider: "OpenAI", status: 401 } },
    },
  ]);
  const { createRoot } = require("react-dom/client");
  root = createRoot(container);
  await React.act(async () => root.render(React.createElement(AssistantPanel, props)));

  const answer = findElement(
    container,
    (element) => element.textContent === "Error: OpenAI rejected your API key."
  );
  const settingsButton = findElement(
    container,
    (element) => element.tagName === "BUTTON" && element.textContent.includes("Open Settings")
  );
  const details = findElement(container, (element) => element.tagName === "DETAILS");
  assert.ok(answer && settingsButton && details, "shows the answer, Open Settings and details");

  let selectionEnd = null;
  globalThis.window.getSelection = () => ({
    isCollapsed: false,
    rangeCount: 1,
    getRangeAt: () => ({ startContainer: answer, endContainer: selectionEnd }),
    toString: () => "selected text",
  });
  const onKeyDown = globalThis.document.addEventListener.mock.calls.findLast(
    (call) => call.arguments[0] === "keydown"
  ).arguments[1];
  const copiesSelectionEndingIn = (node) => {
    selectionEnd = node;
    const preventDefault = t.mock.fn();
    onKeyDown({ key: "c", metaKey: true, ctrlKey: false, altKey: false, preventDefault });
    return preventDefault.mock.callCount() === 1;
  };

  assert.equal(copiesSelectionEndingIn(answer), true, "a selection inside the answer is copied");
  assert.equal(copiesSelectionEndingIn(settingsButton), false, "Open Settings is never copied");
  assert.equal(copiesSelectionEndingIn(details), false, "technical details are never copied");
});

test("a failed Assistant resize releases its open claim so opening can retry", async (t) => {
  installBrowserGlobals(t);
  const vite = await createRendererServer(t, {
    cachePrefix: "openwhispr-assistant-open-failure-test-",
  });
  const { useAssistantPanel } = await vite.ssrLoadModule("/hooks/useAssistantPanel.js");
  let resizeCalls = 0;
  let assistant;

  function Harness() {
    assistant = useAssistantPanel({
      requestMainWindowSize: async () => {
        resizeCalls += 1;
        throw new Error("resize failed");
      },
      dictationErrorActionCount: 0,
      recordingControlsRef: { current: null },
    });
    return null;
  }
  renderToStaticMarkup(React.createElement(Harness));

  await assistant.openPanel();
  await assistant.openPanel();

  assert.equal(resizeCalls, 2);
  assert.equal(assistant.openRef.current, false);
});

test("a failed live-transcript resize releases its open claim so opening can retry", async (t) => {
  installBrowserGlobals(t);
  const vite = await createRendererServer(t, {
    cachePrefix: "openwhispr-live-transcript-open-failure-test-",
  });
  const { useLiveTranscriptPanel } = await vite.ssrLoadModule("/hooks/useLiveTranscriptPanel.js");
  let resizeCalls = 0;
  let liveTranscript;

  function Harness() {
    liveTranscript = useLiveTranscriptPanel({
      resizeToContent: async () => {
        resizeCalls += 1;
        throw new Error("resize failed");
      },
      assistantOpenRef: { current: false },
      isRecording: true,
      isProcessing: false,
      isAssistantVoice: false,
    });
    return null;
  }
  renderToStaticMarkup(React.createElement(Harness));

  liveTranscript.reopen();
  await new Promise((resolve) => setImmediate(resolve));
  liveTranscript.reopen();
  await new Promise((resolve) => setImmediate(resolve));

  assert.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,
        plainText: true,
      },
    });
  });
  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,
    plainText: true,
  };

  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);
});

test("spoken commands answer on the Voice Assistant scope with connector tools offered", async (t) => {
  await renderAssistantPanel(t, []);

  const options = globalThis.__assistantPanelStreamingOptions;
  assert.equal(options.inferenceScope, "dictationAgent");
  assert.equal(options.allowConnectors, true);
});

test("a pending approval shows in the panel and replaces the tool overlay", async (t) => {
  const markup = await renderAssistantPanel(
    t,
    [
      { id: "user-1", role: "user", content: "post the summary to eng", isStreaming: false },
      {
        id: "assistant-1",
        role: "assistant",
        content: "",
        isStreaming: true,
        toolCalls: [
          { id: "call-1", name: "slack_send_message", arguments: "{}", status: "executing" },
        ],
      },
    ],
    {
      agentState: "tool-executing",
      activeToolName: "slack_send_message",
      approvals: {
        "assistant-1::call-1": {
          key: "assistant-1::call-1",
          messageId: "assistant-1",
          toolCallId: "call-1",
          actionId: "a1",
          connectorId: "slack",
          state: "pending",
          preview: {
            verbKey: "default",
            destinationLabel: "#eng",
            accountLabel: "chad",
            body: "x",
          },
        },
      },
    }
  );

  assert.match(markup, /data-approval-card="call-1"/);
  assert.doesNotMatch(markup, /data-tool-invocation=/);
});

test("an approval request opens the hidden panel of a caret-delivered command", 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-approval-open-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: "post the summary to eng",
      attachment: null,
      selectedContext: null,
      delivery: {
        mode: "paste",
        sessionId: "caret-session",
        restoreClipboard: true,
        allowClipboardFallback: false,
      },
    });
  });
  assert.equal(assistant.open, false);

  // onApprovalRequested routes to the panel's onResponseContent handler.
  await React.act(async () => {
    assistant.handleResponseContent();
  });

  assert.equal(assistant.openRef.current, true);
  assert.equal(assistant.thinking, false);
});

test("only a plain-text caret delivery asks the model for plain prose", async (t) => {
  let root = null;
  t.after(async () => {
    if (root) await React.act(async () => root.unmount());
    delete globalThis.__assistantPanelSentOptions;
  });
  installBrowserGlobals(t);
  const container = installInteractiveDom(t);
  const sentOptions = [];
  globalThis.__assistantPanelSentOptions = sentOptions;
  const vite = await createRendererServer(t, {
    cachePrefix: "openwhispr-assistant-plain-text-test-",
    mockModules: {
      "/chat/useChatPersistence": `
        export function useChatPersistence() {
          return {
            messages: [],
            setMessages() {},
            conversationId: null,
            async createConversation() { return 1; },
            async loadConversation() {},
            saveUserMessage() {},
            saveAssistantMessage() {},
            handleNewChat() {},
          };
        }
      `,
      "/chat/useChatStreaming": `
        export function useChatStreaming() {
          return { agentState: "idle", activeToolName: null, toolStatus: "", cancelStream() {} };
        }
      `,
      "/chat/useChatMessageSender": `
        export function useChatMessageSender() {
          return async (_text, options) => {
            globalThis.__assistantPanelSentOptions.push(options);
            return true;
          };
        }
      `,
      useVoiceDraft: `
        export function useVoiceDraft() {
          return { status: "idle", elapsed: 0, readLevel: () => 0, start() {}, stop() {}, cancel() {} };
        }
      `,
      "/hooks/useWindowDrag": `
        export function useWindowDrag() { return { handleMouseDown() {}, handleMouseUp() {} }; }
      `,
      "/stores/settingsStore": `
        const state = { voiceAgentKey: [] };
        export function useSettingsStore(selector) { return selector(state); }
      `,
      "/utils/hotkeys": `
        export function formatHotkeyListLabel() { return ""; }
      `,
      "/ui/useToast": `
        export function useToast() { return { toast() {} }; }
      `,
    },
  });
  const { AssistantPanel } = await vite.ssrLoadModule("/components/dictation/AssistantPanel.tsx");
  const { createRoot } = require("react-dom/client");
  const paste = {
    mode: "paste",
    sessionId: "s",
    restoreClipboard: true,
    allowClipboardFallback: false,
  };
  const render = (id, delivery) =>
    React.createElement(AssistantPanel, {
      pendingCommand: {
        id,
        text: "draft a reply",
        attachment: null,
        selectedContext: null,
        delivery,
      },
      onCommandConsumed: noop,
      onCommandDiscarded: noop,
      onCommandSettled: noop,
      initialConversationId: null,
      onConversationIdChange: noop,
      voiceState: "idle",
      thinking: false,
      open: false,
      footerPhase: "pill",
      horizontalDirection: "right",
      onClose: noop,
      onBusyChange: noop,
      onResponseReadyChange: noop,
      onResponseContent: noop,
      onConversationReset: noop,
      onSelectionContextChange: noop,
    });

  root = createRoot(container);
  await React.act(async () => root.render(render(1, { ...paste, plainText: true })));
  await React.act(async () => root.render(render(2, { ...paste, plainText: false })));
  await React.act(async () => root.render(render(3, { mode: "clipboard" })));

  assert.deepEqual(
    sentOptions.map((options) => options.plainTextResponse),
    [true, false, false]
  );
});

// Render the actual Markdown and evidence; persistence/inference remain synthetic.
for (const scenario of [
  { topic: "microphone", source: "live", list: "ol" },
  { topic: "models", source: "bundled", list: "ol" },
  { topic: "backup", source: "bundled", list: "ul" },
  { topic: "assistant", source: "bundled", unknown: true },
]) {
  test(`voice help renders ${scenario.topic}/${scenario.source} and copies readable evidence`, async (t) => {
    let root = null;
    t.after(async () => {
      if (root) await React.act(async () => root.unmount());
    });
    const topic = require("../../src/config/productHelpTopics.json")[scenario.topic];
    const content = scenario.unknown
      ? "I can't confirm that control from the built-in guidance. Check the official documentation."
      : topic.text;
    installBrowserGlobals(t);
    const container = installInteractiveDom(t);
    const { AssistantPanel, props } = await setupAssistantPanel(
      t,
      [
        {
          id: "help-formatting",
          role: "assistant",
          content,
          isStreaming: false,
          toolCalls: [
            {
              id: "help",
              name: "grounded_product_help",
              status: "completed",
              arguments: "{}",
              metadata: {
                kind: "grounded-help",
                sources: [
                  {
                    title: scenario.topic,
                    path: topic.path,
                    url: `https://docs.openwhispr.com${topic.path}`,
                    source: scenario.source,
                    reason: scenario.source === "live" ? null : "unavailable",
                  },
                ],
                facts: [{ label: "Microphone selection", value: "System Default" }],
                readAt: "2026-10-07T12:00:00.000Z",
              },
            },
          ],
        },
      ],
      { realMarkdown: true }
    );
    const markup = renderToStaticMarkup(React.createElement(AssistantPanel, props));
    if (scenario.list) {
      assert.match(markup, new RegExp(`<${scenario.list}\\b`));
      assert.match(markup, /<strong\b/);
    }
    assert.doesNotMatch(markup, /\*\*/);
    assert.match(markup, /data-help-evidence/);
    assert.match(markup, /Current app settings/);
    assert.match(markup, /System Default/);
    assert.ok(markup.includes(`href="https://docs.openwhispr.com${topic.path}"`));
    assert.match(markup, scenario.source === "live" ? /Article retrieved/ : /Built-in fallback/);
    // Auto-copy confirms the raw answer, so the Copied state must be keyed by it.
    assert.equal(globalThis.__assistantPanelCopyFeedbackText, content);
    const { createRoot } = require("react-dom/client");
    root = createRoot(container);
    await React.act(async () =>
      root.render(React.createElement(AssistantPanel, { ...props, footerPhase: "actions" }))
    );
    const copyButton = findElement(
      container,
      (element) => element.tagName === "BUTTON" && element.textContent.includes("Copy to clipboard")
    );
    await React.act(async () => copyButton.dispatchEvent({ type: "click", bubbles: true }));
    const copy = globalThis.__assistantPanelCopyText;
    assert.doesNotMatch(copy, /\*\*/);
    assert.match(copy, /Input Device: System Default/);
    assert.ok(copy.includes(`https://docs.openwhispr.com${topic.path}`));
    if (scenario.source === "bundled") assert.match(copy, /could not be checked/);
  });
}

test("voice help sources stay with the answer on screen while a follow-up runs", async (t) => {
  let root = null;
  t.after(async () => {
    if (root) await React.act(async () => root.unmount());
  });
  const helpCall = (id, path) => ({
    id,
    name: "search_openwhispr_help",
    status: "completed",
    arguments: "{}",
    metadata: {
      kind: "product-help",
      sources: [
        {
          title: path.split("/").pop(),
          path,
          url: `https://docs.openwhispr.com${path}`,
          source: "live",
          reason: null,
        },
      ],
      readAt: null,
    },
  });
  const answered = {
    id: "answered",
    role: "assistant",
    content: "Open Settings → App → Hotkeys.",
    isStreaming: false,
    toolCalls: [helpCall("first", "/help/dictation/hotkeys")],
  };
  installBrowserGlobals(t);
  const container = installInteractiveDom(t);
  const { AssistantPanel, props } = await setupAssistantPanel(t, [answered]);
  const { createRoot } = require("react-dom/client");
  root = createRoot(container);
  await React.act(async () => root.render(React.createElement(AssistantPanel, props)));

  // The follow-up's lookup has finished but its answer hasn't started streaming.
  globalThis.__assistantPanelMessages = [
    answered,
    { id: "question", role: "user", content: "And local models?" },
    {
      id: "pending",
      role: "assistant",
      content: "",
      isStreaming: true,
      toolCalls: [helpCall("second", "/guides/local-models")],
    },
  ];
  await React.act(async () => root.render(React.createElement(AssistantPanel, { ...props })));

  const link = (path) =>
    findElement(
      container,
      (element) =>
        element.tagName === "A" &&
        element.getAttribute("href") === `https://docs.openwhispr.com${path}`
    );
  assert.match(container.textContent, /Open Settings → App → Hotkeys/);
  assert.ok(link("/help/dictation/hotkeys"), "the answer on screen keeps its own source");
  assert.equal(link("/guides/local-models"), null, "the pending answer's source waits for it");
});