From 6690ef8de23f4ffa936e5458d5ffbb52ee7dcc4e Mon Sep 17 00:00:00 2001 From: Leo310 Date: Wed, 25 Nov 2026 19:35:19 +0100 Subject: [PATCH 1/6] feat(chat): quote selected chat text into the composer Text selected in a chat's message text (assistant replies, tool-timeline text, user bubbles) now becomes the composer's selection chip, like a note selection does. It is held back while selecting, since chat text is mostly selected to copy, and pins when the composer is pressed or focused (capture phase, before the press collapses the selection). The model sees it as a quote, not a file: "[Quoted from earlier in this conversation]" for the same thread, or the source chat's title and path for another one. Whether it is the same thread is fixed on the ref at capture, because the block is rebuilt to strip it and a thread's path changes when it is auto-titled. Closes #591 Co-Authored-By: Claude --- .../chat/CollapsibleUserBubble.svelte | 2 +- src/components/chat/ContextTray.svelte | 6 + src/components/chat/Input.svelte | 8 + src/hooks/useSelection.svelte.ts | 126 +++++++++++- test/hooks/chatSelection.test.ts | 180 ++++++++++++++++++ 5 files changed, 319 insertions(+), 3 deletions(-) create mode 100644 test/hooks/chatSelection.test.ts diff --git a/src/components/chat/CollapsibleUserBubble.svelte b/src/components/chat/CollapsibleUserBubble.svelte index 9bdbc14ac..25fdb5d38 100644 --- a/src/components/chat/CollapsibleUserBubble.svelte +++ b/src/components/chat/CollapsibleUserBubble.svelte @@ -51,7 +51,7 @@ function handleClick(evt: MouseEvent) { class="s2b-overflow-hidden s2b-transition-[max-height] s2b-duration-200 s2b-ease-out s2b-break-words s2b-wrap-anywhere" style:max-height={isExpanded || !isTruncated ? "none" : `${COLLAPSED_HEIGHT}px`} > - + {#if isTruncated && !isExpanded} diff --git a/src/components/chat/ContextTray.svelte b/src/components/chat/ContextTray.svelte index bf25455e8..21409c1db 100644 --- a/src/components/chat/ContextTray.svelte +++ b/src/components/chat/ContextTray.svelte @@ -218,6 +218,12 @@ function onSelectionClick(evt: MouseEvent): void { dismissSelection(); } +/** Adopt a selection in chat message text (see `SelectionTracker.pinChatSelection`). + * The composer calls this when it is pressed or focused. */ +export function pinChatSelection(threadPath: string | null): void { + selectionTracker.pinChatSelection(threadPath); +} + function dismissSelection(): void { dismissedSelection = selectionTracker.selection; selectionTracker.clear(); diff --git a/src/components/chat/Input.svelte b/src/components/chat/Input.svelte index f7dc18911..ed15498ef 100644 --- a/src/components/chat/Input.svelte +++ b/src/components/chat/Input.svelte @@ -1298,6 +1298,12 @@ async function promoteVisibleNoteToAttachment(note: VisibleNote) { savingFiles = false; } } +// Text selected in a chat's messages becomes a quote only once the user turns to +// the composer. Capture phase, so it runs before the press moves the selection +// into the editor and collapses it. +function pinChatSelection(): void { + contextTrayRef?.pinChatSelection(threadPath); +}
= { markdown: "file-text", pdf: "file-type", + chat: "quote", }; +/** Message text inside a chat view that can be quoted: rendered assistant text + * (including the text segments of a tool timeline) and the user's own bubbles. + * Everything else in the view (composer, tray, tool cards, bars) is UI. */ +const QUOTABLE_CHAT_SELECTOR = ".s2b-message-text, .s2b-user-bubble-text"; + +function isInQuotableChatText(node: Node | null): boolean { + const el = node instanceof Element ? node : node?.parentElement; + return Boolean(el?.closest(QUOTABLE_CHAT_SELECTOR)); +} + +function chatLeafContaining(node: Node): WorkspaceLeaf | undefined { + return getPlugin() + .app.workspace.getLeavesOfType(VIEW_TYPE_CHAT) + .find((leaf) => leaf.view.containerEl.contains(node)); +} + +/** + * The live selection when it lies in message text of a chat view. Read from the + * DOM rather than the active leaf: a sidebar chat never becomes the "most recent" + * leaf, so the leaf the selection is in has to be found from the selection itself. + */ +function getChatSelection(): CapturedSelection | undefined { + try { + const domSel = activeWindow.getSelection(); + if (!domSel || domSel.rangeCount === 0 || domSel.isCollapsed) return undefined; + const { anchorNode, focusNode } = domSel; + if (!anchorNode || !focusNode) return undefined; + if (!isInQuotableChatText(anchorNode) || !isInQuotableChatText(focusNode)) return undefined; + const leaf = chatLeafContaining(anchorNode); + if (!leaf || !leaf.view.containerEl.contains(focusNode)) return undefined; + const file = (leaf.view as { file?: { path: string; basename: string } | null }).file; + if (!file) return undefined; + + const text = domSel.toString(); + if (!text.trim()) return undefined; + + const domRanges: Range[] = []; + for (let i = 0; i < domSel.rangeCount; i++) { + domRanges.push(domSel.getRangeAt(i).cloneRange()); + } + return { + ref: { path: file.path, basename: file.basename, viewType: "chat", text, icon: VIEW_ICONS.chat }, + domRanges, + }; + } catch { + return undefined; + } +} + +/** Whether the user clicked (a collapsed selection) into message text of the chat + * at `path` — the chat-side twin of `hasCollapsedSelectionInLeaf`. */ +function hasCollapsedChatSelection(path: string): boolean { + try { + const domSel = activeWindow.getSelection(); + if (!domSel || domSel.rangeCount === 0 || !domSel.isCollapsed) return false; + const node = domSel.anchorNode; + if (!node || !isInQuotableChatText(node)) return false; + const file = (chatLeafContaining(node)?.view as { file?: { path: string } | null } | undefined)?.file; + return file?.path === path; + } catch { + return false; + } +} + /** * Whether the leaf currently holds a *live but collapsed* selection — i.e. the * user has placed a cursor / clicked inside it with no text range. Used to @@ -149,6 +220,14 @@ function selectionCharBudget(): number { * window so a huge selection can't dominate (or overflow) the request. */ export function formatSelectionContext(ref: SelectionRef): string { const { text } = truncateToBudget(ref.text, selectionCharBudget()); + if (ref.viewType === "chat") { + // A chat path means nothing to the model, and a quote from the same thread + // is text it has already seen: what the user adds is *which part* they mean. + const header = ref.sameThread + ? "[Quoted from earlier in this conversation]" + : `[Quoted from the chat "${ref.basename}" (${ref.path})]`; + return `${header}\n${text}`; + } return `[Selected text from ${ref.path}]\n${text}`; } @@ -156,6 +235,11 @@ export function formatSelectionContext(ref: SelectionRef): string { * Reactive tracker for user text selections in the main workspace area. * Polls the active leaf for non-empty selections and exposes a snapshot * that persists even after focus moves to the chat input. + * + * Selections in a chat's own message text are tracked too, but never shown + * live: people select chat text to copy it far more often than to ask about + * it. They are held as a candidate and only become the selection when the + * user engages a composer (`pinChatSelection`). */ export class SelectionTracker { readonly #workspace = getPlugin().app.workspace; @@ -164,6 +248,8 @@ export class SelectionTracker { #refreshFrame: number | undefined; /** When true, selection was pinned (focus left the note) and should be kept. */ #pinned = false; + /** Latest selection in chat message text, waiting for the composer to be engaged. */ + #chatCandidate: CapturedSelection | undefined; readonly #handleSelectionChange = () => this.#scheduleRefresh(); /** The current captured selection ref (serializable). */ @@ -200,7 +286,38 @@ export class SelectionTracker { }); } + /** + * Adopt the selection in chat message text as the captured selection and pin + * it. Called when the user presses or focuses the composer of the chat at + * `threadPath`, before that press moves the selection into the editor — the + * candidate from the last refresh covers the case where it already has. + */ + pinChatSelection(threadPath: string | null) { + const captured = getChatSelection() ?? this.#chatCandidate; + if (!captured) return; + this.#chatCandidate = undefined; + if (this.#selectionEqual(this.#selection, captured)) return; + captured.ref.sameThread = threadPath !== null && captured.ref.path === threadPath; + + const previous = this.#selection; + this.#clearHighlights(); + // A note selection this replaces would otherwise be re-adopted from the + // editor's still-live range on the next refresh. + if (previous && previous.ref.viewType !== "chat") this.#clearNativeSelection(previous); + this.#selection = captured; + this.#pin(); + } + #refresh() { + this.#chatCandidate = getChatSelection(); + const pinnedChat = this.#pinned && this.#selection?.ref.viewType === "chat"; + // Clicking into the quoted chat's message text dismisses the pinned quote, + // like placing a cursor in the note that owns a pinned note selection. + if (pinnedChat && !this.#chatCandidate && hasCollapsedChatSelection(this.#selection?.ref.path ?? "")) { + this.clear(); + return; + } + // `activeLeaf` is deprecated; the most recently focused leaf is the one the // active-leaf-change event just fired for, and it is not always a markdown // view (PDFs count), so `getActiveViewOfType` alone is not enough. @@ -223,7 +340,7 @@ export class SelectionTracker { } // User clicked (placed a cursor) with no range in the note that owns the // pinned selection → treat as an intentional dismissal, not a stray blur. - if (!captured && hasCollapsedSelectionInLeaf(activeLeaf)) { + if (!captured && !pinnedChat && hasCollapsedSelectionInLeaf(activeLeaf)) { this.clear(); } return; @@ -282,6 +399,7 @@ export class SelectionTracker { clear() { const cleared = this.#selection; this.#selection = undefined; + this.#chatCandidate = undefined; this.#pinned = false; this.#clearHighlights(); this.#clearNativeSelection(cleared); @@ -327,6 +445,9 @@ export class SelectionTracker { try { const domSel = activeWindow.getSelection(); if (!domSel || domSel.rangeCount === 0) return; + // A chat leaf also holds the composer, where the selection usually is by + // now: only collapse a range that is still in message text. + if (cleared.ref.viewType === "chat" && !isInQuotableChatText(domSel.anchorNode)) return; const container = this.#leafContainerForPath(path); if (container?.contains(domSel.getRangeAt(0).commonAncestorContainer)) { domSel.removeAllRanges(); @@ -338,7 +459,7 @@ export class SelectionTracker { /** Container element of the visible note leaf owning `path`, if any. */ #leafContainerForPath(path: string): HTMLElement | undefined { - for (const type of ["markdown", "pdf"]) { + for (const type of ["markdown", "pdf", VIEW_TYPE_CHAT]) { for (const leaf of this.#workspace.getLeavesOfType(type)) { if ((leaf.view as { file?: { path: string } }).file?.path === path) { return leaf.view.containerEl; @@ -380,6 +501,7 @@ export class SelectionTracker { // Reset our own state + highlights, but leave the user's live selection // intact (don't collapse it just because the chat view unmounted). this.#selection = undefined; + this.#chatCandidate = undefined; this.#pinned = false; this.#clearHighlights(); for (const ref of this.#refs) { diff --git a/test/hooks/chatSelection.test.ts b/test/hooks/chatSelection.test.ts new file mode 100644 index 000000000..4671d0cfd --- /dev/null +++ b/test/hooks/chatSelection.test.ts @@ -0,0 +1,180 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("../../src/stores/dataStore.svelte", () => ({ + getData: () => ({ getSelectedAgent: () => ({ chatModel: undefined }) }), +})); + +import { SelectionTracker, formatSelectionContext, type SelectionRef } from "../../src/hooks/useSelection.svelte"; +import { setPlugin } from "../../src/stores/state.svelte"; +import { VIEW_TYPE_CHAT } from "../../src/views/chat/viewType"; +import type SecondBrainPlugin from "../../src/main"; + +/* -------------------------------------------------------------------------- + * Quoting text from a chat (#591). + * + * A selection in a chat's message text is never shown live (people select chat + * text to copy it); it becomes the captured selection when the composer is + * engaged, and reaches the model framed as a quote rather than as a file. + * ------------------------------------------------------------------------*/ + +const THREAD = "Chats/Planning.chat"; + +function chatLeaf(path: string) { + const containerEl = document.createElement("div"); + containerEl.innerHTML = ` +
+

The second step is wrong.

+
search_notes
+
+

my draft

`; + document.body.appendChild(containerEl); + const basename = path.replace(/^.*\//, "").replace(/\.chat$/, ""); + return { view: { containerEl, file: { path, basename }, getViewType: () => VIEW_TYPE_CHAT } }; +} + +function select(node: Node, start = 0, end = node.textContent?.length ?? 0) { + const range = document.createRange(); + range.setStart(node, start); + range.setEnd(node, end); + const sel = window.getSelection(); + sel?.removeAllRanges(); + sel?.addRange(range); + document.dispatchEvent(new Event("selectionchange")); + flushFrames(); +} + +let frames: FrameRequestCallback[] = []; +function flushFrames() { + const pending = frames; + frames = []; + for (const cb of pending) cb(0); +} + +function caret(node: Node) { + select(node, 1, 1); +} + +let leaves: ReturnType[] = []; + +beforeEach(() => { + (globalThis as { activeWindow?: Window }).activeWindow = window; + frames = []; + vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => { + frames.push(cb); + return frames.length; + }); + leaves = [chatLeaf(THREAD)]; + setPlugin({ + app: { + workspace: { + on: () => ({}), + offref: () => {}, + getMostRecentLeaf: () => null, + getLeavesOfType: (type: string) => (type === VIEW_TYPE_CHAT ? leaves : []), + getActiveViewOfType: () => null, + }, + }, + } as unknown as SecondBrainPlugin); +}); + +afterEach(() => { + window.getSelection()?.removeAllRanges(); + document.body.innerHTML = ""; + vi.restoreAllMocks(); +}); + +function textOf(selector: string, leaf = leaves[0]): Node { + const el = leaf.view.containerEl.querySelector(selector); + if (!el?.firstChild) throw new Error(`missing ${selector}`); + return el.firstChild; +} + +describe("SelectionTracker — chat quotes", () => { + it("holds a chat selection back until the composer is engaged", () => { + const tracker = new SelectionTracker(); + select(textOf(".answer")); + expect(tracker.selection).toBeUndefined(); + + tracker.pinChatSelection(THREAD); + expect(tracker.selection).toMatchObject({ + path: THREAD, + basename: "Planning", + viewType: "chat", + text: "The second step is wrong.", + sameThread: true, + }); + tracker.destroy(); + }); + + it("still pins the selection after the press already moved it into the editor", () => { + const tracker = new SelectionTracker(); + select(textOf(".answer"), 4, 10); + // The press collapsed the selection before the composer's handler ran. + window.getSelection()?.removeAllRanges(); + tracker.pinChatSelection(THREAD); + expect(tracker.selection?.text).toBe("second"); + tracker.destroy(); + }); + + it("ignores selections outside message text", () => { + const tracker = new SelectionTracker(); + select(textOf(".tool-label")); + tracker.pinChatSelection(THREAD); + expect(tracker.selection).toBeUndefined(); + + select(textOf(".draft")); + tracker.pinChatSelection(THREAD); + expect(tracker.selection).toBeUndefined(); + tracker.destroy(); + }); + + it("marks a quote from another chat as such", () => { + leaves.push(chatLeaf("Chats/Other.chat")); + const tracker = new SelectionTracker(); + select(textOf(".answer", leaves[1])); + tracker.pinChatSelection(THREAD); + expect(tracker.selection).toMatchObject({ path: "Chats/Other.chat", sameThread: false }); + tracker.destroy(); + }); + + it("keeps the pinned quote while typing, and drops it on a click into message text", () => { + const tracker = new SelectionTracker(); + select(textOf(".answer")); + tracker.pinChatSelection(THREAD); + + caret(textOf(".draft")); + expect(tracker.selection?.viewType).toBe("chat"); + + caret(textOf(".answer")); + expect(tracker.selection).toBeUndefined(); + tracker.destroy(); + }); +}); + +describe("formatSelectionContext — chat quotes", () => { + const base: SelectionRef = { + path: THREAD, + basename: "Planning", + viewType: "chat", + text: "Step two", + icon: "quote", + }; + + it("frames a same-thread selection as a quote of the conversation", () => { + expect(formatSelectionContext({ ...base, sameThread: true })).toBe( + "[Quoted from earlier in this conversation]\nStep two", + ); + }); + + it("names the chat a cross-thread quote came from", () => { + expect(formatSelectionContext({ ...base, sameThread: false })).toBe( + '[Quoted from the chat "Planning" (Chats/Planning.chat)]\nStep two', + ); + }); + + it("leaves note selections unchanged", () => { + expect(formatSelectionContext({ ...base, viewType: "markdown", path: "Notes/A.md" })).toBe( + "[Selected text from Notes/A.md]\nStep two", + ); + }); +}); From 3b8c32a86e1a8d60be8f08257b729cb1714bddad Mon Sep 17 00:00:00 2001 From: Leo310 Date: Wed, 25 Nov 2026 19:58:05 +0100 Subject: [PATCH 2/6] fix(chat): tighten chat quotes per review - A selection spanning several messages keeps only their text: the UI between them (an expanded tool card's output, footers) is cut out, one clamped range per message element. - Whether a quote comes from the same thread is decided at send time, not when it was pinned, so a quote that outlives the composer switching threads is no longer sent as "this conversation". - selectionchange is listened on every window document (popouts too), and the pinned highlight is registered on the window that owns it. Co-Authored-By: Claude --- src/components/chat/ContextTray.svelte | 4 +- src/components/chat/Input.svelte | 12 +++- src/hooks/useSelection.svelte.ts | 87 ++++++++++++++++++++------ test/hooks/chatSelection.test.ts | 33 +++++++--- 4 files changed, 103 insertions(+), 33 deletions(-) diff --git a/src/components/chat/ContextTray.svelte b/src/components/chat/ContextTray.svelte index 21409c1db..c3d8209e0 100644 --- a/src/components/chat/ContextTray.svelte +++ b/src/components/chat/ContextTray.svelte @@ -220,8 +220,8 @@ function onSelectionClick(evt: MouseEvent): void { /** Adopt a selection in chat message text (see `SelectionTracker.pinChatSelection`). * The composer calls this when it is pressed or focused. */ -export function pinChatSelection(threadPath: string | null): void { - selectionTracker.pinChatSelection(threadPath); +export function pinChatSelection(): void { + selectionTracker.pinChatSelection(); } function dismissSelection(): void { diff --git a/src/components/chat/Input.svelte b/src/components/chat/Input.svelte index ed15498ef..3a7d4a45d 100644 --- a/src/components/chat/Input.svelte +++ b/src/components/chat/Input.svelte @@ -804,7 +804,7 @@ function sendMessage() { contentToSend, attachments.length > 0 ? [...attachments] : undefined, activeVisibleNotes.length > 0 ? [...activeVisibleNotes] : undefined, - activeSelection ? { ...activeSelection } : undefined, + activeSelection ? withQuoteDestination(activeSelection) : undefined, activeGraphNotes.length > 0 ? [...activeGraphNotes] : undefined, ) .catch((error) => { @@ -1302,7 +1302,15 @@ async function promoteVisibleNoteToAttachment(note: VisibleNote) { // the composer. Capture phase, so it runs before the press moves the selection // into the editor and collapses it. function pinChatSelection(): void { - contextTrayRef?.pinChatSelection(threadPath); + contextTrayRef?.pinChatSelection(); +} + +/** Snapshot of the selection to send. A chat quote is told here, at send time, + * whether it comes from the thread it is sent in: a pinned quote outlives the + * composer switching threads, so the thread it was pinned in says nothing. */ +function withQuoteDestination(selection: SelectionRef): SelectionRef { + if (selection.viewType !== "chat") return { ...selection }; + return { ...selection, sameThread: threadPath !== null && selection.path === threadPath }; } diff --git a/src/hooks/useSelection.svelte.ts b/src/hooks/useSelection.svelte.ts index bbfedddb6..c0e5b2641 100644 --- a/src/hooks/useSelection.svelte.ts +++ b/src/hooks/useSelection.svelte.ts @@ -14,9 +14,9 @@ export interface SelectionRef { text: string; icon: string; /** Chat selections only (`viewType: "chat"`): whether the text was quoted from the - * same conversation it was sent in. Fixed at capture time, because the context block - * is rebuilt from this ref to strip it again and a thread's path changes when it is - * auto-titled. */ + * same conversation it was sent in. Set on the snapshot at send time and stored with + * the message, because the context block is rebuilt from this ref to strip it again + * and a thread's path changes when it is auto-titled. */ sameThread?: boolean; } @@ -51,7 +51,32 @@ function chatLeafContaining(node: Node): WorkspaceLeaf | undefined { } /** - * The live selection when it lies in message text of a chat view. Read from the + * The part of `range` that lies in quotable message text of `container`, one + * clamped range per message element. A drag from one message to another passes + * over the UI between them (an expanded tool card's output, footers); that text + * is not what the user means to quote, so it is cut out rather than sent. + */ +function quotableSlices(range: Range, container: HTMLElement): Range[] { + const slices: Range[] = []; + for (const el of container.querySelectorAll(QUOTABLE_CHAT_SELECTOR)) { + // A quotable element nested in another is covered by its ancestor's slice. + if (el.parentElement?.closest(QUOTABLE_CHAT_SELECTOR)) continue; + if (!range.intersectsNode(el)) continue; + const slice = el.ownerDocument.createRange(); + slice.selectNodeContents(el); + if (slice.compareBoundaryPoints(Range.START_TO_START, range) < 0) { + slice.setStart(range.startContainer, range.startOffset); + } + if (slice.compareBoundaryPoints(Range.END_TO_END, range) > 0) { + slice.setEnd(range.endContainer, range.endOffset); + } + if (!slice.collapsed && slice.toString().trim()) slices.push(slice); + } + return slices; +} + +/** + * The live selection when it covers message text of a chat view. Read from the * DOM rather than the active leaf: a sidebar chat never becomes the "most recent" * leaf, so the leaf the selection is in has to be found from the selection itself. */ @@ -61,19 +86,18 @@ function getChatSelection(): CapturedSelection | undefined { if (!domSel || domSel.rangeCount === 0 || domSel.isCollapsed) return undefined; const { anchorNode, focusNode } = domSel; if (!anchorNode || !focusNode) return undefined; - if (!isInQuotableChatText(anchorNode) || !isInQuotableChatText(focusNode)) return undefined; const leaf = chatLeafContaining(anchorNode); if (!leaf || !leaf.view.containerEl.contains(focusNode)) return undefined; const file = (leaf.view as { file?: { path: string; basename: string } | null }).file; if (!file) return undefined; - const text = domSel.toString(); - if (!text.trim()) return undefined; - const domRanges: Range[] = []; for (let i = 0; i < domSel.rangeCount; i++) { - domRanges.push(domSel.getRangeAt(i).cloneRange()); + domRanges.push(...quotableSlices(domSel.getRangeAt(i), leaf.view.containerEl)); } + if (domRanges.length === 0) return undefined; + const text = domRanges.map((r) => r.toString()).join("\n\n"); + return { ref: { path: file.path, basename: file.basename, viewType: "chat", text, icon: VIEW_ICONS.chat }, domRanges, @@ -251,6 +275,9 @@ export class SelectionTracker { /** Latest selection in chat message text, waiting for the composer to be engaged. */ #chatCandidate: CapturedSelection | undefined; readonly #handleSelectionChange = () => this.#scheduleRefresh(); + /** Every window document `selectionchange` is listened on: the main one plus + * each popout window's, since the event never crosses documents. */ + readonly #listenedDocs = new Set(); /** The current captured selection ref (serializable). */ get selection(): SelectionRef | undefined { @@ -275,7 +302,23 @@ export class SelectionTracker { this.#scheduleRefresh(); }), ]; - document.addEventListener("selectionchange", this.#handleSelectionChange); + this.#listen(document); + this.#workspace.iterateAllLeaves((leaf) => this.#listen(leaf.view.containerEl.ownerDocument)); + this.#refs.push( + this.#workspace.on("window-open", (win) => this.#listen(win.doc)), + this.#workspace.on("window-close", (win) => this.#unlisten(win.doc)), + ); + } + + #listen(doc: Document) { + if (this.#listenedDocs.has(doc)) return; + this.#listenedDocs.add(doc); + doc.addEventListener("selectionchange", this.#handleSelectionChange); + } + + #unlisten(doc: Document) { + if (!this.#listenedDocs.delete(doc)) return; + doc.removeEventListener("selectionchange", this.#handleSelectionChange); } #scheduleRefresh() { @@ -288,16 +331,15 @@ export class SelectionTracker { /** * Adopt the selection in chat message text as the captured selection and pin - * it. Called when the user presses or focuses the composer of the chat at - * `threadPath`, before that press moves the selection into the editor — the - * candidate from the last refresh covers the case where it already has. + * it. Called when the user presses or focuses a composer, before that press + * moves the selection into the editor — the candidate from the last refresh + * covers the case where it already has. */ - pinChatSelection(threadPath: string | null) { + pinChatSelection() { const captured = getChatSelection() ?? this.#chatCandidate; if (!captured) return; this.#chatCandidate = undefined; if (this.#selectionEqual(this.#selection, captured)) return; - captured.ref.sameThread = threadPath !== null && captured.ref.path === threadPath; const previous = this.#selection; this.#clearHighlights(); @@ -385,9 +427,12 @@ export class SelectionTracker { // Reading / PDF: use CSS Custom Highlight API if (captured.domRanges?.length) { try { - if (CSS.highlights) { - const highlight = new Highlight(...captured.domRanges); - CSS.highlights.set("s2b-selection", highlight); + // Each window has its own highlight registry and `Highlight` class: a + // range in a popout only paints when registered on that popout's. + const win = (captured.domRanges[0].startContainer.ownerDocument?.defaultView ?? window) as Window & + typeof globalThis; + if (win.CSS?.highlights) { + win.CSS.highlights.set("s2b-selection", new win.Highlight(...captured.domRanges)); } } catch { /* API may not be available */ @@ -485,7 +530,9 @@ export class SelectionTracker { // Remove CSS Highlight API highlights try { - CSS.highlights?.delete("s2b-selection"); + for (const doc of new Set([document, ...this.#listenedDocs])) { + (doc.defaultView as (Window & typeof globalThis) | null)?.CSS?.highlights?.delete("s2b-selection"); + } } catch { /* safety */ } @@ -508,7 +555,7 @@ export class SelectionTracker { this.#workspace.offref(ref); } this.#refs = []; - document.removeEventListener("selectionchange", this.#handleSelectionChange); + for (const doc of [...this.#listenedDocs]) this.#unlisten(doc); if (this.#refreshFrame !== undefined) { cancelAnimationFrame(this.#refreshFrame); this.#refreshFrame = undefined; diff --git a/test/hooks/chatSelection.test.ts b/test/hooks/chatSelection.test.ts index 4671d0cfd..917911885 100644 --- a/test/hooks/chatSelection.test.ts +++ b/test/hooks/chatSelection.test.ts @@ -25,6 +25,7 @@ function chatLeaf(path: string) {

The second step is wrong.

search_notes
+

Use step three instead.

my draft

`; document.body.appendChild(containerEl); @@ -72,6 +73,7 @@ beforeEach(() => { getMostRecentLeaf: () => null, getLeavesOfType: (type: string) => (type === VIEW_TYPE_CHAT ? leaves : []), getActiveViewOfType: () => null, + iterateAllLeaves: (cb: (leaf: unknown) => void) => leaves.forEach(cb), }, }, } as unknown as SecondBrainPlugin); @@ -95,13 +97,12 @@ describe("SelectionTracker — chat quotes", () => { select(textOf(".answer")); expect(tracker.selection).toBeUndefined(); - tracker.pinChatSelection(THREAD); + tracker.pinChatSelection(); expect(tracker.selection).toMatchObject({ path: THREAD, basename: "Planning", viewType: "chat", text: "The second step is wrong.", - sameThread: true, }); tracker.destroy(); }); @@ -111,7 +112,7 @@ describe("SelectionTracker — chat quotes", () => { select(textOf(".answer"), 4, 10); // The press collapsed the selection before the composer's handler ran. window.getSelection()?.removeAllRanges(); - tracker.pinChatSelection(THREAD); + tracker.pinChatSelection(); expect(tracker.selection?.text).toBe("second"); tracker.destroy(); }); @@ -119,28 +120,42 @@ describe("SelectionTracker — chat quotes", () => { it("ignores selections outside message text", () => { const tracker = new SelectionTracker(); select(textOf(".tool-label")); - tracker.pinChatSelection(THREAD); + tracker.pinChatSelection(); expect(tracker.selection).toBeUndefined(); select(textOf(".draft")); - tracker.pinChatSelection(THREAD); + tracker.pinChatSelection(); expect(tracker.selection).toBeUndefined(); tracker.destroy(); }); - it("marks a quote from another chat as such", () => { + it("records which chat a quote came from", () => { leaves.push(chatLeaf("Chats/Other.chat")); const tracker = new SelectionTracker(); select(textOf(".answer", leaves[1])); - tracker.pinChatSelection(THREAD); - expect(tracker.selection).toMatchObject({ path: "Chats/Other.chat", sameThread: false }); + tracker.pinChatSelection(); + expect(tracker.selection).toMatchObject({ path: "Chats/Other.chat", basename: "Other" }); + tracker.destroy(); + }); + + it("cuts the UI between two messages out of a selection spanning both", () => { + const tracker = new SelectionTracker(); + const range = document.createRange(); + range.setStart(textOf(".answer"), 4); + range.setEnd(textOf(".final"), 3); + window.getSelection()?.removeAllRanges(); + window.getSelection()?.addRange(range); + document.dispatchEvent(new Event("selectionchange")); + flushFrames(); + tracker.pinChatSelection(); + expect(tracker.selection?.text).toBe("second step is wrong.\n\nUse"); tracker.destroy(); }); it("keeps the pinned quote while typing, and drops it on a click into message text", () => { const tracker = new SelectionTracker(); select(textOf(".answer")); - tracker.pinChatSelection(THREAD); + tracker.pinChatSelection(); caret(textOf(".draft")); expect(tracker.selection?.viewType).toBe("chat"); From 3eb5244fce490e3caeb366d700fd63fb2190f2b9 Mon Sep 17 00:00:00 2001 From: Leo310 Date: Wed, 25 Nov 2026 20:01:26 +0100 Subject: [PATCH 3/6] fix(chat): keep a pinned quote on its chat across renames A chat auto-titles itself after its first turn. A quote pinned from it kept the old path, so at send time it no longer matched the composer's thread and went out labelled as coming from another chat. Co-Authored-By: Claude --- src/hooks/useSelection.svelte.ts | 14 ++++++++++++++ test/hooks/chatSelection.test.ts | 20 ++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/hooks/useSelection.svelte.ts b/src/hooks/useSelection.svelte.ts index c0e5b2641..9bdd5d822 100644 --- a/src/hooks/useSelection.svelte.ts +++ b/src/hooks/useSelection.svelte.ts @@ -269,6 +269,7 @@ export class SelectionTracker { readonly #workspace = getPlugin().app.workspace; #selection: CapturedSelection | undefined = $state(undefined); #refs: EventRef[] = []; + #vaultRefs: EventRef[] = []; #refreshFrame: number | undefined; /** When true, selection was pinned (focus left the note) and should be kept. */ #pinned = false; @@ -302,6 +303,17 @@ export class SelectionTracker { this.#scheduleRefresh(); }), ]; + // A chat renames itself after its first turn (auto-title). A quote pinned + // from it must follow, or it would no longer match the composer's thread + // at send time and be labelled as coming from another chat. + this.#vaultRefs.push( + getPlugin().app.vault.on("rename", (file, oldPath) => { + const ref = this.#selection?.ref; + if (!this.#selection || ref?.viewType !== "chat" || ref.path !== oldPath) return; + const basename = (file as { basename?: string }).basename ?? ref.basename; + this.#selection = { ...this.#selection, ref: { ...ref, path: file.path, basename } }; + }), + ); this.#listen(document); this.#workspace.iterateAllLeaves((leaf) => this.#listen(leaf.view.containerEl.ownerDocument)); this.#refs.push( @@ -555,6 +567,8 @@ export class SelectionTracker { this.#workspace.offref(ref); } this.#refs = []; + for (const ref of this.#vaultRefs) getPlugin().app.vault.offref(ref); + this.#vaultRefs = []; for (const doc of [...this.#listenedDocs]) this.#unlisten(doc); if (this.#refreshFrame !== undefined) { cancelAnimationFrame(this.#refreshFrame); diff --git a/test/hooks/chatSelection.test.ts b/test/hooks/chatSelection.test.ts index 917911885..c23745f48 100644 --- a/test/hooks/chatSelection.test.ts +++ b/test/hooks/chatSelection.test.ts @@ -56,6 +56,7 @@ function caret(node: Node) { } let leaves: ReturnType[] = []; +let renameHandler: ((file: { path: string; basename: string }, oldPath: string) => void) | undefined; beforeEach(() => { (globalThis as { activeWindow?: Window }).activeWindow = window; @@ -65,8 +66,16 @@ beforeEach(() => { return frames.length; }); leaves = [chatLeaf(THREAD)]; + renameHandler = undefined; setPlugin({ app: { + vault: { + on: (_name: string, cb: typeof renameHandler) => { + renameHandler = cb; + return {}; + }, + offref: () => {}, + }, workspace: { on: () => ({}), offref: () => {}, @@ -166,6 +175,17 @@ describe("SelectionTracker — chat quotes", () => { }); }); +describe("SelectionTracker — renamed chats", () => { + it("moves a pinned quote along when its chat is auto-titled", () => { + const tracker = new SelectionTracker(); + select(textOf(".answer")); + tracker.pinChatSelection(); + renameHandler?.({ path: "Chats/Roadmap.chat", basename: "Roadmap" }, THREAD); + expect(tracker.selection).toMatchObject({ path: "Chats/Roadmap.chat", basename: "Roadmap" }); + tracker.destroy(); + }); +}); + describe("formatSelectionContext — chat quotes", () => { const base: SelectionRef = { path: THREAD, From 9e02996818c23fa4acb1d41f39da187a4aa63d47 Mon Sep 17 00:00:00 2001 From: Leo310 Date: Thu, 26 Nov 2026 11:56:20 +0100 Subject: [PATCH 4/6] feat(chat): show the quote chip as soon as chat text is selected A chat selection now shows its chip live, like a note selection. The composer still pins it; a selection that collapses before that (copied, then clicked away) drops the chip. Co-Authored-By: Claude --- src/components/chat/ContextTray.svelte | 2 +- src/components/chat/Input.svelte | 6 +-- src/hooks/useSelection.svelte.ts | 58 +++++++++++++++----------- test/hooks/chatSelection.test.ts | 21 ++++++---- 4 files changed, 51 insertions(+), 36 deletions(-) diff --git a/src/components/chat/ContextTray.svelte b/src/components/chat/ContextTray.svelte index c3d8209e0..cb3a1fbd0 100644 --- a/src/components/chat/ContextTray.svelte +++ b/src/components/chat/ContextTray.svelte @@ -218,7 +218,7 @@ function onSelectionClick(evt: MouseEvent): void { dismissSelection(); } -/** Adopt a selection in chat message text (see `SelectionTracker.pinChatSelection`). +/** Keep the quote chip of a selection in chat message text (see `SelectionTracker.pinChatSelection`). * The composer calls this when it is pressed or focused. */ export function pinChatSelection(): void { selectionTracker.pinChatSelection(); diff --git a/src/components/chat/Input.svelte b/src/components/chat/Input.svelte index 3a7d4a45d..29a28e09a 100644 --- a/src/components/chat/Input.svelte +++ b/src/components/chat/Input.svelte @@ -1298,9 +1298,9 @@ async function promoteVisibleNoteToAttachment(note: VisibleNote) { savingFiles = false; } } -// Text selected in a chat's messages becomes a quote only once the user turns to -// the composer. Capture phase, so it runs before the press moves the selection -// into the editor and collapses it. +// Text selected in a chat's messages shows as a quote chip at once, but it is +// kept only once the user turns to the composer. Capture phase, so it runs +// before the press moves the selection into the editor and collapses it. function pinChatSelection(): void { contextTrayRef?.pinChatSelection(); } diff --git a/src/hooks/useSelection.svelte.ts b/src/hooks/useSelection.svelte.ts index 9bdd5d822..dea47f3ca 100644 --- a/src/hooks/useSelection.svelte.ts +++ b/src/hooks/useSelection.svelte.ts @@ -260,10 +260,11 @@ export function formatSelectionContext(ref: SelectionRef): string { * Polls the active leaf for non-empty selections and exposes a snapshot * that persists even after focus moves to the chat input. * - * Selections in a chat's own message text are tracked too, but never shown - * live: people select chat text to copy it far more often than to ask about - * it. They are held as a candidate and only become the selection when the - * user engages a composer (`pinChatSelection`). + * Selections in a chat's own message text are tracked too, and shown live + * like a note selection. A chat leaf holds the composer as well, so engaging + * it changes no active leaf: the composer pins the quote itself + * (`pinChatSelection`). Until then a chat selection that collapses (copied, + * then clicked away) drops its chip. */ export class SelectionTracker { readonly #workspace = getPlugin().app.workspace; @@ -273,8 +274,6 @@ export class SelectionTracker { #refreshFrame: number | undefined; /** When true, selection was pinned (focus left the note) and should be kept. */ #pinned = false; - /** Latest selection in chat message text, waiting for the composer to be engaged. */ - #chatCandidate: CapturedSelection | undefined; readonly #handleSelectionChange = () => this.#scheduleRefresh(); /** Every window document `selectionchange` is listened on: the main one plus * each popout window's, since the event never crosses documents. */ @@ -296,8 +295,9 @@ export class SelectionTracker { this.#refs = [ this.#workspace.on("active-leaf-change", () => { // When focus leaves a note (e.g. to the chat sidebar), - // pin whatever we captured so the chip stays. - if (this.#selection && !this.#pinned) { + // pin whatever we captured so the chip stays. A chat quote is pinned + // only by its composer: leaving the chat for a note drops it. + if (this.#selection && !this.#pinned && this.#selection.ref.viewType !== "chat") { this.#pin(); } this.#scheduleRefresh(); @@ -342,35 +342,45 @@ export class SelectionTracker { } /** - * Adopt the selection in chat message text as the captured selection and pin - * it. Called when the user presses or focuses a composer, before that press - * moves the selection into the editor — the candidate from the last refresh - * covers the case where it already has. + * Pin the chat quote the chip shows. Called when the user presses or focuses + * a composer, before that press moves the selection into the editor; the + * chip adopted on the last refresh covers the case where it already has. */ pinChatSelection() { - const captured = getChatSelection() ?? this.#chatCandidate; - if (!captured) return; - this.#chatCandidate = undefined; - if (this.#selectionEqual(this.#selection, captured)) return; + const live = getChatSelection(); + if (live && !this.#selectionEqual(this.#selection, live)) this.#adoptChatSelection(live); + if (this.#selection?.ref.viewType === "chat" && !this.#pinned) this.#pin(); + } + /** Show a chat selection as the (unpinned) captured selection. */ + #adoptChatSelection(captured: CapturedSelection) { const previous = this.#selection; this.#clearHighlights(); // A note selection this replaces would otherwise be re-adopted from the // editor's still-live range on the next refresh. if (previous && previous.ref.viewType !== "chat") this.#clearNativeSelection(previous); + this.#pinned = false; this.#selection = captured; - this.#pin(); } #refresh() { - this.#chatCandidate = getChatSelection(); - const pinnedChat = this.#pinned && this.#selection?.ref.viewType === "chat"; - // Clicking into the quoted chat's message text dismisses the pinned quote, - // like placing a cursor in the note that owns a pinned note selection. - if (pinnedChat && !this.#chatCandidate && hasCollapsedChatSelection(this.#selection?.ref.path ?? "")) { - this.clear(); + const chat = getChatSelection(); + if (chat) { + if (!this.#selectionEqual(this.#selection, chat)) this.#adoptChatSelection(chat); return; } + if (this.#selection?.ref.viewType === "chat") { + // The selection was never taken to a composer: it was copied, or the + // user clicked away. Drop the chip and look for a note selection. + if (!this.#pinned) this.#selection = undefined; + // Clicking into the quoted chat's message text dismisses the pinned quote, + // like placing a cursor in the note that owns a pinned note selection. + else if (hasCollapsedChatSelection(this.#selection.ref.path)) { + this.clear(); + return; + } + } + const pinnedChat = this.#pinned && this.#selection?.ref.viewType === "chat"; // `activeLeaf` is deprecated; the most recently focused leaf is the one the // active-leaf-change event just fired for, and it is not always a markdown @@ -456,7 +466,6 @@ export class SelectionTracker { clear() { const cleared = this.#selection; this.#selection = undefined; - this.#chatCandidate = undefined; this.#pinned = false; this.#clearHighlights(); this.#clearNativeSelection(cleared); @@ -560,7 +569,6 @@ export class SelectionTracker { // Reset our own state + highlights, but leave the user's live selection // intact (don't collapse it just because the chat view unmounted). this.#selection = undefined; - this.#chatCandidate = undefined; this.#pinned = false; this.#clearHighlights(); for (const ref of this.#refs) { diff --git a/test/hooks/chatSelection.test.ts b/test/hooks/chatSelection.test.ts index c23745f48..2a6e5fdd9 100644 --- a/test/hooks/chatSelection.test.ts +++ b/test/hooks/chatSelection.test.ts @@ -12,9 +12,9 @@ import type SecondBrainPlugin from "../../src/main"; /* -------------------------------------------------------------------------- * Quoting text from a chat (#591). * - * A selection in a chat's message text is never shown live (people select chat - * text to copy it); it becomes the captured selection when the composer is - * engaged, and reaches the model framed as a quote rather than as a file. + * A selection in a chat's message text shows as a chip at once, like a note + * selection; it is kept once the composer is engaged, and reaches the model + * framed as a quote rather than as a file. * ------------------------------------------------------------------------*/ const THREAD = "Chats/Planning.chat"; @@ -101,12 +101,9 @@ function textOf(selector: string, leaf = leaves[0]): Node { } describe("SelectionTracker — chat quotes", () => { - it("holds a chat selection back until the composer is engaged", () => { + it("shows a chat selection as soon as it is made", () => { const tracker = new SelectionTracker(); select(textOf(".answer")); - expect(tracker.selection).toBeUndefined(); - - tracker.pinChatSelection(); expect(tracker.selection).toMatchObject({ path: THREAD, basename: "Planning", @@ -116,6 +113,16 @@ describe("SelectionTracker — chat quotes", () => { tracker.destroy(); }); + it("drops the chip when the selection goes away without the composer being engaged", () => { + const tracker = new SelectionTracker(); + select(textOf(".answer")); + window.getSelection()?.removeAllRanges(); + document.dispatchEvent(new Event("selectionchange")); + flushFrames(); + expect(tracker.selection).toBeUndefined(); + tracker.destroy(); + }); + it("still pins the selection after the press already moved it into the editor", () => { const tracker = new SelectionTracker(); select(textOf(".answer"), 4, 10); From 6ca0c9cefa12fc36c4d96699c8c81bf18368187a Mon Sep 17 00:00:00 2001 From: Leo310 Date: Thu, 26 Nov 2026 12:04:14 +0100 Subject: [PATCH 5/6] feat(chat): give every selection chip the quote icon A selection is a quote wherever it came from; the icon also sets its chip apart from the file chips of visible notes. The icon is no longer stored on the SelectionRef; an icon on older persisted refs is ignored. Co-Authored-By: Claude --- src/components/chat/ContextTray.svelte | 4 ++-- src/components/chat/MessageContainer.svelte | 3 ++- src/hooks/useSelection.svelte.ts | 16 ++++++---------- test/hooks/chatSelection.test.ts | 1 - 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/src/components/chat/ContextTray.svelte b/src/components/chat/ContextTray.svelte index cb3a1fbd0..d5212f57b 100644 --- a/src/components/chat/ContextTray.svelte +++ b/src/components/chat/ContextTray.svelte @@ -7,7 +7,7 @@ import { type VisibleNote, type VisibleNoteRef, } from "../../hooks/useVisibleNotes.svelte"; -import { SelectionTracker, type SelectionRef } from "../../hooks/useSelection.svelte"; +import { SELECTION_ICON, SelectionTracker, type SelectionRef } from "../../hooks/useSelection.svelte"; import type { GraphNoteRef } from "../../stores/chatTimeline"; import type { ChatAttachment } from "../../types/shared"; import { getPlugin } from "../../stores/state.svelte"; @@ -433,7 +433,7 @@ onDestroy(() => { })} onclick={onSelectionClick} > -
+
{selectionPreview(activeSelection.text)} {#if selectionTracker.isLong} ⚠ diff --git a/src/components/chat/MessageContainer.svelte b/src/components/chat/MessageContainer.svelte index 21b83ded8..5187e268a 100755 --- a/src/components/chat/MessageContainer.svelte +++ b/src/components/chat/MessageContainer.svelte @@ -29,6 +29,7 @@ import AssistantStatusNotice from "./AssistantStatusNotice.svelte"; import ToolCallsSection from "./ToolCallsSection.svelte"; import ChatRecommendations from "./ChatRecommendations.svelte"; import { icon } from "../../utils/utils"; +import { SELECTION_ICON } from "../../hooks/useSelection.svelte"; import { getLocale, t } from "../../i18n"; interface Props { @@ -813,7 +814,7 @@ $effect(() => { onmouseover={(evt) => previewReferencedNote(evt, selection.path)} onfocus={(evt) => previewReferencedNote(evt, selection.path)} > - {selection.basename} diff --git a/src/hooks/useSelection.svelte.ts b/src/hooks/useSelection.svelte.ts index dea47f3ca..a39a44742 100644 --- a/src/hooks/useSelection.svelte.ts +++ b/src/hooks/useSelection.svelte.ts @@ -12,7 +12,6 @@ export interface SelectionRef { basename: string; viewType: string; text: string; - icon: string; /** Chat selections only (`viewType: "chat"`): whether the text was quoted from the * same conversation it was sent in. Set on the snapshot at send time and stored with * the message, because the context block is rebuilt from this ref to strip it again @@ -28,11 +27,10 @@ interface CapturedSelection { domRanges?: Range[]; } -const VIEW_ICONS: Record = { - markdown: "file-text", - pdf: "file-type", - chat: "quote", -}; +/** Icon of a selection chip. Every selection is a quote, wherever it came from: + * the icon tells it apart from the file chips of visible notes, and the tooltip + * names the source. Old persisted refs may still carry an `icon`; it is ignored. */ +export const SELECTION_ICON = "quote"; /** Message text inside a chat view that can be quoted: rendered assistant text * (including the text segments of a tool timeline) and the user's own bubbles. @@ -99,7 +97,7 @@ function getChatSelection(): CapturedSelection | undefined { const text = domRanges.map((r) => r.toString()).join("\n\n"); return { - ref: { path: file.path, basename: file.basename, viewType: "chat", text, icon: VIEW_ICONS.chat }, + ref: { path: file.path, basename: file.basename, viewType: "chat", text }, domRanges, }; } catch { @@ -191,7 +189,6 @@ function getSelectionFromLeaf(leaf: WorkspaceLeaf): CapturedSelection | undefine basename: file.basename, viewType: "markdown", text, - icon: VIEW_ICONS.markdown, }, cmRanges: ranges.map((r: { from: number; to: number }) => ({ from: r.from, to: r.to })), }; @@ -220,9 +217,8 @@ function getSelectionFromLeaf(leaf: WorkspaceLeaf): CapturedSelection | undefine domRanges.push(domSel.getRangeAt(i).cloneRange()); } - const icon = viewType === "pdf" ? VIEW_ICONS.pdf : VIEW_ICONS.markdown; return { - ref: { path: file.path, basename: file.basename, viewType, text, icon }, + ref: { path: file.path, basename: file.basename, viewType, text }, domRanges, }; } catch { diff --git a/test/hooks/chatSelection.test.ts b/test/hooks/chatSelection.test.ts index 2a6e5fdd9..3763d68aa 100644 --- a/test/hooks/chatSelection.test.ts +++ b/test/hooks/chatSelection.test.ts @@ -199,7 +199,6 @@ describe("formatSelectionContext — chat quotes", () => { basename: "Planning", viewType: "chat", text: "Step two", - icon: "quote", }; it("frames a same-thread selection as a quote of the conversation", () => { From bc138edd8d071cdad582d87668545fa54f45827f Mon Sep 17 00:00:00 2001 From: Leo310 Date: Thu, 26 Nov 2026 12:14:12 +0100 Subject: [PATCH 6/6] fix(chat): keep the highlight on a pinned note selection in edit mode The highlight went to the active Markdown view, but a note selection is pinned on active-leaf-change, when the active view is already the chat, so no editor ever got it. Find the editor that owns the selection by path. Co-Authored-By: Claude --- src/hooks/useSelection.svelte.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/hooks/useSelection.svelte.ts b/src/hooks/useSelection.svelte.ts index a39a44742..7edd7d6ce 100644 --- a/src/hooks/useSelection.svelte.ts +++ b/src/hooks/useSelection.svelte.ts @@ -429,12 +429,16 @@ export class SelectionTracker { const captured = this.#selection; - // CM6 edit mode: dispatch decoration marks + // CM6 edit mode: dispatch decoration marks into the editor that owns the + // selection. Found by path, not as the active view: pinning happens on + // active-leaf-change, by which time the active view is the chat. if (captured.cmRanges?.length) { try { - const activeView = this.#workspace.getActiveViewOfType(MarkdownView); - if (activeView) { - const cm = getEditorView(activeView.editor); + for (const leaf of this.#workspace.getLeavesOfType("markdown")) { + const view = leaf.view; + if (!(view instanceof MarkdownView) || view.getMode() !== "source") continue; + if (view.file?.path !== captured.ref.path) continue; + const cm = getEditorView(view.editor); if (cm) setSelectionHighlight(cm, captured.cmRanges); } } catch {