Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(workbench): copy chat selections as Markdown and add select all (#2371)
Call White9c41f478d648
diff --git a/ui/src/components/ui/markdown.tsx b/ui/src/components/ui/markdown.tsxindex fcfe9fe0b..48018f4b6 100644--- a/ui/src/components/ui/markdown.tsx+++ b/ui/src/components/ui/markdown.tsx@@ -23,6 +23,12 @@ import {import { inAppChatPath } from '@/lib/applicationRoutes';import { isProxyMediaUrl, readMediaDims } from '@/lib/mediaProxy';import { isAbsoluteWindowsFileHref, resolveLocalFileLink, type LocalFileLinkTarget } from '@/lib/localFileLinks';+import {+ bindMarkdownSource,+ rehypeSourceSpans,+ remarkDefinitionSpans,+ sourceSpanProps,+} from '@/lib/markdownSource';import {MENTION_LINK_SCHEME,linkifyMentions,@@ -348,11 +354,28 @@ function mentionUrlTransform(return defaultUrlTransform(literalAuthority ? repairIpv6Authority(url) : url);}+// Every element is marked with the source range it came from, so a selection+// can be copied back as the Markdown that was written (lib/markdownSource).+const rehypePlugins = [rehypeSourceSpans];++// A custom component draws its own element in place of the one react-markdown+// would have, so it carries the marks itself. The wrapper takes no box of its own.+function withSourceSpan<P extends { node?: unknown }>(render: (props: P) => React.ReactNode) {+ return (props: P) => (+ <span className="contents" {...sourceSpanProps(props.node)}>+ {render(props)}+ </span>+ );+}+// A fenced code block with a hover/tap copy button. The button lives on a// relatively-positioned wrapper (not the <pre>, which scrolls horizontally) so// it stays pinned top-right while the code scrolls. The code text is read from// the rendered <pre> (textContent) rather than re-derived from the markdown AST.-const CodeBlock: React.FC<{ children?: React.ReactNode }> = ({ children }) => {+const CodeBlock: React.FC<{ children?: React.ReactNode; sourceSpan: Record<string, number> }> = ({+ children,+ sourceSpan,+}) => {const { t } = useTranslation();const preRef = React.useRef<HTMLPreElement>(null);const [copied, setCopied] = React.useState(false);@@ -365,7 +388,7 @@ const CodeBlock: React.FC<{ children?: React.ReactNode }> = ({ children }) => {}, []);const label = copied ? t('common.copied') : t('common.copy');return (- <div className="vr-code-block">+ <div className="vr-code-block" {...sourceSpan}><pre ref={preRef}>{children}</pre><buttontype="button"@@ -489,18 +512,27 @@ export const Markdown: React.FC<{const prepared = React.useMemo(() => {let text = content;let binding = citations ?? null;+ const passes: TextEdit[][] = [];if (references && references.length) {const pass = linkifyMentions(text, references);text = pass.text;binding = remapCitations(binding, pass.edits);+ passes.push(pass.edits);}if (secretRequests) {const pass = linkifySecretRequests(text);text = pass.text;binding = remapCitations(binding, pass.edits);+ passes.push(pass.edits);}- return { text, binding };+ return { text, binding, passes };}, [content, references, secretRequests, citations]);+ const sourceRef = React.useCallback(+ (root: HTMLDivElement | null) => {+ if (root) bindMarkdownSource(root, { content, text: prepared.text, passes: prepared.passes });+ },+ [content, prepared],+ );// The citation annotation is only ever read back on the surface that renders// badges, so the walk that writes it is attached only there — every other@@ -528,6 +560,8 @@ export const Markdown: React.FC<{// Unconditional: which destinations were written with a bracketed host is// a fact about this text, not about whether it carries citations.remarkLiteralAuthority,+ // Unconditional too: a copied reference needs its definition (lib/markdownSource).+ remarkDefinitionSpans,...(softBreaks ? [remarkBreaks] : []),...(annotateCitations ? [remarkCitationSpans] : []),],@@ -542,7 +576,7 @@ export const Markdown: React.FC<{// render a real inline <img> for our OWN same-origin media proxy; every// other URL stays a click-through link (or plain text when// non-interactive) so nothing is fetched without an explicit action.- img: ({ src, alt }) => (+ img: withSourceSpan(({ src, alt }) => (<MarkdownImagesrc={src ? String(src) : undefined}alt={alt || undefined}@@ -550,12 +584,12 @@ export const Markdown: React.FC<{localFileWorkdir={localFileWorkdir}onOpenLocalFile={onOpenLocalFile}/>- ),+ )),// Links to our media proxy are agent-produced files → render the// download card (filename + type + download / preview). Other links keep// the normal anchor (interactive) or collapse to plain text inside a// clickable row (non-interactive).- a: ({ href, children, node }) => {+ a: withSourceSpan(({ href, children, node }) => {const url = href ? String(href) : '';// @-agent / #-session mention chips (see lib/mentions). Rendered in both// interactive and non-interactive contexts — a chip is a span, safe inside@@ -630,12 +664,12 @@ export const Markdown: React.FC<{<LinkedImageProvider>{children}</LinkedImageProvider></a>);- },+ }),// Wrap tables in a horizontal-scroll viewport so a wide table scrolls within// the bubble instead of squeezing its columns to fit (see index.css). A plain// <div> is valid in both interactive and preview (clickable-row) surfaces.- table: ({ children }) => (- <div className="vr-table-scroll">+ table: ({ children, node }) => (+ <div className="vr-table-scroll" {...sourceSpanProps(node)}><table>{children}</table></div>),@@ -644,7 +678,7 @@ export const Markdown: React.FC<{// Fenced code blocks get a hover/tap copy button. Only on the// interactive surface — a <button> nested in a clickable preview row// would be invalid interactive content.- pre: ({ children }) => <CodeBlock>{children}</CodeBlock>,+ pre: ({ children, node }) => <CodeBlock sourceSpan={sourceSpanProps(node)}>{children}</CodeBlock>,}: {// GFM task lists render a checkbox <input>; even disabled, an@@ -661,9 +695,10 @@ export const Markdown: React.FC<{const urlTransform = (url: string, _key: string, node: { properties?: Record<string, unknown> }) =>mentionUrlTransform(url, Boolean(onOpenLocalFile), node);return (- <div className={cn('vr-markdown', className)}>+ <div ref={sourceRef} className={cn('vr-markdown', className)}><ReactMarkdownremarkPlugins={remarkPlugins}+ rehypePlugins={rehypePlugins}components={components}urlTransform={urlTransform}>diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex ca1cd9efa..3ef822696 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -4443,8 +4443,7 @@ export const Transcript: React.FC<TranscriptProps> = ({<SelectionQuoteToolbarcontainerRef={scrollRef}// Both write actions are omitted rather than offered just to fail —- // see transcriptSelectionActions. On an archived session that leaves only- // the touch Copy fallback, and on desktop the toolbar renders nothing.+ // see transcriptSelectionActions. Copy (and Select all, inside a bubble) stay.onQuote={selectionActions.quote ? onQuoteSelection : undefined}// Forking needs a bound native session (mirrors the sidebar's fork gate).onAskInNew={selectionActions.askInNew ? onAskInNewSession : undefined}diff --git a/ui/src/components/workbench/SelectionQuoteToolbar.test.tsx b/ui/src/components/workbench/SelectionQuoteToolbar.test.tsxindex eb2f1a795..940d1e66b 100644--- a/ui/src/components/workbench/SelectionQuoteToolbar.test.tsx+++ b/ui/src/components/workbench/SelectionQuoteToolbar.test.tsx@@ -3,6 +3,7 @@ import { createRef } from 'react';import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { Markdown } from '../ui/markdown';import { SelectionQuoteToolbar } from './SelectionQuoteToolbar';vi.mock('react-i18next', () => ({@@ -101,6 +102,27 @@ function mountToolbar() {return containerRef.current!;}+const BUBBLE = 'Use **bold** now';++function mountBubble() {+ const containerRef = createRef<HTMLDivElement>();+ render(+ <>+ <div ref={containerRef}>+ <Markdown content={BUBBLE} />+ <Markdown content="Another bubble" />+ </div>+ <SelectionQuoteToolbar containerRef={containerRef} onQuote={quote} />+ </>,+ );+ return containerRef.current!;+}++function settle() {+ fireEvent(document, new Event('selectionchange'));+ act(() => vi.advanceTimersByTime(150));+}+function selectContainer(container: HTMLDivElement) {const range = document.createRange();range.selectNodeContents(container);@@ -150,12 +172,130 @@ describe('chat selection action gesture lifetime', () => {await Promise.resolve();});+ // No rendered Markdown under the selection: the plain text is copied, and+ // there is no bubble to select all of.expect(writeText).toHaveBeenCalledExactlyOnceWith(TEXT);+ expect(screen.queryByRole('button', { name: 'chat.selection.selectAll' })).toBeNull();expect(screen.queryByRole('toolbar')).not.toBeNull();act(() => vi.advanceTimersByTime(800));expect(screen.queryByRole('toolbar')).toBeNull();});+ it('copies the Markdown the selection was rendered from', async () => {+ const container = mountBubble();+ const range = document.createRange();+ range.selectNodeContents(container.querySelector('.vr-markdown')!);+ window.getSelection()!.addRange(range);+ settle();++ await act(async () => {+ const button = screen.getByRole('button', { name: 'chat.selection.copy' });+ fireEvent.pointerDown(button, press);+ fireEvent.pointerUp(button, press);+ await Promise.resolve();+ });++ expect(writeText).toHaveBeenCalledExactlyOnceWith(BUBBLE);+ });++ it('offers Copy for an image alone, which has Markdown but no text', async () => {+ const containerRef = createRef<HTMLDivElement>();+ const image = '';+ render(+ <>+ <div ref={containerRef}>+ <Markdown content={`Intro.\n\n${image}`} />+ </div>+ <SelectionQuoteToolbar containerRef={containerRef} onQuote={quote} />+ </>,+ );+ const range = document.createRange();+ range.selectNode(containerRef.current!.querySelector('img')!);+ window.getSelection()!.addRange(range);+ settle();++ expect(screen.queryByRole('button', { name: 'chat.selection.quote' })).toBeNull();+ await act(async () => {+ const copy = screen.getByRole('button', { name: 'chat.selection.copy' });+ fireEvent.pointerDown(copy, press);+ fireEvent.pointerUp(copy, press);+ await Promise.resolve();+ });+ expect(writeText).toHaveBeenCalledExactlyOnceWith(image);+ });++ it('copies the whole bubble right after Select all, before the selection settles', async () => {+ const containerRef = createRef<HTMLDivElement>();+ const content = 'Use **bold** now.\n\nSecond paragraph.';+ render(+ <>+ <div ref={containerRef}>+ <Markdown content={content} />+ </div>+ <SelectionQuoteToolbar containerRef={containerRef} onQuote={quote} />+ </>,+ );+ const range = document.createRange();+ range.selectNodeContents(containerRef.current!.querySelector('strong')!);+ window.getSelection()!.addRange(range);+ settle();++ // Two clicks, with no time for the 150 ms settle between them.+ const selectAll = screen.getByRole('button', { name: 'chat.selection.selectAll' });+ fireEvent.pointerDown(selectAll, press);+ fireEvent.pointerUp(selectAll, press);+ await act(async () => {+ const copy = screen.getByRole('button', { name: 'chat.selection.copy' });+ fireEvent.pointerDown(copy, press);+ fireEvent.pointerUp(copy, press);+ await Promise.resolve();+ });++ expect(writeText).toHaveBeenCalledExactlyOnceWith(content);+ });++ it('leaves a selection made after Copy in place', async () => {+ const container = mountToolbar();+ await act(async () => {+ const copy = screen.getByRole('button', { name: 'chat.selection.copy' });+ fireEvent.pointerDown(copy, press);+ fireEvent.pointerUp(copy, press);+ await Promise.resolve();+ });+ expect(writeText).toHaveBeenCalledOnce();++ container.textContent = NEXT_TEXT;+ selectContainer(container);+ act(() => vi.advanceTimersByTime(800));++ expect(window.getSelection()!.toString()).toBe(NEXT_TEXT);+ expect(screen.queryByRole('button', { name: 'chat.selection.quote' })).not.toBeNull();+ });++ it('selects the whole bubble on desktop and stays up over the new selection', async () => {+ coarsePointer = false;+ const container = mountBubble();+ const range = document.createRange();+ range.selectNodeContents(container.querySelector('strong')!);+ window.getSelection()!.addRange(range);+ settle();++ const selectAll = screen.getByRole('button', { name: 'chat.selection.selectAll' });+ fireEvent.pointerDown(selectAll, { ...press, pointerType: 'mouse' });+ fireEvent.pointerUp(selectAll, { ...press, pointerType: 'mouse' });+ settle();++ expect(window.getSelection()!.toString()).toBe('Use bold now');+ expect(screen.queryByRole('toolbar')).not.toBeNull();+ await act(async () => {+ const copy = screen.getByRole('button', { name: 'chat.selection.copy' });+ fireEvent.pointerDown(copy, { ...press, pointerType: 'mouse' });+ fireEvent.pointerUp(copy, { ...press, pointerType: 'mouse' });+ await Promise.resolve();+ });+ expect(writeText).toHaveBeenCalledExactlyOnceWith(BUBBLE);+ });+it('keeps a complete gesture alive when the selection clears before release', () => {mountToolbar();const button = screen.getByRole('button', { name: 'chat.selection.quote' });@@ -380,6 +520,47 @@ describe('chat selection action gesture lifetime', () => {expect(top).toBe(36);});+ it.each([+ ['quote', () => quote],+ ['askInNew', () => ask],+ ] as const)('activates %s from a click alone, as assistive technology sends', (action, consumer) => {+ mountToolbar();+ fireEvent.click(screen.getByRole('button', { name: `chat.selection.${action}` }));+ expect(consumer()).toHaveBeenCalledExactlyOnceWith(TEXT);+ });++ it('selects the whole bubble from a click alone', () => {+ coarsePointer = false;+ const containerRef = createRef<HTMLDivElement>();+ render(+ <>+ <div ref={containerRef}><Markdown content={BUBBLE} /></div>+ <SelectionQuoteToolbar containerRef={containerRef} onQuote={quote} />+ </>,+ );+ const range = document.createRange();+ range.selectNodeContents(containerRef.current!.querySelector('strong')!);+ window.getSelection()!.addRange(range);+ settle();++ fireEvent.click(screen.getByRole('button', { name: 'chat.selection.selectAll' }));++ expect(window.getSelection()!.toString()).toBe('Use bold now');+ });++ it('runs once for a pointer activation and the click that follows it', async () => {+ // Copy keeps the toolbar mounted, so the following click reaches the button.+ mountToolbar();+ const button = screen.getByRole('button', { name: 'chat.selection.copy' });+ await act(async () => {+ fireEvent.pointerDown(button, press);+ fireEvent.pointerUp(button, press);+ fireEvent.click(button);+ await Promise.resolve();+ });+ expect(writeText).toHaveBeenCalledExactlyOnceWith(TEXT);+ });+it.each(['Enter', ' '])('preserves %s keyboard activation', (key) => {mountToolbar();fireEvent.keyDown(screen.getByRole('button', { name: 'chat.selection.quote' }), { key });diff --git a/ui/src/components/workbench/SelectionQuoteToolbar.tsx b/ui/src/components/workbench/SelectionQuoteToolbar.tsxindex 0e86cbf55..aa4e06b55 100644--- a/ui/src/components/workbench/SelectionQuoteToolbar.tsx+++ b/ui/src/components/workbench/SelectionQuoteToolbar.tsx@@ -1,9 +1,10 @@import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';-import { Check, Copy, GitFork, TextQuote } from 'lucide-react';+import { Check, Copy, GitFork, TextQuote, TextSelect } from 'lucide-react';import { Button } from '../ui/button';+import { selectedMarkdown, wholeMarkdownRange } from '../../lib/markdownSource';import { copyTextToClipboard } from '../../lib/utils';type SelectionRect = {@@ -16,7 +17,13 @@ type SelectionRect = {};type SelectionState = {+ // What Quote and Ask in a new session take; empty for an image or a rule alone.text: string;+ // What Copy writes: the selected Markdown source, or the plain text when the+ // selection reaches no rendered Markdown.+ copyText: string;+ // The selection widened to the whole bubble(s); null outside any bubble.+ whole: Range | null;top: number;bottom: number;left: number;@@ -28,6 +35,8 @@ const TOOLBAR_H = 36;const GAP = 8;const EDGE = 8;const PRESS_GRACE_MS = 700;+// The native click that follows a pointer or keyboard activation already handled.+const CLICK_AFTER_ACTIVATION_MS = 700;// iOS keeps touch sequences that start within this padding around a selection// handle in its native selection gesture recognizer. Keep the web toolbar// outside that region so pointerup/touchend remains deliverable to the button.@@ -47,7 +56,8 @@ const toSelectionRect = (rect: DOMRect | DOMRectReadOnly): SelectionRect => ({// transcript. "Quote" appends the (quoted) selection to the current composer// (only offered when the composer can accept it); "Ask in a new session" forks +// prefills the fork's draft (only offered when the session is forkable); "Copy"-// (touch only) is a fallback for when the OS selection menu doesn't cooperate. It+// copies the Markdown the selected part of the bubble was written in; "Select+// all" widens the selection to the whole bubble and keeps the toolbar up. It// follows the selection through scrolling (hides while scrolling, re-shows at the// new spot) and only disappears when the selection is cleared — so the user can// scroll to dodge the OS menu.@@ -64,6 +74,9 @@ export const SelectionQuoteToolbar: React.FC<{const { t } = useTranslation();const [sel, setSel] = useState<SelectionState | null>(null);const [copied, setCopied] = useState(false);+ // Counts selection changes, so work finishing later (the clipboard write, the+ // dismissal after it) applies only to the selection it was started for.+ const generationRef = useRef(0);const toolbarRef = useRef<HTMLDivElement>(null);const pressRef = useRef<{pointerId: number;@@ -72,10 +85,11 @@ export const SelectionQuoteToolbar: React.FC<{deferred: boolean;} | null>(null);const pressExpiryRef = useRef<number | null>(null);+ const activatedAtRef = useRef(Number.NEGATIVE_INFINITY);const [width, setWidth] = useState(0);const [height, setHeight] = useState(TOOLBAR_H);// Touch (coarse pointer — phones AND tablets/iPads) is where the OS selection- // menu coexists; it drives the stagger-positioning + the touch-only Copy.+ // menu coexists; it drives the stagger-positioning.const [isTouch] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.('(pointer: coarse)').matches,);@@ -90,7 +104,13 @@ export const SelectionQuoteToolbar: React.FC<{}const text = selection.toString().trim();const range = selection.getRangeAt(0);- if (!text || !container.contains(range.commonAncestorContainer)) {+ if (!container.contains(range.commonAncestorContainer)) {+ setSel(null);+ return;+ }+ // An image or a rule has no text but still has Markdown to copy.+ const markdown = selectedMarkdown(range, container);+ if (!text && !markdown) {setSel(null);return;}@@ -104,6 +124,8 @@ export const SelectionQuoteToolbar: React.FC<{}setSel({text,+ copyText: markdown ?? text,+ whole: wholeMarkdownRange(range, container),top: rect.top,bottom: rect.bottom,left: rect.left + rect.width / 2,@@ -144,6 +166,8 @@ export const SelectionQuoteToolbar: React.FC<{clearPress();};const onSelectionChange = () => {+ generationRef.current += 1;+ setCopied(false);const press = pressRef.current;const currentText = window.getSelection()?.toString().trim() ?? '';if (press && (!currentText || currentText === press.selectionText)) {@@ -191,9 +215,9 @@ export const SelectionQuoteToolbar: React.FC<{}, [sel, onQuote, onAskInNew, isTouch]);if (!sel) return null;- // Nothing left to offer (read-only transcript on a pointer device, where the- // OS already provides copy) — render no chrome rather than an empty bar.- if (!onQuote && !onAskInNew && !isTouch) return null;+ // Quote and Ask in a new session carry text, so an image or a rule alone offers neither.+ const quote = sel.text ? onQuote : undefined;+ const ask = sel.text ? onAskInNew : undefined;const dismiss = () => {clearPress(false);@@ -210,16 +234,27 @@ export const SelectionQuoteToolbar: React.FC<{dismiss();};const runCopy = () => {- const text = sel.text;- void copyTextToClipboard(text).then((ok) => {- if (ok) {- setCopied(true);- window.setTimeout(dismiss, 800);- }+ const generation = generationRef.current;+ void copyTextToClipboard(sel.copyText).then((ok) => {+ if (!ok || generationRef.current !== generation) return;+ setCopied(true);+ window.setTimeout(() => {+ if (generationRef.current === generation) dismiss();+ }, 800);});};+ // Nothing dismisses, since the bubble is still selected: the toolbar is+ // re-read over the widened selection at once, so Copy right after copies it.+ const runSelectAll = () => {+ const selection = window.getSelection();+ if (!sel.whole || !selection) return;+ selection.removeAllRanges();+ selection.addRange(sel.whole.cloneRange());+ recompute();+ };- // Activate on pointerup (mouse + touch) and Enter/Space (keyboard). The+ // Activate on pointerup (mouse + touch), Enter/Space (keyboard), or a click no+ // pointer or key activation preceded (assistive technology). The// pointerdown preventDefault keeps the text selection alive. We deliberately// keep only a short-lived gesture match here: iOS can deliver pointerdown// for a touch near a selection handle without ever delivering pointerup, so@@ -256,14 +291,22 @@ export const SelectionQuoteToolbar: React.FC<{if (!releasedInside) {return;}+ activatedAtRef.current = e.timeStamp;run();};const handleKeyDown = (e: React.KeyboardEvent, run: () => void) => {if (e.key === 'Enter' || e.key === ' ') {e.preventDefault();+ activatedAtRef.current = e.timeStamp;run();}};+ // Assistive technology (VoiceOver, TalkBack, switch access) activates a button+ // with a click alone; a pointer or key activation is followed by one as well.+ const handleClick = (e: React.MouseEvent, run: () => void) => {+ if (e.timeStamp - activatedAtRef.current < CLICK_AFTER_ACTIVATION_MS) return;+ run();+ };const toolbarHeight = height || TOOLBAR_H;const placementGap = isTouch ? SELECTION_HANDLE_GAP : GAP;@@ -345,45 +388,60 @@ export const SelectionQuoteToolbar: React.FC<{>{/* Separators sit BEFORE each item after the first, so a hidden actionnever leaves a dangling divider at the edge of the bar. */}- {onQuote && (+ {quote && (<Buttonvariant="ghost"className={itemClass}onPointerDown={handlePointerDown}onPointerUp={(e) => handlePointerUp(e, runQuote)}onKeyDown={(e) => handleKeyDown(e, runQuote)}+ onClick={(e) => handleClick(e, runQuote)}><TextQuote className="size-3.5 text-muted" />{t('chat.selection.quote')}</Button>)}- {onAskInNew && (+ {ask && (<>- {onQuote && <span className="h-5 w-px bg-border" />}+ {quote && <span className="h-5 w-px bg-border" />}<Buttonvariant="ghost"className={itemClass}onPointerDown={handlePointerDown}onPointerUp={(e) => handlePointerUp(e, runAsk)}onKeyDown={(e) => handleKeyDown(e, runAsk)}+ onClick={(e) => handleClick(e, runAsk)}><GitFork className="size-3.5 text-muted" />{t('chat.selection.askInNew')}</Button></>)}- {isTouch && (+ {(quote || ask) && <span className="h-5 w-px bg-border" />}+ <Button+ variant="ghost"+ className={itemClass}+ onPointerDown={handlePointerDown}+ onPointerUp={(e) => handlePointerUp(e, runCopy)}+ onKeyDown={(e) => handleKeyDown(e, runCopy)}+ onClick={(e) => handleClick(e, runCopy)}+ >+ {copied ? <Check className="size-3.5 text-mint-ink" /> : <Copy className="size-3.5 text-muted" />}+ {t('chat.selection.copy')}+ </Button>+ {sel.whole && (<>- {(onQuote || onAskInNew) && <span className="h-5 w-px bg-border" />}+ <span className="h-5 w-px bg-border" /><Buttonvariant="ghost"className={itemClass}onPointerDown={handlePointerDown}- onPointerUp={(e) => handlePointerUp(e, runCopy)}- onKeyDown={(e) => handleKeyDown(e, runCopy)}+ onPointerUp={(e) => handlePointerUp(e, runSelectAll)}+ onKeyDown={(e) => handleKeyDown(e, runSelectAll)}+ onClick={(e) => handleClick(e, runSelectAll)}>- {copied ? <Check className="size-3.5 text-mint-ink" /> : <Copy className="size-3.5 text-muted" />}- {t('chat.selection.copy')}+ <TextSelect className="size-3.5 text-muted" />+ {t('chat.selection.selectAll')}</Button></>)}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 540236a98..352f3ade6 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4439,6 +4439,7 @@"quote": "Quote","askInNew": "Ask in a new session","copy": "Copy",+ "selectAll": "Select all","askFailed": "Couldn't start a new session from the selection."},"showPage": {diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 35338441e..9cf4e4794 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4439,6 +4439,7 @@"quote": "引用","askInNew": "在新会话询问","copy": "复制",+ "selectAll": "全选","askFailed": "无法从选中内容新建会话,请重试。"},"showPage": {diff --git a/ui/src/lib/markdownSource.test.tsx b/ui/src/lib/markdownSource.test.tsxnew file mode 100644index 000000000..a290d6af5--- /dev/null+++ b/ui/src/lib/markdownSource.test.tsx@@ -0,0 +1,219 @@+// @vitest-environment jsdom+import { cleanup, render } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { Markdown } from '@/components/ui/markdown';+import type { MentionReference } from '@/lib/mentions';+import { selectedMarkdown, wholeMarkdownRange } from './markdownSource';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++afterEach(cleanup);++const DOC = [+ '## Plan **now**',+ '',+ 'Intro with **bold text** and a [link](https://example.com/a) here.',+ '',+ '- first item',+ '- second `code` item',+ '',+ '```ts',+ 'const a = 1;',+ 'const b = 2;',+ '```',+ '',+ '| key | val |',+ '|---|---|',+ '| x | yes |',+ '',+ '这是**重点**内容。见[文档][docs]。',+ '',+ '[docs]: https://example.com/docs',+].join('\n');++type Edge = [needle: string, side: 'before' | 'after', textNode?: number];++// The DOM point just before or after `needle` in the first (or `textNode`-th)+// rendered text node that holds it.+function pointAt(root: Element, [needle, side, textNode = 0]: Edge): [Node, number] {+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ let seen = 0;+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ const at = node.textContent!.indexOf(needle);+ if (at >= 0 && seen++ === textNode) return [node, side === 'before' ? at : at + needle.length];+ }+ throw new Error(`no text node holds ${needle}`);+}++function rangeOver(container: Element, start: Edge, end: Edge): Range {+ const range = document.createRange();+ range.setStart(...pointAt(container, start));+ range.setEnd(...pointAt(container, end));+ return range;+}++function renderDoc(content = DOC, references?: MentionReference[]) {+ const { container } = render(<Markdown content={content} references={references} />);+ return container;+}++const PARAGRAPH = 'Intro with **bold text** and a [link](https://example.com/a) here.';+const LIST = '- first item\n- second `code` item';+const CODE = '```ts\nconst a = 1;\nconst b = 2;\n```';+const TABLE = '| key | val |\n|---|---|\n| x | yes |';++describe('selectedMarkdown', () => {+ it.each([+ ['the document above', DOC],+ // Whitespace at either end, and the two spaces that make a hard break, are+ // part of what was written.+ ['source with edge whitespace and a hard break', '\n\nfirst line \nsecond line\n'],+ ])('copies a whole bubble of %s byte for byte', (_case, content) => {+ const container = renderDoc(content);+ const range = document.createRange();+ range.selectNodeContents(container.querySelector('.vr-markdown')!);++ expect(selectedMarkdown(range, container)).toBe(content);+ });++ it('copies the whole bubble once a selection touches every block of it', () => {+ const content = 'Only **one** paragraph.\n';+ const container = renderDoc(content);+ expect(selectedMarkdown(rangeOver(container, ['one', 'before'], ['one', 'after']), container)).toBe(content);+ });++ // Each block a selection touches is copied whole, however little of it is selected.+ it.each<[string, Edge, Edge, string]>([+ ['a few words of a paragraph', ['bold', 'before'], ['and', 'after'], PARAGRAPH],+ ['two characters of a link', ['in', 'before'], ['in', 'after'], PARAGRAPH],+ ['a heading', ['Plan', 'before'], ['Plan', 'after'], '## Plan **now**'],+ ['one list item', ['second', 'before'], ['second', 'after'], LIST],+ ['a line of a code block', ['const b', 'before'], ['const b', 'after'], CODE],+ ['one table cell', ['yes', 'before'], ['yes', 'after'], TABLE],+ ['a paragraph and the list after it', ['here', 'before'], ['first', 'after'], `${PARAGRAPH}\n\n${LIST}`],+ ['a code block and the table after it', ['const a', 'before'], ['key', 'after'], `${CODE}\n\n${TABLE}`],+ ])('copies the blocks under %s', (_case, start, end, expected) => {+ const container = renderDoc();+ expect(selectedMarkdown(rangeOver(container, start, end), container)).toBe(expected);+ });++ it('brings along the definition of a reference in the copy', () => {+ const container = renderDoc();+ expect(selectedMarkdown(rangeOver(container, ['重点', 'before'], ['内容', 'after']), container))+ .toBe('这是**重点**内容。见[文档][docs]。\n\n[docs]: https://example.com/docs');+ });++ it('brings along definitions an appended definition needs', () => {+ const container = renderDoc('A claim[^1] here.\n\nNext.\n\n[^1]: See [docs][ref].\n\n[ref]: https://example.com/docs');+ expect(selectedMarkdown(rangeOver(container, ['claim', 'before'], ['here', 'after']), container))+ .toBe('A claim[^1] here.\n\n[^1]: See [docs][ref].\n\n[ref]: https://example.com/docs');+ });++ it('copies a footnote definition selected in the rendered footnotes once', () => {+ // A two-paragraph footnote is one block, wherever it is written.+ const content = 'A claim[^1] here.\n\n[^1]: First part.\n\n Second part.\n\nNext.';+ const container = renderDoc(content);+ expect(selectedMarkdown(rangeOver(container, ['Next', 'before'], ['First', 'after']), container))+ .toBe('[^1]: First part.\n\n Second part.\n\nNext.');+ });++ it('leaves out a block written between two copied ones but not selected', () => {+ // The footnote is written mid-document but rendered after "Third".+ const container = renderDoc('First.\n\n[^1]: Note.\n\nSecond[^1].\n\nThird.');+ expect(selectedMarkdown(rangeOver(container, ['Third', 'before'], ['Note', 'after']), container))+ .toBe('[^1]: Note.\n\nThird.');+ });++ it('copies a mention chip as the marker that was typed', () => {+ const content = 'ask @<claude> or see #<ses_1a2b>\n\nNext.';+ const container = renderDoc(content, [+ { kind: 'agent', name: 'claude' },+ { kind: 'session', session_id: 'ses_1a2b', title: 'Release plan' },+ ]);+ expect(selectedMarkdown(rangeOver(container, ['lease', 'before'], ['pla', 'after']), container))+ .toBe('ask @<claude> or see #<ses_1a2b>');+ });++ // An endpoint resting on an element's edge or in whitespace touches nothing there.+ it.each<[string, string, Edge, (container: Element) => [Node, number], string]>([+ ['the next paragraph', 'Intro with **bold** here.\n\nNext para.', ['here', 'before'], (c) => [c.querySelectorAll('p')[1], 0], 'Intro with **bold** here.'],+ ['the next list item', '- alpha\n- beta\n\nAfter.', ['alpha', 'before'], (c) => [c.querySelectorAll('li')[1], 0], '- alpha\n- beta'],+ ['the paragraph after a code block', '```\nabc\n```\n\nafter\n\nend', ['bc', 'before'], (c) => [c.querySelectorAll('p')[0], 0], '```\nabc\n```'],+ ])('ends a selection before %s', (_case, content, start, end, expected) => {+ const container = renderDoc(content);+ const range = document.createRange();+ range.setStart(...pointAt(container, start));+ range.setEnd(...end(container));++ expect(selectedMarkdown(range, container)).toBe(expected);+ });++ // An image or a rule shows content without text, and selecting it touches its block.+ it.each<[string, string, Edge, (container: Element) => [Node, number], string]>([+ ['an image block', 'Here:\n\n\n\nNext para.', ['Here', 'before'], (c) => [c.querySelectorAll('p')[2], 0], 'Here:\n\n'],+ ['a rule', 'Above\n\n---\n\nBelow', ['Above', 'before'], (c) => [c.querySelectorAll('p')[1], 0], 'Above\n\n---'],+ ])('keeps %s at the edge of a selection', (_case, content, start, end, expected) => {+ const container = renderDoc(content);+ const range = document.createRange();+ range.setStart(...pointAt(container, start));+ range.setEnd(...end(container));++ expect(selectedMarkdown(range, container)).toBe(expected);+ });++ it('copies each bubble a selection crosses, separated by a blank line', () => {+ const { container } = render(+ <>+ <Markdown content={'Intro.\n\nfirst **bubble** text'} />+ <span>12:00</span>+ <Markdown content={'- second\n- bubble\n\nOutro.'} />+ </>,+ );+ const range = rangeOver(container, ['bubble', 'before'], ['second', 'after']);++ expect(selectedMarkdown(range, container)).toBe('first **bubble** text\n\n- second\n- bubble');+ });++ it('reports no Markdown for a selection outside every bubble', () => {+ const { container } = render(+ <>+ <span>12:00</span>+ <Markdown content="body" />+ </>,+ );+ expect(selectedMarkdown(rangeOver(container, ['12', 'before'], ['00', 'after']), container)).toBeNull();+ });+});++describe('wholeMarkdownRange', () => {+ it('widens a selection to every bubble it reaches', () => {+ const { container } = render(+ <>+ <Markdown content={'Intro.\n\nfirst **bubble** text'} />+ <span>12:00</span>+ <Markdown content={'- second\n- bubble\n\nOutro.'} />+ <Markdown content="untouched" />+ </>,+ );+ const whole = wholeMarkdownRange(rangeOver(container, ['bubble', 'before'], ['second', 'after']), container)!;++ expect(selectedMarkdown(whole, container))+ .toBe('Intro.\n\nfirst **bubble** text\n\n- second\n- bubble\n\nOutro.');+ });+ it('does not widen into a bubble the selection only ends at the start of', () => {+ const { container } = render(+ <>+ <Markdown content="first bubble" />+ <Markdown content="next bubble" />+ </>,+ );+ const range = document.createRange();+ range.setStart(...pointAt(container, ['first', 'before']));+ range.setEnd(...pointAt(container, ['next', 'before']));++ expect(wholeMarkdownRange(range, container)!.toString()).toBe('first bubble');+ });+});diff --git a/ui/src/lib/markdownSource.ts b/ui/src/lib/markdownSource.tsnew file mode 100644index 000000000..959b6c4ef--- /dev/null+++ b/ui/src/lib/markdownSource.ts@@ -0,0 +1,286 @@+import type { TextEdit } from '@/lib/citations';++// Selection → the Markdown that was written.+//+// The transcript shows rendered Markdown, but a reader copying from it wants+// the source the bubble was rendered from: `**b**`, not `b`. Copying works in+// whole blocks, because a whole block is self-contained Markdown and a cut+// through one is not (half a list item, half a table, half a link):+//+// - A selection that touches every block of a bubble copies the bubble's+// source byte for byte. Select all does exactly that.+// - Otherwise it copies the source of each top-level block it touches — a+// paragraph, heading, list, quote, code block, table, rule or footnote — whole.+// A selection inside one paragraph copies that paragraph.+// - A reference-style link or footnote in the copy brings its definition along+// when the definition is not in the copy itself.+//+// The renderer marks every element with the source range it came from+// (`data-md-start` / `data-md-end`, UTF-16 offsets into the text ReactMarkdown+// parsed), marks each reference with its definition's range, and binds each+// rendered root to that text.++const START = 'data-md-start';+const END = 'data-md-end';+const DEF_START = 'data-md-def-start';+const DEF_END = 'data-md-def-end';+const ROOT = 'data-md-root';+const MARKED = `[${START}]`;++// What shows content without text.+const TEXTLESS = new Set(['IMG', 'HR']);+const isTextless = (node: Node) => node.nodeType === Node.ELEMENT_NODE && TEXTLESS.has((node as Element).tagName);++// The properties these plugins write, and the attributes they render as.+const ATTRIBUTES = [+ ['dataMdStart', START],+ ['dataMdEnd', END],+ ['dataMdDefStart', DEF_START],+ ['dataMdDefEnd', DEF_END],+] as const;++/** What a rendered Markdown root was rendered from. */+type MarkdownSource = {+ /** The text the caller handed the renderer. */+ content: string;+ /** The text ReactMarkdown parsed: `content` after the renderer's own rewrites. */+ text: string;+ /** Each rewrite pass's edits, in the order the passes ran (see `TextEdit`). */+ passes: readonly (readonly TextEdit[])[];+};++const sources = new WeakMap<Element, MarkdownSource>();++/** Bind a rendered root to its source, so a selection inside it can be copied as Markdown. */+export function bindMarkdownSource(root: Element, source: MarkdownSource): void {+ sources.set(root, source);+ root.setAttribute(ROOT, '');+ root.setAttribute(START, '0');+ root.setAttribute(END, String(source.text.length));+}++type HastNode = {+ type?: string;+ position?: { start?: { offset?: number }; end?: { offset?: number } };+ properties?: Record<string, unknown>;+ children?: HastNode[];+};++type MdastNode = {+ type?: string;+ identifier?: unknown;+ position?: { start?: { offset?: number }; end?: { offset?: number } };+ data?: { hProperties?: Record<string, unknown> };+ children?: MdastNode[];+};++function eachNode<T extends { children?: T[] }>(node: T, visit: (node: T) => void): void {+ visit(node);+ node.children?.forEach((child) => eachNode(child, visit));+}++/** Point each reference at the definition it needs, which renders nowhere near it. */+export function remarkDefinitionSpans() {+ return (tree: unknown) => {+ const kind = (type?: string) => {+ if (type === 'definition' || type === 'linkReference' || type === 'imageReference') return 'link';+ if (type === 'footnoteDefinition' || type === 'footnoteReference') return 'note';+ return null;+ };+ const definitions = new Map<string, [number, number]>();+ eachNode(tree as MdastNode, (node) => {+ const start = node.position?.start?.offset;+ const end = node.position?.end?.offset;+ if (node.type !== 'definition' && node.type !== 'footnoteDefinition') return;+ if (typeof node.identifier !== 'string' || typeof start !== 'number' || typeof end !== 'number') return;+ // The first definition of an identifier is the one a reference resolves to.+ const key = `${kind(node.type)}:${node.identifier}`;+ if (!definitions.has(key)) definitions.set(key, [start, end]);+ });+ eachNode(tree as MdastNode, (node) => {+ if (node.type === 'definition' || node.type === 'footnoteDefinition') return;+ const type = kind(node.type);+ if (!type || typeof node.identifier !== 'string') return;+ const span = definitions.get(`${type}:${node.identifier}`);+ if (!span) return;+ const properties = ((node.data ??= {}).hProperties ??= {});+ properties.dataMdDefStart = span[0];+ properties.dataMdDefEnd = span[1];+ });+ };+}++/** Mark every element with the source range it was rendered from. */+export function rehypeSourceSpans() {+ return (tree: unknown) => {+ eachNode(tree as HastNode, (node) => {+ const start = node.position?.start?.offset;+ const end = node.position?.end?.offset;+ if (node.type !== 'element' || typeof start !== 'number' || typeof end !== 'number') return;+ const properties = (node.properties ??= {});+ properties.dataMdStart = start;+ properties.dataMdEnd = end;+ });+ };+}++/** The marks for the element a custom component renders in place of hast `node`. */+export function sourceSpanProps(node: unknown): Record<string, number> {+ const properties = (node as HastNode | undefined)?.properties ?? {};+ const props: Record<string, number> = {};+ for (const [property, attribute] of ATTRIBUTES) {+ const value = properties[property];+ if (typeof value === 'number') props[attribute] = value;+ }+ return props;+}++const spanStart = (el: Element) => Number(el.getAttribute(START));+const spanEnd = (el: Element) => Number(el.getAttribute(END));++// The selection narrowed to what it selects: characters, images and rules. An+// endpoint resting on an element's edge, between blocks, or in whitespace at+// either end touches nothing there — a triple-click ends at the start of the+// next block, which it did not select.+function selectedContent(range: Range): Range | null {+ const scope = range.commonAncestorContainer;+ const nodes: Node[] = [];+ if (scope.nodeType === Node.TEXT_NODE) {+ nodes.push(scope);+ } else {+ const walker = scope.ownerDocument!.createTreeWalker(scope, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ const content = node.nodeType === Node.TEXT_NODE || isTextless(node);+ if (content && range.intersectsNode(node)) nodes.push(node);+ }+ }+ const selected = (node: Text) => {+ const from = node === range.startContainer ? range.startOffset : 0;+ const to = node === range.endContainer ? range.endOffset : node.data.length;+ return { from, text: node.data.slice(from, to) };+ };+ const holds = (node: Node) => node.nodeType !== Node.TEXT_NODE || selected(node as Text).text.trim() !== '';+ const first = nodes.find(holds);+ const last = [...nodes].reverse().find(holds);+ if (!first || !last) return null;+ const narrowed = range.cloneRange();+ if (first.nodeType === Node.TEXT_NODE) {+ const head = selected(first as Text);+ narrowed.setStart(first, head.from + head.text.search(/\S/));+ } else {+ narrowed.setStart(first, 0);+ }+ if (last.nodeType === Node.TEXT_NODE) {+ const tail = selected(last as Text);+ narrowed.setEnd(last, tail.from + tail.text.search(/\s*$/));+ } else {+ narrowed.setEnd(last, 0);+ }+ return narrowed;+}++// A root's top-level blocks: its outermost marked elements. Footnote+// definitions render inside an unmarked section, and are blocks of their own.+function blocksOf(root: Element): Element[] {+ return Array.from(root.querySelectorAll(MARKED)).filter(+ (el) => el.parentElement?.closest(MARKED) === root,+ );+}++// An offset in the parsed text, carried back through the rewrite passes into+// `content`. An offset inside a rewritten span widens to cover the whole of+// what was rewritten: a mention chip copies as the `@<name>` that was typed.+function toContent(source: MarkdownSource, offset: number, side: 'start' | 'end'): number {+ let at = offset;+ for (let pass = source.passes.length - 1; pass >= 0; pass -= 1) {+ const edits = [...source.passes[pass]].sort((left, right) => left.start - right.start);+ let shift = 0;+ let mapped: number | null = null;+ for (const edit of edits) {+ const from = edit.start + shift;+ if (at <= from) break;+ if (at < from + edit.inserted) {+ mapped = side === 'start' ? edit.start : edit.end;+ break;+ }+ shift += edit.inserted - (edit.end - edit.start);+ }+ at = mapped ?? at - shift;+ }+ return at;+}++function copyFromRoot(range: Range, root: Element): string {+ const source = sources.get(root)!;+ const blocks = blocksOf(root);+ const touched = new Set(blocks.filter((block) => range.intersectsNode(block)));+ if (!touched.size) return '';+ if (touched.size === blocks.length) return source.content;++ // Touched blocks next to each other in the source are copied as one stretch,+ // with what was written between them; a block left out splits the stretch.+ const ordered = [...blocks].sort((left, right) => spanStart(left) - spanStart(right));+ const stretches: Array<[number, number]> = [];+ let open = false;+ for (const block of ordered) {+ if (!touched.has(block)) {+ open = false;+ } else if (open) {+ stretches[stretches.length - 1][1] = spanEnd(block);+ } else {+ stretches.push([spanStart(block), spanEnd(block)]);+ open = true;+ }+ }++ // A definition brought along can itself hold references (a footnote citing a+ // reference link), so collect until nothing copied needs anything more.+ const copied = [...stretches];+ const holds = (start: number, end: number) => copied.some(([left, right]) => start >= left && end <= right);+ const references = Array.from(root.querySelectorAll(`[${DEF_START}]`)).filter((el) => el.hasAttribute(START));+ for (let grew = true; grew;) {+ grew = false;+ for (const el of references) {+ const definition: [number, number] = [Number(el.getAttribute(DEF_START)), Number(el.getAttribute(DEF_END))];+ if (!holds(spanStart(el), spanEnd(el)) || holds(...definition)) continue;+ copied.push(definition);+ grew = true;+ }+ }+ const definitions = copied.slice(stretches.length).sort(([left], [right]) => left - right);+ return [...stretches, ...definitions]+ .map(([start, end]) => source.content.slice(toContent(source, start, 'start'), toContent(source, end, 'end')))+ .join('\n\n');+}++// The rendered Markdown roots `range` reaches inside `container`, in document order.+function markdownRoots(range: Range, container: Element): Element[] {+ return Array.from(container.querySelectorAll(`[${ROOT}]`)).filter(+ (root) => sources.has(root) && range.intersectsNode(root),+ );+}++/**+ * The Markdown source of what `range` selects inside `container`, or null when+ * it reaches no rendered Markdown. A selection across several bubbles copies+ * each bubble's part, separated by a blank line; text outside any bubble (names,+ * timestamps) is not Markdown and is left out.+ */+export function selectedMarkdown(range: Range, container: Element): string | null {+ const selected = selectedContent(range);+ if (!selected) return null;+ const parts = markdownRoots(selected, container).map((root) => copyFromRoot(selected, root));+ return parts.filter((part) => part.trim() !== '').join('\n\n') || null;+}++/** `range` widened to cover every bubble it selects content of, or null when it selects none. */+export function wholeMarkdownRange(range: Range, container: Element): Range | null {+ const selected = selectedContent(range);+ const roots = selected ? markdownRoots(selected, container) : [];+ if (!roots.length) return null;+ const last = roots[roots.length - 1];+ const whole = container.ownerDocument.createRange();+ whole.setStart(roots[0], 0);+ whole.setEnd(last, last.childNodes.length);+ return whole;+}