A desktop coding agent with free access to frontier models.
TypeScript
fix: quotes stay separate, tied to their chat, and survive a reload
ogsamrata358b1f51fdd
diff --git a/apps/app/src/components/chat/message-list.tsx b/apps/app/src/components/chat/message-list.tsxindex 31c6d24b..79dee76d 100644--- a/apps/app/src/components/chat/message-list.tsx+++ b/apps/app/src/components/chat/message-list.tsx@@ -21,7 +21,7 @@ import {WifiOff,} from "lucide-react"import { quoteIntoComposer, unquoteBlock } from "./quote"-import { SelectionQuote } from "./selection-quote"+import { SelectionQuote, selectionInMessage } from "./selection-quote"import {DynamicToolUIPart,isFileUIPart,@@ -861,7 +861,7 @@ const UserMessage = React.memo(</ContextMenuItem>) : null}{messageText ? (- <ContextMenuItem onClick={() => quoteIntoComposer(sessionId, window.getSelection()?.toString().trim() || messageText)}>+ <ContextMenuItem onClick={() => quoteIntoComposer(sessionId, selectionInMessage(window.getSelection(), message.id) || messageText)}><TextQuote className="size-4" />Quote</ContextMenuItem>diff --git a/apps/app/src/components/chat/quote.ts b/apps/app/src/components/chat/quote.tsindex 2fec1107..b549de4b 100644--- a/apps/app/src/components/chat/quote.ts+++ b/apps/app/src/components/chat/quote.ts@@ -21,10 +21,18 @@ export function unquoteBlock(text: string): string | null {return lines.map((line) => line.replace(/^> ?/, "")).join("\n")}-/** The chip label: `Quote: first words…`. */+/** At most `max` user-perceived characters (an emoji or accented letter is never cut in half). */+export function clipGraphemes(text: string, max: number): string {+ const graphemes = typeof Intl !== "undefined" && "Segmenter" in Intl+ ? Array.from(new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(text), (part) => part.segment)+ : Array.from(text)+ return graphemes.length > max ? `${graphemes.slice(0, max).join("").trimEnd()}…` : text+}++/** The chip label: `Quote: first words…` (sendToChat makes it unique among the draft's chips). */export function quoteLabel(text: string): string {const flat = text.replace(/\s+/g, " ").trim()- return `Quote: ${flat.length > LABEL_WORDS ? `${flat.slice(0, LABEL_WORDS).trimEnd()}…` : flat}`+ return `Quote: ${clipGraphemes(flat, LABEL_WORDS)}`}export function quoteIntoComposer(sessionId: string | null, text: string): ChatHandoffResult {diff --git a/apps/app/src/components/chat/selection-quote.tsx b/apps/app/src/components/chat/selection-quote.tsxindex f22bc59c..3fa188c4 100644--- a/apps/app/src/components/chat/selection-quote.tsx+++ b/apps/app/src/components/chat/selection-quote.tsx@@ -6,33 +6,59 @@ import { Button } from "@/components/ui/button"import { quoteIntoComposer } from "./quote"+/** The message element a node sits in (`[data-message-id]`) inside `container`, else null. */+function messageOf(node: Node | null, container: HTMLElement): Element | null {+ const element = node instanceof Element ? node : node?.parentElement+ const message = element?.closest("[data-message-id]") ?? null+ return message && container.contains(message) ? message : null+}++/**+ * The text selected in this chat's transcript now, with the messages it starts and ends in; null when nothing is+ * selected there (a selection elsewhere, in another chat's transcript, or collapsed).+ */+export function transcriptSelection(selection: Selection | null, container: HTMLElement | null): { text: string; from: string; to: string; range: Range } | null {+ const text = selection?.toString() ?? ""+ if (!selection || selection.isCollapsed || !text.trim() || !container || !container.isConnected || selection.rangeCount === 0) return null+ const range = selection.getRangeAt(0)+ const start = messageOf(range.startContainer, container)+ const end = messageOf(range.endContainer, container)+ if (!start || !end) return null+ return { text, from: start.getAttribute("data-message-id") ?? "", to: end.getAttribute("data-message-id") ?? "", range }+}++/** The text selected inside one message element (both ends in it), else null: the context menu's quote. */+export function selectionInMessage(selection: Selection | null, messageId: string, container: ParentNode = document): string | null {+ const text = selection?.toString() ?? ""+ if (!selection || selection.isCollapsed || !text.trim() || selection.rangeCount === 0) return null+ const element = Array.from(container.querySelectorAll("[data-message-id]")).find((node) => node.getAttribute("data-message-id") === messageId)+ if (!element) return null+ const range = selection.getRangeAt(0)+ return element.contains(range.startContainer) && element.contains(range.endContainer) ? text.trim() : null+}++type Anchor = { top: number; left: number; sessionId: string; from: string; to: string }+/*** A "Quote" button over text selected in the transcript (one message or- * several): it puts the selection into the composer as a quote chip.+ * several): it puts the selection into the composer as a quote chip. It belongs+ * to the chat and messages it was made in: another chat clears it, and the+ * click reads the selection again and quotes it only if it is still there.*/export function SelectionQuote({ sessionId, containerRef }: { sessionId: string; containerRef: React.RefObject<HTMLElement | null> }) {- const [anchor, setAnchor] = React.useState<{ top: number; left: number; text: string } | null>(null)+ const [anchor, setAnchor] = React.useState<Anchor | null>(null)React.useEffect(() => {+ // A new chat (navigation) starts with no button.+ setAnchor(null)const update = () => {- const selection = window.getSelection()- const container = containerRef.current- const text = selection?.toString() ?? ""- if (!selection || selection.isCollapsed || !text.trim() || !container || selection.rangeCount === 0) {- setAnchor(null)- return- }- const range = selection.getRangeAt(0)- const inMessage = (node: Node | null) => {- const element = node instanceof Element ? node : node?.parentElement- return Boolean(element && container.contains(element) && element.closest("[data-message-id]"))- }- if (!inMessage(range.startContainer) || !inMessage(range.endContainer)) {+ const found = transcriptSelection(window.getSelection(), containerRef.current)+ if (!found) {setAnchor(null)return}- const rect = range.getBoundingClientRect()- setAnchor({ top: Math.max(8, rect.top - 36), left: Math.min(window.innerWidth - 96, Math.max(8, rect.right - 72)), text })+ const rect = found.range.getBoundingClientRect()+ setAnchor({ top: Math.max(8, rect.top - 36), left: Math.min(window.innerWidth - 96, Math.max(8, rect.right - 72)), sessionId, from: found.from, to: found.to })}document.addEventListener("selectionchange", update)window.addEventListener("scroll", update, true)@@ -40,9 +66,9 @@ export function SelectionQuote({ sessionId, containerRef }: { sessionId: string;document.removeEventListener("selectionchange", update)window.removeEventListener("scroll", update, true)}- }, [containerRef])+ }, [containerRef, sessionId])- if (!anchor) return null+ if (!anchor || anchor.sessionId !== sessionId) return null// In <body>: a transformed ancestor would make `fixed` relative to it.return createPortal(<Button@@ -54,7 +80,9 @@ export function SelectionQuote({ sessionId, containerRef }: { sessionId: string;// Keep the selection while the button is pressed.onMouseDown={(event) => event.preventDefault()}onClick={() => {- quoteIntoComposer(sessionId, anchor.text)+ const now = transcriptSelection(window.getSelection(), containerRef.current)+ // Quoted only if the same chat still has this selection (never text carried over from elsewhere).+ if (now && anchor.sessionId === sessionId && now.from === anchor.from && now.to === anchor.to) quoteIntoComposer(sessionId, now.text)window.getSelection()?.removeAllRanges()setAnchor(null)}}diff --git a/apps/app/src/react-app/domains/session/editor/chat-context.ts b/apps/app/src/react-app/domains/session/editor/chat-context.tsindex 0916f4ae..1891d2a0 100644--- a/apps/app/src/react-app/domains/session/editor/chat-context.ts+++ b/apps/app/src/react-app/domains/session/editor/chat-context.ts@@ -35,12 +35,15 @@ export function sendToChat(sessionId: string | null, instruction: string, chips:const state = store.sessions[sessionId];const draft = state?.draft ?? "";const parts = state?.pasteParts ?? [];- const made = chips.map((chip) => ({- id: `editor-${Math.random().toString(36).slice(2)}`,- label: chip.label.replace(/[[\]]/g, "").slice(0, 120),- text: chip.text,- lines: chip.text.split(/\r?\n/).length,- }));+ // The label is the chip's key in the draft ([pasted text <label>]): never two chips with one label.+ const taken = new Set(parts.map((part) => part.label));+ const made = chips.map((chip) => {+ const base = Array.from(chip.label.replace(/[[\]]/g, "")).slice(0, 120).join("");+ let label = base;+ for (let n = 2; taken.has(label); n += 1) label = `${base} (${n})`;+ taken.add(label);+ return { id: `editor-${Math.random().toString(36).slice(2)}`, label, text: chip.text, lines: chip.text.split(/\r?\n/).length };+ });const placeholders = made.map((part) => `[pasted text ${part.label}]`).join(" ");const lead = draft.trim() ? `${draft.replace(/\s+$/, "")}\n` : "";store.setPasteParts(sessionId, [...parts, ...made]);diff --git a/apps/app/src/react-app/domains/session/surface/composer-state-store.ts b/apps/app/src/react-app/domains/session/surface/composer-state-store.tsindex f68741a7..6920c469 100644--- a/apps/app/src/react-app/domains/session/surface/composer-state-store.ts+++ b/apps/app/src/react-app/domains/session/surface/composer-state-store.ts@@ -3,6 +3,7 @@ import { create } from "zustand";import { createPromptMessageID } from "../../../../app/lib/opencode";import type { ComposerAttachment, ComposerDraft } from "../../../../app/types";import type { ComposerMentionKind } from "./composer/mention-encoding";+import { resolvePastedTextPlaceholders, type PastedTextChip } from "./composer/pasted-text";export type QueuedComposerItem = {id: string;@@ -81,8 +82,12 @@ export function getComposerSessionDraftScope(sessionId: string) {return composerSessionDraftScopes.get(sessionId.trim()) ?? null;}-export function persistableComposerDraftText(text: string) {- return text.replace(/\[attachment [^\]]+\]/g, "");+/**+ * The draft text that survives a reload: attachment tokens dropped (their bytes do not persist) and pasted text and+ * quotes written out in full, since their parts live only in memory (a reload would leave a bare placeholder).+ */+export function persistableComposerDraftText(text: string, pasteParts: readonly Pick<PastedTextChip, "label" | "text">[] = []) {+ return resolvePastedTextPlaceholders(text, pasteParts).replace(/\[attachment [^\]]+\]/g, "");}export function composerDraftNeedsHydration(input: {@@ -90,9 +95,10 @@ export function composerDraftNeedsHydration(input: {nextScopeKey: string;currentText: string;storedText: string;+ pasteParts?: readonly Pick<PastedTextChip, "label" | "text">[];}) {return input.claimedScopeKey !== input.nextScopeKey- || persistableComposerDraftText(input.currentText) !== input.storedText;+ || persistableComposerDraftText(input.currentText, input.pasteParts) !== input.storedText;}function createEmptyComposerSession(): ComposerSessionState {diff --git a/apps/app/src/react-app/domains/session/surface/composer/pasted-text.ts b/apps/app/src/react-app/domains/session/surface/composer/pasted-text.tsindex 17136f18..fc73b444 100644--- a/apps/app/src/react-app/domains/session/surface/composer/pasted-text.ts+++ b/apps/app/src/react-app/domains/session/surface/composer/pasted-text.ts@@ -42,6 +42,12 @@ export function resolvePastedTextPlaceholders(text: string, pastedText: readonlyreturn resolved;}+/** The labels of `[pasted text …]` placeholders in `text` that no part resolves (lost, e.g. after a reload). */+export function unresolvedPasteLabels(text: string, pastedText: readonly Pick<PastedTextChip, "label">[]): string[] {+ const known = new Set(pastedText.map((part) => part.label));+ return [...text.matchAll(/\[pasted text ([^\]]+)\]/g)].map((match) => match[1] ?? "").filter((label) => !known.has(label));+}+export function splitPastedText(text: string) {const segments: PastedTextSegment[] = [];for (const part of text.split(/(\r?\n|\t)/)) {diff --git a/apps/app/src/react-app/domains/session/surface/session-surface.tsx b/apps/app/src/react-app/domains/session/surface/session-surface.tsxindex 935560d5..825f396b 100644--- a/apps/app/src/react-app/domains/session/surface/session-surface.tsx+++ b/apps/app/src/react-app/domains/session/surface/session-surface.tsx@@ -65,7 +65,7 @@ import { decodeComposerMentionValue, encodeComposerMentionValue, type ComposerMeimport { desktopBridge, openDesktopUrl } from "@/app/lib/desktop";import { parseSlashCommandInvocation } from "./composer/slash-command";import { parseConnectSkillToken } from "./composer/connect-skill-token";-import { createPastedTextChip, resolvePastedTextPlaceholders } from "./composer/pasted-text";+import { createPastedTextChip, resolvePastedTextPlaceholders, unresolvedPasteLabels } from "./composer/pasted-text";import {canAdmitNextQueuedItem,claimQueuedSend,@@ -1242,6 +1242,7 @@ export function SessionSurface(props: SessionSurfaceProps) {nextScopeKey: persistedDraftKey,currentText: currentDraft,storedText: nextDraft,+ pasteParts: getComposerPasteParts(currentState, props.sessionId),});if (needsHydration) {@@ -2318,6 +2319,11 @@ export function SessionSurface(props: SessionSurfaceProps) {const sourceAttachments = sourceComposer?.attachments ?? attachments;const text = originalDraft.trim();if (!text && sourceAttachments.length === 0) return;+ // A placeholder whose pasted text or quote is gone (only its token left) is never sent as the token itself.+ if (unresolvedPasteLabels(text, sourceComposer?.pasteParts ?? getComposerPasteParts(useComposerStateStore.getState(), props.sessionId)).length) {+ toast.error("A pasted text or quote in this message is no longer available. Remove its chip and paste or quote it again.");+ return;+ }const nextDraft = {...buildDraft(text, sourceAttachments, sourceComposer),messageId: createPromptMessageID(),@@ -2719,7 +2725,7 @@ export function SessionSurface(props: SessionSurfaceProps) {const current = useComposerStateStore.getState();if (getComposerDraft(current, props.sessionId) !== draft || getComposerAttachments(current, props.sessionId) !== attachments) return;const nextDraft = buildDraft(draft, attachments);- const persistableText = persistableComposerDraftText(nextDraft.text);+ const persistableText = persistableComposerDraftText(nextDraft.text, getComposerPasteParts(current, props.sessionId));persistDraft({ text: persistableText, mode: nextDraft.mode });props.onDraftChange(nextDraft);}, [attachments, buildDraft, draft, hydratedDraftScopeKey, persistDraft, persistedDraftKey, props.onDraftChange, props.sessionId]);diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsxindex 27d32243..41b9fa0b 100644--- a/apps/app/src/react-app/shell/session-route.tsx+++ b/apps/app/src/react-app/shell/session-route.tsx@@ -3836,7 +3836,7 @@ export function SessionRoute() {// flight. Seed its latest continuation in the destination, but// send the immutable submitted snapshot through the scoped mark.saveSessionDraft(sessionDraftScope, workspaceId, session.id, {- text: persistableComposerDraftText(continuation.draft),+ text: persistableComposerDraftText(continuation.draft, continuation.pasteParts),mode: "prompt",});claimComposerSessionDraftScope(session.id, destinationScopeKey);diff --git a/apps/app/tests/quote-send.test.ts b/apps/app/tests/quote-send.test.tsnew file mode 100644index 00000000..84e13874--- /dev/null+++ b/apps/app/tests/quote-send.test.ts@@ -0,0 +1,97 @@+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { afterAll, beforeAll, describe, expect, test } from "bun:test";++const registered = !globalThis.document;+if (registered) GlobalRegistrator.register();++const { clipGraphemes, quoteIntoComposer, quoteLabel, quoteText } = await import("../src/components/chat/quote");+const { selectionInMessage, transcriptSelection } = await import("../src/components/chat/selection-quote");+const { useComposerStateStore, persistableComposerDraftText } = await import("../src/react-app/domains/session/surface/composer-state-store");+const { resolvePastedTextPlaceholders, unresolvedPasteLabels } = await import("../src/react-app/domains/session/surface/composer/pasted-text");+const { draftToParts } = await import("../src/react-app/domains/session/sync/draft-parts");++const SESSION = "ses-quote";+const composer = () => useComposerStateStore.getState().sessions[SESSION];++/** What the session surface's buildDraft sends: one paste part per placeholder, its text resolved. */+function draftOf(text: string) {+ const pasteParts = composer()?.pasteParts ?? [];+ const parts = [...text.matchAll(/\[pasted text ([^\]]+)\]/g)].map((match) => {+ const part = pasteParts.find((item) => item.label === match[1]);+ if (!part) throw new Error(`unresolved ${match[1]}`);+ return { type: "paste" as const, id: part.id, label: part.label, text: part.text, lines: part.lines };+ });+ return { mode: "prompt" as const, parts, attachments: [], text, resolvedText: resolvePastedTextPlaceholders(text, pasteParts) };+}++beforeAll(() => { useComposerStateStore.getState().clearSession?.(SESSION); });+afterAll(async () => {+ useComposerStateStore.getState().clearSession?.(SESSION);+ // Other test files register the DOM themselves.+ if (registered) await GlobalRegistrator.unregister();+});++describe("quotes in the composer", () => {+ test("two quotes with the same first words stay two chips and both reach the model", async () => {+ const prefix = "The parser keeps the old token table when the grammar changes, ";+ quoteIntoComposer(SESSION, `${prefix}first`);+ quoteIntoComposer(SESSION, `${prefix}second`);+ quoteIntoComposer(SESSION, `${prefix}first`); // the same quote again+ const labels = (composer()?.pasteParts ?? []).map((part) => part.label);+ expect(new Set(labels).size).toBe(3);+ const draft = draftOf(composer()?.draft ?? "");+ expect(draft.resolvedText).toBe([quoteText(`${prefix}first`), quoteText(`${prefix}second`), quoteText(`${prefix}first`)].join("\n"));+ // With an attachment token the parts are built token by token (draft-parts.ts): each chip by its own label.+ const withToken = { ...draft, text: `${draft.text} [attachment a1]` };+ const parts = await draftToParts(withToken, "/w", SESSION, null);+ const texts = parts.flatMap((part) => (part.type === "text" ? [part.text] : []));+ expect(texts.filter((text) => text.startsWith(">"))).toEqual([quoteText(`${prefix}first`), quoteText(`${prefix}second`), quoteText(`${prefix}first`)]);+ });++ test("a reload keeps the quote's words, never the placeholder", () => {+ const text = composer()?.draft ?? "";+ const saved = persistableComposerDraftText(text, composer()?.pasteParts ?? []);+ expect(saved).not.toContain("[pasted text");+ expect(saved).toContain("> The parser keeps the old token table");+ // After the reload the parts are gone: the saved words need none, a bare placeholder is refused at send.+ expect(unresolvedPasteLabels(saved, [])).toEqual([]);+ expect(unresolvedPasteLabels("see [pasted text Quote: lost words]", [])).toEqual(["Quote: lost words"]);+ });++ test("the label never cuts an emoji or accented letter in half", () => {+ const text = `${"a".repeat(47)}👩👩👧 tail`;+ expect(clipGraphemes(text, 48)).toBe(`${"a".repeat(47)}👩👩👧…`);+ expect(quoteLabel(`${"é".repeat(60)}`)).toBe(`Quote: ${"é".repeat(48)}…`);+ expect(quoteLabel("😀".repeat(49))).toBe(`Quote: ${"😀".repeat(48)}…`);+ });+});++describe("selection quotes belong to their chat and message", () => {+ const mount = (html: string) => { document.body.innerHTML = html; return document.body.firstElementChild as HTMLElement; };+ const select = (node: Node, start: number, endNode: Node, end: number) => {+ const range = document.createRange();+ range.setStart(node, start); range.setEnd(endNode, end);+ const selection = window.getSelection();+ selection?.removeAllRanges(); selection?.addRange(range);+ return selection;+ };++ test("a selection in another chat's transcript is not this chat's quote", () => {+ const chatA = mount(`<div id="a"><div data-message-id="m1"><p>alpha text</p></div></div><div id="b"><div data-message-id="m9"><p>bravo</p></div></div>`);+ const chatB = document.getElementById("b") as HTMLElement;+ const textA = chatA.querySelector("p")?.firstChild as Node;+ const selection = select(textA, 0, textA, 5);+ expect(transcriptSelection(selection, chatA)?.text).toBe("alpha");+ expect(transcriptSelection(selection, chatB)).toBeNull();+ });++ test("the context menu quotes only a selection inside the clicked message", () => {+ mount(`<div><div data-message-id="m1"><p>first message</p></div><div data-message-id="m2"><p>second message</p></div></div>`);+ const [p1, p2] = Array.from(document.querySelectorAll("p")).map((p) => p.firstChild as Node);+ const inside = select(p1 as Node, 0, p1 as Node, 5);+ expect(selectionInMessage(inside, "m1")).toBe("first");+ expect(selectionInMessage(inside, "m2")).toBeNull();+ const across = select(p1 as Node, 0, p2 as Node, 6);+ expect(selectionInMessage(across, "m1")).toBeNull();+ });+});