diff --git a/src/components/chat/CollapsibleUserBubble.svelte b/src/components/chat/CollapsibleUserBubble.svelte index 9bdbc14a..25fdb5d3 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 bf25455e..d5212f57 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"; @@ -218,6 +218,12 @@ function onSelectionClick(evt: MouseEvent): void { dismissSelection(); } +/** 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(); +} + function dismissSelection(): void { dismissedSelection = selectionTracker.selection; selectionTracker.clear(); @@ -427,7 +433,7 @@ onDestroy(() => { })} onclick={onSelectionClick} > -
+
{selectionPreview(activeSelection.text)} {#if selectionTracker.isLong} ⚠ diff --git a/src/components/chat/Input.svelte b/src/components/chat/Input.svelte index f7dc1891..29a28e09 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) => { @@ -1298,6 +1298,20 @@ async function promoteVisibleNoteToAttachment(note: VisibleNote) { savingFiles = false; } } +// 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(); +} + +/** 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 }; +}
{ 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 1e7c7cf8..7edd7d6c 100644 --- a/src/hooks/useSelection.svelte.ts +++ b/src/hooks/useSelection.svelte.ts @@ -4,6 +4,7 @@ import { getData } from "../stores/dataStore.svelte"; import { clearSelectionHighlight, setSelectionHighlight } from "../editor/selectionHighlightExtension"; import { getEditorView } from "../lib/editor"; import { SELECTION_BUDGET_FRACTION, contextWindowToCharBudget, truncateToBudget } from "../utils/contentBudget"; +import { VIEW_TYPE_CHAT } from "../views/chat/viewType"; /** Serializable snapshot of user-selected text. Persisted in HumanMessage additional_kwargs. */ export interface SelectionRef { @@ -11,7 +12,11 @@ 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 + * and a thread's path changes when it is auto-titled. */ + sameThread?: boolean; } interface CapturedSelection { @@ -22,10 +27,98 @@ interface CapturedSelection { domRanges?: Range[]; } -const VIEW_ICONS: Record = { - markdown: "file-text", - pdf: "file-type", -}; +/** 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. + * 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 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. + */ +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; + 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 domRanges: Range[] = []; + for (let i = 0; i < domSel.rangeCount; i++) { + 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 }, + 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 @@ -96,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 })), }; @@ -125,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 { @@ -149,6 +240,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,15 +255,25 @@ 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, 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; #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; 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 { @@ -182,14 +291,42 @@ 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(); }), ]; - document.addEventListener("selectionchange", this.#handleSelectionChange); + // 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( + 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() { @@ -200,7 +337,47 @@ export class SelectionTracker { }); } + /** + * 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 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; + } + #refresh() { + 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 // view (PDFs count), so `getActiveViewOfType` alone is not enough. @@ -223,7 +400,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; @@ -252,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 { @@ -268,9 +449,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 */ @@ -327,6 +511,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 +525,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; @@ -364,7 +551,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 */ } @@ -386,7 +575,9 @@ export class SelectionTracker { this.#workspace.offref(ref); } this.#refs = []; - document.removeEventListener("selectionchange", this.#handleSelectionChange); + 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); this.#refreshFrame = undefined; diff --git a/test/hooks/chatSelection.test.ts b/test/hooks/chatSelection.test.ts new file mode 100644 index 00000000..3763d68a --- /dev/null +++ b/test/hooks/chatSelection.test.ts @@ -0,0 +1,221 @@ +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 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"; + +function chatLeaf(path: string) { + const containerEl = document.createElement("div"); + containerEl.innerHTML = ` +
+

The second step is wrong.

+
search_notes
+

Use step three instead.

+
+

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[] = []; +let renameHandler: ((file: { path: string; basename: string }, oldPath: string) => void) | undefined; + +beforeEach(() => { + (globalThis as { activeWindow?: Window }).activeWindow = window; + frames = []; + vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => { + frames.push(cb); + return frames.length; + }); + leaves = [chatLeaf(THREAD)]; + renameHandler = undefined; + setPlugin({ + app: { + vault: { + on: (_name: string, cb: typeof renameHandler) => { + renameHandler = cb; + return {}; + }, + offref: () => {}, + }, + workspace: { + on: () => ({}), + offref: () => {}, + getMostRecentLeaf: () => null, + getLeavesOfType: (type: string) => (type === VIEW_TYPE_CHAT ? leaves : []), + getActiveViewOfType: () => null, + iterateAllLeaves: (cb: (leaf: unknown) => void) => leaves.forEach(cb), + }, + }, + } 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("shows a chat selection as soon as it is made", () => { + const tracker = new SelectionTracker(); + select(textOf(".answer")); + expect(tracker.selection).toMatchObject({ + path: THREAD, + basename: "Planning", + viewType: "chat", + text: "The second step is wrong.", + }); + 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); + // The press collapsed the selection before the composer's handler ran. + window.getSelection()?.removeAllRanges(); + tracker.pinChatSelection(); + expect(tracker.selection?.text).toBe("second"); + tracker.destroy(); + }); + + it("ignores selections outside message text", () => { + const tracker = new SelectionTracker(); + select(textOf(".tool-label")); + tracker.pinChatSelection(); + expect(tracker.selection).toBeUndefined(); + + select(textOf(".draft")); + tracker.pinChatSelection(); + expect(tracker.selection).toBeUndefined(); + tracker.destroy(); + }); + + 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(); + 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(); + + caret(textOf(".draft")); + expect(tracker.selection?.viewType).toBe("chat"); + + caret(textOf(".answer")); + expect(tracker.selection).toBeUndefined(); + tracker.destroy(); + }); +}); + +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, + basename: "Planning", + viewType: "chat", + text: "Step two", + }; + + 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", + ); + }); +});