The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(chat): quote a selection from a message into the composer
M3gA-Mind8f21455c1755
diff --git a/app/src/components/assistant-ui/__tests__/thread.quote.test.tsx b/app/src/components/assistant-ui/__tests__/thread.quote.test.tsxnew file mode 100644index 0000000000..b386b6dda5--- /dev/null+++ b/app/src/components/assistant-ui/__tests__/thread.quote.test.tsx@@ -0,0 +1,146 @@+/**+ * Quote-a-selection, proven from the component `/chat` actually mounts.+ *+ * `quote.tsx` was written, reviewed and then imported by nothing except+ * `pages/dev/assistant-ui-demo`. Mounting in that demo proves nothing about the+ * real route, which is the whole reason the audit that found it counted+ * dev-only components separately. So this test drives `Thread` — the component+ * `AssistantUiChat` renders — and never touches `BaseDemo`.+ */+import {+ AssistantRuntimeProvider,+ type ThreadMessageLike,+ useExternalStoreRuntime,+} from '@assistant-ui/react';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { Thread } from '../thread';++const messages: ThreadMessageLike[] = [+ { role: 'user', content: [{ type: 'text', text: 'explain mitochondria' }] },+ {+ role: 'assistant',+ content: [{ type: 'text', text: 'The mitochondria is the powerhouse of the cell.' }],+ },+];++function Harness({ children }: { children?: ReactNode }) {+ const runtime = useExternalStoreRuntime({+ messages,+ isRunning: false,+ convertMessage: (m: ThreadMessageLike) => m,+ onNew: async () => {},+ });+ return (+ <AssistantRuntimeProvider runtime={runtime}>+ <Thread model={null} onModelChange={() => {}} />+ {children}+ </AssistantRuntimeProvider>+ );+}++/**+ * Put a non-collapsed selection over `node` and tell the document about it.+ *+ * The toolbar listens on `document` for `mouseup`, reads `window.getSelection()`+ * inside a `requestAnimationFrame`, and walks up for the `data-message-id` that+ * `MessagePrimitive.Root` emits — so the stub has to be anchored at a real node+ * inside the rendered message, not at a detached one.+ */+function selectWithin(node: Node, text: string) {+ const removeAllRanges = vi.fn();+ vi.spyOn(window, 'getSelection').mockReturnValue({+ isCollapsed: false,+ anchorNode: node,+ focusNode: node,+ rangeCount: 1,+ toString: () => text,+ getRangeAt: () => ({+ getBoundingClientRect: () => ({ top: 100, left: 40, width: 120, height: 18 }),+ }),+ removeAllRanges,+ } as unknown as Selection);+ fireEvent.mouseUp(document);+ return { removeAllRanges };+}++afterEach(() => {+ vi.restoreAllMocks();+});++describe('quoting a selection from the live Thread', () => {+ it('offers a Quote button over a selection inside a message', async () => {+ render(<Harness />);+ const answer = await screen.findByText('The mitochondria is the powerhouse of the cell.');++ expect(document.querySelector('[data-slot="selection-toolbar"]')).toBeNull();+ selectWithin(answer, 'powerhouse of the cell');++ await waitFor(() =>+ expect(document.querySelector('[data-slot="selection-toolbar"]')).not.toBeNull()+ );+ });++ it('drops the excerpt into the composer when Quote is clicked', async () => {+ render(<Harness />);+ const answer = await screen.findByText('The mitochondria is the powerhouse of the cell.');++ // Nothing quoted yet, so the composer shows no preview.+ expect(document.querySelector('[data-slot="composer-quote"]')).toBeNull();++ selectWithin(answer, 'powerhouse of the cell');+ const quoteButton = await waitFor(() => {+ const el = document.querySelector('[data-slot="selection-toolbar-quote"]');+ if (!el) throw new Error('no quote button');+ return el;+ });+ fireEvent.click(quoteButton);++ const preview = await waitFor(() => {+ const el = document.querySelector('[data-slot="composer-quote"]');+ if (!el) throw new Error('no composer quote preview');+ return el;+ });+ // The excerpt itself, not just the chrome — a preview that renders empty+ // would satisfy a presence-only assertion while showing the user nothing.+ expect(preview.textContent).toContain('powerhouse of the cell');+ });++ it('dismisses the quote from the composer', async () => {+ render(<Harness />);+ const answer = await screen.findByText('The mitochondria is the powerhouse of the cell.');+ selectWithin(answer, 'powerhouse of the cell');+ fireEvent.click(+ await waitFor(() => {+ const el = document.querySelector('[data-slot="selection-toolbar-quote"]');+ if (!el) throw new Error('no quote button');+ return el;+ })+ );+ await waitFor(() =>+ expect(document.querySelector('[data-slot="composer-quote"]')).not.toBeNull()+ );++ fireEvent.click(screen.getByLabelText('Dismiss quote'));++ await waitFor(() => expect(document.querySelector('[data-slot="composer-quote"]')).toBeNull());+ });++ it('offers no Quote button for a selection outside any message', async () => {+ // The guard that keeps the toolbar from appearing over the composer, the+ // thread list, or anything else on the page.+ render(+ <Harness>+ <p data-testid="outside">not part of a message</p>+ </Harness>+ );+ const outside = await screen.findByTestId('outside');++ selectWithin(outside, 'not part of a message');++ await new Promise(resolve => setTimeout(resolve, 50));+ expect(document.querySelector('[data-slot="selection-toolbar"]')).toBeNull();+ });+});diff --git a/app/src/components/assistant-ui/thread.tsx b/app/src/components/assistant-ui/thread.tsxindex 5f005899dc..52596b28e5 100644--- a/app/src/components/assistant-ui/thread.tsx+++ b/app/src/components/assistant-ui/thread.tsx@@ -12,6 +12,7 @@ import { ThreadFollowupSuggestions } from '@/components/assistant-ui/follow-up-simport { Image } from '@/components/assistant-ui/image';import { cn } from '@/components/assistant-ui/lib/utils';import { MarkdownText } from '@/components/assistant-ui/markdown-text';+import { ComposerQuotePreview, SelectionToolbar } from '@/components/assistant-ui/quote';import {Reasoning,ReasoningContent,@@ -383,6 +384,18 @@ const ThreadRoot: FC<{</ThreadPrimitive.ViewportFooter></div></ThreadPrimitive.Viewport>++ {/*+ * Select text in any message and a floating "Quote" button appears over+ * the selection; clicking it drops the excerpt into the composer.+ *+ * It lives OUTSIDE the viewport on purpose: it portals itself to the+ * selection's screen position, so nesting it inside the scroller would+ * only give it a clipped, scrolling ancestor for no benefit. It finds the+ * message by the `data-message-id` that `MessagePrimitive.Root` already+ * emits, so neither message component needed changing.+ */}+ <SelectionToolbar /></ThreadPrimitive.Root>);};@@ -689,6 +702,8 @@ const Composer: FC<{// `border-ring` on drag is untouched — that state is meant to break// the pattern.className="border-content-faint/35 focus-within:border-content-faint/90 data-[dragging=true]:border-ring shadow-[0_8px_12px_-4px_rgb(0_0_0/0.09),0_30px_44px_-16px_rgb(0_0_0/0.12)] animate-composer-shadow motion-reduce:animate-none flex w-full cursor-text flex-col gap-2 rounded-(--composer-radius) border bg-(--composer-bg) p-(--composer-padding) transition-[border-color] duration-200 ease-out motion-reduce:transition-none data-[dragging=true]:border-dashed data-[dragging=true]:bg-[color-mix(in_oklab,var(--color-accent)_50%,var(--color-background))]">+ {/* Renders only while a quote is set; dismissing it clears the quote. */}+ <ComposerQuotePreview />{HostComposerAttachments ? <HostComposerAttachments /> : <ComposerAttachments />}{/** Lexical rather than the plain `ComposerPrimitive.Input` textarea,diff --git a/app/src/providers/__tests__/useOpenHumanExternalStore.quote.test.tsx b/app/src/providers/__tests__/useOpenHumanExternalStore.quote.test.tsxnew file mode 100644index 0000000000..f3646aedfc--- /dev/null+++ b/app/src/providers/__tests__/useOpenHumanExternalStore.quote.test.tsx@@ -0,0 +1,112 @@+/**+ * The quote has to survive the send, or the composer's quote chip is scenery.+ *+ * `SelectionToolbarPrimitive.Quote` sets the quote as STRUCTURE —+ * `metadata.custom.quote`, a `{ text, messageId }` — but `surface.send` takes a+ * string. Anything the adapter does not fold into that string never reaches the+ * model, and the user would watch themselves quote a paragraph while the agent+ * answered as though they had not. That is the failure this file exists for.+ */+import type { AppendMessage } from '@assistant-ui/react';+import { configureStore } from '@reduxjs/toolkit';+import { renderHook } from '@testing-library/react';+import type { ReactNode } from 'react';+import { Provider } from 'react-redux';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import chatRuntimeReducer from '../../store/chatRuntimeSlice';+import threadReducer from '../../store/threadSlice';+import { registerChatSurface } from '../chatSurfaceHandlers';+import { useOpenHumanExternalStore } from '../useOpenHumanExternalStore';++vi.mock('../../services/api/threadApi', () => ({+ threadApi: {+ getDerivedTranscript: vi+ .fn()+ .mockResolvedValue({+ threadId: 't-quote',+ items: [],+ total: 0,+ hasMore: false,+ hasTranscript: false,+ }),+ },+}));++const THREAD_ID = 't-quote';++function appended(over: Partial<AppendMessage> = {}): AppendMessage {+ return {+ role: 'user',+ content: [{ type: 'text', text: 'what does this mean?' }],+ parentId: null,+ sourceId: null,+ runConfig: undefined,+ attachments: [],+ metadata: { custom: {} },+ createdAt: new Date(),+ ...over,+ } as unknown as AppendMessage;+}++function withQuote(text: string): AppendMessage {+ return appended({+ metadata: { custom: { quote: { text, messageId: 'm-1' } } },+ } as unknown as Partial<AppendMessage>);+}++function mount() {+ const store = configureStore({+ reducer: { thread: threadReducer, chatRuntime: chatRuntimeReducer },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider store={store}>{children}</Provider>+ );+ return renderHook(() => useOpenHumanExternalStore(THREAD_ID), { wrapper });+}++describe('a quoted excerpt reaching the core', () => {+ let sent: string[];++ beforeEach(() => {+ sent = [];+ registerChatSurface(THREAD_ID, {+ send: async (text: string) => {+ sent.push(text);+ },+ });+ });++ it('sends the excerpt as a blockquote above the question', async () => {+ const { result } = mount();+ await result.current.onNew(withQuote('The mitochondria is the powerhouse of the cell.'));++ expect(sent).toEqual([+ '> The mitochondria is the powerhouse of the cell.\n\nwhat does this mean?',+ ]);+ });++ it('prefixes every line of a multi-line excerpt', async () => {+ // A single `>` on the first line only is not a blockquote — markdown ends+ // it at the first unprefixed line, so the rest of the excerpt would read as+ // the user's own words.+ const { result } = mount();+ await result.current.onNew(withQuote('first line\nsecond line'));++ expect(sent).toEqual(['> first line\n> second line\n\nwhat does this mean?']);+ });++ it('sends the question unchanged when nothing is quoted', async () => {+ const { result } = mount();+ await result.current.onNew(appended());++ expect(sent).toEqual(['what does this mean?']);+ });++ it('ignores a whitespace-only quote rather than sending an empty blockquote', async () => {+ const { result } = mount();+ await result.current.onNew(withQuote(' \n '));++ expect(sent).toEqual(['what does this mean?']);+ });+});diff --git a/app/src/providers/useOpenHumanExternalStore.ts b/app/src/providers/useOpenHumanExternalStore.tsindex f1a939e306..74821626ac 100644--- a/app/src/providers/useOpenHumanExternalStore.ts+++ b/app/src/providers/useOpenHumanExternalStore.ts@@ -228,6 +228,35 @@ function useWelcomeSuggestions(messageCount: number): readonly ThreadSuggestion[);}+/**+ * The excerpt the user quoted, as a markdown blockquote, or `''`.+ *+ * The composer carries a quote as STRUCTURE — `metadata.custom.quote`, a+ * `{ text, messageId }` set by `SelectionToolbarPrimitive.Quote` — but+ * `surface.send` takes a string, so it has to be rendered into the message or+ * it never reaches the model. Dropping it would leave the quote chip in the+ * composer as decoration: the user would watch themselves quote a paragraph+ * and the agent would answer as though they had not.+ *+ * A blockquote is the representation to pick: it is what the excerpt already+ * is, every model reads it as quoted material, and it survives in the+ * persisted message so the turn still makes sense on reload.+ *+ * `messageId` is deliberately dropped. Nothing downstream can resolve it — the+ * core stores no reference between messages — and a raw id in the prompt is+ * noise to the model.+ */+function appendMessageQuote(message: AppendMessage): string {+ const quote = (message.metadata as { custom?: { quote?: { text?: unknown } } } | undefined)+ ?.custom?.quote;+ const text = typeof quote?.text === 'string' ? quote.text.trim() : '';+ if (text.length === 0) return '';+ return `${text+ .split('\n')+ .map(line => `> ${line}`)+ .join('\n')}\n\n`;+}+/*** Build the `ExternalStoreAdapter` that backs `useExternalStoreRuntime`.*@@ -328,7 +357,7 @@ export function useOpenHumanExternalStore(threadId: string | null) {}const text = appendMessageText(message);if (text.length === 0) return;- await surface.send(text);+ await surface.send(`${appendMessageQuote(message)}${text}`);},[threadId]);