Skip to content

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

fix(assistant): paste caret-bound answers as plain text unless the app keeps markdown (#2189)

Joshua5edc0739fc94
diff --git a/docs/superpowers/plans/2026-09-10-agent-paste-plain-text.md b/docs/superpowers/plans/2026-09-10-agent-paste-plain-text.md
new file mode 100644
index 000000000..c7333b4da
--- /dev/null
+++ b/docs/superpowers/plans/2026-09-10-agent-paste-plain-text.md
@@ -0,0 +1,1764 @@
+# Agent answers paste as plain text — implementation plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** A voice-command answer pasted at the caret arrives as plain prose in a plain-text app, as untouched markdown in a markdown-friendly app, and every declined paste leaves one diagnosable line in the debug log.
+
+**Architecture:** The main process decides once, at caret capture, whether the target app accepts markdown (a researched allowlist in `markdownTargets.js`, matched on the identity the platform already exposes) and returns `acceptsMarkdown` with the session id. The renderer carries that verdict into the delivery object as `plainText`. When `plainText` is true a per-request suffix asks the model for prose and `markdownToPlainText` strips whatever slips through before the paste; when false both are skipped. `pasteAtCapturedTarget` logs each refusal code with the probe verdict.
+
+**Tech Stack:** Electron desktop app; TypeScript renderer, CommonJS main process; tests are `node --test` files under `test/` that dynamically import `.ts` through `tsx`; Prettier + ESLint.
+
+**Spec:** `docs/superpowers/specs/2026-09-10-agent-paste-plain-text-design.md` — read it first; every decision below argues from it, and Appendix A is the source of the allowlist.
+
+## Global Constraints
+
+- Branch `fix/agent-paste-plain-text`, based on `origin/main` at `a2c76ef9`. Work in a scratchpad worktree, never by switching branches in the shared `~/dev/openwhispr-desktop` clone.
+- **Never merge.** Open the PR, stop. (Josh's standing rule.)
+- **Do not edit `DEFAULT_CHAT_AGENT_PROMPT`** in `src/config/prompts/registry.ts`, and do not touch `src/config/retiredPrompts.js`. The instruction is a conditional suffix; the hash protocol is deliberately not triggered.
+- **Do not reuse or "generalise" `stripMarkdownPreview`** in `src/components/CommandSearch.tsx`. It collapses newlines into spaces.
+- **Do not touch PR #1952** or anything under the Chromium/Electron paste probe. Independent defect.
+- **No rich-text clipboard work, no browser-tab (window title) detection, no user setting.** All three are scoped out in the spec.
+- **Plain text is the default.** Any error, unreadable pid or unlisted app yields `acceptsMarkdown: false`.
+- **Allowlist entries are lowercase, at least three characters, and never a generic word that another app could carry.** `riot` and `remarkable` are deliberately absent (spec §3). Matching is whole-token or whole-phrase, never bare substring.
+- Run the suite with `nvm exec 24 npm test` — Node 25 (the shell default) fakes one unrelated failure. About 169 Electron-ABI skips are normal locally.
+- The worktree's `node_modules` is a symlink to the clone's. It is excluded via `.git/info/exclude`, but still confirm `git status --short` never lists it before every commit.
+- Commit messages: conventional commits, and end with `Co-Authored-By: Claude Fable 5.1 <[email protected]>`.
+- Before every commit: `npx prettier --write <touched files>`, then `npx eslint <touched files>` from the repo root for `test/**` and TSX/TS renderer files. **`src/helpers/*.js` and `src/utils/**` are linted by neither config** (the root config ignores `src/**`, and `src/eslint.config.js` ignores `helpers/**` and `utils/**`), so ESLint reports them as ignored; Prettier, the tests and `npm run typecheck` are the gate for those. The overall gate is `npm run quality-check` in Task 9.
+
+---
+
+## File map
+
+| File | Responsibility |
+| -------------------------------------------------------------- | -------------------------------------------------------------------------------- |
+| `src/helpers/markdownToPlainText.ts` (create) | Pure function: markdown → plain text, every line break preserved |
+| `test/helpers/markdownToPlainText.test.js` (create) | One test per strip rule, plus the must-not-alter cases |
+| `src/helpers/markdownTargets.js` (create) | The allowlist, the vetoes, and `isMarkdownTargetSignature` |
+| `test/helpers/markdownTargets.test.js` (create) | Every platform identity shape matches; plain-text apps and vetoes never do |
+| `src/helpers/selectionManager.js` (modify) | Resolve the verdict at capture; store it on the session; log every paste refusal |
+| `src/types/electron.ts` (modify) | `acceptsMarkdown` on the `editable` capture result |
+| `test/helpers/selectionManager.test.js` (modify) | Logger stub; verdict tests; one test per refusal code |
+| `src/helpers/audioManager.js` (modify) | Carry `deliveryAcceptsMarkdown` next to `deliverySessionId` |
+| `test/helpers/audioManagerAssistantDirective.test.js` (modify) | The verdict rides into `pendingAssistantConversation` |
+| `src/hooks/useAudioRecording.js` (modify) | Pass the verdict into `createAssistantResponseDelivery` |
+| `src/helpers/assistantResponseDelivery.ts` (modify) | `plainText` on the paste delivery; strip only when it is true |
+| `test/helpers/assistantResponseDelivery.test.js` (modify) | `plainText` derivation; stripped vs verbatim per delivery |
+| `src/config/prompts/registry.ts` (modify) | `PLAIN_TEXT_RESPONSE_SUFFIX` constant beside the chat-agent prompt |
+| `src/config/prompts/index.ts` (modify) | `appendPlainTextResponseSuffix(prompt)` beside the other suffix helpers |
+| `src/config/prompts.ts` (modify) | Re-export the new helper |
+| `test/helpers/agentPlainTextSuffix.test.js` (create) | Suffix appends once at the end; panel prompt never carries it |
+| `src/components/chat/useChatStreaming.ts` (modify) | `plainTextResponse` option; append the suffix last |
+| `src/components/dictation/AssistantPanel.tsx` (modify) | Pass `plainTextResponse` from `delivery.plainText` |
+
+---
+
+### Task 1: the newline-preserving strip helper
+
+**Files:**
+
+- Create: `src/helpers/markdownToPlainText.ts`
+- Test: `test/helpers/markdownToPlainText.test.js`
+
+**Interfaces:**
+
+- Produces: `export function markdownToPlainText(markdown: string): string` — pure, synchronous, never throws on any string input.
+
+This task's code was executed as a throwaway check on 2026-09-10 under Node 24: 11/11 pass, Prettier and ESLint clean. Copy it as written.
+
+- [ ] **Step 1: Write the failing tests**
+
+Create `test/helpers/markdownToPlainText.test.js`:
+
+````js
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const helperModule = import("../../src/helpers/markdownToPlainText.ts");
+
+// Every case pins one rule from the spec's table. The first test is the one
+// that matters most: it is exactly what the search-preview helper in
+// CommandSearch.tsx would fail, because it collapses newlines into spaces.
+test("paragraphs, blank lines and line breaks survive untouched", async () => {
+ const { markdownToPlainText } = await helperModule;
+ const answer = "First paragraph.\n\nSecond paragraph,\nwrapped onto a second line.";
+ assert.equal(markdownToPlainText(answer), answer);
+});
+
+test("emphasis markers are removed and the words kept", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("**bold** and *em* and __b__ and _e_ and ~~s~~"),
+ "bold and em and b and e and s"
+ );
+ assert.equal(markdownToPlainText("**x**"), "x");
+});
+
+test("headings lose their marks", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(markdownToPlainText("## Title\nBody"), "Title\nBody");
+});
+
+test("inline code and fenced blocks keep their content verbatim", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("Run `npm test`.\n```bash\nnpm test\n```\nDone."),
+ "Run npm test.\nnpm test\nDone."
+ );
+ assert.equal(markdownToPlainText("```\n**not bold**\n```"), "**not bold**");
+});
+
+test("links keep their text and their url; images keep their alt text", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("see [the docs](https://x.y/d)"),
+ "see the docs (https://x.y/d)"
+ );
+ assert.equal(markdownToPlainText("[https://x.y](https://x.y)"), "https://x.y");
+ assert.equal(markdownToPlainText("![a chart](chart.png)"), "a chart");
+});
+
+test("star and plus bullets become dashes; dashes and numbers stay as typed", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("* one\n+ two\n- three\n1. four"),
+ "- one\n- two\n- three\n1. four"
+ );
+});
+
+test("blockquote markers are removed at line start only", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(markdownToPlainText("> quoted\n>> nested\nx > y"), "quoted\nnested\nx > y");
+});
+
+test("horizontal rules are removed", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(markdownToPlainText("a\n---\nb\n* * *\nc"), "a\nb\nc");
+});
+
+test("tables become tab-separated rows without the alignment row", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("| Name | Qty |\n|---|---:|\n| Apples | **3** |"),
+ "Name\tQty\nApples\t3"
+ );
+});
+
+test("markdown escapes resolve to the escaped character", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(markdownToPlainText("\\*literal\\* and 5 \\_ 6"), "*literal* and 5 _ 6");
+ assert.equal(markdownToPlainText("\\*\\*kept\\*\\*"), "**kept**");
+});
+
+test("plain-text conventions a human would type are never altered", async () => {
+ const { markdownToPlainText } = await helperModule;
+ const answer = "2 * 3 * 4 = 24\nsnake_case_name stays\na lone * star\n#hashtag\nx > y";
+ assert.equal(markdownToPlainText(answer), answer);
+});
+````
+
+- [ ] **Step 2: Run the tests to verify they fail**
+
+Run: `nvm exec 24 node --import tsx --test test/helpers/markdownToPlainText.test.js`
+Expected: every test FAILS with `Cannot find module '../../src/helpers/markdownToPlainText.ts'`.
+
+- [ ] **Step 3: Write the implementation**
+
+Create `src/helpers/markdownToPlainText.ts`:
+
+```ts
+// Turns a model answer into text that is safe to paste into a plain-text
+// field. Every line break is preserved: paragraphs, blank lines and list
+// lines survive. This is deliberately NOT stripMarkdownPreview from
+// CommandSearch.tsx — that helper collapses newlines into spaces to feed
+// one-line search previews and would flatten a multi-paragraph answer.
+//
+// The rules only touch syntax a human would not type in plain text. A `- `
+// bullet, a `1.` number, `2 * 3`, snake_case, `#hashtag` and `x > y` are all
+// left exactly as written.
+
+const FENCE_LINE = /^\s*(`{3,}|~{3,}).*$/;
+const HORIZONTAL_RULE = /^\s*([-*_])(\s*\1){2,}\s*$/;
+const TABLE_ROW = /^\s*\|.*\|\s*$/;
+const TABLE_ALIGNMENT_CELL = /^:?-+:?$/;
+
+function stripInline(text: string): string {
+ return (
+ text
+ .replace(/(?<!\\)`([^`]+)`/g, "$1")
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
+ .replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_match, label: string, url: string) =>
+ label === url ? url : `${label} (${url})`
+ )
+ .replace(/(?<!\\)(\*\*|__)(\S(?:.*?\S)?)\1/g, "$2")
+ .replace(/(?<!\\)~~(\S(?:.*?\S)?)~~/g, "$1")
+ // Markers must hug non-space on the inside, not sit inside a word on the
+ // outside, and not be escaped — so `2 * 3`, snake_case and `\*` survive.
+ .replace(/(?<![\w*\\])\*(\S(?:.*?\S)?)\*(?![\w*])/g, "$1")
+ .replace(/(?<![\w_\\])_(\S(?:.*?\S)?)_(?![\w_])/g, "$1")
+ // Escapes resolve last so an escaped marker is never re-stripped.
+ .replace(/\\([\\`*_{}[\]()#+\-.!|>~])/g, "$1")
+ );
+}
+
+export function markdownToPlainText(markdown: string): string {
+ const lines: string[] = [];
+ let inFence = false;
+
+ for (const line of markdown.split(/\r?\n/)) {
+ if (FENCE_LINE.test(line)) {
+ inFence = !inFence;
+ continue;
+ }
+ if (inFence) {
+ lines.push(line);
+ continue;
+ }
+ if (HORIZONTAL_RULE.test(line)) continue;
+
+ if (TABLE_ROW.test(line)) {
+ const cells = line
+ .trim()
+ .slice(1, -1)
+ .split("|")
+ .map((cell) => cell.trim());
+ if (cells.every((cell) => TABLE_ALIGNMENT_CELL.test(cell))) continue;
+ lines.push(cells.map(stripInline).join("\t"));
+ continue;
+ }
+
+ const block = line
+ .replace(/^(\s{0,3}>\s?)+/, "")
+ .replace(/^\s{0,3}#{1,6}\s+/, "")
+ .replace(/^(\s*)[*+]\s+/, "$1- ");
+ lines.push(stripInline(block));
+ }
+
+ return lines
+ .join("\n")
+ .replace(/[ \t]+$/gm, "")
+ .trim();
+}
+```
+
+- [ ] **Step 4: Run the tests to verify they pass**
+
+Run: `nvm exec 24 node --import tsx --test test/helpers/markdownToPlainText.test.js`
+Expected: 11 tests PASS.
+
+- [ ] **Step 5: Format, lint, commit**
+
+```bash
+npx prettier --write src/helpers/markdownToPlainText.ts test/helpers/markdownToPlainText.test.js
+npx eslint src/helpers/markdownToPlainText.ts
+npx eslint test/helpers/markdownToPlainText.test.js
+git status --short # must list only the two files, never node_modules
+git add src/helpers/markdownToPlainText.ts test/helpers/markdownToPlainText.test.js
+git commit -m "feat(assistant): newline-preserving markdown-to-plain-text helper
+
+Pure helper for text that is about to be pasted into a plain-text app.
+Keeps every line break, which is why stripMarkdownPreview (search
+previews, collapses newlines) is not reused.
+
+Co-Authored-By: Claude Fable 5.1 <[email protected]>"
+```
+
+---
+
+### Task 2: the markdown-friendly target list
+
+**Files:**
+
+- Create: `src/helpers/markdownTargets.js`
+- Test: `test/helpers/markdownTargets.test.js`
+
+**Interfaces:**
+
+- Produces (CommonJS): `MARKDOWN_TARGET_SIGNATURES: string[]`, `MARKDOWN_TARGET_VETOES: string[]`, `isMarkdownTargetSignature(signature: string | null | undefined): boolean`. Task 3 requires this module from `selectionManager.js`.
+
+The list is the spec's Appendix A, tokens column. Do not add an entry that is not in Appendix A; if research turns up a new app, add it to the spec's appendix first with its evidence.
+
+- [ ] **Step 1: Write the failing tests**
+
+Create `test/helpers/markdownTargets.test.js`:
+
+```js
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const {
+ isMarkdownTargetSignature,
+ MARKDOWN_TARGET_SIGNATURES,
+} = require("../../src/helpers/markdownTargets");
+
+// Each signature below is the exact shape one platform hands the matcher:
+// macOS "<.app folder name> <executable>", Windows "<exe> <window class>",
+// Linux "<WM_CLASS>". One representative per group of the spec's Appendix A.
+test("markdown-friendly apps match on every platform's identity shape", () => {
+ for (const signature of [
+ "Obsidian Obsidian", // macOS, resolved from the pid
+ "Visual Studio Code Code", // macOS: .app name and executable differ
+ "IntelliJ IDEA idea", // macOS JetBrains
+ "ChatGPT ChatGPT", // macOS AI prompt box
+ "Google Gemini Gemini", // macOS, Chromium-path app name plus executable
+ "Notion Notion",
+ "Discord Discord",
+ "Linear Linear",
+ "Obsidian.exe Chrome_WidgetWin_1", // Windows exe + Electron window class
+ "Code.exe Chrome_WidgetWin_1",
+ "idea64.exe SunAwtFrame",
+ "notepad++.exe Notepad++",
+ "M365Copilot.exe",
+ "md.obsidian.obsidian", // Linux Flatpak WM_CLASS
+ "net.cozic.joplin_desktop",
+ "jetbrains-idea",
+ "dev.zed.zed",
+ "code",
+ "org.kde.kate",
+ ]) {
+ assert.equal(isMarkdownTargetSignature(signature), true, signature);
+ }
+});
+
+test("plain-text apps, own-dialect chat tools, browsers and near-miss names never match", () => {
+ for (const signature of [
+ "TextEdit TextEdit",
+ "Notes Notes",
+ "Microsoft Word Microsoft Word",
+ "Pages Pages",
+ "Mail Mail",
+ "WINWORD.EXE",
+ "notepad.exe Notepad",
+ "gedit",
+ "Slack Slack",
+ "Microsoft Teams MSTeams",
+ "ms-teams.exe",
+ "WhatsApp WhatsApp",
+ "Telegram Telegram",
+ "Xcode Xcode", // "code" must not match inside Xcode
+ "Notion Calendar Notion Calendar", // veto
+ "Notion Mail Notion Mail", // veto
+ "Google Chrome Google Chrome",
+ "Safari Safari",
+ "Arc Arc",
+ "Riot Client RiotClientUx.exe", // the reason "riot" is not an entry
+ "reMarkable reMarkable", // the reason "remarkable" is not an entry
+ "",
+ null,
+ undefined,
+ ]) {
+ assert.equal(isMarkdownTargetSignature(signature), false, String(signature));
+ }
+});
+
+test("every entry is lowercase, at least three characters, and free of generic tokens", () => {
+ for (const entry of MARKDOWN_TARGET_SIGNATURES) {
+ assert.equal(entry, entry.toLowerCase(), entry);
+ assert.ok(entry.length >= 3, entry);
+ }
+ for (const banned of ["riot", "remarkable", "notes", "mail", "word", "text", "app"]) {
+ assert.ok(!MARKDOWN_TARGET_SIGNATURES.includes(banned), banned);
+ }
+});
+```
+
+- [ ] **Step 2: Run the tests to verify they fail**
+
+Run: `nvm exec 24 node --test test/helpers/markdownTargets.test.js`
+Expected: FAIL with `Cannot find module '../../src/helpers/markdownTargets'`.
+
+- [ ] **Step 3: Write the list and the matcher**
+
+Create `src/helpers/markdownTargets.js`:
+
+```js
+// Apps whose text surface wants markdown left alone: markdown-native editors,
+// apps that convert pasted markdown into formatting, chat tools whose composer
+// is standard markdown, AI prompt boxes (a model reads markdown happily) and
+// code editors / IDEs (nothing renders formatting there, and a developer's
+// backticks and fences are deliberate). Anything not listed gets plain text —
+// the safe default, because a wrong verdict here pastes literal asterisks
+// into someone's document.
+//
+// Matching is by whole token or phrase, never bare substring, so "code" does
+// not match "Xcode". Entries are lowercase and never a generic word another
+// app could carry: "riot" (Element's Flatpak id) would match the Riot Games
+// launcher and "remarkable" (a small Linux editor) the reMarkable tablet app,
+// so neither is here. The identity matched per platform:
+// macOS — the .app folder name + executable resolved from the pid
+// ("Visual Studio Code Code"), plus the copy helper's app name
+// Windows — the exe name ("Code.exe", "idea64.exe") + window class
+// Linux — the WM_CLASS ("code", "md.obsidian.obsidian", "jetbrains-idea")
+// Evidence per app, and the apps deliberately excluded:
+// docs/superpowers/specs/2026-09-10-agent-paste-plain-text-design.md, Appendix A–C.
+
+const MARKDOWN_TARGET_SIGNATURES = [
+ // Markdown-native note editors — the file is markdown.
+ "obsidian",
+ "typora",
+ "logseq",
+ "joplin",
+ "zettlr",
+ "ia writer",
+ "ulysses",
+ "simplenote",
+ "inkdrop",
+ "marktext",
+ "noteplan",
+ "drafts",
+ "macdown",
+ "markedit",
+ "nota",
+ "byword",
+ "fsnotes",
+ "the archive",
+ "qownnotes",
+ "boost note",
+ "boostnote",
+ "notable",
+ "supernotes",
+ "heynote",
+ "apostrophe",
+ "ghostwriter",
+ "abricotine",
+ // Apps that convert pasted markdown into formatting (vendor-documented).
+ "notion",
+ "evernote",
+ "notesnook",
+ "workflowy",
+ "bear",
+ "craft",
+ "remnote",
+ "anytype",
+ "siyuan",
+ "capacities",
+ "reflect",
+ "heptabase",
+ "roam",
+ "appflowy",
+ // Chat composers that are standard markdown (not Slack, Teams, WhatsApp or
+ // Telegram — their dialects turn **bold** into stray asterisks).
+ "discord",
+ "zulip",
+ "mattermost",
+ "element",
+ "rocket.chat",
+ "rocketchat",
+ // Work tools whose long-text fields convert pasted markdown.
+ "linear",
+ "todoist",
+ "ticktick",
+ "trello",
+ // AI prompt boxes — the model reads markdown.
+ "chatgpt",
+ "claude",
+ "gemini",
+ "perplexity",
+ "copilot",
+ "m365copilot",
+ "poe",
+ "lm studio",
+ "lm-studio",
+ "ollama",
+ "jan",
+ "msty",
+ "chatbox",
+ "boltai",
+ "cherry studio",
+ "cherry-studio",
+ "anythingllm",
+ "anythingllmdesktop",
+ "witsy",
+ "gpt4all",
+ // Code editors and IDEs — nothing renders formatting; the AI chat panels
+ // inside them are prompt boxes. Not general prose editors (TextEdit,
+ // Notepad, gedit): those are the plain-text case.
+ "visual studio code",
+ "code",
+ "vscodium",
+ "codium",
+ "cursor",
+ "windsurf",
+ "devin",
+ "zed",
+ "trae",
+ "kiro",
+ "antigravity",
+ "void",
+ "positron",
+ "pearai",
+ "aide",
+ "intellij",
+ "idea",
+ "idea64",
+ "pycharm",
+ "webstorm",
+ "phpstorm",
+ "rider",
+ "rider64",
+ "goland",
+ "clion",
+ "rubymine",
+ "datagrip",
+ "android studio",
+ "studio64",
+ "jetbrains",
+ "sublime",
+ "sublime_text",
+ "subl",
+ "nova",
+ "bbedit",
+ "coteditor",
+ "kate",
+ "notepad++",
+ "emacs",
+ "runemacs",
+ "macvim",
+ "gvim",
+ "neovide",
+ "devenv",
+];
+
+// Checked first, as plain substrings. An app that carries a listed name but
+// is not a markdown surface — the veto wins.
+const MARKDOWN_TARGET_VETOES = ["notion calendar", "notion mail", "xcode"];
+
+const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+// Whole-token / whole-phrase match: the entry must be bounded on both sides by
+// the start or end of the signature or by a character that is not a letter or
+// digit. Dots, hyphens, underscores and spaces all count as boundaries, which
+// is what makes "md.obsidian.obsidian", "jetbrains-idea" and "Code.exe" match
+// while "Xcode" does not.
+const TOKEN_PATTERNS = MARKDOWN_TARGET_SIGNATURES.map(
+ (entry) => new RegExp(`(?:^|[^a-z0-9])${escapeRegExp(entry)}(?:$|[^a-z0-9])`)
+);
+
+function isMarkdownTargetSignature(signature) {
+ if (!signature) return false;
+ const normalized = String(signature).toLowerCase();
+ if (MARKDOWN_TARGET_VETOES.some((veto) => normalized.includes(veto))) return false;
+ return TOKEN_PATTERNS.some((pattern) => pattern.test(normalized));
+}
+
+module.exports = {
+ MARKDOWN_TARGET_SIGNATURES,
+ MARKDOWN_TARGET_VETOES,
+ isMarkdownTargetSignature,
+};
+```
+
+- [ ] **Step 4: Run the tests to verify they pass**
+
+Run: `nvm exec 24 node --test test/helpers/markdownTargets.test.js`
+Expected: 3 tests PASS. If a "never match" case fails, the fix is to remove or narrow the offending entry, never to loosen the test.
+
+- [ ] **Step 5: Format, lint, commit**
+
+```bash
+npx prettier --write src/helpers/markdownTargets.js test/helpers/markdownTargets.test.js
+npx eslint src/helpers/markdownTargets.js test/helpers/markdownTargets.test.js
+git status --short
+git add src/helpers/markdownTargets.js test/helpers/markdownTargets.test.js
+git commit -m "feat(assistant): allowlist of apps whose caret keeps markdown
+
+Markdown-native editors, markdown-converting note apps, standard-markdown
+chat composers, AI prompt boxes and code editors, matched by whole token
+on the identity each platform already exposes. Plain text stays the
+default for everything else. Evidence per app lives in the design spec.
+
+Co-Authored-By: Claude Fable 5.1 <[email protected]>"
+```
+
+---
+
+### Task 3: decide the verdict at capture, in the main process
+
+**Files:**
+
+- Modify: `src/helpers/selectionManager.js` (require at line 3; `captureSelectedText` editable branch, lines 176–183; `_isTerminalPid`, lines 516–525; new methods beside it)
+- Modify: `src/types/electron.ts` (the `captureSelectedText` return type, lines 1116–1132)
+- Test: `test/helpers/selectionManager.test.js`
+
+**Interfaces:**
+
+- Consumes: `isMarkdownTargetSignature` from Task 2.
+- Produces: the `editable` capture result becomes `{ status: "editable", sessionId, acceptsMarkdown: boolean }`; the caret session object gains `acceptsMarkdown`; new methods `_readTargetNames(pid): Promise<string>` and `_targetAcceptsMarkdown(target): Promise<boolean>`. Task 4 reads `acceptsMarkdown` off the capture result; Task 8 reads it off the session.
+
+- [ ] **Step 1: Write the failing tests**
+
+Append to `test/helpers/selectionManager.test.js` (reuse its `makeHarness`, `SelectionManager` and `loadSelectionManager`):
+
+```js
+test("a caret in a markdown-native macOS app is reported as accepting markdown", async () => {
+ const { manager } = makeHarness({ selections: [{ state: "none", editable: true }] });
+ manager._readExecutablePath = async () => "/Applications/Obsidian.app/Contents/MacOS/Obsidian";
+
+ const result = await manager.captureSelectedText({ probeEditable: true });
+
+ assert.equal(result.status, "editable");
+ assert.equal(result.acceptsMarkdown, true);
+ assert.equal(manager.sessions.get(result.sessionId).acceptsMarkdown, true);
+});
+
+test("a caret in a plain-text macOS app is reported as wanting plain text", async () => {
+ const { manager } = makeHarness({ selections: [{ state: "none", editable: true }] });
+ manager._readExecutablePath = async () =>
+ "/System/Applications/TextEdit.app/Contents/MacOS/TextEdit";
+
+ const result = await manager.captureSelectedText({ probeEditable: true });
+
+ assert.equal(result.status, "editable");
+ assert.equal(result.acceptsMarkdown, false);
+ assert.equal(manager.sessions.get(result.sessionId).acceptsMarkdown, false);
+});
+
+test("an unreadable pid defaults the caret to plain text", async () => {
+ const { manager } = makeHarness({ selections: [{ state: "none", editable: true }] });
+ manager._readExecutablePath = async () => "";
+
+ const result = await manager.captureSelectedText({ probeEditable: true });
+
+ assert.equal(result.status, "editable");
+ assert.equal(result.acceptsMarkdown, false);
+});
+
+test("Windows and Linux caret targets are judged by the identity they already carry", async () => {
+ const { manager } = makeHarness();
+ manager._readExecutablePath = async () => {
+ throw new Error("must not spawn ps for a target that names its app");
+ };
+
+ assert.equal(
+ await manager._targetAcceptsMarkdown({
+ kind: "win-hwnd",
+ id: "00001A2B",
+ exeName: "Obsidian.exe",
+ windowClass: "Chrome_WidgetWin_1",
+ }),
+ true
+ );
+ assert.equal(
+ await manager._targetAcceptsMarkdown({
+ kind: "win-hwnd",
+ id: "00001A2B",
+ exeName: "WINWORD.EXE",
+ }),
+ false
+ );
+ assert.equal(
+ await manager._targetAcceptsMarkdown({
+ kind: "x11-window",
+ id: "0x1",
+ windowClass: "md.obsidian.obsidian",
+ }),
+ true
+ );
+ assert.equal(await manager._targetAcceptsMarkdown(null), false);
+});
+
+test("a Linux AT-SPI target resolves its executable like the terminal check does", async () => {
+ const { manager } = makeHarness();
+ manager._readExecutablePath = async (pid) => (pid === 77 ? "obsidian" : "");
+
+ assert.equal(await manager._targetAcceptsMarkdown({ kind: "atspi-pid", id: 77 }), true);
+ assert.equal(await manager._targetAcceptsMarkdown({ kind: "atspi-pid", id: 78 }), false);
+});
+```
+
+- [ ] **Step 2: Run the tests to verify they fail**
+
+Run: `nvm exec 24 node --import tsx --test test/helpers/selectionManager.test.js`
+Expected: the five new tests FAIL (`result.acceptsMarkdown` is `undefined`; `_targetAcceptsMarkdown is not a function`). Every pre-existing test still PASSES.
+
+- [ ] **Step 3: Resolve and store the verdict**
+
+In `src/helpers/selectionManager.js`, add the require after the existing `debugLogger` require:
+
+```js
+const { isMarkdownTargetSignature } = require("./markdownTargets");
+```
+
+Replace the editable branch inside `captureSelectedText` (currently):
+
+```js
+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 };
+}
+```
+
+with:
+
+```js
+if (capture.status === "editable") {
+ const sessionId = crypto.randomUUID();
+ // Decided once, here, and carried on both the session and the result:
+ // the renderer asks the model for plain prose and strips markdown only
+ // when the target is not a markdown-friendly app.
+ const acceptsMarkdown = await this._targetAcceptsMarkdown(capture.target);
+ this.sessions.set(sessionId, {
+ kind: "caret",
+ target: capture.target,
+ acceptsMarkdown,
+ expiresAt: this.now() + SESSION_TTL_MS,
+ });
+ return { status: "editable", sessionId, acceptsMarkdown };
+}
+```
+
+Replace `_isTerminalPid` (currently lines 516–525) with the three methods below. The first is the existing method with its path parsing moved into `_readTargetNames`; the behaviour is unchanged.
+
+```js
+ async _isTerminalPid(pid) {
+ if (!this.clipboardManager.isTerminalSignature) return false;
+ const names = await this._readTargetNames(pid);
+ return names ? this.clipboardManager.isTerminalSignature(names) : false;
+ }
+
+ // "<bundle name> <executable name>" for a pid — "Visual Studio Code Code" on
+ // macOS, the bare comm name on Linux — or "" when the pid cannot be read.
+ async _readTargetNames(pid) {
+ const executablePath = await this._readExecutablePath(pid);
+ if (!executablePath) return "";
+ // 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 `${bundleName} ${executableName}`.trim();
+ }
+
+ // Windows and Linux X11 targets name their app on the target; macOS AX and
+ // Linux AT-SPI targets carry only a pid, so resolve the executable exactly
+ // as the terminal check does. A miss or an error means plain text.
+ async _targetAcceptsMarkdown(target) {
+ if (!target) return false;
+ try {
+ const parts = [this._targetSignature(target)];
+ const pid = target.kind === "mac-pid" ? target.pid : target.kind === "atspi-pid" ? target.id : null;
+ if (pid) parts.push(await this._readTargetNames(pid));
+ return isMarkdownTargetSignature(parts.join(" ").trim());
+ } catch {
+ return false;
+ }
+ }
+```
+
+- [ ] **Step 4: Type the new field**
+
+In `src/types/electron.ts`, change the `editable` variant of the `captureSelectedText` return type from:
+
+```ts
+ | {
+ status: "editable";
+ sessionId: string;
+ }
+```
+
+to:
+
+```ts
+ | {
+ status: "editable";
+ sessionId: string;
+ /** True when the captured app keeps markdown (spec Appendix A); false means plain text. */
+ acceptsMarkdown: boolean;
+ }
+```
+
+- [ ] **Step 5: Run the tests and the typecheck**
+
+Run: `nvm exec 24 node --import tsx --test test/helpers/selectionManager.test.js && nvm exec 24 npm run typecheck`
+Expected: all tests PASS, including the five new ones; typecheck exits 0.
+
+- [ ] **Step 6: Format, lint, commit**
+
+```bash
+npx prettier --write src/helpers/selectionManager.js src/types/electron.ts test/helpers/selectionManager.test.js
+npx eslint src/helpers/selectionManager.js test/helpers/selectionManager.test.js
+(cd src && npx eslint types/electron.ts)
+git status --short
+git add src/helpers/selectionManager.js src/types/electron.ts test/helpers/selectionManager.test.js
+git commit -m "feat(assistant): decide at caret capture whether the target keeps markdown
+
+captureSelectedText resolves the app under the caret against the
+markdown-target list once, stores the verdict on the session and returns
+it as acceptsMarkdown. macOS and AT-SPI pids resolve through the same
+executable lookup the terminal check uses; Windows and X11 targets are
+judged by the exe name and window class they already carry.
+
+Co-Authored-By: Claude Fable 5.1 <[email protected]>"
+```
+
+---
+
+### Task 4: carry the verdict to the delivery object
+
+**Files:**
+
+- Modify: `src/helpers/audioManager.js` (`_bankAssistantDirective` lines 2585–2600; `_bankPanelAgentCommand` lines 2618–2635; `processAgentCommand` lines 2665–2700)
+- Modify: `src/hooks/useAudioRecording.js` (lines 504–531)
+- Modify: `src/helpers/assistantResponseDelivery.ts` (the `AssistantResponseDelivery` type and `createAssistantResponseDelivery`)
+- Test: `test/helpers/audioManagerAssistantDirective.test.js`, `test/helpers/assistantResponseDelivery.test.js`
+
+**Interfaces:**
+
+- Consumes: `capture.acceptsMarkdown` from Task 3.
+- Produces: `pendingAssistantConversation.deliveryAcceptsMarkdown: boolean` (present only with `deliverySessionId`); `createAssistantResponseDelivery({ ..., acceptsMarkdown?: boolean })`; the paste delivery variant `{ mode: "paste"; sessionId; restoreClipboard; allowClipboardFallback; plainText: boolean }`. Tasks 5 and 7 read `delivery.plainText`.
+
+- [ ] **Step 1: Write the failing tests**
+
+In `test/helpers/audioManagerAssistantDirective.test.js`, the existing test "a verified caret is delivered to the captured input" (the one asserting `deliverySessionId: "caret-session"`) must now expect the verdict too. Change its `assert.deepEqual(manager.pendingAssistantConversation, {...})` to:
+
+```js
+assert.deepEqual(manager.pendingAssistantConversation, {
+ transcript: "draft a reply",
+ screenContext: null,
+ deliverySessionId: "caret-session",
+ deliveryAcceptsMarkdown: false,
+});
+```
+
+Then append:
+
+```js
+test("a caret in a markdown-friendly app carries that verdict with the session id", async (t) => {
+ const { createManager } = await loadAudioManagerHarness(t, {
+ cachePrefix: "openwhispr-assistant-caret-markdown-",
+ settingsKey: "__assistantCaretMarkdownSettings",
+ settings: { autoPasteEnabled: true },
+ mockModules: {
+ "/services/ReasoningService": 'export default { processText: async () => "" };',
+ },
+ });
+ const { manager } = managerWithCapture(createManager, {
+ status: "editable",
+ sessionId: "caret-session",
+ acceptsMarkdown: true,
+ });
+
+ await manager.processAgentCommand("draft a reply", "gpt", "Aria", {
+ selectionEditReachable: true,
+ });
+
+ assert.deepEqual(manager.pendingAssistantConversation, {
+ transcript: "draft a reply",
+ screenContext: null,
+ deliverySessionId: "caret-session",
+ deliveryAcceptsMarkdown: true,
+ });
+});
+```
+
+The test "a verified caret stays panel-first when auto-paste is disabled" already asserts no `deliverySessionId`; it must still pass unchanged, which proves the verdict is absent without a caret delivery.
+
+In `test/helpers/assistantResponseDelivery.test.js`, change `PASTE_DELIVERY` to carry the new field and extend the mode test:
+
+```js
+const PASTE_DELIVERY = {
+ mode: "paste",
+ sessionId: "caret-session",
+ ...PASTE_OPTIONS,
+ plainText: true,
+};
+```
+
+and inside "Assistant delivery mode follows Auto-Paste and target state":
+
+```js
+const createDelivery = (autoPasteEnabled, deliverySessionId, acceptsMarkdown) =>
+ createAssistantResponseDelivery({
+ autoPasteEnabled,
+ deliverySessionId,
+ acceptsMarkdown,
+ ...PASTE_OPTIONS,
+ });
+
+assert.equal(createDelivery(false), null);
+assert.deepEqual(createDelivery(true), { mode: "clipboard" });
+assert.deepEqual(createDelivery(true, "caret-session"), PASTE_DELIVERY);
+assert.deepEqual(createDelivery(true, "caret-session", false), PASTE_DELIVERY);
+assert.deepEqual(createDelivery(true, "caret-session", true), {
+ ...PASTE_DELIVERY,
+ plainText: false,
+});
+```
+
+- [ ] **Step 2: Run the tests to verify they fail**
+
+Run: `nvm exec 24 node --import tsx --test test/helpers/audioManagerAssistantDirective.test.js test/helpers/assistantResponseDelivery.test.js`
+Expected: the changed caret test and the new markdown test FAIL on the missing `deliveryAcceptsMarkdown`; the delivery mode test FAILS on the missing `plainText`. Everything else PASSES.
+
+- [ ] **Step 3: Carry it through the audio manager**
+
+In `src/helpers/audioManager.js`:
+
+`_bankAssistantDirective` — change the destructure and the spread:
+
+```js
+const { selectedContext, deliverySessionId, deliveryAcceptsMarkdown } = options || {};
+this.pendingAssistantConversation = {
+ transcript,
+ // resolveReasoningRoute mirrors an attached screenContext into
+ // rawScreenContext (same object), so the raw carry is the single source
+ // to read — it also survives when this attach gate dropped the image
+ // (the panel re-decides for its own request).
+ screenContext: config?.rawScreenContext ?? null,
+ ...(selectedContext ? { selectedContext } : {}),
+ // The verdict only means something next to a caret session.
+ ...(deliverySessionId
+ ? { deliverySessionId, deliveryAcceptsMarkdown: deliveryAcceptsMarkdown === true }
+ : {}),
+};
+```
+
+`_bankPanelAgentCommand` — accept and forward the field:
+
+```js
+ _bankPanelAgentCommand(
+ text,
+ agentName,
+ config,
+ { selectedContext, selectedText, deliverySessionId, deliveryAcceptsMarkdown } = {}
+ ) {
+```
+
+and its last statement:
+
+```js
+this._bankAssistantDirective(transcript, config, {
+ selectedContext,
+ deliverySessionId,
+ deliveryAcceptsMarkdown,
+});
+```
+
+`processAgentCommand` — directly after the `deliverySessionId` const:
+
+```js
+// True when the caret sits in a markdown-friendly app (Obsidian, an AI
+// prompt box), so the panel neither asks for plain prose nor strips the
+// answer. Meaningless without a caret delivery, so undefined then.
+const deliveryAcceptsMarkdown = deliverySessionId ? capture.acceptsMarkdown === true : undefined;
+```
+
+and add `deliveryAcceptsMarkdown,` to both `_bankPanelAgentCommand(...)` option objects in that method (the `!config?.selectionEditReachable` branch and the `standalone || caret` branch).
+
+- [ ] **Step 4: Carry it into the delivery object**
+
+In `src/hooks/useAudioRecording.js`, the destructure at line 504 becomes:
+
+```js
+const { screenContext, transcript, selectedContext, deliverySessionId, deliveryAcceptsMarkdown } =
+ result.assistantConversation;
+```
+
+and the `createAssistantResponseDelivery` call gains one argument:
+
+```js
+ delivery: createAssistantResponseDelivery({
+ autoPasteEnabled,
+ deliverySessionId,
+ acceptsMarkdown: deliveryAcceptsMarkdown === true,
+ restoreClipboard: !keepTranscriptionInClipboard,
+ allowClipboardFallback: isAccessibilitySkipped(),
+ }),
+```
+
+In `src/helpers/assistantResponseDelivery.ts`, the type and the factory become:
+
+```ts
+export type AssistantResponseDelivery =
+ | {
+ mode: "paste";
+ sessionId: string;
+ restoreClipboard: boolean;
+ allowClipboardFallback: boolean;
+ /** Ask for prose and strip markdown before pasting. False for a markdown-friendly target. */
+ plainText: boolean;
+ }
+ | { mode: "clipboard" };
+```
+
+```ts
+export function createAssistantResponseDelivery({
+ autoPasteEnabled,
+ deliverySessionId,
+ acceptsMarkdown = false,
+ restoreClipboard,
+ allowClipboardFallback,
+}: {
+ autoPasteEnabled: boolean;
+ deliverySessionId?: string;
+ acceptsMarkdown?: boolean;
+ restoreClipboard: boolean;
+ allowClipboardFallback: boolean;
+}): AssistantResponseDelivery | null {
+ if (!autoPasteEnabled) return null;
+ if (!deliverySessionId) return { mode: "clipboard" };
+
+ return {
+ mode: "paste",
+ sessionId: deliverySessionId,
+ restoreClipboard,
+ allowClipboardFallback,
+ plainText: !acceptsMarkdown,
+ };
+}
+```
+
+- [ ] **Step 5: Run the tests and the typecheck**
+
+Run: `nvm exec 24 node --import tsx --test test/helpers/audioManagerAssistantDirective.test.js test/helpers/assistantResponseDelivery.test.js && nvm exec 24 npm run typecheck`
+Expected: all PASS; typecheck exits 0.
+
+- [ ] **Step 6: Format, lint, commit**
+
+```bash
+npx prettier --write src/helpers/audioManager.js src/hooks/useAudioRecording.js src/helpers/assistantResponseDelivery.ts test/helpers/audioManagerAssistantDirective.test.js test/helpers/assistantResponseDelivery.test.js
+npx eslint src/helpers/audioManager.js src/helpers/assistantResponseDelivery.ts test/helpers/audioManagerAssistantDirective.test.js test/helpers/assistantResponseDelivery.test.js
+(cd src && npx eslint hooks/useAudioRecording.js)
+git status --short
+git add src/helpers/audioManager.js src/hooks/useAudioRecording.js src/helpers/assistantResponseDelivery.ts test/helpers/audioManagerAssistantDirective.test.js test/helpers/assistantResponseDelivery.test.js
+git commit -m "feat(assistant): carry the markdown verdict from capture to the delivery object
+
+acceptsMarkdown rides next to deliverySessionId through the audio manager
+and useAudioRecording, and the paste delivery gains plainText (its
+negation) for the panel and the delivery helper to act on.
+
+Co-Authored-By: Claude Fable 5.1 <[email protected]>"
+```
+
+---
+
+### Task 5: strip before pasting, only for plain-text targets
+
+**Files:**
+
+- Modify: `src/helpers/assistantResponseDelivery.ts` (`deliverAssistantResponse`)
+- Test: `test/helpers/assistantResponseDelivery.test.js`
+
+**Interfaces:**
+
+- Consumes: `markdownToPlainText` (Task 1), `delivery.plainText` (Task 4).
+- Produces: no signature change.
+
+- [ ] **Step 1: Write the failing tests**
+
+Append to `test/helpers/assistantResponseDelivery.test.js`:
+
+```js
+const MARKDOWN_RESPONSE = "**Bold** start.\n\n* item one\n* item two";
+const PLAIN_RESPONSE = "Bold start.\n\n- item one\n- item two";
+
+test("a plain-text caret target receives the response stripped of markdown", async () => {
+ const { deliverAssistantResponse } = await deliveryModule;
+ const { dependencies, pastes, writes } = createDeliveryHarness(true);
+
+ assert.deepEqual(
+ await deliverAssistantResponse(PASTE_DELIVERY, MARKDOWN_RESPONSE, dependencies),
+ { pasted: true, copied: false }
+ );
+ assert.equal(pastes[0].text, PLAIN_RESPONSE);
+ assert.deepEqual(writes, []);
+});
+
+test("the clipboard fallback of a refused plain-text paste carries the same stripped text", async () => {
+ const { deliverAssistantResponse } = await deliveryModule;
+ const { dependencies, writes } = createDeliveryHarness(false);
+
+ assert.deepEqual(
+ await deliverAssistantResponse(PASTE_DELIVERY, MARKDOWN_RESPONSE, dependencies),
+ { pasted: false, copied: true }
+ );
+ assert.deepEqual(writes, [PLAIN_RESPONSE]);
+});
+
+test("a markdown-friendly caret target receives the response verbatim", async () => {
+ const { deliverAssistantResponse } = await deliveryModule;
+ const { dependencies, pastes } = createDeliveryHarness(true);
+
+ await deliverAssistantResponse(
+ { ...PASTE_DELIVERY, plainText: false },
+ MARKDOWN_RESPONSE,
+ dependencies
+ );
+ assert.equal(pastes[0].text, MARKDOWN_RESPONSE);
+});
+
+test("a clipboard-only delivery keeps the response verbatim", async () => {
+ const { deliverAssistantResponse } = await deliveryModule;
+ const { dependencies, writes } = createDeliveryHarness(false);
+
+ await deliverAssistantResponse({ mode: "clipboard" }, MARKDOWN_RESPONSE, dependencies);
+ assert.deepEqual(writes, [MARKDOWN_RESPONSE]);
+});
+```
+
+- [ ] **Step 2: Run the tests to verify the first two fail**
+
+Run: `nvm exec 24 node --import tsx --test test/helpers/assistantResponseDelivery.test.js`
+Expected: the two plain-text tests FAIL (the markdown is still pasted / copied); the verbatim tests PASS already.
+
+- [ ] **Step 3: Apply the strip**
+
+In `src/helpers/assistantResponseDelivery.ts`, add the import at the top:
+
+```ts
+import { markdownToPlainText } from "./markdownToPlainText";
+```
+
+Replace `deliverAssistantResponse` with:
+
+```ts
+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") {
+ // plainText is the main process's verdict on the captured app. When set,
+ // the model was asked for prose (plainTextResponse) and this is the floor
+ // under a model that drifts back to markdown. It covers the clipboard
+ // fallback too: a refused paste leaves the user about to paste the same
+ // text by hand into the same field. A markdown-friendly target (Obsidian,
+ // an AI prompt box) gets the answer exactly as written.
+ const text = delivery.plainText ? markdownToPlainText(content) : content;
+ try {
+ const result = await electronAPI?.pasteAtCapturedTarget?.(delivery.sessionId, text, {
+ restoreClipboard: delivery.restoreClipboard,
+ allowClipboardFallback: delivery.allowClipboardFallback,
+ });
+ if (result?.success === true) return { pasted: true, copied: false };
+ } catch {}
+ return {
+ pasted: false,
+ copied: await copyAssistantResponse(text, electronAPI, clipboard),
+ };
+ }
+
+ // A clipboard-only delivery is shown in the panel as rendered markdown and
+ // its Copy button yields the raw markdown; keep the two copy paths equal.
+ return {
+ pasted: false,
+ copied: await copyAssistantResponse(content, electronAPI, clipboard),
+ };
+}
+```
+
+- [ ] **Step 4: Run the tests to verify they pass**
+
+Run: `nvm exec 24 node --import tsx --test test/helpers/assistantResponseDelivery.test.js`
+Expected: all PASS.
+
+- [ ] **Step 5: Format, lint, commit**
+
+```bash
+npx prettier --write src/helpers/assistantResponseDelivery.ts test/helpers/assistantResponseDelivery.test.js
+npx eslint src/helpers/assistantResponseDelivery.ts test/helpers/assistantResponseDelivery.test.js
+git status --short
+git add src/helpers/assistantResponseDelivery.ts test/helpers/assistantResponseDelivery.test.js
+git commit -m "fix(assistant): paste caret-bound answers as plain text unless the app keeps markdown
+
+A plainText paste delivery, and the clipboard fallback of a refused one,
+go through markdownToPlainText. Markdown-friendly targets and
+clipboard-only deliveries stay verbatim.
+
+Co-Authored-By: Claude Fable 5.1 <[email protected]>"
+```
+
+---
+
+### Task 6: the plain-prose prompt suffix
+
+**Files:**
+
+- Modify: `src/config/prompts/registry.ts` (after `DEFAULT_CHAT_AGENT_PROMPT`, lines 3–8)
+- Modify: `src/config/prompts/index.ts` (import on line 5; new function after `appendDictionarySuffix`, which ends at line 59)
+- Modify: `src/config/prompts.ts` (export block, lines 3–9)
+- Test: `test/helpers/agentPlainTextSuffix.test.js`
+
+**Interfaces:**
+
+- Produces: `export const PLAIN_TEXT_RESPONSE_SUFFIX: string` (registry) and `export function appendPlainTextResponseSuffix(prompt: string): string` (index, re-exported from `src/config/prompts.ts`). Task 7 imports the function from `"../../config/prompts"`.
+
+- [ ] **Step 1: Write the failing tests**
+
+Create `test/helpers/agentPlainTextSuffix.test.js`:
+
+```js
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const promptsModule = import("../../src/config/prompts.ts");
+const registryModule = import("../../src/config/prompts/registry.ts");
+
+test("the plain-text suffix is appended once, at the very end", async () => {
+ const { appendPlainTextResponseSuffix } = await promptsModule;
+ const { PLAIN_TEXT_RESPONSE_SUFFIX } = await registryModule;
+
+ const result = appendPlainTextResponseSuffix("BASE PROMPT");
+
+ assert.ok(result.startsWith("BASE PROMPT"));
+ assert.ok(result.endsWith(PLAIN_TEXT_RESPONSE_SUFFIX));
+ assert.equal(result.split("OUTPUT FORMAT:").length, 2);
+});
+
+test("the suffix names every markdown construct the strip helper removes", async () => {
+ const { PLAIN_TEXT_RESPONSE_SUFFIX } = await registryModule;
+ for (const construct of ["asterisks", "backticks", "heading", "list", "tables", "link"]) {
+ assert.match(PLAIN_TEXT_RESPONSE_SUFFIX, new RegExp(construct));
+ }
+});
+
+// The panel renders markdown, so a panel-bound answer must never be asked
+// for plain prose. Guards against someone "simplifying" the suffix into the
+// default prompt later — that would also trip the prompt-hash protocol.
+test("a panel-bound agent prompt carries no plain-text instruction", async () => {
+ const { getAgentSystemPrompt } = await promptsModule;
+ assert.ok(!getAgentSystemPrompt().includes("OUTPUT FORMAT:"));
+ assert.ok(!getAgentSystemPrompt(["web_search"], "some note").includes("OUTPUT FORMAT:"));
+});
+```
+
+- [ ] **Step 2: Run the tests to verify they fail**
+
+Run: `nvm exec 24 node --import tsx --test test/helpers/agentPlainTextSuffix.test.js`
+Expected: the first two FAIL (`appendPlainTextResponseSuffix is not a function` / `PLAIN_TEXT_RESPONSE_SUFFIX` undefined); the third PASSES.
+
+- [ ] **Step 3: Add the constant**
+
+In `src/config/prompts/registry.ts`, directly after the `DEFAULT_CHAT_AGENT_PROMPT` constant (leave that constant and the comment above it byte-for-byte unchanged):
+
+```ts
+// Appended per request — never baked into the default above — when the
+// answer is pasted at a caret that wants plain text. Conditional on purpose:
+// the panel renders markdown, so panel answers keep it; markdown-friendly
+// apps (see src/helpers/markdownTargets.js) keep it; a user's custom chat
+// prompt still receives it; and the shipped default text (and its hash in
+// retiredPrompts.js) stays unchanged. English-only because the chat-agent
+// prompt it extends is English-only (i18nKey: null).
+export const PLAIN_TEXT_RESPONSE_SUFFIX =
+ "\n\nOUTPUT FORMAT: Your answer will be inserted as plain text exactly where the user is typing, " +
+ "inside another application. Write plain prose with no markdown: no asterisks, underscores, " +
+ "backticks, heading marks, bullet or numbered-list markers, tables, or link syntax. " +
+ "Use ordinary sentences and paragraphs. If several items must be listed, put each on its " +
+ "own line with no marker.";
+```
+
+- [ ] **Step 4: Add the append helper and re-export it**
+
+In `src/config/prompts/index.ts`, change the registry import (line 5) to:
+
+```ts
+import { PROMPT_KINDS, PLAIN_TEXT_RESPONSE_SUFFIX, type PromptKind } from "./registry";
+```
+
+and add, directly after `appendDictionarySuffix`:
+
+```ts
+// Appended last, after every other suffix, when the answer will be pasted at
+// a plain-text caret — trailing instructions are the ones models weight most
+// (the same reason wrapCleanupTranscript re-anchors the contract after the
+// transcript).
+export function appendPlainTextResponseSuffix(prompt: string): string {
+ return prompt + PLAIN_TEXT_RESPONSE_SUFFIX;
+}
+```
+
+In `src/config/prompts.ts`, add `appendPlainTextResponseSuffix,` to the export block so it reads:
+
+```ts
+export {
+ resolvePrompt,
+ getDefaultPromptText,
+ appendDictionarySuffix,
+ appendScreenContextSuffix,
+ appendPlainTextResponseSuffix,
+ wrapCleanupTranscript,
+} from "./prompts/index";
+```
+
+- [ ] **Step 5: Run the new tests and the hash-protocol test**
+
+Run: `nvm exec 24 node --import tsx --test test/helpers/agentPlainTextSuffix.test.js test/helpers/retiredPrompts.test.js`
+Expected: all PASS. `retiredPrompts.test.js` passing unchanged is the proof the default prompt's hash did not move.
+
+- [ ] **Step 6: Format, lint, commit**
+
+```bash
+npx prettier --write src/config/prompts/registry.ts src/config/prompts/index.ts src/config/prompts.ts test/helpers/agentPlainTextSuffix.test.js
+npx eslint src/config/prompts/registry.ts src/config/prompts/index.ts src/config/prompts.ts
+npx eslint test/helpers/agentPlainTextSuffix.test.js
+git status --short
+git add src/config/prompts/registry.ts src/config/prompts/index.ts src/config/prompts.ts test/helpers/agentPlainTextSuffix.test.js
+git commit -m "feat(assistant): plain-prose prompt suffix for plain-text caret answers
+
+A conditional suffix rather than an edit to DEFAULT_CHAT_AGENT_PROMPT, so
+panel answers keep markdown, custom prompts are covered, and the
+prompt-hash snapshot is untouched.
+
+Co-Authored-By: Claude Fable 5.1 <[email protected]>"
+```
+
+---
+
+### Task 7: wire the suffix to plain-text caret sends
+
+**Files:**
+
+- Modify: `src/components/chat/useChatStreaming.ts` (import block lines 13–17; `SendToAIOptions` lines 78–92; suffix application after the screen-context block around line 356)
+- Modify: `src/components/dictation/AssistantPanel.tsx` (lines 203–210, the pending-command effect)
+
+**Interfaces:**
+
+- Consumes: `appendPlainTextResponseSuffix` (Task 6), `delivery.plainText` (Task 4).
+- Produces: `SendToAIOptions.plainTextResponse?: boolean`.
+
+This task has no unit test: the hook is React-bound and the change is a few lines of plumbing. Its verification is `npm run typecheck` here and the manual dev-build check in Task 9.
+
+- [ ] **Step 1: Add the option**
+
+In `src/components/chat/useChatStreaming.ts`, inside `SendToAIOptions`, directly after the `suppressResponseContent` entry:
+
+```ts
+ /** Asks the model for plain prose because the answer will be pasted into a plain-text app. */
+ plainTextResponse?: boolean;
+```
+
+- [ ] **Step 2: Import and apply the suffix last**
+
+Change the prompts import to:
+
+```ts
+import {
+ appendDictionarySuffix,
+ appendPlainTextResponseSuffix,
+ appendScreenContextSuffix,
+ getAgentSystemPrompt,
+} from "../../config/prompts";
+```
+
+Directly after the block that ends with `systemPrompt = appendScreenContextSuffix(systemPrompt, settings.uiLanguage);` and its closing `}` (and before the `if (attachment) { transformLastUserMessage(` block), add:
+
+```ts
+if (options?.plainTextResponse) {
+ // Last on purpose: trailing instructions are the ones models weight most.
+ systemPrompt = appendPlainTextResponseSuffix(systemPrompt);
+}
+```
+
+- [ ] **Step 3: Pass the flag from the panel**
+
+In `src/components/dictation/AssistantPanel.tsx`, the pending-command effect currently has:
+
+```ts
+const delivery = pendingCommand.delivery;
+const targetsCapturedInput = delivery?.mode === "paste";
+```
+
+Add directly after those two lines:
+
+```ts
+// Suppressing the panel content and asking for prose are different
+// decisions: a caret in Obsidian still keeps the compact pill, but the
+// model writes markdown for it.
+const plainTextResponse = delivery?.mode === "paste" && delivery.plainText;
+```
+
+and in the `sendMessage` call change:
+
+```ts
+ suppressResponseContent: targetsCapturedInput,
+```
+
+to:
+
+```ts
+ suppressResponseContent: targetsCapturedInput,
+ plainTextResponse,
+```
+
+- [ ] **Step 4: Typecheck**
+
+Run: `nvm exec 24 npm run typecheck`
+Expected: exits 0 with no output.
+
+- [ ] **Step 5: Format, lint, commit**
+
+```bash
+npx prettier --write src/components/chat/useChatStreaming.ts src/components/dictation/AssistantPanel.tsx
+npx eslint src/components/chat/useChatStreaming.ts src/components/dictation/AssistantPanel.tsx
+git status --short
+git add src/components/chat/useChatStreaming.ts src/components/dictation/AssistantPanel.tsx
+git commit -m "feat(assistant): ask for plain prose when the answer targets a plain-text caret
+
+plainTextResponse follows delivery.plainText and appends the suffix last
+in the system prompt. Reaches every route: the cloud stream forwards the
+client system prompt on every tool-loop step.
+
+Co-Authored-By: Claude Fable 5.1 <[email protected]>"
+```
+
+---
+
+### Task 8: log every declined paste
+
+**Files:**
+
+- Modify: `src/helpers/selectionManager.js` (`pasteAtCapturedTarget`; new private method after it)
+- Test: `test/helpers/selectionManager.test.js` (loader at lines 10–25; new tests appended)
+
+**Interfaces:**
+
+- Consumes: `session.acceptsMarkdown` (Task 3).
+- Produces: no change to return values. New log lines, scope `"clipboard"`:
+ - `info` `"Assistant response paste declined"` with meta `{ code, platform, sessionFound, sessionKind?, probeStatus?, probeCode? }`
+ - `debug` `"Assistant response pasted"` with meta `{ targetKind, acceptsMarkdown, platform }`
+
+- [ ] **Step 1: Stub the logger in the test loader**
+
+In `test/helpers/selectionManager.test.js`, directly above `const originalLoad = Module._load;` add:
+
+```js
+// selectionManager requires "./debugLogger" at load; the stub records every
+// line so tests can assert what a declined paste leaves in the debug log.
+const logged = [];
+const debugLoggerStub = {
+ debug: (message, meta, scope) => logged.push({ level: "debug", message, meta, scope }),
+ info: (message, meta, scope) => logged.push({ level: "info", message, meta, scope }),
+ warn: (message, meta, scope) => logged.push({ level: "warn", message, meta, scope }),
+ trace: () => {},
+ log: () => {},
+ error: () => {},
+};
+const declines = () =>
+ logged.filter((entry) => entry.message === "Assistant response paste declined");
+```
+
+Inside `loadWithElectronMock`, directly after the `if (request === "electron")` block, add:
+
+```js
+if (request === "./debugLogger") {
+ return debugLoggerStub;
+}
+```
+
+Run the existing file to confirm the stub did not break anything:
+`nvm exec 24 node --import tsx --test test/helpers/selectionManager.test.js` → all existing tests PASS.
+
+- [ ] **Step 2: Write the failing tests**
+
+Append to `test/helpers/selectionManager.test.js`:
+
+```js
+test("a paste declined by a changed target logs the code and the probe verdict", async () => {
+ logged.length = 0;
+ const { manager } = makeHarness({
+ selections: [
+ { state: "none", editable: true },
+ { state: "selected", text: "new selection" },
+ ],
+ });
+ const capture = await manager.captureSelectedText({ probeEditable: true });
+ await manager.pasteAtCapturedTarget(capture.sessionId, "Agent response");
+
+ assert.equal(declines().length, 1);
+ const [entry] = declines();
+ assert.equal(entry.level, "info");
+ assert.equal(entry.scope, "clipboard");
+ assert.equal(entry.meta.code, "target_changed");
+ assert.equal(entry.meta.platform, "darwin");
+ assert.equal(entry.meta.sessionFound, true);
+ assert.equal(entry.meta.sessionKind, "caret");
+ assert.equal(entry.meta.probeStatus, "selected");
+});
+
+test("a paste against a missing or expired session logs session_expired", async () => {
+ logged.length = 0;
+ const { manager, pastes } = makeHarness();
+
+ assert.deepEqual(await manager.pasteAtCapturedTarget("missing-session", "Agent response"), {
+ success: false,
+ code: "session_expired",
+ });
+ assert.equal(pastes.length, 0);
+ const [entry] = declines();
+ assert.equal(entry.meta.code, "session_expired");
+ assert.equal(entry.meta.sessionFound, false);
+});
+
+test("a selection session offered as a caret target logs its kind", async () => {
+ logged.length = 0;
+ const { manager } = makeHarness({ selections: ["some selected text"] });
+ const capture = await manager.captureSelectedText();
+
+ assert.equal(
+ (await manager.pasteAtCapturedTarget(capture.sessionId, "x")).code,
+ "session_expired"
+ );
+ const [entry] = declines();
+ assert.equal(entry.meta.sessionFound, true);
+ assert.equal(entry.meta.sessionKind, "selection");
+});
+
+test("empty text logs invalid_replacement before any clipboard work", async () => {
+ logged.length = 0;
+ const { manager, pastes } = makeHarness();
+
+ assert.deepEqual(await manager.pasteAtCapturedTarget("any-session", ""), {
+ success: false,
+ code: "invalid_replacement",
+ });
+ assert.equal(pastes.length, 0);
+ assert.equal(declines()[0].meta.code, "invalid_replacement");
+});
+
+test("a paste the clipboard helper reports as not pasted logs paste_failed", async () => {
+ logged.length = 0;
+ const { manager } = makeHarness({
+ selections: [
+ { state: "none", editable: true },
+ { state: "none", editable: true },
+ ],
+ pasteResult: { pasted: false, restoreComplete: Promise.resolve() },
+ });
+ const capture = await manager.captureSelectedText({ probeEditable: true });
+
+ assert.deepEqual(await manager.pasteAtCapturedTarget(capture.sessionId, "Agent response"), {
+ success: false,
+ code: "paste_failed",
+ });
+ const [entry] = declines();
+ assert.equal(entry.meta.code, "paste_failed");
+ assert.equal(entry.meta.probeStatus, "editable");
+});
+
+test("a successful paste logs no decline and one debug line carrying the markdown verdict", async () => {
+ logged.length = 0;
+ const { manager } = makeHarness({
+ selections: [
+ { state: "none", editable: true },
+ { state: "none", editable: true },
+ ],
+ });
+ manager._readExecutablePath = async () => "/Applications/Obsidian.app/Contents/MacOS/Obsidian";
+ const capture = await manager.captureSelectedText({ probeEditable: true });
+
+ assert.deepEqual(await manager.pasteAtCapturedTarget(capture.sessionId, "Agent response"), {
+ success: true,
+ });
+ assert.equal(declines().length, 0);
+ const successes = logged.filter((entry) => entry.message === "Assistant response pasted");
+ assert.equal(successes.length, 1);
+ assert.equal(successes[0].level, "debug");
+ assert.equal(successes[0].meta.platform, "darwin");
+ assert.equal(successes[0].meta.acceptsMarkdown, true);
+});
+```
+
+- [ ] **Step 3: Run the tests to verify they fail**
+
+Run: `nvm exec 24 node --import tsx --test test/helpers/selectionManager.test.js`
+Expected: the six new tests FAIL (`declines()` is empty / `entry` is undefined); every pre-existing test still PASSES.
+
+- [ ] **Step 4: Add the logging**
+
+In `src/helpers/selectionManager.js`, replace `pasteAtCapturedTarget` with:
+
+```js
+ async pasteAtCapturedTarget(sessionId, text, options = {}) {
+ if (typeof text !== "string" || text.length === 0) {
+ return this._declineAssistantPaste("invalid_replacement", {
+ sessionFound: this.sessions.has(sessionId),
+ });
+ }
+
+ return this.clipboardManager.runClipboardOperation(async () => {
+ this._pruneSessions();
+ const session = this.sessions.get(sessionId);
+ this.sessions.delete(sessionId);
+ if (!session || session.kind !== "caret") {
+ return this._declineAssistantPaste("session_expired", {
+ sessionFound: Boolean(session),
+ sessionKind: session?.kind ?? null,
+ });
+ }
+
+ const current = await this._readCurrentSelection(session.target, { probeEditable: true });
+ if (current.status !== "editable") {
+ return this._declineAssistantPaste("target_changed", {
+ sessionFound: true,
+ sessionKind: "caret",
+ probeStatus: current.status,
+ probeCode: current.code ?? null,
+ });
+ }
+
+ 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 this._declineAssistantPaste("paste_failed", {
+ sessionFound: true,
+ sessionKind: "caret",
+ probeStatus: "editable",
+ });
+ }
+ debugLogger.debug(
+ "Assistant response pasted",
+ {
+ targetKind: session.target?.kind ?? null,
+ acceptsMarkdown: session.acceptsMarkdown === true,
+ platform: this.platform,
+ },
+ "clipboard"
+ );
+ return { success: true };
+ } catch (error) {
+ debugLogger.warn("Assistant response paste failed", { error: error.message }, "clipboard");
+ return { success: false, code: "paste_failed", error: error.message };
+ }
+ });
+ }
+
+ // One line per refusal. The renderer discards the code it receives, so the
+ // debug log is the only place a declined assistant paste can be diagnosed.
+ _declineAssistantPaste(code, details = {}) {
+ debugLogger.info(
+ "Assistant response paste declined",
+ { code, platform: this.platform, ...details },
+ "clipboard"
+ );
+ return { success: false, code };
+ }
+```
+
+The returned objects are identical to before (`{ success: false, code }`), so no caller changes.
+
+- [ ] **Step 5: Run the tests to verify they pass**
+
+Run: `nvm exec 24 node --import tsx --test test/helpers/selectionManager.test.js`
+Expected: all PASS, including the six new ones.
+
+- [ ] **Step 6: Format, lint, commit**
+
+```bash
+npx prettier --write src/helpers/selectionManager.js test/helpers/selectionManager.test.js
+npx eslint src/helpers/selectionManager.js test/helpers/selectionManager.test.js
+git status --short
+git add src/helpers/selectionManager.js test/helpers/selectionManager.test.js
+git commit -m "fix(assistant): log every declined caret paste with its probe verdict
+
+pasteAtCapturedTarget returned four refusal codes and logged none of
+them. Each decline now leaves one info line (code, session state, probe
+status/code, platform) and a success leaves one debug line that also
+records whether the target was judged markdown-friendly.
+
+Co-Authored-By: Claude Fable 5.1 <[email protected]>"
+```
+
+---
+
+### Task 9: full verification, manual check, PR
+
+**Files:** none new. Uses the `openwhispr-dev-build` skill for the manual check.
+
+- [ ] **Step 1: Full suite and quality gate**
+
+```bash
+nvm exec 24 npm test
+nvm exec 24 npm run quality-check
+```
+
+Expected: `npm test` reports 0 failures (about 169 Electron-ABI skips are normal locally). `quality-check` (format check + typecheck) exits 0. If Prettier reflows a file, run `npx prettier --write` on it and amend the relevant commit.
+
+- [ ] **Step 2: Push the branch**
+
+```bash
+git status --short # empty, and never lists node_modules
+git log --oneline origin/main..HEAD # the spec, the plan, and eight implementation commits
+git push -u origin fix/agent-paste-plain-text
+```
+
+- [ ] **Step 3: Manual verification on a dev build (macOS)**
+
+Stand the branch up with the `openwhispr-dev-build` skill (it isolates a throwaway profile against the production API). Enable debug logging in the app's settings and note the log file it names. Then:
+
+1. **Plain-text target.** Open TextEdit in plain-text mode (Format → Make Plain Text) and place the caret in the document. Trigger a voice command that invites structure, e.g. "give me three reasons to drink more water". **Pass:** prose lands at the caret with no `*`, `#`, `` ` `` or `|`; items, if listed, sit on their own lines without markers; the log carries `Assistant response pasted` with `acceptsMarkdown: false`.
+2. **Markdown-friendly target.** Open the ChatGPT desktop app (native, so paste works today; Obsidian and other Electron apps do not receive agent paste on macOS until PR #1952 lands) and place the caret in its prompt box. Trigger "give me a markdown table of three fruits and their colours". **Pass:** the table lands with its pipes intact and no stripping; the log carries `acceptsMarkdown: true`. Do not send the prompt.
+3. **Declined paste.** Trigger another command in TextEdit and, while the answer streams, click the Finder desktop. **Pass:** the answer is not pasted, it lands on the clipboard, and the log carries `Assistant response paste declined` with `code: target_changed` and a `probeStatus` / `probeCode`.
+4. **History and Copy.** Open the panel's conversation for the step 1 turn. **Pass:** the stored answer is the model's prose, and the panel's Copy button copies it unchanged. For the step 2 turn the stored answer is the markdown table.
+
+Record the outcome of each step in the PR body. If step 1 pastes markdown while the log says `acceptsMarkdown: false`, the strip did not run: check that `delivery.plainText` reached `deliverAssistantResponse`. If step 2 pastes stripped text, check the log's verdict first: a `false` there means the identity string did not match, so add the exact `"<bundle> <executable>"` the log implies to the matcher test and fix the entry.
+
+Tear the dev build down when finished (the skill's `teardown`), and never trust a teardown OK without `git status` in the shared clone coming back clean.
+
+- [ ] **Step 4: Open the PR, never merge it**
+
+```bash
+gh pr create --repo OpenWhispr/openwhispr --base main --head fix/agent-paste-plain-text \
+ --title "fix(assistant): paste caret-bound answers as plain text unless the app keeps markdown" \
+ --body-file - <<'PRBODY'
+## Problem
+
+When a voice-command answer pastes at the caret, it arrives with markdown intact: `**bold**` lands as literal asterisks in a plain document. Nothing told the model to write prose and nothing in the delivery path touched the text. At the same time, plain text is the wrong answer for markdown editors, AI prompt boxes, standard-markdown chat tools and code editors, which many of our users live in. Separately, `pasteAtCapturedTarget` returned four refusal codes and logged none of them, so a declined paste was undiagnosable.
+
+## Fix
+
+- **Decide at capture:** `captureSelectedText` judges the app under the caret against `src/helpers/markdownTargets.js` (a researched allowlist matched by whole token on the identity each platform already exposes: `.app` name and executable on macOS, exe name on Windows, WM_CLASS on Linux) and returns `acceptsMarkdown`. Plain text is the default for anything unlisted or unreadable. The list, the evidence per app, and the apps deliberately excluded (Slack, Teams, WhatsApp and Telegram use dialects where `**bold**` leaves stray asterisks) are in the design spec's appendices.
+- **Instruct:** for a plain-text caret, `plainTextResponse` appends `PLAIN_TEXT_RESPONSE_SUFFIX` last in the system prompt. Conditional rather than an edit to `DEFAULT_CHAT_AGENT_PROMPT`, so panel answers keep rendered markdown, users' custom chat prompts are covered, and `retiredPrompts.js` is untouched.
+- **Strip:** `markdownToPlainText` (new, newline-preserving — deliberately not `stripMarkdownPreview`, which collapses newlines) runs inside `deliverAssistantResponse` for plain-text paste deliveries and their clipboard fallback. Markdown-friendly targets and clipboard-only deliveries stay verbatim. History stores what the model wrote; the strip only touches the pasted bytes.
+- **Log:** each of the four refusals in `pasteAtCapturedTarget` emits one `info` line with the code, session state and probe verdict; a success emits one `debug` line that also records the markdown verdict. Return values unchanged.
+
+Design: `docs/superpowers/specs/2026-09-10-agent-paste-plain-text-design.md`. Out of scope, on purpose: rich-text clipboard, per-site detection for web apps in a browser (needs the window title; the natural follow-up once #1952 makes browser targets reachable), a user setting, and PR #1952 itself (Chromium/Electron targets never paste at all today — once it lands the allowlist becomes load-bearing, because most markdown-friendly apps are Electron).
+
+## Tests
+
+- `test/helpers/markdownToPlainText.test.js` — one case per strip rule plus the must-not-alter cases (`2 * 3`, snake_case, `#hashtag`, `x > y`, `\*`) and a two-paragraph answer.
+- `test/helpers/markdownTargets.test.js` — every platform identity shape for listed apps matches; plain-text apps, own-dialect chat tools, browsers, `Xcode` and the vetoes never match; no generic tokens.
+- `test/helpers/selectionManager.test.js` — verdict on the capture result and session for macOS, Windows, Linux and unreadable pids; one test per refusal code; success logs the verdict.
+- `test/helpers/audioManagerAssistantDirective.test.js` — the verdict rides with the session id and is absent without a caret delivery.
+- `test/helpers/assistantResponseDelivery.test.js` — `plainText` derivation; stripped vs verbatim per delivery.
+- `test/helpers/agentPlainTextSuffix.test.js` — suffix appends once at the end; panel prompt never carries it.
+- `test/helpers/retiredPrompts.test.js` unchanged and green: the prompt-hash protocol was not triggered.
+- Manual on a macOS dev build: (results of Task 9 step 3 go here — TextEdit plain, ChatGPT app markdown, declined paste logged, history and Copy untouched)
+
+🤖 Generated with [Claude Code](https://claude.com/claude-code)
+PRBODY
+```
+
+Stop here. Do not merge, do not enable auto-merge, do not request a merge.
+
+- [ ] **Step 5: Clean up the worktree**
+
+```bash
+rm <worktree>/node_modules # the symlink only
+git -C ~/dev/openwhispr-desktop worktree remove <worktree>
+git -C ~/dev/openwhispr-desktop status --short # must be clean
+```
+
+---
+
+## Self-review against the spec
+
+- **Spec §0 (decide once at capture):** Task 2 (list and matcher) and Task 3 (resolution per platform, stored on the session, returned on the result, plain text on any miss or error).
+- **Spec §1 (tell the model, per request):** Task 6 (constant + helper) and Task 7 (option, applied last, gated on `delivery.plainText`). Task 4 carries the verdict the gate reads.
+- **Spec §2 (strip as the floor):** Task 1 (helper, every rule in the spec's table has a test) and Task 5 (plain-text paste and its fallback only; markdown-friendly and clipboard-only verbatim).
+- **Spec §3 (the allowlist):** Task 2 carries exactly the Appendix A tokens, grouped as the spec groups them, with the vetoes and the generic-token ban tested.
+- **Spec §4 (history and panel copy):** no code; Task 5 strips only the delivered bytes, and Task 9 step 3.4 verifies history and Copy are untouched.
+- **Spec §5 (log the refusal):** Task 8, all four codes plus the probe verdict and the debug success line with `acceptsMarkdown`.
+- **Spec "what this does not do":** enforced by Global Constraints (no rich text, no browser-tab detection, no setting, no #1952, no default-prompt edit).
+- **Spec "testing":** every listed file has a task; the manual steps are Task 9 step 3.
+- **Type consistency:** `markdownToPlainText` (Tasks 1, 5); `isMarkdownTargetSignature` (Tasks 2, 3); `_readTargetNames`, `_targetAcceptsMarkdown`, `acceptsMarkdown` on the capture result and session (Tasks 3, 4, 8); `deliveryAcceptsMarkdown` (Task 4 only, audio manager to hook); `plainText` on the paste delivery (Tasks 4, 5, 7); `PLAIN_TEXT_RESPONSE_SUFFIX`, `appendPlainTextResponseSuffix` (Tasks 6, 7); `plainTextResponse` (Task 7); `_declineAssistantPaste` (Task 8). Named identically everywhere they appear.
diff --git a/docs/superpowers/specs/2026-09-10-agent-paste-plain-text-design.md b/docs/superpowers/specs/2026-09-10-agent-paste-plain-text-design.md
new file mode 100644
index 000000000..0c1087780
--- /dev/null
+++ b/docs/superpowers/specs/2026-09-10-agent-paste-plain-text-design.md
@@ -0,0 +1,533 @@
+# Agent answers paste as plain text — design
+
+**Date:** 2026-09-10, revised 2026-09-11 (markdown-friendly targets)
+**Status:** approved by Josh, 2026-09-13 — build may proceed against the plan; nothing merges without him
+**Origin:** Finding 3 of the 1.10.0 release testing report (titan,
+`artefacts/reports/2026-09-10-openwhispr-1-10-0-release-testing.md`)
+
+## The problem
+
+When a voice command's answer is pasted where the user was typing, the text
+arrives with markdown syntax intact. Bold emphasis lands as literal asterisks,
+headings as hash marks, bullets as dashes and stars. In a plain document that
+reads as garbage.
+
+Two halves, both real:
+
+1. Nothing tells the model to avoid markdown. The chat-agent prompt is three
+ sentences about being a concise voice assistant and says nothing about
+ output format. Current models default to markdown.
+2. Nothing in the delivery path touches the text. `deliverAssistantResponse`
+ in `src/helpers/assistantResponseDelivery.ts` hands the model's output
+ verbatim to `pasteAtCapturedTarget`.
+
+A third, adjacent gap sits in the same code: when the main process declines to
+paste, it returns one of four refusal codes and logs none of them. That is why
+the feature reads as unreliable rather than as limited.
+
+And a fourth, raised by Josh on 2026-09-11: **plain text is wrong for a large
+class of targets.** Markdown-native editors (Obsidian, Typora), apps that
+convert pasted markdown (Notion, Craft), chat tools whose composer is standard
+markdown (Discord, Mattermost), AI prompt boxes (ChatGPT, Claude, Cursor's
+chat) and code editors all want the markdown left alone. Many OpenWhispr users
+are developers, and AI prompt boxes in particular are a daily surface for them.
+
+## The decision
+
+**Instruct the model, then strip as a safety net — but only when the target
+wants plain text. A researched allowlist of markdown-friendly apps keeps their
+markdown untouched.** Plus the missing log line, because the code is already
+open.
+
+Why not instruct alone: models drift, and a single leaked `**` on a customer's
+document is a visible defect. Why not strip alone: a stripped table is
+unreadable and a stripped list loses its shape, whereas a model asked for prose
+writes flowing sentences that need no stripping. Why the allowlist: the strip
+is blind to its destination, and for a markdown editor or an AI prompt box it
+would actively damage a good answer. Plain text stays the default for anything
+not on the list, because the cost of a wrong "keeps markdown" verdict (literal
+asterisks in someone's document) is higher than the cost of a wrong "plain
+text" verdict (a flat but readable answer in Obsidian).
+
+### One refinement to the handover's framing
+
+The handover assumed the instruction means editing `DEFAULT_CHAT_AGENT_PROMPT`
+and therefore following the prompt-hash retirement protocol. It does not, and
+it should not:
+
+- **The panel renders markdown.** `AssistantPanel.tsx` displays answers through
+ `MarkdownRenderer`. When the answer targets the panel rather than the caret,
+ markdown is the right output. A base-prompt edit would degrade every panel
+ answer to fix caret answers.
+- **Custom prompts bypass the default entirely.** `resolvePrompt("chatAgent")`
+ returns the user's `customPrompts.chatAgent` when one is set. An edit to the
+ default never reaches those users. A suffix appended per request does, which
+ is exactly how the dictionary and screen-context suffixes already work.
+- **The shipped default text does not change**, so the retired-hash set and the
+ current-hash snapshot in `src/config/retiredPrompts.js` stay as they are.
+
+So the instruction is a **conditional suffix**, appended only when the answer
+is destined for a caret that wants plain text. The base prompt is untouched.
+
+## Design
+
+### 0. The main process decides, once, at capture time
+
+The main process already identifies the app under the caret, because it has to
+check the caret is still there before pasting. What it knows differs by
+platform, and the allowlist matches on all of it:
+
+| Platform | Identity available | Source in code |
+| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
+| macOS | The `.app` folder name and executable name, resolved from the pid (`"Visual Studio Code Code"`, `"Obsidian Obsidian"`); on the Chromium path also the copy helper's localized app name | `_isTerminalPid` → `_readExecutablePath` (`ps -o comm=`); `_readMacSelectionViaClipboard` (`appName`) |
+| Windows | The exe name (`"Obsidian.exe"`, `"idea64.exe"`) and window class (almost always `Chrome_WidgetWin_1` for Electron, so the exe is the discriminator) | `lastTarget.exeName` / `windowClass` from the fast-paste helper's `--detect` run |
+| Linux | The WM_CLASS (`"obsidian"`, `"md.obsidian.obsidian"` under Flatpak, `"jetbrains-idea"`), or for AT-SPI targets a pid resolved like macOS | `_getLinuxTarget` (`windowClass`); `_isTerminalPid` for `atspi-pid` |
+
+The precedents are `_isLineCopyEditor` (an editor-name list) and
+`isTerminalSignature` (a terminal-name list). The markdown check follows the
+same shape with one difference: **it matches whole tokens or phrases, never
+bare substrings**, so `code` does not match `Xcode`, and short names cannot
+false-match inside longer ones. A few explicit vetoes are checked first
+(`notion calendar`, `notion mail`, `xcode`).
+
+The verdict is computed **once, when the caret session is created** in
+`captureSelectedText`, stored on the session, and returned to the renderer as
+`acceptsMarkdown: boolean` on the `editable` capture result. Nothing is
+resolved again at paste time. A pid that cannot be read, an app not on the
+list, or any error yields `false`: plain text is the safe default.
+
+### 1. Tell the model, per request
+
+`SendToAIOptions` in `src/components/chat/useChatStreaming.ts` gains one
+optional flag:
+
+```ts
+/** Asks for plain prose because the answer will be pasted into another app. */
+plainTextResponse?: boolean;
+```
+
+The renderer already carries the caret session id from the capture result to
+the panel (`audioManager` → `pendingAssistantConversation.deliverySessionId` →
+`useAudioRecording` → `createAssistantResponseDelivery`). `acceptsMarkdown`
+rides the same route as `deliveryAcceptsMarkdown`, and the delivery object's
+`paste` variant gains `plainText: boolean` (`!acceptsMarkdown`).
+
+`AssistantPanel.tsx` already computes `targetsCapturedInput` (delivery mode is
+`paste`) and passes `suppressResponseContent` from it. It passes
+`plainTextResponse` from `delivery.mode === "paste" && delivery.plainText`. The
+two flags stay separate because they mean different things: one is about what
+the panel shows, the other about what the model writes. A caret in Obsidian
+still suppresses the panel content; it just does not ask for prose.
+
+`useChatStreaming.sendToAI` appends the suffix **last**, after the dictionary
+and screen-context suffixes, so it sits where models weight instructions most
+(the same reasoning the cleanup prompt documents in `src/config/prompts/index.ts`).
+
+The suffix is an English constant, `PLAIN_TEXT_RESPONSE_SUFFIX`, defined in
+`src/config/prompts/registry.ts` beside `DEFAULT_CHAT_AGENT_PROMPT`. It is not
+localised because the chat-agent prompt it extends is not localised
+(`i18nKey: null`). It is applied by a new `appendPlainTextResponseSuffix(prompt)`
+in `src/config/prompts/index.ts`, re-exported from `src/config/prompts.ts`
+alongside the other `append*Suffix` helpers.
+
+Text:
+
+> OUTPUT FORMAT: Your answer will be inserted as plain text exactly where the
+> user is typing, inside another application. Write plain prose with no
+> markdown: no asterisks, underscores, backticks, heading marks, bullet or
+> numbered-list markers, tables, or link syntax. Use ordinary sentences and
+> paragraphs. If several items must be listed, put each on its own line with no
+> marker.
+
+The suffix reaches every route. The cloud route forwards the client-built
+system prompt on every step of the tool loop (`processTextStreamingCloud` →
+`streamFromIPC` with `systemPrompt`), and the BYOK, LAN and local routes take
+it through `processTextStreamingAI`. No server change is needed.
+
+### 2. Strip before pasting, as the floor
+
+A new pure helper, `markdownToPlainText(text)` in
+`src/helpers/markdownToPlainText.ts`. It preserves every line break. That is
+the whole reason it is a new helper: the existing `stripMarkdownPreview` in
+`src/components/CommandSearch.tsx` collapses all newlines into one space
+because it feeds one-line search previews, and it must not be reused or
+"generalised" for this.
+
+Rules, chosen so that nothing a human would type in plain text is ever
+altered:
+
+| Markdown | Becomes |
+| --------------------------------------------------- | ------------------------------------------------------------------------------- |
+| ` ```lang ` fences | Fence lines removed, the code inside kept verbatim |
+| `` `code` `` | `code` |
+| `# Heading` … `###### Heading` | `Heading` |
+| `**bold**`, `__bold__` | `bold` |
+| `*em*`, `_em_` (paired, hugging non-space) | `em` |
+| `~~struck~~` | `struck` |
+| `[text](url)` | `text (url)`, or just `url` when text equals url |
+| `![alt](url)` | `alt` |
+| `* item`, `+ item` | `- item` |
+| `- item`, `1. item` | unchanged — humans type these in plain text |
+| `> quoted` | `quoted` |
+| `---`, `***`, `___` on a line by itself | line removed |
+| `\| a \| b \|` rows | outer pipes dropped, cells joined by a tab; the `\|---\|` alignment row removed |
+| `\*`, `\_`, `` \` `` and the other markdown escapes | the escaped character |
+
+Explicitly not altered: `2 * 3 * 4` (spaces around the star), `snake_case_names`
+(underscore inside a word), a lone `*` or `_`, an escaped marker such as `\*`,
+and `>` anywhere but line start.
+
+Where it is applied: inside `deliverAssistantResponse`, **only when
+`delivery.mode === "paste"` and `delivery.plainText` is true**, and to both the
+paste and its clipboard fallback (the answer was written for the caret; if the
+paste is refused and the text lands on the clipboard, the user is about to
+paste it into the same place by hand). A paste delivery with `plainText: false`
+(a markdown-friendly target) and a `mode: "clipboard"` delivery both stay
+verbatim: the clipboard-only answer is shown in the panel as rendered markdown,
+and copying it manually already yields raw markdown, so the two copy paths stay
+consistent.
+
+### 3. The allowlist
+
+`src/helpers/markdownTargets.js` (CommonJS, main process, no Electron
+imports so it tests in plain Node) exports the list, the vetoes, and
+`isMarkdownTargetSignature(signature)`. The list is data, grouped by why
+markdown is right there:
+
+1. **Markdown-native note editors** — the file _is_ markdown.
+2. **Apps that convert pasted markdown into formatting** — vendor-documented.
+3. **Chat composers that are standard markdown** — Discord, Zulip, Mattermost,
+ Element, Rocket.Chat. Not Slack, Teams, WhatsApp or Telegram, whose dialects
+ turn `**bold**` into stray asterisks and have no headings (Appendix B).
+4. **Work tools whose long-text fields convert pasted markdown** — Linear,
+ Todoist, TickTick, Trello. Their short title fields are plain text, but an
+ agent answer lands in a description or comment in practice.
+5. **AI prompt boxes** — a language model reads markdown happily, and a
+ stripped table or code fence would make the prompt worse.
+6. **Code editors and IDEs** — nothing renders formatting there, a developer's
+ backticks and fences are deliberate, and the AI chat panels inside Cursor,
+ VS Code and the JetBrains family are prompt boxes. General-purpose plain-text
+ editors used for prose (TextEdit, Notepad) are **not** in this group:
+ TextEdit is the reproduction case for this whole defect.
+
+Inclusion rule: an app is listed only when its markdown-on-paste behaviour is
+documented by the vendor or is the app's defining property (Appendix A carries
+the evidence per app). An **unverified identity string is acceptable** because
+a wrong name merely fails to match and falls back to plain text; a
+**generic token is not**, because it could match an unrelated app and paste
+markdown into a plain document. That is why `riot` (Element's Flatpak id) is
+absent, since it would match the Riot Games launcher, and why `remarkable`
+(a small Linux editor) is absent, since it would match the reMarkable tablet
+app.
+
+Apps whose behaviour is mixed, undocumented or contested go to Appendix C and
+are added only after a hand test.
+
+### 4. Conversation history and the panel copy
+
+Decided, not discovered:
+
+- **History stores what the model wrote.** With the suffix, a caret-targeted
+ turn is stored as prose. That is correct: the stored turn is the answer the
+ user received. For a markdown-friendly target the stored turn is markdown,
+ also what the user received.
+- **The strip never touches history.** It is a delivery transform applied to
+ the bytes handed to the paste, not to the message. If the model drifts and
+ emits a stray `**`, the panel's conversation view still shows the rendered
+ version and the pasted text shows the clean one.
+- **The panel's Copy button is unchanged.** It copies the stored content.
+
+### 5. Log the refusal
+
+`SelectionManager.pasteAtCapturedTarget` in `src/helpers/selectionManager.js`
+gets a single `debugLogger.info` at every decline, scope `clipboard`, carrying
+enough to diagnose without a trace through four files:
+
+```
+Assistant response paste declined { code, sessionFound, sessionKind, probeStatus, probeCode, platform }
+```
+
+where `code` is one of the four existing refusal codes (`invalid_replacement`,
+`session_expired`, `target_changed`, `paste_failed`), and `probeStatus` /
+`probeCode` are the editable-probe verdict that produced `target_changed`
+(`target_unavailable`, `accessibility_unavailable`, `selection_unavailable`,
+`unsupported_platform`, …). A matching `debug`-level line records a successful
+paste with the target kind and the session's `acceptsMarkdown` verdict, so a
+"why did this paste markdown" question is answered by the log too. The
+existing `warn` on a thrown paste error stays.
+
+Nothing about the return values changes; the renderer keeps receiving the same
+`{ success, code }`.
+
+## What this does not do
+
+- **Rich text.** Pasting into Notes, Word or Mail, raw markdown is wrong but so
+ is flattened text, because those targets accept real formatting. Doing that
+ right means writing rich text (RTF or HTML) to the clipboard alongside plain
+ text and letting the target choose. Separate, larger work.
+- **Web apps in a browser.** The identity available today is the browser
+ (`Google Chrome`, `Arc`, `Safari`), never the site, so ChatGPT, Claude,
+ Notion, GitHub or Linear in a tab get plain text like any other browser
+ target — and so, correctly, do Gmail and Google Docs. Telling them apart
+ needs the focused window's title (the page title, readable through the
+ accessibility API on macOS and `GetWindowText` on Windows) matched against a
+ site list. That is the natural follow-up once PR #1952 makes browser targets
+ reachable at all; it is not in this change. Every AI tool in the list ships a
+ desktop app, which is why the desktop allowlist already covers the most
+ common case Josh raised.
+- **PR #1952.** Agent paste never succeeds in Chromium and Electron targets
+ (VS Code, Slack, Arc, Obsidian) for the unrelated reason that PR addresses.
+ That PR is someone else's open work, conflicts with main, and is not touched.
+ Note the consequence: today this defect is visible only in native macOS apps;
+ the moment #1952 lands the allowlist becomes load-bearing, because most of
+ the markdown-friendly apps are Electron. On macOS today the allowlist can be
+ exercised only through native apps such as the ChatGPT and Gemini desktop
+ apps, Bear and iA Writer.
+- **Localising the suffix.** The chat-agent prompt is English-only today; the
+ suffix follows it.
+- **Renderer-side logging.** `deliverAssistantResponse` still swallows the
+ refusal code. The main-process debug log is the single log file, so that is
+ where the line goes.
+- **A user setting.** "Paste answers as plain text / as written" would let a
+ user override the list. Not now: the list should earn its keep first, and a
+ setting is where a wrong default hides.
+
+## Testing
+
+All under the repo's `node --test` runner (`npm test`, Node 24).
+
+- `test/helpers/markdownToPlainText.test.js`: one case per rule above, plus the
+ "must not alter" cases, plus a two-paragraph answer that proves paragraphs
+ survive (the trap the search-preview helper would fail).
+- `test/helpers/markdownTargets.test.js`: every platform's identity shape for a
+ listed app matches; plain-text apps, the excluded chat dialects, `Xcode`, the
+ vetoes and browsers never match; every entry is lowercase and at least three
+ characters.
+- `test/helpers/selectionManager.test.js`: a caret in a listed macOS app yields
+ `acceptsMarkdown: true` on the capture result and the session; a caret in
+ TextEdit yields `false`; an unreadable pid yields `false`; Windows and Linux
+ targets are judged by exe name and window class; each of the four paste
+ refusals emits the info line with its code; a successful paste emits the
+ debug line with the verdict.
+- `test/helpers/audioManagerAssistantDirective.test.js`: the verdict rides
+ next to the session id into `pendingAssistantConversation`, and is absent
+ when there is no caret delivery.
+- `test/helpers/assistantResponseDelivery.test.js`: `createAssistantResponseDelivery`
+ sets `plainText` from the verdict; a plain-text paste and its clipboard
+ fallback receive the stripped text; a markdown-friendly paste and a
+ `clipboard` delivery receive the original text.
+- `test/helpers/agentPlainTextSuffix.test.js`: `appendPlainTextResponseSuffix`
+ appends the constant once; the base `getAgentSystemPrompt` output does not
+ contain it (so panel answers are unaffected).
+- `test/helpers/retiredPrompts.test.js`: unchanged and still green, which is
+ the proof the hash protocol was not triggered.
+- Manual, on a dev build (`openwhispr-dev-build` skill), macOS: ask a question
+ that invites a list while the caret is in TextEdit; confirm prose with no
+ markers lands and the log shows `acceptsMarkdown: false`. Repeat with the
+ caret in the ChatGPT desktop app's prompt box (a native app, so paste works
+ today); confirm markdown lands intact and the log shows `acceptsMarkdown:
+true`. Then dismiss the target before the answer arrives and confirm the
+ `target_changed` line appears with its probe code.
+
+## Verification of the premises
+
+Checked against `origin/main` at `a2c76ef9` on 2026-09-10 and 2026-09-11:
+
+- `deliverAssistantResponse` passes `content` untouched to
+ `pasteAtCapturedTarget` (`src/helpers/assistantResponseDelivery.ts`).
+- `DEFAULT_CHAT_AGENT_PROMPT` is three sentences with no format instruction
+ (`src/config/prompts/registry.ts`).
+- `AssistantPanel.tsx` line 209 passes `suppressResponseContent:
+targetsCapturedInput`; content still reaches `persistence.saveAssistantMessage`.
+- `pasteAtCapturedTarget` returns four refusal codes and logs only the thrown
+ case (`src/helpers/selectionManager.js` lines 257–291).
+- The cloud route forwards the client `systemPrompt` on every tool-loop step
+ (`src/services/ReasoningService.ts` around line 1115).
+- `stripMarkdownPreview` collapses `\n+` to a space
+ (`src/components/CommandSearch.tsx` line 64).
+- Target identity per platform: macOS `_isTerminalPid` resolves
+ `"<bundle> <executable>"` from `ps -o comm=` (`selectionManager.js` 516–529);
+ the macOS copy helper prints the app's `localizedName`
+ (`resources/macos-fast-paste.swift` line 32); the Windows helper prints
+ `WINDOW_CLASS` and `EXE_NAME` on detect (`resources/windows-fast-paste.c`
+ 295–297); Linux targets carry `windowClass` (`selectionManager.js` 577–603).
+ No helper reads a window title today.
+- The caret session id travels `captureSelectedText` → `audioManager`
+ (`deliverySessionId`, lines 2666–2679) → `useAudioRecording.js` 504–530 →
+ `createAssistantResponseDelivery`.
+- Installed on Josh's Mac and inspected for `.app` name / executable:
+ Obsidian/Obsidian, Notion/Notion, Slack/Slack, Discord/Discord, Visual
+ Studio Code/Code, ChatGPT/ChatGPT, Claude/Claude, Linear/Linear, Microsoft
+ Teams/MSTeams, WhatsApp/WhatsApp, Gemini/Gemini, Ollama/Ollama,
+ Antigravity/Antigravity.
+
+## Appendix A — markdown-friendly targets (the allowlist, with evidence)
+
+Research on 2026-09-11 by three parallel agents (note editors; chat and work
+tools; AI tools and IDEs), cross-checked against Homebrew cask manifests for
+`.app` names, Flathub and upstream `.desktop` files for Linux WM_CLASS, and
+the apps installed on Josh's Mac for executables. "unverified" means the
+identity string follows the vendor's naming convention but no manifest or
+binary was inspected; per the inclusion rule that is acceptable because a miss
+falls back to plain text. Tokens are what `markdownTargets.js` carries.
+
+### A1. Markdown-native note editors
+
+| App | Platforms | Evidence | macOS `.app` / executable | Windows exe | Linux WM_CLASS | Tokens |
+| -------------------- | --------- | -------------------------------------------------------- | --------------------------------------- | ---------------------------- | ------------------------------------------------------------------- | ------------------------------------ |
+| Obsidian | m/w/l | edits `.md` on disk | Obsidian / Obsidian (inspected) | Obsidian.exe | obsidian; md.obsidian.Obsidian (Flatpak) | `obsidian` |
+| Typora | m/w/l | support.typora.io/Copy-and-Paste | Typora / Typora (cask) | Typora.exe | typora (Flathub); io.typora.Typora (Flatpak) | `typora` |
+| Logseq | m/w/l | markdownguide.org/tools/logseq | Logseq / Logseq (cask) | Logseq.exe | Logseq (Flathub); com.logseq.Logseq (Flatpak) | `logseq` |
+| Joplin | m/w/l | joplinapp.org/help/apps/rich_text_editor (default is md) | Joplin / Joplin (cask) | Joplin.exe | joplin (electron-builder); net.cozic.joplin_desktop (Flatpak) | `joplin` |
+| Zettlr | m/w/l | docs.zettlr.com/en/editor | Zettlr / Zettlr (cask) | Zettlr.exe (unverified) | zettlr; com.zettlr.Zettlr (Flatpak) | `zettlr` |
+| iA Writer | m | ia.net/writer/how-to/format-text | iA Writer (MAS, unverified) | — | — | `ia writer` |
+| Ulysses | m | help.ulysses.app smart copy and paste | Ulysses (MAS, unverified) | — | — | `ulysses` |
+| Simplenote | m/w/l | markdownguide.org/tools/simplenote (editor shows source) | Simplenote (cask) | Simplenote.exe (unverified) | simplenote (unverified); com.simplenote.Simplenote (Flatpak) | `simplenote` |
+| Inkdrop | m/w/l | forum.inkdrop.app thread 4956 | Inkdrop (cask) | Inkdrop.exe | inkdrop (unverified) | `inkdrop` |
+| MarkText | m/w/l | marktext.me/docs (cask deprecated 2026-09, unsigned) | MarkText (cask) | MarkText.exe (unverified) | marktext (electron-builder); com.github.marktext.marktext (Flatpak) | `marktext` |
+| NotePlan | m | help.noteplan.co/article/45 | NotePlan (MAS, unverified) | — | — | `noteplan` |
+| Drafts | m | docs.getdrafts.com/docs/settings/markdown | Drafts (MAS, unverified) | — | — | `drafts` |
+| MacDown | m | macdown.uranusjr.com/features | MacDown / MacDown (cask) | — | — | `macdown` |
+| MarkEdit | m | github.com/MarkEdit-app/MarkEdit | MarkEdit / MarkEdit (cask) | — | — | `markedit` |
+| Nota | m | nota.md: "no transformations on copy or paste" | Nota (cask) | — | — | `nota` |
+| Byword | m | bywordapp.com | Byword (MAS, unverified) | — | — | `byword` |
+| FSNotes | m | fsnot.es | FSNotes (cask) | — | — | `fsnotes` |
+| The Archive | m | zettelkasten.de/the-archive (plain markdown) | The Archive (cask) | — | — | `the archive` |
+| QOwnNotes | m/w/l | github.com/pbek/QOwnNotes (Qt plain text) | QOwnNotes / QOwnNotes (cask) | QOwnNotes.exe (unverified) | qownnotes (unverified); org.qownnotes.QOwnNotes (Flatpak) | `qownnotes` |
+| Boost Note / Notable | m/w/l | boostnote.io, notable.app (source editors) | Boost Note (cask); Notable (unverified) | unverified | unverified | `boost note`, `boostnote`, `notable` |
+| Supernotes | m/w/l | help.supernotes.app | Supernotes (cask) | unverified | unverified | `supernotes` |
+| Heynote | m/w/l | github.com/heyman/heynote | Heynote / Heynote (cask) | Heynote.exe (unverified) | heynote (unverified) | `heynote` |
+| Apostrophe | l | apps.gnome.org/Apostrophe | — | — | org.gnome.gitlab.somas.Apostrophe (Flatpak) | `apostrophe` |
+| Ghostwriter (KDE) | w/l | github.com/KDE/ghostwriter | — | ghostwriter.exe (unverified) | ghostwriter (unverified); org.kde.ghostwriter (Flatpak) | `ghostwriter` |
+| Abricotine | m/w/l | github.com/brrd/abricotine (dormant) | unverified | unverified | abricotine (desktopName) | `abricotine` |
+
+### A2. Apps that convert pasted markdown into formatting
+
+| App | Platforms | Evidence | macOS `.app` / executable | Windows exe | Linux WM_CLASS | Tokens |
+| ------------- | --------- | --------------------------------------------------------------------- | ---------------------------- | -------------------------- | ------------------------------ | --------------------------------------------------- |
+| Notion | m/w | markdownguide.org/tools/notion (converts on paste) | Notion / Notion (inspected) | Notion.exe | — | `notion` (vetoes: `notion calendar`, `notion mail`) |
+| Evernote | m/w | help.evernote.com 39988720040211 (plain-text markdown converts on ⌘V) | Evernote (cask) | Evernote.exe (unverified) | unverified | `evernote` |
+| Notesnook | m/w/l | blog.notesnook.com v3.0.27 "pasting markdown directly" | Notesnook / Notesnook (cask) | Notesnook.exe (unverified) | start-notesnook (Flathub) | `notesnook` |
+| WorkFlowy | m/w | blog.workflowy.com/proper-markdown-pasting | WorkFlowy (cask) | unverified | — | `workflowy` |
+| Bear | m | bear.app/faq/how-to-use-markdown-in-bear | Bear (MAS, unverified) | — | — | `bear` |
+| Craft | m/w | support.craft.do formatting | Craft (cask) | Craft.exe (unverified) | — | `craft` |
+| RemNote | m/w/l | help.remnote.com 6030579 | RemNote (cask) | unverified | unverified | `remnote` |
+| Anytype | m/w/l | community.anytype.io/t/1314 (converts, gaps on checkboxes) | Anytype (cask) | Anytype.exe (unverified) | io.anytype.anytype (Flathub) | `anytype` |
+| SiYuan | m/w/l | github.com/siyuan-note/siyuan (Protyle) | SiYuan / SiYuan (cask) | unverified | SiYuan (Flathub) | `siyuan` |
+| Capacities | m/w | docs.capacities.io/reference/import | Capacities (cask) | unverified | unverified | `capacities` |
+| Reflect | m/w | curtismchale.ca in-depth-look-at-reflect | Reflect (cask) | unverified | — | `reflect` |
+| Heptabase | m/w | wiki.heptabase.com | Heptabase (cask) | unverified | unverified | `heptabase` |
+| Roam Research | m/w/l | outlinersoftware.com desktop announcement (md per block) | Roam Research (cask) | unverified | unverified | `roam` |
+| AppFlowy | m/w/l | appflowy.io (Notion-like block editor, converts on paste) | AppFlowy (cask) | AppFlowy.exe (winget) | io.appflowy.AppFlowy (Flathub) | `appflowy` |
+
+### A3. Chat composers that are standard markdown
+
+| App | Platforms | Evidence | macOS `.app` / executable | Windows exe | Linux WM_CLASS | Tokens |
+| ----------- | --------- | ----------------------------------------------------------- | ----------------------------- | ---------------------------- | -------------------------------- | --------------------------- |
+| Discord | m/w/l | Discord markdown guide (headings, lists, fences; no tables) | Discord / Discord (inspected) | Discord.exe | discord | `discord` |
+| Zulip | m/w/l | zulip.com/help/format-your-message-using-markdown | Zulip (unverified) | Zulip.exe (unverified) | org.zulip.Zulip (Flatpak) | `zulip` |
+| Mattermost | m/w/l | docs.mattermost.com format-messages | Mattermost (unverified) | Mattermost.exe (unverified) | com.mattermost.Desktop (Flatpak) | `mattermost` |
+| Element | m/w/l | matrix-react-sdk PR 8358 (markdown parsed at send) | Element (unverified) | Element.exe (unverified) | Element; im.riot.Riot (Flatpak) | `element` (not `riot`) |
+| Rocket.Chat | m/w/l | docs.rocket.chat/docs/messages | Rocket.Chat (unverified) | Rocket.Chat.exe (unverified) | chat.rocket.RocketChat (Flatpak) | `rocket.chat`, `rocketchat` |
+
+### A4. Work tools whose long-text fields convert pasted markdown
+
+| App | Platforms | Evidence | macOS `.app` / executable | Windows exe | Linux WM_CLASS | Tokens |
+| -------- | --------- | ------------------------------------------------------------------- | --------------------------- | ------------------------- | ------------------------------- | ---------- |
+| Linear | m/w | linear.app/docs/editor (pasted markdown becomes rich text) | Linear / Linear (inspected) | Linear.exe (unverified) | — | `linear` |
+| Todoist | m/w/l | todoist.com/help format-text (descriptions, comments; titles plain) | Todoist (unverified) | Todoist.exe (unverified) | com.todoist.Todoist (Flatpak) | `todoist` |
+| TickTick | m/w/l | blog.ticktick.com markdown quick start | TickTick (unverified) | TickTick.exe (unverified) | com.ticktick.TickTick (Flatpak) | `ticktick` |
+| Trello | m/w | support.atlassian.com how-to-format-your-text-in-trello | Trello (unverified) | trello.exe | — | `trello` |
+
+### A5. AI prompt boxes
+
+| App | Platforms | Evidence | macOS `.app` / executable | Windows exe | Linux WM_CLASS | Tokens |
+| ------------------ | --------- | ----------------------------------------- | ------------------------------ | ------------------------------------- | ---------------------- | ----------------------------------- |
+| ChatGPT | m/w | model reads markdown | ChatGPT / ChatGPT (inspected) | ChatGPT.exe | — | `chatgpt` |
+| Claude | m/w | model reads markdown | Claude / Claude (inspected) | Claude.exe (unverified) | — | `claude` |
+| Google Gemini | m | native app since 2026-04 | Gemini / Gemini (inspected) | — | — | `gemini` |
+| Perplexity | m | perplexity cask | Perplexity (cask) | — | — | `perplexity` |
+| Microsoft Copilot | m/w | consumer app; M365 Copilot on Windows | Microsoft Copilot (unverified) | Copilot.exe; M365Copilot.exe | — | `copilot`, `m365copilot` |
+| GitHub Copilot app | m/w/l | github.com/features/ai (standalone, 2026) | GitHub Copilot (unverified) | GitHub Copilot.exe (unverified) | unverified | `copilot` |
+| Poe | m/w | poe.com/pages/get-poe | Poe (cask) | Poe.exe | — | `poe` |
+| LM Studio | m/w/l | lm-studio cask | LM Studio (cask) | LM Studio.exe | lm-studio (unverified) | `lm studio`, `lm-studio` |
+| Ollama app | m/w | docs.ollama.com/windows | Ollama / Ollama (inspected) | ollama app.exe (unverified) | — | `ollama` |
+| Jan | m/w/l | github.com/janhq/jan | Jan (unverified) | Jan.exe (unverified) | Jan (unverified) | `jan` |
+| Msty | m/w/l | msty cask | Msty (cask) | Msty.exe (unverified) | Msty (unverified) | `msty` |
+| Chatbox | m/w/l | chatbox cask | Chatbox (cask) | Chatbox.exe (unverified) | Chatbox (unverified) | `chatbox` |
+| BoltAI | m | boltai.com | BoltAI (cask) | — | — | `boltai` |
+| Cherry Studio | m/w/l | cherry-studio cask | Cherry Studio (cask) | Cherry Studio.exe | cherry-studio | `cherry studio`, `cherry-studio` |
+| AnythingLLM | m/w/l | Mintplex-Labs releases | AnythingLLM (cask) | AnythingLLMDesktop.exe (unverified) | unverified | `anythingllm`, `anythingllmdesktop` |
+| Witsy | m/w/l | witsy cask | Witsy (cask) | Witsy.exe (unverified) | unverified | `witsy` |
+| GPT4All | m/w/l | nomic-ai/gpt4all | GPT4All (unverified) | gpt4all.exe or chat.exe (conflicting) | unverified | `gpt4all` |
+
+### A6. Code editors and IDEs
+
+| App | Platforms | macOS `.app` / executable | Windows exe | Linux WM_CLASS | Tokens |
+| ------------------------------------------------------------ | --------- | ------------------------------------------------------------------------- | ------------------------------------------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Visual Studio Code (+Insiders) | m/w/l | Visual Studio Code / Code (inspected); Insiders unverified | Code.exe; Code - Insiders.exe | Code; code-insiders | `visual studio code`, `code` |
+| VSCodium | m/w/l | VSCodium / Electron (unverified) | VSCodium.exe (unverified) | codium; VSCodium | `vscodium`, `codium` |
+| Cursor | m/w/l | Cursor / Cursor | Cursor.exe | Cursor (xprop-confirmed) | `cursor` |
+| Windsurf → Devin Desktop | m/w/l | Windsurf / Electron; Devin (unverified, rebrand 2026-06) | Windsurf.exe; Devin.exe | Windsurf; Devin | `windsurf`, `devin` |
+| Zed | m/w/l | Zed (cask) | zed.exe (unverified) | dev.zed.Zed | `zed` |
+| Trae, Kiro, Void, Positron | m/w/l | Trae, Kiro, Void, Positron (.app; exec unverified) | Trae.exe, Kiro.exe, Void.exe, Positron.exe (unverified) | trae, kiro, void, co.posit.positron | `trae`, `kiro`, `void`, `positron` |
+| Antigravity | m/w/l | Antigravity / Antigravity and Antigravity IDE / Electron (both inspected) | Antigravity-x64.exe | Antigravity (unverified) | `antigravity` |
+| PearAI, Aide | m/w/l | PearAI, Aide (stale projects) | PearAI.exe, Aide.exe (unverified) | pearai, aide (unverified) | `pearai`, `aide` |
+| IntelliJ IDEA (Ultimate, CE) | m/w/l | IntelliJ IDEA / idea; IntelliJ IDEA CE / idea | idea64.exe | jetbrains-idea | `intellij`, `idea`, `idea64`, `jetbrains` |
+| PyCharm (+CE) | m/w/l | PyCharm / pycharm | pycharm64.exe | jetbrains-pycharm(-ce) | `pycharm`, `pycharm64` |
+| WebStorm, PhpStorm, Rider, GoLand, CLion, RubyMine, DataGrip | m/w/l | `<Name>.app` / lowercase name | `<name>64.exe` | jetbrains-`<name>` | `webstorm`, `webstorm64`, `phpstorm`, `phpstorm64`, `rider`, `rider64`, `goland`, `goland64`, `clion`, `clion64`, `rubymine`, `rubymine64`, `datagrip`, `datagrip64` |
+| Android Studio | m/w/l | Android Studio / studio | studio64.exe | jetbrains-studio (unverified) | `android studio`, `studio64` |
+| Sublime Text | m/w/l | Sublime Text / sublime_text | sublime_text.exe | subl; Sublime_text | `sublime`, `sublime_text`, `subl` |
+| Nova, BBEdit, CotEditor | m | Nova, BBEdit, CotEditor (casks; exec unverified) | — | — | `nova`, `bbedit`, `coteditor` |
+| Notepad++ | w | — | notepad++.exe (winget) | — | `notepad++` |
+| Kate (KDE) | m/w/l | kate / kate (cask) | kate.exe (unverified) | org.kde.kate; kate | `kate` |
+| Emacs (GUI) | m/w/l | Emacs / Emacs (cask) | emacs.exe, runemacs.exe | Emacs | `emacs`, `runemacs` |
+| MacVim / gVim / Neovide | m/w/l | MacVim / MacVim; Neovide / neovide | gvim.exe; neovide.exe | gvim; neovide | `macvim`, `gvim`, `neovide` |
+| Visual Studio | w | — | devenv.exe | — | `devenv` |
+
+## Appendix B — deliberately excluded, and why
+
+| App | Reason |
+| -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Apple Notes, Word, TextEdit, Pages, Mail | Show literal `**` and `#`. TextEdit is the reproduction case. |
+| Microsoft OneNote | No markdown parsing in any version (unmarkdown.com/blog/onenote-markdown). |
+| Slack | Own dialect: `*bold*`, no headings; the composer's conversion is a typing rule ("add an asterisk and press the spacebar") that does not fire on paste (slack.com/help 202288908, 360039953113). **Verified by a paste on Josh's Mac, 2026-09-13:** every marker stayed literal, including `- dash item` and `* star item`; only the URL was auto-linked and unfurled. |
+| Microsoft Teams | "Markdown-style" dialect with single-asterisk bold, rendered as a live preview while typing; vendor and community tests report paste is not parsed (support.microsoft.com use-markdown-formatting). **Verified by a paste on Josh's Mac, 2026-09-13:** identical to Slack — every marker stayed literal, including `- dash item` and `* star item`; only the URL was auto-linked. |
+| WhatsApp Desktop | Own dialect (`*bold*`, `_italic_`, bullets since 2024); `**bold**` and `#` are garbage. |
+| Telegram Desktop | Converts inline emphasis only; `#` headings and list markers stay literal. |
+| Signal | No markdown by design. |
+| Google Chat | Own dialect and PWA-only (no distinct process). |
+| Asana, ClickUp, Basecamp, Monday, Things 3 | Markdown shortcuts fire while typing, not on paste (Asana, ClickUp — ClickUp turns pasted markdown into a code block); Trix rich text (Basecamp); rich or plain text only (Monday, Things). |
+| UpNote | Plain ⌘V does not convert; conversion needs the separate "Paste from Markdown" command (help.getupnote.com). |
+| Amplenote | Vendor forum: "When you take markdown text and paste it into Amplenote, it just stays plain text." |
+| Trilium / TriliumNext | Default note type is CKEditor rich text; raw markdown is a separate opt-in note type. |
+| Zim Wiki, Cherrytree | Own wiki dialect (Zim); default node is rich text (Cherrytree). |
+| Xcode | An IDE for Swift and C where literal markdown is garbage outside a `.md` file; explicitly vetoed so `code` cannot match it. |
+| Notepad, TextEdit | General-purpose plain-text editors used for prose by non-developers. |
+| Raycast, Alfred | The main surface is a launcher search field, not a prose or prompt box. |
+| Marked 2, Panda, Google Keep, Coda, SilverBullet, Open WebUI, TypingMind, Jira, Confluence, GitLab | Previewer with no editable pane; browser prototype; web or PWA only with no process identity of their own (browser follow-up). |
+| Cline, Roo Code, Continue, Foam, Dendron | Live inside VS Code and carry its identity; VS Code is listed. |
+| Grok, Le Chat (Mistral) | No official desktop app as of 2026-09; only third-party wrappers with unstable names. |
+| Quiver, Haroopad, Turtl, Atom, JetBrains Fleet, Skype, Height, Sourcegraph Cody app, Windsurf legacy name kept | Abandoned or discontinued (Fleet 2025-12, Skype 2025-05, Height 2025-09). Windsurf's old name is kept alongside Devin. |
+| reMarkable-named editor | The Linux "Remarkable" markdown editor is omitted because the token would match the reMarkable tablet's desktop app. |
+
+## Appendix C — hand-test before adding
+
+Behaviour mixed, undocumented or contested. Each needs one real paste on an
+installed copy before it goes on the list.
+
+- **Tana** (`Tana Outliner.app`): "Tana Paste" is a markdown-like dialect;
+ vanilla markdown converts only partially.
+- **AFFiNE** (`AFFiNE.app`): converts, but open bugs collapse structured
+ documents on paste (AFFiNE#12313).
+- **Standard Notes** (`Standard Notes.app`, Flatpak `org.standardnotes.standardnotes`):
+ behaviour depends on the note type (Plain is raw, Super is rich text); two
+ research passes disagreed on the default.
+- **Agenda** (`Agenda.app`): markdown shortcuts documented for typing only.
+- **Mem, Slite, FuseBase/Nimbus, Saga, Twos**: typing shortcuts documented,
+ paste behaviour not.
+- **Zed on Windows, Claude for Windows**: identities changed recently (Zed
+ Windows preview; Claude moved to MSIX in 2026-02); confirm the exe names.
+- **Any MAS-only app** (Bear, iA Writer, Ulysses, NotePlan, Drafts, Byword):
+ `.app` names follow convention and are unverified; a wrong name only means
+ plain text, but a check on an installed copy would close the gap.
diff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.ts
index 4ed77a274..eb1b91e3b 100644
--- a/src/components/chat/useChatStreaming.ts
+++ b/src/components/chat/useChatStreaming.ts
@@ -14,6 +14,7 @@ import {
import { usePolicyStore } from "../../stores/policyStore";
import {
appendDictionarySuffix,
+ appendPlainTextResponseSuffix,
appendScreenContextSuffix,
getAgentSystemPrompt,
} from "../../config/prompts";
@@ -94,6 +95,8 @@ export interface SendToAIOptions {
selectedContext?: AgentSelectionContext;
/** Keeps a caret-destined voice response in the compact pill while it streams. */
suppressResponseContent?: boolean;
+ /** Asks the model for plain prose because the answer will be pasted into a plain-text app. */
+ plainTextResponse?: boolean;
/** Per-request completion hook used to deliver a finished voice response. */
onComplete?: (result: {
assistantId: string;
@@ -363,6 +366,9 @@ export function useChatStreaming({
// for cloud context once openwhispr-api#157 vision-routes that field.
systemPrompt = appendScreenContextSuffix(systemPrompt, settings.uiLanguage);
}
+ if (options?.plainTextResponse) {
+ systemPrompt = appendPlainTextResponseSuffix(systemPrompt);
+ }
if (attachment) {
transformLastUserMessage(history, (message) => ({
role: "user",
diff --git a/src/components/dictation/AssistantPanel.tsx b/src/components/dictation/AssistantPanel.tsx
index 50dbe0175..d31c1521f 100644
--- a/src/components/dictation/AssistantPanel.tsx
+++ b/src/components/dictation/AssistantPanel.tsx
@@ -197,6 +197,8 @@ export function AssistantPanel({
const commandId = pendingCommand.id;
const delivery = pendingCommand.delivery;
const targetsCapturedInput = delivery?.mode === "paste";
+ // A caret in a markdown-friendly app still keeps the compact pill.
+ const plainTextResponse = delivery?.mode === "paste" && delivery.plainText;
let responseDelivered = false;
if (pendingCommand.selectedContext) {
setSelectedContext(null);
@@ -206,6 +208,7 @@ export function AssistantPanel({
attachment: pendingCommand.attachment ?? undefined,
selectedContext: pendingCommand.selectedContext ?? undefined,
suppressResponseContent: targetsCapturedInput,
+ plainTextResponse,
onComplete: delivery
? async ({ content }) => {
const result = await deliverAssistantResponse(delivery, content);
diff --git a/src/config/prompts.ts b/src/config/prompts.ts
index c3b2bc07c..93882f13f 100644
--- a/src/config/prompts.ts
+++ b/src/config/prompts.ts
@@ -5,6 +5,7 @@ export {
getDefaultPromptText,
appendDictionarySuffix,
appendScreenContextSuffix,
+ appendPlainTextResponseSuffix,
wrapCleanupTranscript,
} from "./prompts/index";
export { PROMPT_KINDS, PROMPT_KIND_LIST, type PromptKind } from "./prompts/registry";
diff --git a/src/config/prompts/index.ts b/src/config/prompts/index.ts
index acf67d90e..7c2a3c8b3 100644
--- a/src/config/prompts/index.ts
+++ b/src/config/prompts/index.ts
@@ -2,7 +2,7 @@ import i18n, { normalizeUiLanguage } from "../../i18n";
import { useSettingsStore } from "../../stores/settingsStore";
import { en as enPrompts } from "../../locales/prompts";
import { getLanguageInstruction } from "../../utils/languageSupport";
-import { PROMPT_KINDS, type PromptKind } from "./registry";
+import { PROMPT_KINDS, PLAIN_TEXT_RESPONSE_SUFFIX, type PromptKind } from "./registry";
export { PROMPT_KINDS, PROMPT_KIND_LIST, type PromptKind } from "./registry";
@@ -58,6 +58,11 @@ export function appendDictionarySuffix(
return prompt + suffix + customDictionary.join(", ");
}
+// Append after every other suffix: trailing instructions are the ones models weight most.
+export function appendPlainTextResponseSuffix(prompt: string): string {
+ return prompt + PLAIN_TEXT_RESPONSE_SUFFIX;
+}
+
function applySubstitutions(template: string, opts: ResolvePromptOptions): string {
const name = opts.agentName?.trim() || "Assistant";
let prompt = template.replace(/\{\{agentName\}\}/g, name);
diff --git a/src/config/prompts/registry.ts b/src/config/prompts/registry.ts
index b95ea4690..ea9bbaff4 100644
--- a/src/config/prompts/registry.ts
+++ b/src/config/prompts/registry.ts
@@ -7,6 +7,14 @@ const DEFAULT_CHAT_AGENT_PROMPT =
"Keep answers brief unless the user asks for detail. " +
"You may be given a transcription of spoken input, so handle informal phrasing gracefully.";
+// Appended per request, not baked into the default: the panel renders markdown.
+export const PLAIN_TEXT_RESPONSE_SUFFIX =
+ "\n\nOUTPUT FORMAT: Your answer will be inserted as plain text exactly where the user is typing, " +
+ "inside another application. Write plain prose with no markdown: no asterisks, underscores, " +
+ "backticks, heading marks, bullet or numbered-list markers, tables, or link syntax. " +
+ "Use ordinary sentences and paragraphs. If several items must be listed, put each on its " +
+ "own line with no marker.";
+
export const PROMPT_KINDS = {
cleanup: {
i18nKey: "cleanupPrompt" as const,
diff --git a/src/helpers/assistantResponseDelivery.ts b/src/helpers/assistantResponseDelivery.ts
index a6b24f029..849da78bb 100644
--- a/src/helpers/assistantResponseDelivery.ts
+++ b/src/helpers/assistantResponseDelivery.ts
@@ -1,9 +1,13 @@
+import { markdownToPlainText } from "./markdownToPlainText";
+
export type AssistantResponseDelivery =
| {
mode: "paste";
sessionId: string;
restoreClipboard: boolean;
allowClipboardFallback: boolean;
+ /** Ask for prose and strip markdown before pasting. False for a markdown-friendly target. */
+ plainText: boolean;
}
| { mode: "clipboard" };
@@ -28,11 +32,13 @@ interface AssistantResponseDeliveryDependencies {
export function createAssistantResponseDelivery({
autoPasteEnabled,
deliverySessionId,
+ acceptsMarkdown,
restoreClipboard,
allowClipboardFallback,
}: {
autoPasteEnabled: boolean;
deliverySessionId?: string;
+ acceptsMarkdown?: boolean;
restoreClipboard: boolean;
allowClipboardFallback: boolean;
}): AssistantResponseDelivery | null {
@@ -44,6 +50,7 @@ export function createAssistantResponseDelivery({
sessionId: deliverySessionId,
restoreClipboard,
allowClipboardFallback,
+ plainText: !acceptsMarkdown,
};
}
@@ -74,15 +81,24 @@ export async function deliverAssistantResponse(
const clipboard = dependencies.clipboard ?? navigator.clipboard;
if (delivery.mode === "paste") {
+ // The strip also covers the clipboard fallback (the user pastes into the
+ // same field by hand); an answer it empties entirely is pasted raw.
+ const text = delivery.plainText ? markdownToPlainText(content) || content : content;
try {
- const result = await electronAPI?.pasteAtCapturedTarget?.(delivery.sessionId, content, {
+ const result = await electronAPI?.pasteAtCapturedTarget?.(delivery.sessionId, text, {
restoreClipboard: delivery.restoreClipboard,
allowClipboardFallback: delivery.allowClipboardFallback,
});
if (result?.success === true) return { pasted: true, copied: false };
} catch {}
+ return {
+ pasted: false,
+ copied: await copyAssistantResponse(text, electronAPI, clipboard),
+ };
}
+ // A clipboard-only delivery is shown in the panel as rendered markdown and
+ // its Copy button yields the raw markdown; keep the two copy paths equal.
return {
pasted: false,
copied: await copyAssistantResponse(content, electronAPI, clipboard),
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 5bb50841f..a154b5438 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -2696,7 +2696,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
// and previews stay truthful.
_bankAssistantDirective(transcript, config, options = {}) {
if (!this.isProcessing) return;
- const { selectedContext, deliverySessionId } = options || {};
+ const { selectedContext, deliverySessionId, deliveryAcceptsMarkdown } = options || {};
this.pendingAssistantConversation = {
transcript,
// resolveReasoningRoute mirrors an attached screenContext into
@@ -2705,7 +2705,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
// (the panel re-decides for its own request).
screenContext: config?.rawScreenContext ?? null,
...(selectedContext ? { selectedContext } : {}),
- ...(deliverySessionId ? { deliverySessionId } : {}),
+ ...(deliverySessionId ? { deliverySessionId, deliveryAcceptsMarkdown } : {}),
};
}
@@ -2731,7 +2731,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
text,
agentName,
config,
- { selectedContext, selectedText, deliverySessionId } = {}
+ { selectedContext, selectedText, deliverySessionId, deliveryAcceptsMarkdown } = {}
) {
this.assertAgentAllowedByPolicy();
const settings = getSettings();
@@ -2744,7 +2744,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
config?.snippets ?? settings.snippets
);
const transcript = selectedText === undefined ? command : `${command}\n\n"${selectedText}"`;
- this._bankAssistantDirective(transcript, config, { selectedContext, deliverySessionId });
+ this._bankAssistantDirective(transcript, config, {
+ selectedContext,
+ deliverySessionId,
+ deliveryAcceptsMarkdown,
+ });
return text;
}
@@ -2781,6 +2785,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
captureDisposition === "caret" && getSettings().autoPasteEnabled
? capture.sessionId
: undefined;
+ const deliveryAcceptsMarkdown = capture?.acceptsMarkdown === true;
if (!config?.selectionEditReachable) {
// No in-place editor: the panel never types, so only a readable
@@ -2791,6 +2796,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
? capture.text
: undefined,
deliverySessionId,
+ deliveryAcceptsMarkdown,
});
}
@@ -2808,7 +2814,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
if (captureDisposition === "standalone" || captureDisposition === "caret") {
- return this._bankPanelAgentCommand(text, agentName, config, { deliverySessionId });
+ return this._bankPanelAgentCommand(text, agentName, config, {
+ deliverySessionId,
+ deliveryAcceptsMarkdown,
+ });
}
if (capture?.status !== "selected") {
diff --git a/src/helpers/markdownTargets.js b/src/helpers/markdownTargets.js
new file mode 100644
index 000000000..1552379b9
--- /dev/null
+++ b/src/helpers/markdownTargets.js
@@ -0,0 +1,180 @@
+// Apps whose text surface wants markdown left alone: markdown-native editors,
+// apps that convert pasted markdown into formatting, chat tools whose composer
+// is standard markdown, AI prompt boxes (a model reads markdown happily) and
+// code editors / IDEs (nothing renders formatting there, and a developer's
+// backticks and fences are deliberate). Anything not listed gets plain text —
+// the safe default, because a wrong verdict here pastes literal asterisks
+// into someone's document.
+//
+// Matching is by whole token or phrase, never bare substring, so "code" does
+// not match "Xcode". Entries are lowercase and never a generic word another
+// app could carry: "riot" (Element's Flatpak id) would match the Riot Games
+// launcher and "remarkable" (a small Linux editor) the reMarkable tablet app,
+// so neither is here. The identity matched per platform:
+// macOS — the .app folder name + executable resolved from the pid
+// ("Visual Studio Code Code"), plus the copy helper's app name
+// Windows — the exe name ("Code.exe", "idea64.exe") + window class
+// Linux — the WM_CLASS ("code", "md.obsidian.obsidian", "jetbrains-idea")
+// Evidence per app, and the apps deliberately excluded:
+// docs/superpowers/specs/2026-09-10-agent-paste-plain-text-design.md, Appendix A–C.
+
+const MARKDOWN_TARGET_SIGNATURES = [
+ // Markdown-native note editors — the file is markdown.
+ "obsidian",
+ "typora",
+ "logseq",
+ "joplin",
+ "zettlr",
+ "ia writer",
+ "ulysses",
+ "simplenote",
+ "inkdrop",
+ "marktext",
+ "noteplan",
+ "drafts",
+ "macdown",
+ "markedit",
+ "nota",
+ "byword",
+ "fsnotes",
+ "the archive",
+ "qownnotes",
+ "boost note",
+ "boostnote",
+ "notable",
+ "supernotes",
+ "heynote",
+ "apostrophe",
+ "ghostwriter",
+ "abricotine",
+ // Apps that convert pasted markdown into formatting (vendor-documented).
+ "notion",
+ "evernote",
+ "notesnook",
+ "workflowy",
+ "bear",
+ "craft",
+ "remnote",
+ "anytype",
+ "siyuan",
+ "capacities",
+ "reflect",
+ "heptabase",
+ "roam",
+ "appflowy",
+ // Chat composers that are standard markdown (not Slack, Teams, WhatsApp or
+ // Telegram — their dialects turn **bold** into stray asterisks).
+ "discord",
+ "zulip",
+ "mattermost",
+ "element",
+ "rocket.chat",
+ "rocketchat",
+ // Work tools whose long-text fields convert pasted markdown.
+ "linear",
+ "todoist",
+ "ticktick",
+ "trello",
+ // AI prompt boxes — the model reads markdown.
+ "chatgpt",
+ "claude",
+ "gemini",
+ "perplexity",
+ "copilot",
+ "m365copilot",
+ "poe",
+ "lm studio",
+ "lm-studio",
+ "ollama",
+ "jan",
+ "msty",
+ "chatbox",
+ "boltai",
+ "cherry studio",
+ "cherry-studio",
+ "anythingllm",
+ "anythingllmdesktop",
+ "witsy",
+ "gpt4all",
+ // Code editors and IDEs — nothing renders formatting; the AI chat panels
+ // inside them are prompt boxes. Not general prose editors (TextEdit,
+ // Notepad, gedit): those are the plain-text case.
+ "visual studio code",
+ "code",
+ "vscodium",
+ "codium",
+ "cursor",
+ "windsurf",
+ "devin",
+ "zed",
+ "trae",
+ "kiro",
+ "antigravity",
+ "void",
+ "positron",
+ "pearai",
+ "aide",
+ "intellij",
+ "idea",
+ "idea64",
+ "pycharm",
+ "pycharm64",
+ "webstorm",
+ "webstorm64",
+ "phpstorm",
+ "phpstorm64",
+ "rider",
+ "rider64",
+ "goland",
+ "goland64",
+ "clion",
+ "clion64",
+ "rubymine",
+ "rubymine64",
+ "datagrip",
+ "datagrip64",
+ "android studio",
+ "studio64",
+ "jetbrains",
+ "sublime",
+ "sublime_text",
+ "subl",
+ "nova",
+ "bbedit",
+ "coteditor",
+ "kate",
+ "notepad++",
+ "emacs",
+ "runemacs",
+ "macvim",
+ "gvim",
+ "neovide",
+ "devenv",
+];
+
+// Checked first, as plain substrings. An app that carries a listed name but
+// is not a markdown surface — the veto wins.
+const MARKDOWN_TARGET_VETOES = ["notion calendar", "notion mail"];
+
+const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+// Whole-token / whole-phrase match: the entry must be bounded on both sides by
+// the start or end of the signature or by a character that is not a letter or
+// digit. Dots, hyphens, underscores and spaces all count as boundaries, which
+// is what makes "md.obsidian.obsidian", "jetbrains-idea" and "Code.exe" match
+// while "Xcode" does not.
+const TOKEN_PATTERNS = MARKDOWN_TARGET_SIGNATURES.map(
+ (entry) => new RegExp(`(?:^|[^a-z0-9])${escapeRegExp(entry)}(?:$|[^a-z0-9])`)
+);
+
+function isMarkdownTargetSignature(signature) {
+ if (!signature) return false;
+ const normalized = String(signature).toLowerCase();
+ if (MARKDOWN_TARGET_VETOES.some((veto) => normalized.includes(veto))) return false;
+ return TOKEN_PATTERNS.some((pattern) => pattern.test(normalized));
+}
+
+module.exports = {
+ MARKDOWN_TARGET_SIGNATURES,
+ isMarkdownTargetSignature,
+};
diff --git a/src/helpers/markdownToPlainText.ts b/src/helpers/markdownToPlainText.ts
new file mode 100644
index 000000000..18f9450dd
--- /dev/null
+++ b/src/helpers/markdownToPlainText.ts
@@ -0,0 +1,233 @@
+// Turns a model answer into text that is safe to paste into a plain-text
+// field. Every line break is preserved: paragraphs, blank lines and list
+// lines survive. This is deliberately NOT stripMarkdownPreview from
+// CommandSearch.tsx — that helper collapses newlines into spaces to feed
+// one-line search previews and would flatten a multi-paragraph answer.
+//
+// The rules only touch syntax a human would not type in plain text. A `- `
+// bullet, a `1.` number, `2 * 3`, snake_case, `#hashtag` and `x > y` are all
+// left exactly as written.
+//
+// The inline rules are applied per line, so emphasis that spans a line break
+// and setext (underlined) headings are out of scope: the prompt suffix that
+// asks the model for plain prose is the primary defence, and this helper is
+// the floor under a model that drifts back to markdown.
+
+const FENCE_LINE = /^\s*(`{3,}|~{3,})(.*)$/;
+const HORIZONTAL_RULE = /^\s*([-*_])(\s*\1){2,}\s*$/;
+const TABLE_ROW = /^\s*\|.*\|\s*$/;
+const TABLE_ALIGNMENT_CELL = /^:?-+:?$/;
+
+const WEB_URL = /(?:https?|ftp):\/\/[^\s<>"`]+/;
+// Spaces belong to a directory only when another path component follows;
+// otherwise the match would swallow the prose after an unquoted filename.
+const WINDOWS_PATH =
+ /(?:[a-z]:\\|\\\\[^\s\\<>:"|?*`]+\\)(?:[^\\\r\n<>:"|?*`]*\\(?=[^\s\\<>:"|?*`]))*[^\s<>:"|?*`]*/;
+const RELATIVE_WINDOWS_PATH =
+ /(?<![a-z0-9\\])(?:__[a-z0-9.-][a-z0-9_.-]*__|_[a-z0-9.-][a-z0-9_.-]*_|[a-z0-9.-][a-z0-9_.-]*)\\[^\s<>:"|`]+/;
+// Paired underscores in a relative directory are part of its name; any
+// surrounding emphasis must stay outside the protected path.
+const POSIX_PATH =
+ /(?<![a-z0-9/])(?:(?<!~)~\/|\.{1,2}\/|\/|__[a-z0-9.-][a-z0-9_.-]*__\/|_[a-z0-9.-][a-z0-9_.-]*_\/|[a-z0-9.-][a-z0-9_.-]*\/)[^\s<>"`]+/;
+const LITERAL_RESOURCE = new RegExp(
+ `${WEB_URL.source}|${WINDOWS_PATH.source}|${RELATIVE_WINDOWS_PATH.source}|${POSIX_PATH.source}`,
+ "gi"
+);
+
+function hasWindowsPathStructure(text: string): boolean {
+ // A lone prose escape (under\_score) is ambiguous. Require a path prefix,
+ // a separator that cannot be a Markdown escape, or a filename extension.
+ return (
+ /^(?:[a-z]:\\|\\\\|\.{1,2}\\)/i.test(text) ||
+ /\\[a-z0-9]/i.test(text) ||
+ /\\[^\\]*\.[a-z0-9]/i.test(text)
+ );
+}
+
+function stripLinks(text: string, preserve: (content: string) => string): string {
+ let result = "";
+ let previousEnd = 0;
+ for (const match of text.matchAll(/(!?)\[([^\]]*)\]\(/g)) {
+ if (match.index < previousEnd) continue;
+ const destinationStart = match.index + match[0].length;
+ let destinationEnd = destinationStart;
+ let depth = 0;
+ // A destination can contain nested or escaped parentheses. Its first `)`
+ // is not necessarily the end of the link.
+ for (; destinationEnd < text.length; destinationEnd += 1) {
+ const character = text[destinationEnd];
+ if (character === "\\" && destinationEnd + 1 < text.length) {
+ destinationEnd += 1;
+ } else if (character === "(") {
+ depth += 1;
+ } else if (character === ")") {
+ if (depth === 0) break;
+ depth -= 1;
+ } else if (/\s/.test(character)) {
+ break;
+ }
+ }
+ const closing = text.slice(destinationEnd).match(/^(?:\s+(?:"[^"]*"|'[^']*'))?\)/);
+ if (depth !== 0 || !closing) continue;
+ const destination = text.slice(destinationStart, destinationEnd).replace(/\\([\\()])/g, "$1");
+ const label = match[2];
+ result += text.slice(previousEnd, match.index);
+ result += match[1]
+ ? label
+ : label === destination
+ ? preserve(destination)
+ : `${label} (${preserve(destination)})`;
+ previousEnd = destinationEnd + closing[0].length;
+ }
+ return result + text.slice(previousEnd);
+}
+
+function hasOpenEmphasis(text: string, marker: string): boolean {
+ let count = 0;
+ for (const match of text.matchAll(/(?<!\\)(\*{1,3}|_{1,3}|~~)/g)) {
+ if (match[0] !== marker) continue;
+ const before = text[match.index - 1] ?? "";
+ const after = text[match.index + marker.length] ?? "";
+ if (marker.startsWith("_") && /\w/.test(before) && /\w/.test(after)) continue;
+ count += 1;
+ }
+ return count % 2 === 1;
+}
+
+function stripInline(text: string): string {
+ // Code, URL destinations and file paths are data, even when they contain
+ // markdown punctuation. Use a prefix absent from the input to avoid collisions.
+ const literals: string[] = [];
+ let placeholderPrefix = "";
+ while (text.includes(placeholderPrefix)) placeholderPrefix += "";
+ const preserve = (content: string): string => {
+ literals.push(content);
+ return `${placeholderPrefix}${literals.length - 1}`;
+ };
+ const withPlaceholders = text.replace(
+ /(?<![\\`])(`+)(?!`)(.*?)(?<!`)\1(?!`)/g,
+ (_match, _delimiter: string, content: string): string =>
+ // Markdown permits padding a code span with one space at either end
+ // so literal backticks do not merge with the delimiters.
+ preserve(/^ .* $/.test(content) && /[^ ]/.test(content) ? content.slice(1, -1) : content)
+ );
+ let resourceEnd = 0;
+ let resourceContext = "";
+
+ const stripped = stripLinks(withPlaceholders, preserve)
+ .replace(
+ /(["'])((?:[a-z]:\\|\\\\[^\s\\]+\\|[a-z0-9_.-]+\\|~\/|\.{1,2}\/|\/|[a-z0-9_.-]+\/)[^\r\n]*?)\1/gi,
+ (match, quote: string, path: string): string =>
+ path.includes("/") || hasWindowsPathStructure(path) ? quote + preserve(path) + quote : match
+ )
+ .replace(LITERAL_RESOURCE, (resource: string, offset: number, source: string): string => {
+ if (!resource.includes("/") && !hasWindowsPathStructure(resource)) return resource;
+ // Earlier resources cannot open emphasis; only the surrounding prose can.
+ resourceContext += source.slice(resourceEnd, offset);
+ resourceEnd = offset + resource.length;
+ // A marked-up word after whitespace belongs to prose, not an unquoted
+ // directory. Quoted paths were already protected, including such names.
+ const proseStart = resource.search(/\s+(?=(?:__\S.*?__|_\S.*?_|~~\S.*?~~)(?:\s|$))/);
+ if (proseStart !== -1) {
+ const prose = resource.slice(proseStart);
+ resourceContext += prose;
+ return preserve(resource.slice(0, proseStart)) + prose;
+ }
+ const closing = resource.match(/(\*{1,3}|_{1,3}|~~)([.,!?;:)\]]*)$/);
+ if (closing && hasOpenEmphasis(resourceContext, closing[1])) {
+ resourceContext += closing[0];
+ return preserve(resource.slice(0, -closing[0].length)) + closing[0];
+ }
+ return preserve(resource);
+ })
+ // Escaped punctuation is literal, including at a would-be closing marker.
+ .replace(/\\([\\`*_{}[\]()#+\-.!|>~])/g, (_match, literal: string): string => preserve(literal))
+ // `**` may sit intraword (intraword bold is legitimate); `__` requires a
+ // non-word close that is also not `(`, so dunder identifiers such as
+ // `__init__` (immediately followed by a call's `(`) are never mistaken
+ // for emphasis, while `__bold__ word` still strips.
+ .replace(/(?<!\\)\*\*(\S(?:.*?\S)??)\*\*/g, "$1")
+ .replace(/(?<![\w\\])__(\S(?:.*?\S)??)__(?![\w(])/g, "$1")
+ .replace(/(?<!\\)~~(\S(?:.*?\S)??)~~/g, "$1")
+ // Markers must hug non-space on the inside, not sit inside a word on the
+ // outside, and not be escaped — so `2 * 3`, snake_case and `\*` survive.
+ // The single-underscore content also may not start or end with `_` itself,
+ // so a dunder like `__init__` is never absorbed as `_` + `_init_` + `_`.
+ .replace(/(?<![\w*\\])\*(\S(?:.*?\S)??)\*(?![\w*])/g, "$1")
+ .replace(/(?<![\w_\\])_(?!_)(\S(?:.*?[^\s_])??)_(?![\w_])/g, "$1");
+
+ // A literal can itself hold placeholders (a code span inside a link destination).
+ const placeholder = new RegExp(`${placeholderPrefix}(\\d+)`, "g");
+ const restore = (text: string): string =>
+ text.replace(placeholder, (_match: string, index: string): string =>
+ restore(literals[Number(index)])
+ );
+ return restore(stripped);
+}
+
+function splitTableCells(row: string): string[] {
+ const cells: string[] = [];
+ let cell = "";
+ let backslashes = 0;
+ for (const character of row.trim().slice(1, -1)) {
+ if (character === "|" && backslashes % 2 === 0) {
+ cells.push(cell.trim());
+ cell = "";
+ } else {
+ cell += character;
+ }
+ backslashes = character === "\\" ? backslashes + 1 : 0;
+ }
+ cells.push(cell.trim());
+ return cells;
+}
+
+export function markdownToPlainText(markdown: string): string {
+ const lines: string[] = [];
+ const codeLines = new Set<number>();
+ let openingFence: string | null = null;
+
+ for (const line of markdown.split(/\r?\n/)) {
+ const fence = line.match(FENCE_LINE);
+ if (openingFence) {
+ if (
+ fence &&
+ fence[1][0] === openingFence[0] &&
+ fence[1].length >= openingFence.length &&
+ fence[2].trim() === ""
+ ) {
+ openingFence = null;
+ } else {
+ codeLines.add(lines.length);
+ lines.push(line);
+ }
+ continue;
+ }
+ if (fence && (fence[1][0] === "~" || !fence[2].includes("`"))) {
+ openingFence = fence[1];
+ continue;
+ }
+ if (HORIZONTAL_RULE.test(line)) continue;
+
+ if (TABLE_ROW.test(line)) {
+ const cells = splitTableCells(line);
+ if (cells.every((cell) => TABLE_ALIGNMENT_CELL.test(cell))) continue;
+ lines.push(cells.map(stripInline).join("\t"));
+ continue;
+ }
+
+ const block = line
+ .replace(/^(\s{0,3}>\s?)+/, "")
+ .replace(/^\s{0,3}#{1,6}\s+/, "")
+ .replace(/^(\s*)\*\s+/, "$1- ");
+ lines.push(stripInline(block).replace(/[ \t]+$/, ""));
+ }
+
+ // Trim only prose padding: code whitespace and table edge cells are data.
+ let start = 0;
+ let end = lines.length;
+ while (start < end && !codeLines.has(start) && /^ *$/.test(lines[start])) start += 1;
+ while (end > start && !codeLines.has(end - 1) && /^ *$/.test(lines[end - 1])) end -= 1;
+ if (start < end && !codeLines.has(start)) lines[start] = lines[start].replace(/^ +/, "");
+ return lines.slice(start, end).join("\n");
+}
diff --git a/src/helpers/selectionManager.js b/src/helpers/selectionManager.js
index a1d897c69..c31f1529e 100644
--- a/src/helpers/selectionManager.js
+++ b/src/helpers/selectionManager.js
@@ -1,6 +1,7 @@
const crypto = require("crypto");
const { execFile, spawn } = require("child_process");
const debugLogger = require("./debugLogger");
+const { isMarkdownTargetSignature } = require("./markdownTargets");
const SESSION_TTL_MS = 5 * 60 * 1000;
const MAX_SELECTION_EDIT_CODE_POINTS = 6000;
@@ -176,12 +177,15 @@ class SelectionManager {
const capture = await this._readCurrentSelection(expectedTarget, { probeEditable });
if (capture.status === "editable") {
const sessionId = crypto.randomUUID();
+ // The renderer asks for plain prose and strips markdown only when the
+ // target is not a markdown-friendly app.
+ const acceptsMarkdown = await this._targetAcceptsMarkdown(capture.target);
this.sessions.set(sessionId, {
kind: "caret",
target: capture.target,
expiresAt: this.now() + SESSION_TTL_MS,
});
- return { status: "editable", sessionId };
+ return { status: "editable", sessionId, acceptsMarkdown };
}
if (capture.status !== "selected") return capture;
@@ -257,7 +261,9 @@ class SelectionManager {
async pasteAtCapturedTarget(sessionId, text, options = {}) {
if (typeof text !== "string" || text.length === 0) {
- return { success: false, code: "invalid_replacement" };
+ return this._declineAssistantPaste("invalid_replacement", {
+ sessionFound: this.sessions.has(sessionId),
+ });
}
return this.clipboardManager.runClipboardOperation(async () => {
@@ -265,12 +271,20 @@ class SelectionManager {
const session = this.sessions.get(sessionId);
this.sessions.delete(sessionId);
if (!session || session.kind !== "caret") {
- return { success: false, code: "session_expired" };
+ return this._declineAssistantPaste("session_expired", {
+ sessionFound: Boolean(session),
+ sessionKind: session?.kind ?? null,
+ });
}
const current = await this._readCurrentSelection(session.target, { probeEditable: true });
if (current.status !== "editable") {
- return { success: false, code: "target_changed" };
+ return this._declineAssistantPaste("target_changed", {
+ sessionFound: true,
+ sessionKind: "caret",
+ probeStatus: current.status,
+ probeCode: current.code ?? null,
+ });
}
try {
@@ -281,7 +295,11 @@ class SelectionManager {
});
await pasteResult?.restoreComplete;
if (pasteResult?.pasted === false) {
- return { success: false, code: "paste_failed" };
+ return this._declineAssistantPaste("paste_failed", {
+ sessionFound: true,
+ sessionKind: "caret",
+ probeStatus: "editable",
+ });
}
return { success: true };
} catch (error) {
@@ -291,6 +309,17 @@ class SelectionManager {
});
}
+ // One line per refusal. The renderer discards the code it receives, so the
+ // debug log is the only place a declined assistant paste can be diagnosed.
+ _declineAssistantPaste(code, details = {}) {
+ debugLogger.info(
+ "Assistant response paste declined",
+ { code, platform: this.platform, ...details },
+ "clipboard"
+ );
+ return { success: false, code };
+ }
+
_pruneSessions() {
const now = this.now();
for (const [id, session] of this.sessions) {
@@ -533,13 +562,36 @@ class SelectionManager {
// the parsing below degrades to the bare name unchanged.
async _isTerminalPid(pid) {
if (!this.clipboardManager.isTerminalSignature) return false;
+ const names = await this._readTargetNames(pid);
+ return names ? this.clipboardManager.isTerminalSignature(names) : false;
+ }
+
+ // "<bundle name> <executable name>" for a pid — "Visual Studio Code Code" on
+ // macOS, the bare comm name on Linux — or "" when the pid cannot be read.
+ async _readTargetNames(pid) {
const executablePath = await this._readExecutablePath(pid);
- if (!executablePath) return false;
+ if (!executablePath) return "";
// 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}`);
+ return `${bundleName} ${executableName}`.trim();
+ }
+
+ // Windows and Linux X11 targets name their app on the target; macOS AX and
+ // Linux AT-SPI targets carry only a pid, so resolve the executable exactly
+ // as the terminal check does. A miss or an error means plain text.
+ async _targetAcceptsMarkdown(target) {
+ if (!target) return false;
+ try {
+ const parts = [this._targetSignature(target)];
+ const pid =
+ target.kind === "mac-pid" ? target.pid : target.kind === "atspi-pid" ? target.id : null;
+ if (pid) parts.push(await this._readTargetNames(pid));
+ return isMarkdownTargetSignature(parts.join(" ").trim());
+ } catch {
+ return false;
+ }
}
async _readExecutablePath(pid) {
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
index ac5830b26..b63ef2239 100644
--- a/src/hooks/useAudioRecording.js
+++ b/src/hooks/useAudioRecording.js
@@ -611,8 +611,13 @@ export const useAudioRecording = (toast, options = {}) => {
setTranscript(result.text);
if (result.assistantConversation) {
window.electronAPI?.hideDictationPreview?.();
- const { screenContext, transcript, selectedContext, deliverySessionId } =
- result.assistantConversation;
+ const {
+ screenContext,
+ transcript,
+ selectedContext,
+ deliverySessionId,
+ deliveryAcceptsMarkdown,
+ } = result.assistantConversation;
const command = {
text: expandSnippets(transcript, getSettings().snippets),
attachment: screenContext
@@ -636,6 +641,7 @@ export const useAudioRecording = (toast, options = {}) => {
delivery: createAssistantResponseDelivery({
autoPasteEnabled,
deliverySessionId,
+ acceptsMarkdown: deliveryAcceptsMarkdown,
restoreClipboard: !keepTranscriptionInClipboard,
allowClipboardFallback: isAccessibilitySkipped(),
}),
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 7006963b3..e7ae788a8 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1147,6 +1147,8 @@ declare global {
| {
status: "editable";
sessionId: string;
+ /** True when the captured app keeps markdown (spec Appendix A); false means plain text. */
+ acceptsMarkdown: boolean;
}
| {
status: "none" | "unavailable" | "target_changed" | "too_large";
diff --git a/test/helpers/assistantPanel.test.js b/test/helpers/assistantPanel.test.js
index 15c0ea486..2f2159643 100644
--- a/test/helpers/assistantPanel.test.js
+++ b/test/helpers/assistantPanel.test.js
@@ -621,6 +621,7 @@ test("a caret-delivered command returns the hidden Assistant to the idle pill",
sessionId: "caret-session",
restoreClipboard: true,
allowClipboardFallback: false,
+ plainText: true,
},
});
});
@@ -665,6 +666,7 @@ test("a follow-up into an open panel strips caret delivery and stays panel-first
sessionId: "caret-session",
restoreClipboard: true,
allowClipboardFallback: false,
+ plainText: true,
};
assistant.openRef.current = true;
@@ -689,3 +691,109 @@ test("a follow-up into an open panel strips caret delivery and stays panel-first
});
assert.deepEqual(assistant.pendingCommand.delivery, delivery);
});
+
+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]
+ );
+});
diff --git a/test/helpers/assistantResponseDelivery.test.js b/test/helpers/assistantResponseDelivery.test.js
index d93f0b967..e889655b9 100644
--- a/test/helpers/assistantResponseDelivery.test.js
+++ b/test/helpers/assistantResponseDelivery.test.js
@@ -11,6 +11,7 @@ const PASTE_DELIVERY = {
mode: "paste",
sessionId: "caret-session",
...PASTE_OPTIONS,
+ plainText: true,
};
function createDeliveryHarness(pasteSuccess) {
@@ -38,16 +39,22 @@ function createDeliveryHarness(pasteSuccess) {
test("Assistant delivery mode follows Auto-Paste and target state", async () => {
const { createAssistantResponseDelivery } = await deliveryModule;
- const createDelivery = (autoPasteEnabled, deliverySessionId) =>
+ const createDelivery = (autoPasteEnabled, deliverySessionId, acceptsMarkdown) =>
createAssistantResponseDelivery({
autoPasteEnabled,
deliverySessionId,
+ acceptsMarkdown,
...PASTE_OPTIONS,
});
assert.equal(createDelivery(false), null);
assert.deepEqual(createDelivery(true), { mode: "clipboard" });
assert.deepEqual(createDelivery(true, "caret-session"), PASTE_DELIVERY);
+ assert.deepEqual(createDelivery(true, "caret-session", false), PASTE_DELIVERY);
+ assert.deepEqual(createDelivery(true, "caret-session", true), {
+ ...PASTE_DELIVERY,
+ plainText: false,
+ });
});
test("a captured Assistant target receives the response without replacing the clipboard", async () => {
@@ -82,3 +89,62 @@ test("no Assistant target and a lost target both copy the completed response", a
assert.deepEqual(writes, [RESPONSE], delivery.mode);
}
});
+
+const MARKDOWN_RESPONSE = "**Bold** start.\n\n* item one\n* item two";
+const PLAIN_RESPONSE = "Bold start.\n\n- item one\n- item two";
+
+test("a plain-text caret target receives the response stripped of markdown", async () => {
+ const { deliverAssistantResponse } = await deliveryModule;
+ const { dependencies, pastes, writes } = createDeliveryHarness(true);
+
+ assert.deepEqual(
+ await deliverAssistantResponse(PASTE_DELIVERY, MARKDOWN_RESPONSE, dependencies),
+ { pasted: true, copied: false }
+ );
+ assert.equal(pastes[0].text, PLAIN_RESPONSE);
+ assert.deepEqual(writes, []);
+});
+
+test("the clipboard fallback of a refused plain-text paste carries the same stripped text", async () => {
+ const { deliverAssistantResponse } = await deliveryModule;
+ const { dependencies, writes } = createDeliveryHarness(false);
+
+ assert.deepEqual(
+ await deliverAssistantResponse(PASTE_DELIVERY, MARKDOWN_RESPONSE, dependencies),
+ { pasted: false, copied: true }
+ );
+ assert.deepEqual(writes, [PLAIN_RESPONSE]);
+});
+
+test("an answer the strip empties is pasted raw rather than as nothing", async () => {
+ const { deliverAssistantResponse } = await deliveryModule;
+ const { dependencies, pastes, writes } = createDeliveryHarness(true);
+ const ONLY_SYNTAX = "---\n```\n```";
+
+ assert.deepEqual(await deliverAssistantResponse(PASTE_DELIVERY, ONLY_SYNTAX, dependencies), {
+ pasted: true,
+ copied: false,
+ });
+ assert.equal(pastes[0].text, ONLY_SYNTAX);
+ assert.deepEqual(writes, []);
+});
+
+test("a markdown-friendly caret target receives the response verbatim", async () => {
+ const { deliverAssistantResponse } = await deliveryModule;
+ const { dependencies, pastes } = createDeliveryHarness(true);
+
+ await deliverAssistantResponse(
+ { ...PASTE_DELIVERY, plainText: false },
+ MARKDOWN_RESPONSE,
+ dependencies
+ );
+ assert.equal(pastes[0].text, MARKDOWN_RESPONSE);
+});
+
+test("a clipboard-only delivery keeps the response verbatim", async () => {
+ const { deliverAssistantResponse } = await deliveryModule;
+ const { dependencies, writes } = createDeliveryHarness(false);
+
+ await deliverAssistantResponse({ mode: "clipboard" }, MARKDOWN_RESPONSE, dependencies);
+ assert.deepEqual(writes, [MARKDOWN_RESPONSE]);
+});
diff --git a/test/helpers/audioManagerAssistantDirective.test.js b/test/helpers/audioManagerAssistantDirective.test.js
index 06a92ed8d..4209b48e6 100644
--- a/test/helpers/audioManagerAssistantDirective.test.js
+++ b/test/helpers/audioManagerAssistantDirective.test.js
@@ -79,10 +79,38 @@ test("a verified caret banks targeted response delivery when auto-paste is enabl
transcript: "draft a reply",
screenContext: null,
deliverySessionId: "caret-session",
+ deliveryAcceptsMarkdown: false,
});
assert.equal(modelCalls.length, 0, "caret delivery must retain the chat Agent route");
});
+test("a caret in a markdown-friendly app carries that verdict with the session id", async (t) => {
+ const { createManager } = await loadAudioManagerHarness(t, {
+ cachePrefix: "openwhispr-assistant-caret-markdown-",
+ settingsKey: "__assistantCaretMarkdownSettings",
+ settings: { autoPasteEnabled: true },
+ mockModules: {
+ "/services/ReasoningService": 'export default { processText: async () => "" };',
+ },
+ });
+ const { manager } = managerWithCapture(createManager, {
+ status: "editable",
+ sessionId: "caret-session",
+ acceptsMarkdown: true,
+ });
+
+ await manager.processAgentCommand("draft a reply", "gpt", "Aria", {
+ selectionEditReachable: true,
+ });
+
+ assert.deepEqual(manager.pendingAssistantConversation, {
+ transcript: "draft a reply",
+ screenContext: null,
+ deliverySessionId: "caret-session",
+ deliveryAcceptsMarkdown: true,
+ });
+});
+
test("a verified caret stays panel-first when auto-paste is disabled", async (t) => {
const { createManager } = await loadAudioManagerHarness(t, {
cachePrefix: "openwhispr-assistant-caret-panel-",
diff --git a/test/helpers/markdownTargets.test.js b/test/helpers/markdownTargets.test.js
new file mode 100644
index 000000000..d4d26a449
--- /dev/null
+++ b/test/helpers/markdownTargets.test.js
@@ -0,0 +1,80 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const {
+ isMarkdownTargetSignature,
+ MARKDOWN_TARGET_SIGNATURES,
+} = require("../../src/helpers/markdownTargets");
+
+// Each signature below is the exact shape one platform hands the matcher:
+// macOS "<.app folder name> <executable>", Windows "<exe> <window class>",
+// Linux "<WM_CLASS>". One representative per group of the spec's Appendix A.
+test("markdown-friendly apps match on every platform's identity shape", () => {
+ for (const signature of [
+ "Obsidian Obsidian", // macOS, resolved from the pid
+ "Visual Studio Code Code", // macOS: .app name and executable differ
+ "IntelliJ IDEA idea", // macOS JetBrains
+ "ChatGPT ChatGPT", // macOS AI prompt box
+ "Google Gemini Gemini", // macOS, Chromium-path app name plus executable
+ "Notion Notion",
+ "Discord Discord",
+ "Linear Linear",
+ "Obsidian.exe Chrome_WidgetWin_1", // Windows exe + Electron window class
+ "Code.exe Chrome_WidgetWin_1",
+ "idea64.exe SunAwtFrame",
+ "pycharm64.exe SunAwtFrame",
+ "webstorm64.exe",
+ "datagrip64.exe",
+ "notepad++.exe Notepad++",
+ "M365Copilot.exe",
+ "md.obsidian.obsidian", // Linux Flatpak WM_CLASS
+ "net.cozic.joplin_desktop",
+ "jetbrains-idea",
+ "dev.zed.zed",
+ "code",
+ "org.kde.kate",
+ ]) {
+ assert.equal(isMarkdownTargetSignature(signature), true, signature);
+ }
+});
+
+test("plain-text apps, own-dialect chat tools, browsers and near-miss names never match", () => {
+ for (const signature of [
+ "TextEdit TextEdit",
+ "Notes Notes",
+ "Microsoft Word Microsoft Word",
+ "Pages Pages",
+ "Mail Mail",
+ "WINWORD.EXE",
+ "notepad.exe Notepad",
+ "gedit",
+ "Slack Slack",
+ "Microsoft Teams MSTeams",
+ "ms-teams.exe",
+ "WhatsApp WhatsApp",
+ "Telegram Telegram",
+ "Xcode Xcode", // "code" must not match inside Xcode
+ "Notion Calendar Notion Calendar", // veto
+ "Notion Mail Notion Mail", // veto
+ "Google Chrome Google Chrome",
+ "Safari Safari",
+ "Arc Arc",
+ "Riot Client RiotClientUx.exe", // the reason "riot" is not an entry
+ "reMarkable reMarkable", // the reason "remarkable" is not an entry
+ "",
+ null,
+ undefined,
+ ]) {
+ assert.equal(isMarkdownTargetSignature(signature), false, String(signature));
+ }
+});
+
+test("every entry is lowercase, at least three characters, and free of generic tokens", () => {
+ for (const entry of MARKDOWN_TARGET_SIGNATURES) {
+ assert.equal(entry, entry.toLowerCase(), entry);
+ assert.ok(entry.length >= 3, entry);
+ }
+ for (const banned of ["riot", "remarkable", "notes", "mail", "word", "text", "app"]) {
+ assert.ok(!MARKDOWN_TARGET_SIGNATURES.includes(banned), banned);
+ }
+});
diff --git a/test/helpers/markdownToPlainText.test.js b/test/helpers/markdownToPlainText.test.js
new file mode 100644
index 000000000..d3bba4429
--- /dev/null
+++ b/test/helpers/markdownToPlainText.test.js
@@ -0,0 +1,340 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const helperModule = import("../../src/helpers/markdownToPlainText.ts");
+
+// Every case pins one rule from the spec's table. The first test is the one
+// that matters most: it is exactly what the search-preview helper in
+// CommandSearch.tsx would fail, because it collapses newlines into spaces.
+test("paragraphs, blank lines and line breaks survive untouched", async () => {
+ const { markdownToPlainText } = await helperModule;
+ const answer = "First paragraph.\n\nSecond paragraph,\nwrapped onto a second line.";
+ assert.equal(markdownToPlainText(answer), answer);
+});
+
+test("emphasis markers are removed and the words kept", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("**bold** and *em* and __b__ and _e_ and ~~s~~"),
+ "bold and em and b and e and s"
+ );
+ assert.equal(markdownToPlainText("**x**"), "x");
+ assert.equal(
+ markdownToPlainText("**A** or **B**, *x* or *y*, __a__ or __b__, ~~a~~ or ~~b~~, _a_ or _b_"),
+ "A or B, x or y, a or b, a or b, a or b"
+ );
+});
+
+test("headings lose their marks", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(markdownToPlainText("## Title\nBody"), "Title\nBody");
+});
+
+test("inline code and fenced blocks keep their content verbatim", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("Run `npm test`.\n```bash\nnpm test\n```\nDone."),
+ "Run npm test.\nnpm test\nDone."
+ );
+ assert.equal(markdownToPlainText("```\n**not bold**\n```"), "**not bold**");
+});
+
+test("links keep their text and their url; images keep their alt text", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("see [the docs](https://x.y/d)"),
+ "see the docs (https://x.y/d)"
+ );
+ assert.equal(markdownToPlainText("[https://x.y](https://x.y)"), "https://x.y");
+ assert.equal(markdownToPlainText("![a chart](chart.png)"), "a chart");
+});
+
+test("star bullets become dashes; plus, dashes and numbers stay as typed", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("* one\n+ two\n- three\n1. four"),
+ "- one\n+ two\n- three\n1. four"
+ );
+});
+
+test("blockquote markers are removed at line start only", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(markdownToPlainText("> quoted\n>> nested\nx > y"), "quoted\nnested\nx > y");
+});
+
+test("horizontal rules are removed", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(markdownToPlainText("a\n---\nb\n* * *\nc"), "a\nb\nc");
+});
+
+test("tables become tab-separated rows without the alignment row", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("| Name | Qty |\n|---|---:|\n| Apples | **3** |"),
+ "Name\tQty\nApples\t3"
+ );
+});
+
+test("markdown escapes resolve to the escaped character", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(markdownToPlainText("\\*literal\\* and 5 \\_ 6"), "*literal* and 5 _ 6");
+ assert.equal(markdownToPlainText("\\*\\*kept\\*\\*"), "**kept**");
+ assert.equal(markdownToPlainText(String.raw`\_literal\_`), "_literal_");
+ assert.equal(
+ markdownToPlainText(String.raw`**An escaped under\_score.**`),
+ "An escaped under_score."
+ );
+ assert.equal(markdownToPlainText(String.raw`"under\_score"`), '"under_score"');
+ assert.equal(markdownToPlainText(String.raw`\_literal\_name\_`), "_literal_name_");
+ assert.equal(markdownToPlainText(String.raw`**Use foo\*bar\*baz.**`), "Use foo*bar*baz.");
+});
+
+test("plain-text conventions a human would type are never altered", async () => {
+ const { markdownToPlainText } = await helperModule;
+ const answer =
+ "2 * 3 * 4 = 24\nsnake_case_name stays\na lone * star\n#hashtag\nx > y\n+ 5 points";
+ assert.equal(markdownToPlainText(answer), answer);
+});
+
+test("dunder identifiers survive the underscored-bold guard", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(markdownToPlainText("def __init__(self): pass"), "def __init__(self): pass");
+ assert.equal(markdownToPlainText("MAX__VALUE stays"), "MAX__VALUE stays");
+ assert.equal(markdownToPlainText("__bold__ word"), "bold word");
+});
+
+test("inline code content is verbatim, never run through other inline rules", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(markdownToPlainText("use `__init__` here"), "use __init__ here");
+ assert.equal(markdownToPlainText("inline `**not bold**` code"), "inline **not bold** code");
+ assert.equal(markdownToPlainText("`C:\\Users\\me`"), "C:\\Users\\me");
+});
+
+test("a literal placeholder sequence in the input survives the restore step", async () => {
+ const { markdownToPlainText } = await helperModule;
+ // The private-use placeholders are an internal device; text that happens to
+ // contain the same sequence indexes no captured span and must come back as
+ // it arrived rather than as "undefined".
+ const answer = "text with \u{E000}0\u{E001} literal";
+ assert.equal(markdownToPlainText(answer), answer);
+ assert.equal(markdownToPlainText(`${answer} and \`__init__\``), `${answer} and __init__`);
+});
+
+test("URLs keep their literal destinations while surrounding emphasis is removed", async () => {
+ const { markdownToPlainText } = await helperModule;
+ const url = "https://github.com/acme/service/blob/main/pkg/__init__.py";
+ assert.equal(markdownToPlainText(`Open ${url}`), `Open ${url}`);
+ assert.equal(markdownToPlainText(`[**Source**](${url})`), `Source (${url})`);
+ assert.equal(markdownToPlainText(`[${url}](${url})`), url);
+ assert.equal(markdownToPlainText(`**${url}**`), url);
+ assert.equal(markdownToPlainText(`_${url}_.`), `${url}.`);
+ assert.equal(markdownToPlainText("[module](../pkg/__init__.py)"), "module (../pkg/__init__.py)");
+});
+
+test("plain Windows paths survive alongside ordinary markdown and escapes", async () => {
+ const { markdownToPlainText } = await helperModule;
+ for (const path of [
+ String.raw`\\fileserver\finance\budget.xlsx`,
+ String.raw`C:\_archive\report.txt`,
+ ]) {
+ assert.equal(markdownToPlainText(`Open ${path}.`), `Open ${path}.`);
+ assert.equal(markdownToPlainText(`**${path}** and **read** it.`), `${path} and read it.`);
+ assert.equal(markdownToPlainText(`_${path}_`), path);
+ }
+ assert.equal(markdownToPlainText(String.raw`\*literal\*`), "*literal*");
+});
+
+test("emphasis can enclose prose and literal resources together", async () => {
+ const { markdownToPlainText } = await helperModule;
+ for (const resource of ["https://example.com/__init__.py", String.raw`C:\_archive\report.txt`]) {
+ for (const marker of ["**", "*", "__", "_", "~~"]) {
+ assert.equal(markdownToPlainText(`${marker}Open ${resource}${marker}`), `Open ${resource}`);
+ assert.equal(markdownToPlainText(`(${marker}${resource}${marker}).`), `(${resource}).`);
+ }
+ }
+ const plain = "snake_case https://example.com/trailing_";
+ assert.equal(markdownToPlainText(plain), plain);
+ assert.equal(
+ markdownToPlainText("https://example.com/trailing_ then _https://example.com/__init__.py_"),
+ "https://example.com/trailing_ then https://example.com/__init__.py"
+ );
+});
+
+test("Windows directories with spaces and quoted filenames remain literal", async () => {
+ const { markdownToPlainText } = await helperModule;
+ for (const path of [
+ String.raw`C:\My Documents\_archive\report.txt`,
+ String.raw`\\fileserver\Shared Documents\_archive\report.txt`,
+ ]) {
+ assert.equal(markdownToPlainText(`Open ${path} and **read** it.`), `Open ${path} and read it.`);
+ assert.equal(markdownToPlainText(`**Read** ${path}.`), `Read ${path}.`);
+ }
+ const quoted = String.raw`"C:\My Documents\report _draft_.txt"`;
+ assert.equal(
+ markdownToPlainText(`Open ${quoted} and **read** it.`),
+ `Open ${quoted} and read it.`
+ );
+ assert.equal(
+ markdownToPlainText(String.raw`C:\report.txt and __read__ \*literal\*`),
+ String.raw`C:\report.txt and read *literal*`
+ );
+ assert.equal(
+ markdownToPlainText(String.raw`C:\report.txt and __read__ \_literal\_`),
+ String.raw`C:\report.txt and read _literal_`
+ );
+});
+
+test("only a matching closing fence ends literal code", async () => {
+ const { markdownToPlainText } = await helperModule;
+ for (const opening of ["````markdown", "~~~~markdown"]) {
+ const marker = opening[0];
+ const body = ["```js", 'const label = "**draft**";', "```", "~~~", `${marker.repeat(4)} text`];
+ const answer = ["Example:", opening, ...body, marker.repeat(5), "**Done.**"].join("\n");
+ assert.equal(markdownToPlainText(answer), ["Example:", ...body, "Done."].join("\n"));
+ }
+});
+
+test("escaped table pipes remain inside their cell and preserve empty cells", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("| Choice | Meaning |\n| --- | --- |\n| A \\| B | either choice |"),
+ "Choice\tMeaning\nA | B\teither choice"
+ );
+ assert.equal(markdownToPlainText(String.raw`| A\\| B |`), "A\\\tB");
+ assert.equal(markdownToPlainText(String.raw`| A\\\|B | C |`), "A\\|B\tC");
+ assert.equal(markdownToPlainText("| A | | C |"), "A\t\tC");
+});
+
+test("POSIX paths retain literal underscores alongside surrounding emphasis", async () => {
+ const { markdownToPlainText } = await helperModule;
+ for (const path of [
+ "/tmp/__init__.py",
+ "/home/me/__pycache__/config.py",
+ "~/__work__/code",
+ "./__cache__/file",
+ "../pkg/__init__.py",
+ "pkg/__init__.py",
+ "__pycache__/config.py",
+ "_work_/code",
+ "my_package/__init__.py",
+ ]) {
+ assert.equal(markdownToPlainText(`Open ${path} and **read** it.`), `Open ${path} and read it.`);
+ for (const marker of ["**", "*", "__", "_", "~~"]) {
+ assert.equal(markdownToPlainText(`Open ${marker}${path}${marker}.`), `Open ${path}.`);
+ }
+ }
+});
+
+test("quoted POSIX paths retain spaces and literal filename punctuation", async () => {
+ const { markdownToPlainText } = await helperModule;
+ const answer = 'Open "/Users/me/My Documents/report _draft_.txt" and **read** it.';
+ assert.equal(
+ markdownToPlainText(answer),
+ 'Open "/Users/me/My Documents/report _draft_.txt" and read it.'
+ );
+});
+
+test("link destinations preserve balanced and escaped parentheses", async () => {
+ const { markdownToPlainText } = await helperModule;
+ for (const [url, destination] of [
+ ["https://example.com/a_(b)/__init__.py", "https://example.com/a_(b)/__init__.py"],
+ ["https://example.com/a_(b_(c))/__init__.py", "https://example.com/a_(b_(c))/__init__.py"],
+ [String.raw`https://example.com/a_\(b\)/__init__.py`, "https://example.com/a_(b)/__init__.py"],
+ ]) {
+ assert.equal(markdownToPlainText(`[**Source**](${url})`), `Source (${destination})`);
+ assert.equal(markdownToPlainText(`[Source](${url} "A title")`), `Source (${destination})`);
+ assert.equal(markdownToPlainText(`![A chart](${url})`), "A chart");
+ assert.equal(markdownToPlainText(`![A chart](${url} 'Chart title')`), "A chart");
+ }
+ const malformed = "[Source](https://example.com/a_(b)";
+ assert.equal(markdownToPlainText(malformed), malformed);
+});
+
+test("inline code matches whole delimiter runs and retains literal backticks", async () => {
+ const { markdownToPlainText } = await helperModule;
+ for (const [input, expected] of [
+ ["Run ``echo `whoami` ``.", "Run echo `whoami` ."],
+ ["Run `` echo `whoami` ``.", "Run echo `whoami`."],
+ ["Use ``a`b`` here.", "Use a`b here."],
+ ["Use ```a``b`c``` here.", "Use a``b`c here."],
+ ["Use `` **bold** `code` `` here.", "Use **bold** `code` here."],
+ ["Use ``unclosed` here.", "Use ``unclosed` here."],
+ ["Keep ` ` spaces.", "Keep spaces."],
+ ]) {
+ assert.equal(markdownToPlainText(input), expected);
+ }
+});
+
+test("table conversion preserves empty edge cells and column alignment", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("| | 2025 | 2026 |\n|---|---|---|\n| Revenue | 100 | 200 |"),
+ "\t2025\t2026\nRevenue\t100\t200"
+ );
+ assert.equal(
+ markdownToPlainText("\n| A | B | |\n|---|---|---|\n| | value | |\n\n"),
+ "A\tB\t\n\tvalue\t"
+ );
+ assert.equal(markdownToPlainText("| | | |"), "\t\t");
+ assert.equal(markdownToPlainText(" Prose. \n\nMore prose. \n"), "Prose.\n\nMore prose.");
+});
+
+test("inline backtick spans at line start are not mistaken for fences", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(
+ markdownToPlainText("```hello```\nThis is the next paragraph."),
+ "hello\nThis is the next paragraph."
+ );
+ assert.equal(markdownToPlainText("````a`b````\n**Done.**"), "a`b\nDone.");
+});
+
+test("relative Windows paths and wildcard commands retain their separators", async () => {
+ const { markdownToPlainText } = await helperModule;
+ for (const path of [
+ String.raw`.\_cache\output.txt`,
+ String.raw`..\_cache\output.txt`,
+ String.raw`src\__tests__\index.test.ts`,
+ String.raw`src\*.ts`,
+ String.raw`__cache__\file.txt`,
+ String.raw`_cache_\file.txt`,
+ String.raw`src\[name]\_cache_.ts`,
+ ]) {
+ assert.equal(markdownToPlainText(`Open ${path} and **read** it.`), `Open ${path} and read it.`);
+ for (const marker of ["**", "*", "__", "_", "~~"]) {
+ assert.equal(markdownToPlainText(`${marker}${path}${marker}`), path);
+ }
+ }
+ assert.equal(markdownToPlainText(String.raw`Run dir src\*.ts`), String.raw`Run dir src\*.ts`);
+ assert.equal(
+ markdownToPlainText(String.raw`Open "src\My Files\_draft_.txt" and **read** it.`),
+ String.raw`Open "src\My Files\_draft_.txt" and read it.`
+ );
+});
+
+test("escaped punctuation inside emphasis is not a closing delimiter", async () => {
+ const { markdownToPlainText } = await helperModule;
+ for (const [input, expected] of [
+ [String.raw`*Use \* for wildcard matches.*`, "Use * for wildcard matches."],
+ [String.raw`_Use \_ as the separator._`, "Use _ as the separator."],
+ [String.raw`**Use \*\* for bold.**`, "Use ** for bold."],
+ [String.raw`__Use \_\_ for bold.__`, "Use __ for bold."],
+ [String.raw`~~Use \~\~ for strike.~~`, "Use ~~ for strike."],
+ ]) {
+ assert.equal(markdownToPlainText(input), expected);
+ }
+});
+
+test("fenced code preserves whitespace at the edges of an answer", async () => {
+ const { markdownToPlainText } = await helperModule;
+ const code = " if enabled:\n run()\n return value ";
+ for (const padding of ["", "\n", " \n\n"]) {
+ assert.equal(markdownToPlainText(`${padding}\`\`\`python\n${code}\n\`\`\`${padding}`), code);
+ }
+ assert.equal(markdownToPlainText("```\n\n value\n\n```"), "\n value\n");
+});
+
+test("code spans inside a quoted path or a link destination restore fully", async () => {
+ const { markdownToPlainText } = await helperModule;
+ assert.equal(markdownToPlainText('"/tmp/`x`"'), '"/tmp/x"');
+ assert.equal(markdownToPlainText("See [docs](https://a.com/`x`)"), "See docs (https://a.com/x)");
+});
diff --git a/test/helpers/selectionManager.test.js b/test/helpers/selectionManager.test.js
index 4b0e1b7f9..03f0c7524 100644
--- a/test/helpers/selectionManager.test.js
+++ b/test/helpers/selectionManager.test.js
@@ -5,6 +5,20 @@ const { EventEmitter } = require("node:events");
const childProcess = require("node:child_process");
const selectionManagerPath = require.resolve("../../src/helpers/selectionManager");
+// selectionManager requires "./debugLogger" at load; the stub records every
+// line so tests can assert what a declined paste leaves in the debug log.
+const logged = [];
+const debugLoggerStub = {
+ debug: (message, meta, scope) => logged.push({ level: "debug", message, meta, scope }),
+ info: (message, meta, scope) => logged.push({ level: "info", message, meta, scope }),
+ warn: (message, meta, scope) => logged.push({ level: "warn", message, meta, scope }),
+ trace: () => {},
+ log: () => {},
+ error: () => {},
+};
+const declines = () =>
+ logged.filter((entry) => entry.message === "Assistant response paste declined");
+
const originalLoad = Module._load;
function loadSelectionManager({ spawn } = {}) {
@@ -13,6 +27,9 @@ function loadSelectionManager({ spawn } = {}) {
if (request === "electron") {
return { clipboard: { readText: () => "", writeText: () => {} } };
}
+ if (request === "./debugLogger") {
+ return debugLoggerStub;
+ }
if (request === "child_process" && spawn) {
return { ...childProcess, spawn };
}
@@ -817,3 +834,158 @@ test("empty replacement output is rejected without consuming a paste", async ()
});
assert.equal(pastes.length, 0);
});
+
+test("a caret in a markdown-native macOS app is reported as accepting markdown", async () => {
+ const { manager } = makeHarness({ selections: [{ state: "none", editable: true }] });
+ manager._readExecutablePath = async () => "/Applications/Obsidian.app/Contents/MacOS/Obsidian";
+
+ const result = await manager.captureSelectedText({ probeEditable: true });
+
+ assert.equal(result.status, "editable");
+ assert.equal(result.acceptsMarkdown, true);
+});
+
+test("a caret in a plain-text macOS app is reported as wanting plain text", async () => {
+ const { manager } = makeHarness({ selections: [{ state: "none", editable: true }] });
+ manager._readExecutablePath = async () =>
+ "/System/Applications/TextEdit.app/Contents/MacOS/TextEdit";
+
+ const result = await manager.captureSelectedText({ probeEditable: true });
+
+ assert.equal(result.status, "editable");
+ assert.equal(result.acceptsMarkdown, false);
+});
+
+test("an unreadable pid defaults the caret to plain text", async () => {
+ const { manager } = makeHarness({ selections: [{ state: "none", editable: true }] });
+ manager._readExecutablePath = async () => "";
+
+ const result = await manager.captureSelectedText({ probeEditable: true });
+
+ assert.equal(result.status, "editable");
+ assert.equal(result.acceptsMarkdown, false);
+});
+
+test("Windows and Linux caret targets are judged by the identity they already carry", async () => {
+ const { manager } = makeHarness();
+ manager._readExecutablePath = async () => {
+ throw new Error("must not spawn ps for a target that names its app");
+ };
+
+ assert.equal(
+ await manager._targetAcceptsMarkdown({
+ kind: "win-hwnd",
+ id: "00001A2B",
+ exeName: "Obsidian.exe",
+ windowClass: "Chrome_WidgetWin_1",
+ }),
+ true
+ );
+ assert.equal(
+ await manager._targetAcceptsMarkdown({
+ kind: "win-hwnd",
+ id: "00001A2B",
+ exeName: "WINWORD.EXE",
+ }),
+ false
+ );
+ assert.equal(
+ await manager._targetAcceptsMarkdown({
+ kind: "x11-window",
+ id: "0x1",
+ windowClass: "md.obsidian.obsidian",
+ }),
+ true
+ );
+ assert.equal(await manager._targetAcceptsMarkdown(null), false);
+});
+
+test("a Linux AT-SPI target resolves its executable like the terminal check does", async () => {
+ const { manager } = makeHarness();
+ manager._readExecutablePath = async (pid) => (pid === 77 ? "obsidian" : "");
+
+ assert.equal(await manager._targetAcceptsMarkdown({ kind: "atspi-pid", id: 77 }), true);
+ assert.equal(await manager._targetAcceptsMarkdown({ kind: "atspi-pid", id: 78 }), false);
+});
+
+test("a paste declined by a changed target logs the code and the probe verdict", async () => {
+ logged.length = 0;
+ const { manager } = makeHarness({
+ selections: [
+ { state: "none", editable: true },
+ { state: "selected", text: "new selection" },
+ ],
+ });
+ const capture = await manager.captureSelectedText({ probeEditable: true });
+ await manager.pasteAtCapturedTarget(capture.sessionId, "Agent response");
+
+ assert.equal(declines().length, 1);
+ const [entry] = declines();
+ assert.equal(entry.level, "info");
+ assert.equal(entry.scope, "clipboard");
+ assert.equal(entry.meta.code, "target_changed");
+ assert.equal(entry.meta.platform, "darwin");
+ assert.equal(entry.meta.sessionFound, true);
+ assert.equal(entry.meta.sessionKind, "caret");
+ assert.equal(entry.meta.probeStatus, "selected");
+});
+
+test("a paste against a missing or expired session logs session_expired", async () => {
+ logged.length = 0;
+ const { manager, pastes } = makeHarness();
+
+ assert.deepEqual(await manager.pasteAtCapturedTarget("missing-session", "Agent response"), {
+ success: false,
+ code: "session_expired",
+ });
+ assert.equal(pastes.length, 0);
+ const [entry] = declines();
+ assert.equal(entry.meta.code, "session_expired");
+ assert.equal(entry.meta.sessionFound, false);
+});
+
+test("a selection session offered as a caret target logs its kind", async () => {
+ logged.length = 0;
+ const { manager } = makeHarness({ selections: ["some selected text"] });
+ const capture = await manager.captureSelectedText();
+
+ assert.equal(
+ (await manager.pasteAtCapturedTarget(capture.sessionId, "x")).code,
+ "session_expired"
+ );
+ const [entry] = declines();
+ assert.equal(entry.meta.sessionFound, true);
+ assert.equal(entry.meta.sessionKind, "selection");
+});
+
+test("empty text logs invalid_replacement before any clipboard work", async () => {
+ logged.length = 0;
+ const { manager, pastes } = makeHarness();
+
+ assert.deepEqual(await manager.pasteAtCapturedTarget("any-session", ""), {
+ success: false,
+ code: "invalid_replacement",
+ });
+ assert.equal(pastes.length, 0);
+ assert.equal(declines()[0].meta.code, "invalid_replacement");
+});
+
+test("a paste the clipboard helper reports as not pasted logs paste_failed", async () => {
+ logged.length = 0;
+ const { manager } = makeHarness({
+ selections: [
+ { state: "none", editable: true },
+ { state: "none", editable: true },
+ ],
+ pasteResult: { pasted: false, restoreComplete: Promise.resolve() },
+ });
+ const capture = await manager.captureSelectedText({ probeEditable: true });
+
+ assert.deepEqual(await manager.pasteAtCapturedTarget(capture.sessionId, "Agent response"), {
+ success: false,
+ code: "paste_failed",
+ });
+ const [entry] = declines();
+ assert.equal(entry.meta.code, "paste_failed");
+ assert.equal(entry.meta.probeStatus, "editable");
+});
diff --git a/test/helpers/useChatStreamingFlush.test.js b/test/helpers/useChatStreamingFlush.test.js
index c0398d35e..69cca71f9 100644
--- a/test/helpers/useChatStreamingFlush.test.js
+++ b/test/helpers/useChatStreamingFlush.test.js
@@ -443,3 +443,26 @@ for (const withContent of [true, false]) {
await assertNoLateWrites(harness);
});
}
+
+test("plainTextResponse appends the plain-text instruction to the system prompt", async (t) => {
+ const requestBodies = [];
+ const originalFetch = globalThis.fetch;
+ t.after(() => {
+ globalThis.fetch = originalFetch;
+ });
+ globalThis.fetch = async (_url, init) => {
+ requestBodies.push(String(init?.body));
+ return new Response(sseEvent({ content: "ok" }, "stop") + "data: [DONE]\n\n", {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+ };
+ const harness = await renderChatStreaming(t);
+
+ await harness.captured.sendToAI("draft a reply", [], { plainTextResponse: true });
+ await harness.captured.sendToAI("draft a reply", []);
+
+ assert.equal(requestBodies.length, 2);
+ assert.match(requestBodies[0], /OUTPUT FORMAT:/);
+ assert.doesNotMatch(requestBodies[1], /OUTPUT FORMAT:/);
+});