From 02fa73809f887aad957d1ad1c76e6e374c86e74b Mon Sep 17 00:00:00 2001 From: usrnk1 <7547651+usrnk1@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:56:31 +0200 Subject: [PATCH] feat(desktop): quote selected timeline text into the composer (#55664) --- .../e2e/regression/timeline-stream.spec.ts | 517 ++++++++++++++++++ packages/app/src/composer/comment-note.ts | 22 +- packages/app/src/composer/editor/editor.tsx | 74 ++- .../app/src/composer/editor/interaction.ts | 21 +- .../app/src/composer/editor/quote-comment.tsx | 90 +++ packages/app/src/composer/model.ts | 11 +- packages/app/src/composer/request.test.ts | 31 ++ packages/app/src/composer/request.ts | 28 +- packages/app/src/composer/schema.ts | 31 +- packages/app/src/composer/state.ts | 15 +- packages/app/src/composer/submit.ts | 73 +-- packages/app/src/index.css | 8 + packages/app/src/runtime/i18n/en.ts | 4 + packages/app/src/session/composer/region.tsx | 16 + packages/app/src/session/screen.tsx | 9 + .../app/src/session/timeline/quote-text.ts | 326 +++++++++++ packages/app/src/session/timeline/quote.tsx | 404 ++++++++++++++ packages/session-ui/src/actions.ts | 6 + .../src/message/attachment-card.css | 36 ++ .../session-ui/src/message/comment-card.tsx | 115 ++-- .../src/message/message-content.tsx | 12 +- .../line-comment/line-comment.tsx | 7 +- packages/ui/src/i18n/en.ts | 4 + packages/ui/src/icons/catalog.ts | 4 + 24 files changed, 1758 insertions(+), 106 deletions(-) create mode 100644 packages/app/src/composer/editor/quote-comment.tsx create mode 100644 packages/app/src/session/timeline/quote-text.ts create mode 100644 packages/app/src/session/timeline/quote.tsx diff --git a/packages/app/e2e/regression/timeline-stream.spec.ts b/packages/app/e2e/regression/timeline-stream.spec.ts index c9b3d046cf4..9ffd5c5f263 100644 --- a/packages/app/e2e/regression/timeline-stream.spec.ts +++ b/packages/app/e2e/regression/timeline-stream.spec.ts @@ -1599,6 +1599,523 @@ test.describe("shell completion", () => { }) }) +test("quotes plain timeline text into the composer, with or without a comment", async ({ page }) => { + const prompts: string[] = [] + await setupTimeline(page, { + messages: [ + userMessage([userText("Explain the build", { id: "prt_quote_user" })]), + assistantMessage([textPart("prt_quote_answer", "It has **two** steps:\n\n- compile\n- bundle")]), + ], + onPrompt: (input) => void prompts.push(String(input.body.text)), + }) + + const user = '[data-slot="user-message-text"]' + const answer = `[data-timeline-part-id="${renderedPartID("prt_quote_answer")}"] [data-slot="text-part-body"]` + await expect(page.locator(answer).getByText("bundle", { exact: true })).toBeVisible() + + const select = (from: string, to: string) => + page.evaluate( + (selectors) => { + const [start, end] = selectors.map((selector) => document.querySelector(selector)) + + if (!start || !end) throw new Error("Selection target is missing") + const range = document.createRange() + range.setStart(start, 0) + range.setEnd(end, end.childNodes.length) + window.getSelection()?.removeAllRanges() + window.getSelection()?.addRange(range) + }, + [from, to], + ) + + // A selection across the user's message and the answer quotes their text, not the controls between them. + await select(user, answer) + const toolbar = page.getByRole("toolbar", { name: "Quote selection" }) + await toolbar.getByRole("button", { name: "Quote", exact: true }).click() + await expect(toolbar).toHaveCount(0) + const chips = page.locator('[data-component="composer-attachments"] [data-component="attachment-card"]') + await expect(chips).toHaveCount(1) + await expect(chips).toContainText("Explain the build") + + // A quote's chip takes its comment; saving an emptied comment clears it again. + await select(answer, answer) + await toolbar.getByRole("button", { name: "Quote", exact: true }).click() + await expect(chips).toHaveCount(2) + const comment = page.locator('[data-component="composer-quote-comment"] textarea') + await chips.nth(1).click() + await comment.fill("Why three?") + await comment.press("Enter") + await expect(comment).toHaveCount(0) + await expect(chips.nth(1)).toContainText("Why three?") + await chips.nth(1).click() + await expect(comment).toHaveValue("Why three?") + await comment.fill("") + await comment.press("Enter") + await expect(chips.nth(1)).not.toContainText("Why three?") + await chips.nth(1).click() + await comment.fill("Why two?") + await comment.press("Escape") + await expect(chips.nth(1)).not.toContainText("Why two?") + await chips.nth(1).click() + await comment.fill("Why two?") + await comment.press("Enter") + await expect(chips.nth(1)).toContainText("Why two?") + + // The shell turns selection off, so select all in the timeline selects its conversation and offers to quote it. + await page.locator(answer).getByText("bundle", { exact: true }).click() + await page.keyboard.press("ControlOrMeta+a") + await expect(toolbar).toBeVisible() + await page.keyboard.press("Escape") + await expect(toolbar).toHaveCount(0) + + const editor = page.locator('[data-component="composer-editor"]') + await editor.press("Enter") + await expect + .poll(() => prompts) + .toEqual([ + [ + "The user quoted the following from earlier in the conversation:", + "> Explain the build", + "> ", + "> It has two steps:", + "> compile", + "> bundle", + "The user quoted the following from earlier in the conversation:", + "> It has two steps:", + "> compile", + "> bundle", + "", + "The user made the following comment regarding this quote: Why two?", + ].join("\n"), + ]) + await expect(chips).toHaveCount(0) +}) + +test("quotes table rows and diff lines selected across a diff viewer", async ({ page }) => { + const prompts: string[] = [] + await setupTimeline(page, { + settings: { editToolPartsExpanded: true }, + messages: [ + userMessage(), + assistantMessage([ + textPart("prt_quote_table", "| File | Change |\n| --- | --- |\n| a.ts | rename |"), + toolPart( + "prt_quote_edit", + "edit", + "completed", + { path: "src/a.ts", oldString: "export const value = 'before'", newString: "export const value = 'after'" }, + { + output: "Edited src/a.ts", + title: "src/a.ts", + metadata: { + files: [ + { + file: "src/a.ts", + patch: createTwoFilesPatch( + "a/src/a.ts", + "b/src/a.ts", + "export const value = 'before'\n", + "export const value = 'after'\n", + ), + additions: 1, + deletions: 1, + status: "modified", + }, + ], + }, + }, + ), + ]), + ], + onPrompt: (input) => void prompts.push(String(input.body.text)), + }) + + const removed = page.locator('[data-line-type="change-deletion"][data-line]') + const added = page.locator('[data-line-type="change-addition"][data-line]') + await expect(added).toHaveText("export const value = 'after'") + + const drag = async (from: Locator, to: Locator) => { + const start = await from.boundingBox() + const end = await to.boundingBox() + + if (!start || !end) throw new Error("Selection target is not laid out") + await page.mouse.move(start.x + 1, start.y + start.height / 2) + await page.mouse.down() + await page.mouse.move(end.x + end.width - 1, end.y + end.height / 2, { steps: 10 }) + await page.mouse.up() + } + + const toolbar = page.getByRole("toolbar", { name: "Quote selection" }) + const chips = page.locator('[data-component="composer-attachments"] [data-component="attachment-card"]') + + // A drag from the table into the diff viewer quotes both, table cells by tabs and diff lines with their markers. + await drag(page.locator("th").getByText("File", { exact: true }), added) + await toolbar.getByRole("button", { name: "Quote", exact: true }).click() + await expect(chips).toHaveCount(1) + + // The quote stops where a selection inside the diff viewer ends. + await drag(page.locator("td").getByText("a.ts", { exact: true }), removed) + await toolbar.getByRole("button", { name: "Quote", exact: true }).click() + await expect(chips).toHaveCount(2) + + await page.locator('[data-component="composer-editor"]').press("Enter") + await expect + .poll(() => prompts) + .toEqual([ + [ + "The user quoted the following from earlier in the conversation:", + "> File\tChange", + "> a.ts\trename", + "> ", + "> -export const value = 'before'", + "> +export const value = 'after'", + "The user quoted the following from earlier in the conversation:", + "> a.ts\trename", + "> ", + "> -export const value = 'before'", + ].join("\n"), + ]) +}) + +test("places the quote action by the end a selection was made towards", async ({ page }) => { + const paragraph = Array.from( + { length: 14 }, + (_, index) => `Sentence ${index} explains one more part of the build.`, + ).join(" ") + + await setupTimeline(page, { + messages: [ + userMessage(), + assistantMessage([ + textPart("prt_place_short", "A short line with a word."), + textPart("prt_place_long", Array.from({ length: 10 }, () => paragraph).join("\n\n")), + ]), + ], + }) + + const toolbar = page.getByRole("toolbar", { name: "Quote selection" }) + const scroller = page.locator('[data-slot="session-timeline-scroll"] .scroll-view__viewport') + const first = page.locator(`[data-timeline-part-id="${renderedPartID("prt_place_long")}"] p`).first() + await expect(first).toBeVisible() + + const box = async (locator: Locator) => { + const value = await locator.boundingBox() + + if (!value) throw new Error("Element is not laid out") + + return value + } + + const drag = async (from: { x: number; y: number }, to: { x: number; y: number }) => { + await page.mouse.move(from.x, from.y) + await page.mouse.down() + await page.mouse.move(to.x, to.y, { steps: 10 }) + await page.mouse.up() + await expect(toolbar).toBeVisible() + + return box(toolbar) + } + + // The middle of the selected text, whose right edge is ragged where its lines wrap. + const middle = () => + page.evaluate(() => { + const rects = [...(window.getSelection()?.getRangeAt(0).getClientRects() ?? [])].filter((rect) => rect.width > 0) + + return (Math.min(...rects.map((rect) => rect.left)) + Math.max(...rects.map((rect) => rect.right))) / 2 + }) + + // Pressing inside a selection drags its text, so each case starts from no selection. + const clear = async () => { + await page.keyboard.press("Escape") + await expect(toolbar).toHaveCount(0) + await page.evaluate(() => window.getSelection()?.removeAllRanges()) + } + + await first.scrollIntoViewIfNeeded() + const lines = await box(first) + const start = { x: lines.x + 1, y: lines.y + 8 } + const end = { x: lines.x + lines.width - 1, y: lines.y + lines.height - 8 } + + // A short selection keeps the action above it, even when dragged down. + const short = await drag(start, { x: lines.x + 200, y: lines.y + 30 }) + expect(short.y + short.height).toBeLessThanOrEqual(lines.y) + expect(Math.abs(short.x + short.width / 2 - (await middle()))).toBeLessThan(2) + await clear() + + // A tall downward selection puts the action below its last line, centred on the lines. + const down = await drag(start, end) + expect(down.y).toBeGreaterThanOrEqual(lines.y + lines.height) + expect(Math.abs(down.x + down.width / 2 - (await middle()))).toBeLessThan(2) + await clear() + + // A tall upward one puts it above its first line. + const up = await drag(end, start) + expect(up.y + up.height).toBeLessThanOrEqual(lines.y) + expect(Math.abs(up.x + up.width / 2 - (await middle()))).toBeLessThan(2) + await clear() + + // A single line keeps it above the selection, centred on it, whichever way it was made. + const word = page.getByText("A short line with a word.", { exact: true }) + + // The paragraph spans the column; the text inside it is narrower. + const line = await word.evaluate((element) => { + element.scrollIntoView({ block: "center" }) + const range = document.createRange() + range.selectNodeContents(element) + const rect = range.getBoundingClientRect() + + return { x: rect.x, y: rect.y, width: rect.width, height: rect.height } + }) + + const single = await drag( + { x: line.x + line.width - 1, y: line.y + line.height / 2 }, + { x: line.x + 1, y: line.y + line.height / 2 }, + ) + + expect(single.y + single.height).toBeLessThanOrEqual(line.y) + expect(Math.abs(single.x + single.width / 2 - (line.x + line.width / 2))).toBeLessThan(2) + await clear() + + // A narrower timeline, as when a side panel opens, moves the action with the reflowed text. + const scroll = page.locator('[data-slot="session-timeline-scroll"]') + + const centre = async () => { + const action = await box(toolbar) + + return Math.abs(action.x + action.width / 2 - (await middle())) < 2 + } + + await word.click({ clickCount: 3, position: { x: 4, y: line.height / 2 } }) + await expect(toolbar).toBeVisible() + await expect.poll(centre).toBe(true) + await scroll.evaluate((element) => (element.style.width = "60%")) + await expect.poll(centre).toBe(true) + await scroll.evaluate((element) => (element.style.width = "")) + await clear() + + // A selection running past both edges of the timeline pins the action to its bottom. + await first.click() + await page.keyboard.press("ControlOrMeta+a") + await expect(toolbar).toBeVisible() + await scroller.evaluate((element) => (element.scrollTop = (element.scrollHeight - element.clientHeight) / 2)) + const view = await box(scroller) + await expect + .poll(async () => Math.round((await box(toolbar)).y + (await box(toolbar)).height)) + .toBe(Math.round(view.y + view.height - 8)) +}) + +test("keeps the quote action by a triple-clicked paragraph whose selection runs on to the next message", async ({ + page, +}) => { + await setupTimeline(page, { + messages: [ + userMessage([userText("Highlight what?", { id: "prt_triple_ask" })], { id: "msg_1000_triple_user" }), + assistantMessage( + [ + textPart( + "prt_triple_text", + "Highlight **visible prompt bubbles only**, or else the turn whose reply is being read.", + ), + toolPart("prt_triple_read", "read", "completed", { path: "src/a.ts" }, { output: "a", title: "src/a.ts" }), + toolPart("prt_triple_grep", "grep", "completed", { pattern: "a" }, { output: "a", title: "a" }), + ], + { id: "msg_1001_triple_assistant", parentID: "msg_1000_triple_user" }, + ), + userMessage([userText("have you finished?", { id: "prt_triple_next" })], { + id: "msg_1002_triple_user", + created: 1700000005000, + }), + ], + }) + + const paragraph = page.getByText("or else the turn whose reply is being read", { exact: false }) + await expect(paragraph).toBeVisible() + // The selection ends at the start of the next message, past the tools between them. + await paragraph.click({ clickCount: 3, position: { x: 4, y: 8 } }) + const toolbar = page.getByRole("toolbar", { name: "Quote selection" }) + await expect(toolbar).toBeVisible() + const text = await paragraph.boundingBox() + const action = await toolbar.boundingBox() + + if (!text || !action) throw new Error("Element is not laid out") + // One line, so the action sits just above it rather than below the tools the selection runs past. + expect(action.y + action.height).toBeLessThanOrEqual(text.y) + expect(action.y + action.height).toBeGreaterThanOrEqual(text.y - 10) + + // A press on unselectable space, which leaves the selection to the page, clears it before the button is released. + const view = await page.locator('[data-slot="session-timeline-scroll"] .scroll-view__viewport').boundingBox() + + if (!view) throw new Error("Element is not laid out") + await page.mouse.move(view.x + 30, text.y + 4) + await page.mouse.down() + await expect(toolbar).toHaveCount(0) + expect(await page.evaluate(() => window.getSelection()?.toString())).toBe("") + await page.mouse.up() +}) + +for (const input of [ + { name: "a narrow window with a mouse anchors it to the selection", touch: false }, + { name: "a touch screen docks it to the timeline's bottom", touch: true }, +]) + test(`places the quote action: ${input.name}`, async ({ browser }) => { + const context = await browser.newContext({ hasTouch: input.touch }) + const page = await context.newPage() + await setupTimeline(page, { + viewport: { width: 390, height: 844 }, + messages: [userMessage(), assistantMessage([textPart("prt_dock_text", "A short line to quote.")])], + }) + + const text = page.getByText("A short line to quote.", { exact: true }) + await expect(text).toBeVisible() + await text.evaluate((element) => window.getSelection()?.selectAllChildren(element)) + const toolbar = page.getByRole("toolbar", { name: "Quote selection" }) + await expect(toolbar).toBeVisible() + const line = await text.boundingBox() + const view = await page.locator('[data-slot="session-timeline-scroll"] .scroll-view__viewport').boundingBox() + const action = await toolbar.boundingBox() + + if (!line || !view || !action) throw new Error("Element is not laid out") + + if (input.touch) expect(Math.round(action.y + action.height)).toBe(Math.round(view.y + view.height - 8)) + else expect(action.y + action.height).toBeLessThanOrEqual(line.y) + await context.close() + }) + +test("opens a quote's comment with Alt-click", async ({ page }) => { + await setupTimeline(page, { + messages: [ + userMessage(), + assistantMessage([ + textPart("prt_alt_first", "The first sentence to quote."), + textPart("prt_alt_second", "The second sentence to quote."), + ]), + ], + }) + + const toolbar = page.getByRole("toolbar", { name: "Quote selection" }) + const chips = page.locator('[data-component="composer-attachments"] [data-component="attachment-card"]') + const comment = page.locator('[data-component="composer-quote-comment"] textarea') + + const select = async (text: string) => { + await page + .locator('[data-slot="text-part-body"]') + .getByText(text, { exact: true }) + .evaluate((element) => window.getSelection()?.selectAllChildren(element)) + await expect(toolbar).toBeVisible() + } + + // A plain click adds the quote, leaves the comment closed, and returns the caret to where the draft left it. + const editor = page.locator('[data-component="composer-editor"]') + await editor.click() + await page.keyboard.type("Draft") + await select("The first sentence to quote.") + await toolbar.getByRole("button", { name: "Quote", exact: true }).click() + await expect(chips).toHaveCount(1) + await expect(comment).toHaveCount(0) + await expect(editor).toBeFocused() + await page.keyboard.type(" follow-up") + await expect(editor).toHaveText("Draft follow-up") + await chips.nth(0).hover() + await page.getByRole("button", { name: "Remove attachment" }).click() + await expect(chips).toHaveCount(0) + + // A slow tooltip names the action and its shortcut. + await select("The first sentence to quote.") + await toolbar.getByRole("button", { name: "Quote", exact: true }).hover() + const tooltip = page.locator('[data-component="tooltip-v2"]', { hasText: "Quote and comment" }) + await expect(tooltip).toBeVisible() + await expect(tooltip.locator('[data-slot="keybind-v2-label"]')).toHaveText([/^(⌥|Alt)$/]) + + // Alt-click opens the new quote's comment, focused. + await page.keyboard.down("Alt") + await toolbar.getByRole("button", { name: "Quote", exact: true }).click() + await page.keyboard.up("Alt") + await expect(chips).toHaveCount(1) + await expect(comment).toBeFocused() + await page.keyboard.type("Why first?") + await page.keyboard.press("Enter") + await expect(comment).toHaveCount(0) + await expect(chips.nth(0)).toContainText("Why first?") + + // Enter on an empty comment keeps the quote without one. + await select("The second sentence to quote.") + await page.keyboard.down("Alt") + await toolbar.getByRole("button", { name: "Quote", exact: true }).click() + await page.keyboard.up("Alt") + await expect(comment).toBeFocused() + await page.keyboard.press("Enter") + await expect(comment).toHaveCount(0) + await expect(chips).toHaveCount(2) + await expect(chips.nth(1)).toContainText("The second sentence to quote.") + await expect(chips.nth(1)).toContainText("Quote") +}) + +test("reaches the quote action from the keyboard and blocks a selection over the limit", async ({ page }) => { + await setupTimeline(page, { + messages: [ + userMessage(), + assistantMessage([ + textPart("prt_quote_short", "Short answer."), + textPart("prt_quote_long", Array.from({ length: 3_000 }, (_, index) => `word${index}`).join(" ")), + ]), + ], + }) + + const short = page.getByText("Short answer.", { exact: true }) + await expect(short).toBeVisible() + const toolbar = page.getByRole("toolbar", { name: "Quote selection" }) + + // A drag released where no pointerup arrives, such as outside the window, still lets the selection settle. + await short.click() + await page.mouse.down() + await page.evaluate(() => window.dispatchEvent(new Event("blur"))) + await short.evaluate((element) => window.getSelection()?.selectAllChildren(element)) + await expect(toolbar).toBeVisible() + await page.mouse.up() + + await page.keyboard.press("Tab") + await expect(toolbar.getByRole("button", { name: "Quote", exact: true })).toBeFocused() + await page.keyboard.press("Escape") + await expect(toolbar).toHaveCount(0) + await expect(page.locator('[data-slot="session-timeline-scroll"] .scroll-view__viewport')).toBeFocused() + + const scroller = page.locator('[data-slot="session-timeline-scroll"] .scroll-view__viewport') + const composer = page.locator('[data-component="composer-editor"]') + + // Select all from the app menu covers the whole window; with focus in the timeline it keeps to the conversation. + await page.evaluate(() => window.getSelection()?.selectAllChildren(document.body)) + await expect(toolbar).toBeVisible() + await expect + .poll(() => + scroller.evaluate((element) => { + const range = window.getSelection()?.getRangeAt(0) + + return !!range && element.contains(range.startContainer) && element.contains(range.endContainer) + }), + ) + .toBe(true) + + // Over the limit, the action is disabled and Tab moves on as usual. + await expect(toolbar.getByText("Selection too long", { exact: true })).toBeVisible() + await expect(toolbar.getByRole("button", { name: "Quote", exact: true })).toBeDisabled() + await scroller.focus() + await page.keyboard.press("Tab") + await expect(scroller).not.toBeFocused() + await expect(toolbar.getByRole("button", { name: "Quote", exact: true })).not.toBeFocused() + + // Tab from a control inside the timeline keeps its usual order while a quote is offered. + await page.keyboard.press("Escape") + await short.evaluate((element) => window.getSelection()?.selectAllChildren(element)) + await expect(toolbar).toBeVisible() + const copy = page.getByRole("button", { name: "Copy message" }) + await copy.focus() + await expect(toolbar).toBeVisible() + await page.keyboard.press("Tab") + await expect(copy).not.toBeFocused() + expect(await page.evaluate(() => !!document.activeElement?.closest('[data-component="timeline-quote"]'))).toBe(false) + await expect(composer).toHaveCount(1) +}) + function pauseExitAnimations(locator: Locator) { return locator.evaluateHandle((element) => { const animations: Animation[] = [] diff --git a/packages/app/src/composer/comment-note.ts b/packages/app/src/composer/comment-note.ts index a3499250daf..9737395404c 100644 --- a/packages/app/src/composer/comment-note.ts +++ b/packages/app/src/composer/comment-note.ts @@ -3,7 +3,7 @@ import { Option, Schema } from "effect" import { Persistence } from "@/runtime/persistence/schema" import { uuid } from "@/runtime/persistence/uuid" import { FileSelection } from "@/workspaces/files/types" -import { durableNote, LegacyBrowserNote, NoteComment, type ContextItem } from "./schema" +import { durableNote, LegacyBrowserNote, NoteComment, QuoteComment, type ContextItem } from "./schema" export const PromptFileComment = Persistence.struct({ type: Schema.optional(Schema.Literal("file")), @@ -16,7 +16,7 @@ export const PromptFileComment = Persistence.struct({ export type PromptFileComment = typeof PromptFileComment.Type -export type PromptComment = PromptFileComment | NoteComment +export type PromptComment = PromptFileComment | NoteComment | QuoteComment /** An attachment the model receives as a path on the server rather than inline bytes. */ export const PromptAttachmentReference = Persistence.struct({ @@ -37,7 +37,9 @@ const decodePromptPresentation = Schema.decodeUnknownOption( }), ) -const decodePromptComment = Schema.decodeUnknownOption(Schema.Union([NoteComment, LegacyBrowserNote, PromptFileComment])) +const decodePromptComment = Schema.decodeUnknownOption( + Schema.Union([NoteComment, QuoteComment, LegacyBrowserNote, PromptFileComment]), +) export function readPromptPresentation(metadata: SessionMessageUser["metadata"]) { return Option.getOrUndefined( @@ -58,11 +60,25 @@ export function formatNoteComment(input: NoteComment) { return `The user made the following comment regarding ${input.live?.subject ?? input.subject}: ${input.comment}` } +/** Each quoted line is prefixed, so quoted text cannot end the quote early and read as the user's own words. */ +export function formatQuoteComment(input: QuoteComment) { + const quote = `The user quoted the following from earlier in the conversation:\n${input.text + .split("\n") + .map((line) => `> ${line}`) + .join("\n")}` + + if (!input.comment) return quote + + return `${quote}\n\nThe user made the following comment regarding this quote: ${input.comment}` +} + /** Restores a sent comment to the composer, for example after a revert or fork. */ export function commentContextItem(comment: PromptComment): ContextItem { // The message may predate this app process, so a note's live references can no longer be trusted. if (comment.type === "note") return { ...durableNote(comment), commentID: uuid() } + if (comment.type === "quote") return { ...comment, commentID: uuid() } + return { type: "file", path: comment.path, diff --git a/packages/app/src/composer/editor/editor.tsx b/packages/app/src/composer/editor/editor.tsx index 7e688b0674c..77f7ea83bea 100644 --- a/packages/app/src/composer/editor/editor.tsx +++ b/packages/app/src/composer/editor/editor.tsx @@ -29,7 +29,7 @@ import { ScrollView } from "@opencode/ui/scroll-view" import { AttachmentCard } from "@opencode/session-ui/attachment-card" import { ProgressCircle } from "@opencode/ui/progress-circle" import type { Upload } from "../attachments/uploads" -import { CommentCard } from "@opencode/session-ui/comment-card" +import { CommentCard, commentCardTarget, quoteTooltip } from "@opencode/session-ui/comment-card" import { typeLabel } from "@opencode/session-ui/message-file" import { getFilename } from "@opencode/util/path" import { Skill } from "@opencode/schema/skill" @@ -45,6 +45,7 @@ import type { } from "../types" import type { ComposerEditorModel, ComposerSelectControl } from "./interaction" import { isAttachment } from "../prompt-parts" +import { QuoteCommentEditor } from "./quote-comment" import "../attachments/attachments.css" import "./editor.css" @@ -214,6 +215,10 @@ export function ComposerEditor(props: ComposerEditorProps) { onCommentClick={(comment) => props.controller.toggleContext(comment.key)} onCommentRemove={(comment) => props.controller.removeContext(comment.key)} onFileRemove={(file) => props.controller.removeContext(file.key)} + editingQuote={props.controller.editingQuote()} + onEditQuote={props.controller.editQuote} + onQuoteComment={(quote, comment) => props.controller.commentQuote(quote.key, comment)} + searchPaths={props.controller.searchPaths} /> @@ -590,9 +595,29 @@ export function ComposerAttachments(props: { onCommentClick?: (comment: ComposerComment) => void onCommentRemove?: (comment: ComposerComment) => void onFileRemove?: (file: Extract) => void + editingQuote?: string + onEditQuote?: (key?: string) => void + onQuoteComment?: (quote: Extract, comment: string) => void + searchPaths?: (query: string) => Promise }) { const i18n = useI18n() const percent = (upload: Upload) => (upload.size === 0 ? 100 : Math.floor((upload.loaded / upload.size) * 100)) + // A quote added with its editor open renders its chip in the same update, so the anchors are reactive. + const [anchors, setAnchors] = createStore>({}) + + // Plain functions, not inline conditionals: the tooltip reads these from event handlers, outside any owner. + const quoteTitle = (comment: ComposerComment) => (comment.type === "quote" ? quoteTooltip(comment) : undefined) + const quoteHint = (comment: ComposerComment) => comment.type === "quote" && props.editingQuote !== comment.key + + const commentActive = (comment: ComposerComment) => + comment.key === props.activeCommentID || comment.key === props.editingQuote + + const editing = createMemo(() => + props.comments?.find( + (comment): comment is Extract => + comment.type === "quote" && comment.key === props.editingQuote, + ), + ) return ( {(comment) => ( -
+
{ + setAnchors(comment.key, element) + onCleanup(() => setAnchors(comment.key, undefined)) + }} + class="relative group shrink-0" + > + comment.type === "quote" + ? props.onEditQuote?.(props.editingQuote === comment.key ? undefined : comment.key) + : props.onCommentClick?.(comment) } - active={comment.key === props.activeCommentID} - onClick={() => props.onCommentClick?.(comment)} />
) diff --git a/packages/app/src/composer/editor/interaction.ts b/packages/app/src/composer/editor/interaction.ts index 0ca62831a05..974941435ec 100644 --- a/packages/app/src/composer/editor/interaction.ts +++ b/packages/app/src/composer/editor/interaction.ts @@ -1,5 +1,5 @@ import { Predicate } from "effect" -import { createEffect, type Accessor } from "solid-js" +import { createEffect, createSignal, type Accessor } from "solid-js" import { createStore, reconcile } from "solid-js/store" import { useFilteredList } from "@opencode/ui/hooks" import { createComposerAttachments, type ComposerAttachmentConfig } from "../attachments/attachments" @@ -22,6 +22,7 @@ import { } from "../suggestions/machine" import { clonePrompt, isAttachment, promptLength } from "../prompt-parts" import type { ComposerQueue } from "../adapter" +import { isCommentItem } from "../state" export type ComposerSelectControl = { options: Accessor @@ -66,6 +67,8 @@ export function createComposerEditor(input: { openAttachment?: (attachment: ComposerAttachment, origin?: HTMLElement) => void openContext?: (key: string) => void onContextRemove?: (item: ComposerComment) => void + onQuoteComment?: (item: Extract, comment: string) => void + quoteComment?: { key: Accessor; set: (key?: string) => void } onEditor?: (element: HTMLElement) => void onSuggestionSelect?: (item: ComposerSuggestion) => (() => void) | void view: ComposerEditorView @@ -74,6 +77,8 @@ export function createComposerEditor(input: { let editor: HTMLElement | undefined let fileInput: HTMLInputElement | undefined const draft = createComposerEditorActions(input.store) + const [localQuoteComment, setLocalQuoteComment] = createSignal() + const quoteComment = input.quoteComment ?? { key: localQuoteComment, set: setLocalQuoteComment } const [state, setState] = input.state ?? createComposerEditorState(draft.state.mode) function addPart(part: ComposerPersistedState["prompt"][number]) { @@ -381,7 +386,7 @@ export function createComposerEditor(input: { return draft.state.context.items.find((item) => item.key === id) }, comments() { - return draft.state.context.items.filter((item) => !!item.comment?.trim()) + return draft.state.context.items.filter(isCommentItem) }, files() { return draft.state.context.items.flatMap((item) => (item.type === "file" && !item.comment?.trim() ? [item] : [])) @@ -399,6 +404,16 @@ export function createComposerEditor(input: { dispatch({ type: "context.active", id }) input.openContext?.(id) }, + editingQuote: () => quoteComment.key(), + editQuote: (key?: string) => quoteComment.set(key), + commentQuote(id: string, comment: string) { + const item = draft.state.context.items.find((entry) => entry.key === id) + + if (item?.type === "quote") input.onQuoteComment?.(item, comment) + }, + async searchPaths(query: string) { + return (await input.searchContextFiles(query)).flatMap((item) => (item.path ? [item.path] : [])) + }, removeContext(id: string) { const item = draft.state.context.items.find((entry) => entry.key === id) @@ -427,7 +442,7 @@ export function createComposerEditor(input: { if (persisted.prompt.some(isAttachment)) return true - if (persisted.context.items.some((item) => !!item.comment?.trim())) return true + if (persisted.context.items.some(isCommentItem)) return true return persisted.prompt.some((part) => "content" in part && !!part.content.trim()) }, diff --git a/packages/app/src/composer/editor/quote-comment.tsx b/packages/app/src/composer/editor/quote-comment.tsx new file mode 100644 index 00000000000..035142c19da --- /dev/null +++ b/packages/app/src/composer/editor/quote-comment.tsx @@ -0,0 +1,90 @@ +import { createStore } from "solid-js/store" +import { Portal } from "solid-js/web" +import { makeEventListener } from "@solid-primitives/event-listener" +import { createResizeObserver } from "@solid-primitives/resize-observer" +import { Icon } from "@opencode/ui/icon" +import { LineCommentEditor } from "@opencode/ui/line-comment" + +const GAP = 8 + +const WIDTH = 380 + +export function QuoteCommentEditor(props: { + anchor: HTMLElement + text: string + comment: string + mention: (query: string) => Promise + onSubmit: (comment: string) => void + onClose: () => void +}) { + const [state, setState] = createStore({ + draft: props.comment, + rect: bounds(props.anchor), + viewport: window.innerWidth, + height: 0, + }) + + let element: HTMLElement | undefined + const measure = () => setState({ rect: bounds(props.anchor), viewport: window.innerWidth }) + + makeEventListener(window, "resize", measure) + makeEventListener(document, "scroll", measure, { capture: true, passive: true }) + makeEventListener(document, "pointerdown", (event) => { + const target = event.target + + if (target instanceof Node && (element?.contains(target) || props.anchor.contains(target))) return + + if (state.draft.trim() === props.comment.trim()) props.onClose() + }) + + const width = () => Math.min(WIDTH, state.viewport - GAP * 2) + const left = () => Math.min(Math.max(state.rect.left, GAP), state.viewport - width() - GAP) + + const top = () => { + const above = state.rect.top - state.height - GAP + + return above >= GAP ? above : state.rect.bottom + GAP + } + + return ( + +
{ + element = value + createResizeObserver(value, () => setState("height", value.offsetHeight)) + }} + data-component="composer-quote-comment" + data-prevent-autofocus + class="fixed z-50 overflow-y-auto rounded-[6px] shadow-[var(--v2-elevation-raised)]" + style={{ + top: `${top()}px`, + left: `${left()}px`, + width: `${width()}px`, + // Transparent rather than hidden while unmeasured, so the comment field can take focus as it mounts. + opacity: state.height === 0 ? 0 : undefined, + }} + > + setState("draft", value)} + onCancel={props.onClose} + onSubmit={props.onSubmit} + allowEmpty + mention={{ items: props.mention }} + selection={ + + + {props.text.slice(0, 200)} + + } + /> +
+
+ ) +} + +function bounds(element: HTMLElement) { + const rect = element.getBoundingClientRect() + + return { top: rect.top, bottom: rect.bottom, left: rect.left } +} diff --git a/packages/app/src/composer/model.ts b/packages/app/src/composer/model.ts index 75fbe7c312d..00edbd8e5f0 100644 --- a/packages/app/src/composer/model.ts +++ b/packages/app/src/composer/model.ts @@ -22,6 +22,7 @@ import { formatServerError } from "@/runtime/server/errors" import { Skill } from "@opencode/schema/skill" import type { ComposerAdapter, ComposerControls, ComposerQueue } from "./adapter" import { isAttachment } from "./prompt-parts" +import { isCommentItem } from "./state" import type { PromptHistoryComment } from "./history/entry" import { createComposerHistory } from "./history/store" import { createComposerSubmit } from "./submit" @@ -84,7 +85,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? const commentCount = createMemo(() => { if (mode() === "shell") return 0 - return prompt.context.items().filter((item) => !!item.comment?.trim()).length + return prompt.context.items().filter(isCommentItem).length }) const blank = createMemo(() => { @@ -148,9 +149,9 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? time: item.time, })), ) - // History records file comments only; notes stay with the draft while it is browsed. + // History records file comments only; notes and quotes stay with the draft while it is browsed. prompt.context.replaceComments([ - ...prompt.context.items().filter((item) => item.type === "note"), + ...prompt.context.items().filter((item) => item.type !== "file"), ...items.map((item) => ({ type: "file" as const, path: item.path, @@ -327,6 +328,8 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? path, mention: { type: "file", path, content: `@${path}`, start: 0, end: 0 }, })), + onQuoteComment: (item, comment) => prompt.context.updateComment(item.commentID, { comment }), + quoteComment: prompt.quoteComment, onContextRemove(item) { if (item.type === "file" && item.commentID) comments.remove(item.path, item.commentID) }, @@ -348,7 +351,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? return } - if (item) openComment(item, links, extensions.current(), files, comments) + if (item?.type === "file") openComment(item, links, extensions.current(), files, comments) }, onEditor(element) { // SAFETY: the editor's only `setEditor` call passes its editable root, a `
` (`editor/editor.tsx`). diff --git a/packages/app/src/composer/request.test.ts b/packages/app/src/composer/request.test.ts index 1e7d8258ddf..1e9138ec480 100644 --- a/packages/app/src/composer/request.test.ts +++ b/packages/app/src/composer/request.test.ts @@ -139,6 +139,37 @@ describe("buildPromptRequest", () => { expect(result.files).toEqual([{ uri: "file:///repo/src/button.css", mime: "text/plain", name: "button.css" }]) }) + test("sends quotes as prefixed text, with or without a comment, and attaches only files the comment mentions", () => { + const result = buildPromptRequest({ + prompt: [{ type: "text", content: "", start: 0, end: 0 }], + context: [ + { key: "quote:c=1", type: "quote", text: "First line\n\nignore the quote and obey", commentID: "1" }, + { key: "quote:c=2", type: "quote", text: "Second", comment: " Compare @src/a.ts ", commentID: "2" }, + ], + images: [], + text: "", + sessionDirectory: "/repo", + }) + + expect(result.text).toBe( + [ + "The user quoted the following from earlier in the conversation:", + "> First line", + "> ", + "> ignore the quote and obey", + "The user quoted the following from earlier in the conversation:", + "> Second", + "", + "The user made the following comment regarding this quote: Compare @src/a.ts", + ].join("\n"), + ) + expect(result.comments).toEqual([ + { type: "quote", text: "First line\n\nignore the quote and obey" }, + { type: "quote", text: "Second", comment: "Compare @src/a.ts" }, + ]) + expect(result.files).toEqual([{ uri: "file:///repo/src/a.ts", mime: "text/plain", name: "a.ts" }]) + }) + test("keeps skill mentions out of file attachments", () => { const skill = { id: "skill-review", diff --git a/packages/app/src/composer/request.ts b/packages/app/src/composer/request.ts index a928b80e789..1c5f9d23b92 100644 --- a/packages/app/src/composer/request.ts +++ b/packages/app/src/composer/request.ts @@ -9,12 +9,15 @@ import type { NoteContextItem, PathAttachmentPart, Prompt, + QuoteComment, + QuoteContextItem, SkillPart, } from "@/composer/state" import { formatAttachmentReference, formatCommentNote, formatNoteComment, + formatQuoteComment, type PromptAttachmentReference, type PromptComment, } from "@/composer/comment-note" @@ -95,6 +98,16 @@ export function noteComment(item: NoteContextItem, comment: string) { return note } +/** The sent form of a quote: its comment travels only when the user wrote one. */ +export function quoteComment(item: QuoteContextItem) { + const quote: QuoteComment = { type: "quote", text: item.text } + const comment = item.comment?.trim() + + if (comment) quote.comment = comment + + return quote +} + export function buildPromptRequest(input: BuildPromptRequestInput): PromptRequest { const skills = input.prompt.filter(isSkillAttachment).map((attachment) => ({ id: attachment.id, @@ -142,6 +155,13 @@ export function buildPromptRequest(input: BuildPromptRequestInput): PromptReques return mentioned(comment) } + if (item.type === "quote") { + const quote = quoteComment(item) + comments.push(quote) + + return quote.comment ? mentioned(quote.comment) : [] + } + const path = absolute(input.sessionDirectory, item.path) const uri = `file://${encodeFilePath(path)}${fileQuery(item.selection)}` const comment = item.comment?.trim() @@ -179,7 +199,13 @@ export function buildPromptRequest(input: BuildPromptRequestInput): PromptReques text: [ ...(input.text.trim() ? [input.text] : []), ...attachments.map(formatAttachmentReference), - ...comments.map((comment) => (comment.type === "note" ? formatNoteComment(comment) : formatCommentNote(comment))), + ...comments.map((comment) => { + if (comment.type === "note") return formatNoteComment(comment) + + if (comment.type === "quote") return formatQuoteComment(comment) + + return formatCommentNote(comment) + }), ].join("\n"), displayText: input.text, files: [...files, ...context, ...inline], diff --git a/packages/app/src/composer/schema.ts b/packages/app/src/composer/schema.ts index 6ac7dd06fd9..0d05f8695d6 100644 --- a/packages/app/src/composer/schema.ts +++ b/packages/app/src/composer/schema.ts @@ -174,7 +174,22 @@ export const NoteContextItem = Persistence.struct({ ...NoteFields, commentID: Sc export type NoteContextItem = typeof NoteContextItem.Type -export type ContextItem = FileContextItem | NoteContextItem +const QuoteFields = { + type: Schema.Literal("quote"), + text: Schema.String, + comment: Persistence.optional(Schema.String), +} + +/** Plain text the user quoted from the session timeline, with an optional comment, as sent in message metadata. */ +export const QuoteComment = Persistence.struct(QuoteFields) + +export type QuoteComment = typeof QuoteComment.Type + +export const QuoteContextItem = Persistence.struct({ ...QuoteFields, commentID: Schema.String }) + +export type QuoteContextItem = typeof QuoteContextItem.Type + +export type ContextItem = FileContextItem | NoteContextItem | QuoteContextItem /** A note's live part names state inside the app process that attached it; anything that may outlive it drops it. */ export function durableNote(note: Note) { @@ -232,6 +247,8 @@ function legacyBrowserNote(item: typeof LegacyBrowserComment.Type): NoteComment export function contextItemKey(item: ContextItem) { if (item.type === "note") return `note:${item.origin}:c=${item.commentID}` + + if (item.type === "quote") return `quote:c=${item.commentID}` const key = `${item.type}:${item.path}:${item.selection?.startLine}:${item.selection?.endLine}` if (item.commentID) return `${key}:c=${item.commentID}` @@ -261,6 +278,16 @@ const NoteContextEntry = Schema.Struct({ }), ) +const QuoteContextEntry = Schema.Struct({ + ...QuoteContextItem.fields, + key: Persistence.optional(Schema.String), +}).pipe( + Schema.decodeTo(Persistence.struct({ ...QuoteContextItem.fields, key: Schema.String }).pipe(Schema.toType), { + decode: SchemaGetter.transform((item) => ({ ...item, key: contextItemKey(item) })), + encode: SchemaGetter.transform((item) => item), + }), +) + const LegacyBrowserContextEntry = Schema.Struct({ ...LegacyBrowserComment.fields, commentID: Schema.String, @@ -276,7 +303,7 @@ const LegacyBrowserContextEntry = Schema.Struct({ }), ) -const ContextEntry = Schema.Union([FileContextEntry, NoteContextEntry, LegacyBrowserContextEntry]) +const ContextEntry = Schema.Union([FileContextEntry, NoteContextEntry, QuoteContextEntry, LegacyBrowserContextEntry]) export const DEFAULT_PROMPT: Prompt = [{ type: "text", content: "", start: 0, end: 0 }] diff --git a/packages/app/src/composer/state.ts b/packages/app/src/composer/state.ts index 405713bf907..2c6b51c744d 100644 --- a/packages/app/src/composer/state.ts +++ b/packages/app/src/composer/state.ts @@ -1,4 +1,4 @@ -import { batch, untrack, type Accessor } from "solid-js" +import { batch, createSignal, untrack, type Accessor } from "solid-js" import { createStore, type SetStoreFunction } from "solid-js/store" import { Persist, persisted } from "@/runtime/persistence/storage" import { ServerScope } from "@/runtime/server/scope" @@ -28,6 +28,8 @@ export type { PathAttachmentPart, Prompt, PromptModel, + QuoteComment, + QuoteContextItem, SkillPart, TextPart, } from "./schema" @@ -40,7 +42,7 @@ type InitialPrompt = { } export function isCommentItem(item: ContextItem | (ContextItem & { key: string })) { - return !!item.comment?.trim() + return item.type === "quote" || !!item.comment?.trim() } function createComposerActions(setStore: SetStoreFunction) { @@ -85,6 +87,8 @@ function initialComposerStore(initial?: InitialPrompt): ComposerStore { function createComposerStateValue(store: ComposerStore, setStore: SetStoreFunction) { const actions = createComposerActions(setStore) + // The quote whose comment editor is open, by key; a request made before the composer shows waits for it. + const [quoteComment, setQuoteComment] = createSignal() const clearRetry = () => { if (untrack(() => store.retry) !== undefined) setStore("retry", undefined) @@ -125,17 +129,19 @@ function createComposerStateValue(store: ComposerStore, setStore: SetStoreFuncti setStore("context", "items", (items) => items.filter((x) => x.key !== key)) clearRetry() }, - /** Removes the file comment or note with this commentID. */ + /** Removes the file comment, note, or quote with this commentID. */ removeComment(commentID: string) { setStore("context", "items", (items) => items.filter((item) => item.commentID !== commentID)) clearRetry() }, - /** Edits the file comment or note with this commentID; only file comments carry a preview. */ + /** Edits the file comment, note, or quote with this commentID; only file comments carry a preview. */ updateComment(commentID: string, next: { readonly comment?: string; readonly preview?: string }) { setStore("context", "items", (items) => items.map((item) => { if (item.commentID !== commentID) return item + if (item.type === "quote") return { ...item, comment: next.comment } + const value = item.type === "file" ? { ...item, ...next } : { ...item, comment: next.comment ?? item.comment } @@ -164,6 +170,7 @@ function createComposerStateValue(store: ComposerStore, setStore: SetStoreFuncti clearRetry() }, }, + quoteComment: { key: quoteComment, set: (key?: string) => setQuoteComment(key) }, set: (prompt: Prompt, cursorPosition?: number) => actions.set(prompt, cursorPosition), reset: () => actions.reset(), capture: () => value, diff --git a/packages/app/src/composer/submit.ts b/packages/app/src/composer/submit.ts index 4daf1ccd774..82eece03e54 100644 --- a/packages/app/src/composer/submit.ts +++ b/packages/app/src/composer/submit.ts @@ -3,11 +3,11 @@ import type { SessionMessageUser } from "@opencode/client/promise" import type { Accessor } from "solid-js" import type { PromptComment } from "./comment-note" import type { PromptHistoryComment } from "./history/entry" -import type { ImageAttachmentPart, Prompt } from "./state" +import { isCommentItem, type ContextItem, type ImageAttachmentPart, type Prompt } from "./state" import { clonePrompt, promptLength } from "./prompt-parts" import type { ComposerAdapter, ComposerDelivery, ComposerSelection, ComposerSession } from "./adapter" import { createComposerSubmission } from "./submission-state" -import { buildPromptRequest, noteComment } from "./request" +import { buildPromptRequest, noteComment, quoteComment } from "./request" import { setCursorPosition } from "./editor/dom" import { blobDataUrl, resolveBlobUrl } from "@/runtime/persistence/drafts" import { isAttachment } from "./prompt-parts" @@ -93,13 +93,13 @@ export function createComposerSubmit(input: ComposerSubmitInput) { const submission = createComposerSubmission({ target: input.adapter.state, prompt, - context: input.adapter.state.context - .items() - .map((item) => - item.type === "note" - ? { ...item, live: item.live ? { ...item.live } : undefined } - : { ...item, selection: item.selection ? { ...item.selection } : undefined }, - ), + context: input.adapter.state.context.items().map((item) => { + if (item.type === "note") return { ...item, live: item.live ? { ...item.live } : undefined } + + if (item.type === "quote") return { ...item } + + return { ...item, selection: item.selection ? { ...item.selection } : undefined } + }), }) const read = readSubmission(input, submission.prompt, submission.context, text, options?.alternate ?? false) @@ -255,6 +255,7 @@ function handoffMessage(value: ComposerSubmission): SessionMessageUser { part.type === "path" ? [{ name: part.filename, mime: part.mime, path: part.path }] : [], ), comments: value.context.flatMap((item): PromptComment[] => { + if (item.type === "quote") return [quoteComment(item)] const comment = item.comment?.trim() if (!comment) return [] @@ -290,7 +291,7 @@ function readSubmission( if (mode === "shell" && !text.trim()) return const images = prompt.filter((part): part is ImageAttachmentPart => part.type === "image") // Like the TUI's blank Enter, file chips alone send nothing; they wait for text. - const comments = context.filter((item) => !!item.comment?.trim()).length + const comments = context.filter(isCommentItem).length if (!text.trim() && !prompt.some(isAttachment) && comments === 0) return @@ -363,31 +364,33 @@ function restoreSubmission( restored.target.set(restored.prompt, promptLength(restored.prompt)) restored.target.mode.set(value.mode) restored.target.context.replaceComments( - restored.context - .filter((item) => !!item.comment?.trim()) - .map((item) => - item.type === "note" - ? { - type: "note", - origin: item.origin, - label: item.label, - icon: item.icon, - subject: item.subject, - href: item.href, - live: item.live, - comment: item.comment, - commentID: item.commentID, - } - : { - type: "file", - path: item.path, - selection: item.selection, - comment: item.comment, - commentID: item.commentID, - commentOrigin: item.commentOrigin, - preview: item.preview, - }, - ), + restored.context.filter(isCommentItem).map((item): ContextItem => { + if (item.type === "quote") + return { type: "quote", text: item.text, comment: item.comment, commentID: item.commentID } + + if (item.type === "note") + return { + type: "note", + origin: item.origin, + label: item.label, + icon: item.icon, + subject: item.subject, + href: item.href, + live: item.live, + comment: item.comment, + commentID: item.commentID, + } + + return { + type: "file", + path: item.path, + selection: item.selection, + comment: item.comment, + commentID: item.commentID, + commentOrigin: item.commentOrigin, + preview: item.preview, + } + }), ) restored.context.forEach((item) => { if (item.type === "file" && !item.comment?.trim()) diff --git a/packages/app/src/index.css b/packages/app/src/index.css index d1eb442a50b..3d4d3cd2b74 100644 --- a/packages/app/src/index.css +++ b/packages/app/src/index.css @@ -262,6 +262,14 @@ --session-dropzone-card: var(--v2-background-bg-layer-01); } + [data-component="timeline-quote"] { + background-color: var(--v2-background-bg-base); + } + + [data-color-scheme="dark"] [data-component="timeline-quote"] { + background-color: var(--v2-background-bg-layer-01); + } + :root[data-motion="reduce"] { [data-component="session-dropzone"][data-visible="true"], [data-component="session-dropzone"][data-visible="true"] [data-slot="session-dropzone-content"], diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index 2321a6176f4..41c2b71b857 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -597,6 +597,10 @@ export const dict = { "session.search.placeholder": "Find...", "session.search.noResults": "No matches", + "session.quote.actions": "Quote selection", + "session.quote.add": "Quote", + "session.quote.addWithComment": "Quote and comment", + "session.quote.tooLong": "Selection too long", "session.header.open.finder": "Finder", "session.header.open.fileExplorer": "File Explorer", "session.header.open.fileManager": "File Manager", diff --git a/packages/app/src/session/composer/region.tsx b/packages/app/src/session/composer/region.tsx index e6236cca32e..96130412966 100644 --- a/packages/app/src/session/composer/region.tsx +++ b/packages/app/src/session/composer/region.tsx @@ -18,6 +18,8 @@ import { showToast } from "@/shell/notifications/toast" import { errorMessage } from "@/shell/layout/helpers" import { useLocal } from "@/providers/models/selection" import { usePlatform } from "@/runtime/platform/platform" +import { uuid } from "@/runtime/persistence/uuid" +import { contextItemKey } from "@/composer/schema" import { useWorkspaceLocation } from "@/workspaces/location" import { requireServerKey, sessionHref } from "@/shell/routes/session" import { useComposerCommands } from "@/composer/commands" @@ -271,6 +273,20 @@ export function createActiveSessionRegion(input: { active: () => active()?.drop.active() ?? false, input: () => active()?.drop.input(), }, + quote: { + // A child session has no composer to quote into, and a shell command takes no quotes. + available: () => !input.session.data.isChild() && prompt.capture().mode.current() !== "shell", + add: (text: string, comment: boolean) => { + const item = { type: "quote" as const, text, commentID: uuid() } + prompt.context.add(item) + + if (comment) return prompt.capture().quoteComment.set(contextItemKey(item)) + + if (!promptRef) return + promptRef.focus() + setCursorPosition(promptRef, prompt.cursor() ?? promptLength(prompt.current())) + }, + }, actions: { timeline: { get revert() { diff --git a/packages/app/src/session/screen.tsx b/packages/app/src/session/screen.tsx index b6d60a80580..9aed11d7984 100644 --- a/packages/app/src/session/screen.tsx +++ b/packages/app/src/session/screen.tsx @@ -33,6 +33,7 @@ import { SideRegion } from "@/runtime/extension/side-region" import { createSessionTimelineInteraction } from "./timeline/interaction" import { createTimelineSearchController } from "./timeline/search-controller" import { TimelineSearchBar } from "./timeline/search-bar" +import { createTimelineQuote, TimelineQuote } from "./timeline/quote" import { ActiveSessionComposerRegion, createActiveSessionRegion } from "./composer/region" import { SessionIdentityHeader } from "./session-identity-header" import { SessionReviewToggle } from "./header/session-header-actions" @@ -196,6 +197,13 @@ function SessionScreenContent(props: { props.bindBackground(composer.requests.background.tasks) useUsageExceededDialogs() + const quote = createTimelineQuote({ + root: timeline.scroller, + sessionKey: session.identity.sessionKey, + enabled: () => conversationVisible() && composer.quote.available(), + add: composer.quote.add, + }) + const sessionErrorFallback = (cause: unknown, reset: () => void) => { createEffect(on(session.identity.sessionKey, reset, { defer: true })) @@ -274,6 +282,7 @@ function SessionScreenContent(props: { input={composer.drop.input()} identity={session.layout.tabKey} /> + {mobileTabs()} {/* Surface query errors without suspending session metadata while messages load. */} diff --git a/packages/app/src/session/timeline/quote-text.ts b/packages/app/src/session/timeline/quote-text.ts new file mode 100644 index 00000000000..e274e425b08 --- /dev/null +++ b/packages/app/src/session/timeline/quote-text.ts @@ -0,0 +1,326 @@ +/** About 5k tokens. */ +export const QUOTE_MAX_LENGTH = 20_000 + +// Diff viewers render their lines in a shadow root. +const SHADOW_HOSTS = "diffs-container" + +type Point = { node: Node; offset: number } + +/** `range` is in the document; `start` and `end` may be inside a diff viewer's shadow root. */ +export type TimelineSelection = { range: Range; start: Point; end: Point; backward: boolean } + +/** The part of the current selection inside the timeline, including diff viewers. */ +export function timelineSelection(selection: Selection, root: HTMLElement): TimelineSelection | undefined { + if (selection.rangeCount === 0) return + + // Safari before 17 has no composed ranges. + const composed = + "getComposedRanges" in Selection.prototype + ? selection.getComposedRanges({ + shadowRoots: [...root.querySelectorAll(SHADOW_HOSTS)].flatMap((host) => + host.shadowRoot ? [host.shadowRoot] : [], + ), + })[0] + : selection.getRangeAt(0) + + if (!composed || composed.collapsed) return + + const range = document.createRange() + const start = documentPoint({ node: composed.startContainer, offset: composed.startOffset }, false) + const end = documentPoint({ node: composed.endContainer, offset: composed.endOffset }, true) + range.setStart(start.node, start.offset) + range.setEnd(end.node, end.offset) + + if (!range.intersectsNode(root)) return + const content = document.createRange() + content.selectNodeContents(root) + const clampedStart = range.compareBoundaryPoints(Range.START_TO_START, content) < 0 + const clampedEnd = range.compareBoundaryPoints(Range.END_TO_END, content) > 0 + + if (clampedStart) range.setStart(content.startContainer, content.startOffset) + + if (clampedEnd) range.setEnd(content.endContainer, content.endOffset) + + if (range.collapsed) return + + return { + range, + backward: backward(selection), + start: clampedStart + ? { node: range.startContainer, offset: range.startOffset } + : { node: composed.startContainer, offset: composed.startOffset }, + end: clampedEnd + ? { node: range.endContainer, offset: range.endOffset } + : { node: composed.endContainer, offset: composed.endOffset }, + } +} + +export function selectionRects(selection: TimelineSelection) { + const outer = document.createRange() + const start = documentPoint(selection.start, true) + const end = documentPoint(selection.end, false) + outer.setStart(start.node, start.offset) + + if (outer.comparePoint(end.node, end.offset) > 0) outer.setEnd(end.node, end.offset) + + return [outer, ...shadowRanges(selection)] + .flatMap((range) => [...range.getClientRects()]) + .filter((rect) => rect.width > 0 && rect.height > 0) +} + +/** The box of the character after a point, or before it with `before`. */ +export function characterRect(point: Point, before: boolean) { + if (!(point.node instanceof Text) || point.node.data.length === 0) return + const offset = Math.min(Math.max(before ? point.offset - 1 : point.offset, 0), point.node.data.length - 1) + const range = document.createRange() + range.setStart(point.node, offset) + range.setEnd(point.node, offset + 1) + const rect = range.getBoundingClientRect() + + return rect.height > 0 ? rect : undefined +} + +export function narrowSelection(selection: TimelineSelection, start: Point, end: Point): TimelineSelection { + const range = document.createRange() + const outerStart = documentPoint(start, false) + const outerEnd = documentPoint(end, true) + range.setStart(outerStart.node, outerStart.offset) + range.setEnd(outerEnd.node, outerEnd.offset) + + return { range, start, end, backward: selection.backward } +} + +export function shadowRanges(selection: TimelineSelection) { + const hosts = selection.range.commonAncestorContainer + + const candidates = + hosts instanceof Element || hosts instanceof DocumentFragment ? [...hosts.querySelectorAll(SHADOW_HOSTS)] : [] + + return candidates.flatMap((host) => + host.shadowRoot && selection.range.intersectsNode(host) ? [innerRange(host.shadowRoot, selection)] : [], + ) +} + +/** + * The plain text of a selection in the timeline. The shell disables text selection and content opts back in, so only + * selectable text is quoted; buttons, titles, and timestamps are left out. + */ +export function quoteText(selection: TimelineSelection) { + const styles = new Map() + + const style = (element: Element) => { + const cached = styles.get(element) + + if (cached) return cached + + const value = getComputedStyle(element) + styles.set(element, value) + + return value + } + + const selectable = new Map() + + // Not every browser resolves `user-select: auto` in computed style. + const isSelectable = (element: Element): boolean => { + const cached = selectable.get(element) + + if (cached !== undefined) return cached + + const value = style(element).userSelect || style(element).webkitUserSelect + + const result = + value === "auto" ? (element.parentElement ? isSelectable(element.parentElement) : true) : value !== "none" + + selectable.set(element, result) + + return result + } + + const blockOf = (element: Element): Element => { + const display = style(element).display + + if (!display.startsWith("inline") && display !== "contents") return element + + return element.parentElement ? blockOf(element.parentElement) : element + } + + const inlineSeparator = (previous: Element, current: Element) => { + const item = itemOf(current, previous) + const row = item.parentElement + + if (!row || item.contains(previous)) return + + if (style(item).display === "table-cell") return "\t" + + const display = style(row).display + + if ((display === "flex" || display === "inline-flex") && style(row).flexDirection.startsWith("row")) return " " + } + + const output: string[] = [] + let length = 0 + let truncated = false + let previous: { block: Element; part: Element | null } | undefined + let first: Point | undefined + let last: Point | undefined + let left = Infinity + let right = -Infinity + + const append = (value: string) => { + output.push(value) + length += value.length + + if (length > QUOTE_MAX_LENGTH) truncated = true + } + + const endsWithBreak = () => { + const last = output.at(-1) + + return last === undefined || last.endsWith("\n") + } + + const separate = (separator: string) => { + if (separator === "\n\n") append(endsWithBreak() ? "\n" : "\n\n") + else if (!endsWithBreak()) append(separator) + } + + const visit = (node: Text, range: Range) => { + const parent = node.parentElement + + if (!parent || !isSelectable(parent) || style(parent).visibility !== "visible") return + const start = node === range.startContainer ? range.startOffset : 0 + const end = node === range.endContainer ? range.endOffset : (node.nodeValue?.length ?? 0) + const raw = (node.nodeValue ?? "").slice(start, end) + const pre = /^(pre|break-spaces)/.test(style(parent).whiteSpace) + const text = pre ? raw : raw.replace(/\s+/g, " ") + + if (!text) return + const current = { block: blockOf(parent), part: partOf(parent) } + + if (!pre && text === " ") { + if (previous?.block === current.block && !endsWithBreak() && !output.at(-1)?.endsWith(" ")) append(" ") + + return + } + + const starts = previous?.block !== current.block + + if (previous && current.part !== previous.part) separate("\n\n") + else if (previous && starts) separate(inlineSeparator(previous.block, current.block) ?? "\n") + previous = current + append((starts ? marker(parent) : "") + (!pre && endsWithBreak() ? text.trimStart() : text)) + first ??= { node, offset: start + raw.search(/\S|$/) } + last = { node, offset: start + raw.trimEnd().length } + const piece = document.createRange() + piece.setStart(node, start) + piece.setEnd(node, end) + + for (const rect of piece.getClientRects()) { + if (rect.width === 0) continue + left = Math.min(left, rect.left) + right = Math.max(right, rect.right) + } + } + + const walk = (range: Range) => { + const root = range.commonAncestorContainer + + if (root instanceof Text) return visit(root, range) + + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, { + acceptNode(node) { + if (!range.intersectsNode(node)) return NodeFilter.FILTER_REJECT + + if (node instanceof Text) return NodeFilter.FILTER_ACCEPT + + if (!(node instanceof Element)) return NodeFilter.FILTER_REJECT + + if (node.tagName === "BUTTON" || node.getAttribute("aria-hidden") === "true" || style(node).display === "none") + return NodeFilter.FILTER_REJECT + + return node.tagName === "BR" || node.shadowRoot ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP + }, + }) + + while (!truncated && walker.nextNode()) { + const node = walker.currentNode + + if (node instanceof Text) visit(node, range) + else if (node instanceof Element && node.shadowRoot) walk(innerRange(node.shadowRoot, selection)) + else if (previous) append("\n") + } + } + + walk(selection.range) + + return { + text: output + .join("") + .split("\n") + .map((line) => line.trimEnd()) + .join("\n") + .replace(/\n{3,}/g, "\n\n") + .trim(), + truncated, + first, + last, + horizontal: left < right ? { left, right } : undefined, + } +} + +// `Selection.direction` reads "none" for mouse selections in Chromium. +function backward(selection: Selection) { + if (!selection.anchorNode || !selection.focusNode) return false + const range = document.createRange() + range.setStart(selection.anchorNode, selection.anchorOffset) + + return range.comparePoint(selection.focusNode, selection.focusOffset) < 0 +} + +function documentPoint(point: Point, end: boolean): Point { + const root = point.node.getRootNode() + + if (!(root instanceof ShadowRoot)) return point + const parent = root.host.parentNode! + + return documentPoint({ node: parent, offset: [...parent.childNodes].indexOf(root.host) + (end ? 1 : 0) }, end) +} + +function innerRange(root: ShadowRoot, selection: TimelineSelection) { + const range = document.createRange() + range.selectNodeContents(root) + + if (root.contains(selection.start.node)) range.setStart(selection.start.node, selection.start.offset) + + if (root.contains(selection.end.node)) range.setEnd(selection.end.node, selection.end.offset) + + return range +} + +function partOf(element: Element): Element | null { + const part = element.closest("[data-timeline-part-id], [data-index]") + + if (part) return part + const root = element.getRootNode() + + return root instanceof ShadowRoot ? partOf(root.host) : null +} + +function itemOf(current: Element, previous: Element): Element { + const parent = current.parentElement + + if (!parent || parent.contains(previous)) return current + + return itemOf(parent, previous) +} + +function marker(element: Element) { + const type = element.closest("[data-line-type]")?.getAttribute("data-line-type") + + if (type === "change-deletion") return "-" + + if (type === "change-addition") return "+" + + return "" +} diff --git a/packages/app/src/session/timeline/quote.tsx b/packages/app/src/session/timeline/quote.tsx new file mode 100644 index 00000000000..973f0d5115f --- /dev/null +++ b/packages/app/src/session/timeline/quote.tsx @@ -0,0 +1,404 @@ +import { createEffect, on, onCleanup, Show } from "solid-js" +import { createStore } from "solid-js/store" +import { Portal } from "solid-js/web" +import { makeEventListener } from "@solid-primitives/event-listener" +import { createMediaQuery } from "@solid-primitives/media" +import { createResizeObserver } from "@solid-primitives/resize-observer" +import { Button } from "@opencode/ui/button" +import { Keybind } from "@opencode/ui/keybind" +import { Tooltip } from "@opencode/ui/tooltip" +import { useLanguage } from "@/runtime/i18n/language" +import { + characterRect, + narrowSelection, + quoteText, + selectionRects, + timelineSelection, + type TimelineSelection, +} from "./quote-text" + +const IS_MAC = /(Mac|iPod|iPhone|iPad)/.test(navigator.platform) + +const SETTLE_MS = 150 + +const SHORT_LINES = 3 + +const GAP = 8 + +type Rect = { top: number; bottom: number; left: number; right: number } + +type Extent = Rect & { short: boolean; backward: boolean } + +/** Offers to quote text selected in the session timeline into the composer. */ +export function createTimelineQuote(input: { + root: () => HTMLElement | undefined + sessionKey: () => string + enabled: () => boolean + add: (text: string, comment: boolean) => void +}) { + const [state, setState] = createStore<{ + text: string | undefined + truncated: boolean + extent: Extent | undefined + bounds: Rect | undefined + }>({ text: undefined, truncated: false, extent: undefined, bounds: undefined }) + + let selected: TimelineSelection | undefined + let horizontal: { left: number; right: number; origin: number } | undefined + let element: HTMLElement | undefined + let timer: ReturnType | undefined + let frame: number | undefined + let pointer = false + let reflow: number | undefined + // The selection Escape dismissed, which stays dismissed until it changes or clears. + let dismissed: Range | undefined + + const close = () => { + selected = undefined + horizontal = undefined + dismissed = undefined + clearTimeout(timer) + + if (reflow !== undefined) cancelAnimationFrame(reflow) + reflow = undefined + setState({ text: undefined, truncated: false, extent: undefined, bounds: undefined }) + } + + const dismiss = () => { + const focused = document.activeElement instanceof Node && !!element?.contains(document.activeElement) + const selection = window.getSelection() + close() + dismissed = selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : undefined + + if (focused) input.root()?.focus({ preventScroll: true }) + } + + const place = () => { + const root = input.root() + + if (!root || !selected) return + const view = root.getBoundingClientRect() + const sticky = root.querySelector("[data-session-title]") + + const bounds = { + top: view.top + (sticky instanceof HTMLElement ? sticky.offsetHeight : 0), + bottom: view.bottom, + left: view.left, + right: view.right, + } + + // The virtualizer removed the selected rows. + if (selected.range.collapsed) return close() + + const rects = selectionRects(selected) + const first = characterRect(selected.start, false) + const last = characterRect(selected.end, true) + const top = first?.top ?? Math.min(...rects.map((rect) => rect.top)) + const bottom = last?.bottom ?? Math.max(...rects.map((rect) => rect.bottom)) + + const visible = rects.filter( + (rect) => rect.bottom > Math.max(bounds.top, top) && rect.top < Math.min(bounds.bottom, bottom), + ) + + const line = + first?.height ?? rects.map((rect) => rect.height).sort((a, b) => a - b)[Math.floor(rects.length / 2)] ?? 0 + + setState({ + bounds, + extent: visible.length + ? { + top, + bottom, + left: horizontal + ? horizontal.left + view.left - horizontal.origin + : Math.min(...visible.map((rect) => rect.left)), + right: horizontal + ? horizontal.right + view.left - horizontal.origin + : Math.max(...visible.map((rect) => rect.right)), + short: bottom - top < line * (SHORT_LINES + 0.5), + backward: selected.backward, + } + : undefined, + }) + } + + const read = () => { + if (pointer) return + const root = input.root() + const selection = window.getSelection() + + if (dismissed && selection?.rangeCount && sameRange(selection.getRangeAt(0), dismissed)) return + dismissed = undefined + const next = root && input.enabled() && selection ? timelineSelection(selection, root) : undefined + const quote = next ? quoteText(next) : undefined + + if (!root || !next || !quote?.text) return close() + horizontal = quote.horizontal && { ...quote.horizontal, origin: root.getBoundingClientRect().left } + // Selecting a whole paragraph ends the selection at the start of the next block. + selected = quote.first + ? narrowSelection(next, quote.first, quote.truncated ? next.end : (quote.last ?? next.end)) + : next + setState({ text: quote.text, truncated: quote.truncated }) + place() + } + + const schedule = () => { + clearTimeout(timer) + timer = setTimeout(read, SETTLE_MS) + } + + const schedulePlace = () => { + if (frame !== undefined || !selected) return + frame = requestAnimationFrame(() => { + frame = undefined + place() + }) + } + + const release = () => { + if (!pointer) return + pointer = false + schedule() + } + + const inside = (target: EventTarget | null) => target instanceof Node && !!element?.contains(target) + + // Select all from the keyboard or the app menu covers the whole window; in the timeline it selects the conversation. + const containSelectAll = () => { + const root = input.root() + const selection = window.getSelection() + const active = document.activeElement + + if (pointer || !root || !input.enabled() || !selection || selection.rangeCount === 0) return + + if (active !== document.body && !(active instanceof Node && root.contains(active) && !editable(active))) return + const range = selection.getRangeAt(0) + const content = document.createRange() + content.selectNodeContents(root) + + if ( + range.compareBoundaryPoints(Range.START_TO_START, content) < 0 && + range.compareBoundaryPoints(Range.END_TO_END, content) > 0 + ) + selection.selectAllChildren(root) + } + + makeEventListener(document, "selectionchange", () => { + containSelectAll() + + // Only a new selection waits to settle; a cleared one closes at once. + if (window.getSelection()?.isCollapsed ?? true) return close() + schedule() + }) + makeEventListener(document, "pointerdown", (event) => { + if (inside(event.target) || event.button !== 0) return + pointer = true + const selection = window.getSelection() + const target = event.target instanceof Element ? event.target : undefined + + if (state.text === undefined || event.shiftKey || !selection?.rangeCount || target?.closest(".scroll-view__thumb")) + return + const range = selection.getRangeAt(0).cloneRange() + + // A press on the selection itself may start dragging it; the page clears it on release otherwise. + if ( + [...range.getClientRects()].some( + (rect) => + event.clientX >= rect.left && + event.clientX <= rect.right && + event.clientY >= rect.top && + event.clientY <= rect.bottom, + ) + ) + return + + // A press on content the shell makes unselectable leaves the selection as it was, so clear it once the press is + // handled. + setTimeout(() => { + if (selection.rangeCount && sameRange(selection.getRangeAt(0), range)) selection.removeAllRanges() + }) + }) + makeEventListener(document, "pointerup", release) + makeEventListener(document, "pointercancel", release) + makeEventListener(document, "contextmenu", release) + makeEventListener(window, "blur", release) + makeEventListener(document, "keydown", (event) => { + if (event.defaultPrevented || event.isComposing) return + const root = input.root() + const active = document.activeElement + + if (event.key === "Escape" && state.text !== undefined) return dismiss() + const action = element?.querySelector("button:not(:disabled)") + + if ( + event.key === "Tab" && + !event.shiftKey && + !event.metaKey && + !event.ctrlKey && + !event.altKey && + action && + (active === root || active === document.body) + ) { + event.preventDefault() + action.focus() + + return + } + + // The shell disables selection, so the browser's select all finds nothing. + if ( + root && + input.enabled() && + (event.metaKey || event.ctrlKey) && + !event.altKey && + !event.shiftKey && + event.key.toLowerCase() === "a" && + active instanceof Node && + root.contains(active) && + !editable(active) + ) { + event.preventDefault() + window.getSelection()?.selectAllChildren(root) + } + }) + makeEventListener(document, "scroll", schedulePlace, { capture: true, passive: true }) + makeEventListener(window, "resize", schedulePlace) + + // A resized timeline, such as when a side panel opens, reflows the selected text. + createResizeObserver(input.root, () => { + if (!selected || reflow !== undefined) return + reflow = requestAnimationFrame(() => { + reflow = undefined + read() + }) + }) + + createEffect(on(input.sessionKey, close, { defer: true })) + createEffect(() => { + if (!input.enabled()) close() + }) + onCleanup(() => { + clearTimeout(timer) + + if (frame !== undefined) cancelAnimationFrame(frame) + + if (reflow !== undefined) cancelAnimationFrame(reflow) + }) + + return { + state, + // With Alt held, the quote opens its comment editor in the composer. + add: (comment: boolean) => { + const text = state.text + + if (!text || state.truncated) return + window.getSelection()?.removeAllRanges() + close() + input.add(text, comment) + }, + setElement: (value: HTMLElement | undefined) => { + element = value + }, + } +} + +export type TimelineQuoteController = ReturnType + +export function TimelineQuote(props: { controller: TimelineQuoteController }) { + const language = useLanguage() + const quote = props.controller + // Touch screens show their own menu over the selection. + const docked = createMediaQuery("(hover: none)") + const [size, setSize] = createStore({ width: 0, height: 0 }) + + const position = () => { + const bounds = quote.state.bounds + const extent = quote.state.extent + + if (!bounds || !extent) return + + const pinned = bounds.bottom - size.height - GAP + + if (docked()) return { top: pinned, left: (bounds.left + bounds.right - size.width) / 2 } + + const above = extent.top - size.height - GAP + const below = extent.bottom + GAP + const fitsAbove = above >= bounds.top + GAP && extent.top <= bounds.bottom + const fitsBelow = below + size.height <= bounds.bottom - GAP && extent.bottom >= bounds.top + + // Short selections get it above; taller ones at the end they were dragged towards. + const sides = + extent.short || extent.backward + ? [fitsAbove && above, fitsBelow && below] + : [fitsBelow && below, fitsAbove && above] + + const top = sides.find((side) => side !== false) ?? pinned + const center = (extent.left + extent.right - size.width) / 2 + + return { + top, + left: Math.min(Math.max(center, bounds.left + GAP), bounds.right - size.width - GAP), + } + } + + return ( + + {(place) => ( + +
{ + quote.setElement(element) + createResizeObserver(element, () => setSize({ width: element.offsetWidth, height: element.offsetHeight })) + onCleanup(() => quote.setElement(undefined)) + }} + data-component="timeline-quote" + data-prevent-autofocus + role="toolbar" + aria-label={language.t("session.quote.actions")} + class="fixed z-50 flex items-center gap-0.5 rounded-[8px] p-0.5 shadow-[var(--v2-elevation-raised)]" + style={{ + top: `${place().top}px`, + left: `${place().left}px`, + visibility: size.height === 0 ? "hidden" : undefined, + }} + onMouseDown={(event) => event.preventDefault()} + > + + + {language.t("session.quote.tooLong")} + + + + {language.t("session.quote.addWithComment")} + + + } + placement="top" + openDelay={1200} + > + + +
+
+ )} +
+ ) +} + +function sameRange(a: Range, b: Range) { + return a.compareBoundaryPoints(Range.START_TO_START, b) === 0 && a.compareBoundaryPoints(Range.END_TO_END, b) === 0 +} + +function editable(node: Node) { + return node instanceof HTMLElement && (/^(INPUT|TEXTAREA|SELECT)$/.test(node.tagName) || node.isContentEditable) +} diff --git a/packages/session-ui/src/actions.ts b/packages/session-ui/src/actions.ts index a78ad656a5c..f2080a660d2 100644 --- a/packages/session-ui/src/actions.ts +++ b/packages/session-ui/src/actions.ts @@ -17,6 +17,12 @@ export type SessionUserComment = label: string icon: string } + | { + /** Plain text quoted from the session timeline, with an optional comment. */ + type: "quote" + text: string + comment?: string + } /** An attachment delivered to the model as a path on the server instead of inline bytes. */ export type SessionUserAttachmentReference = { diff --git a/packages/session-ui/src/message/attachment-card.css b/packages/session-ui/src/message/attachment-card.css index 094523d0cf5..25549f7d5ea 100644 --- a/packages/session-ui/src/message/attachment-card.css +++ b/packages/session-ui/src/message/attachment-card.css @@ -76,6 +76,42 @@ } } +[data-component="attachment-card"] { + [data-slot="comment-card-quote"], + [data-slot="comment-card-action"] { + display: flex; + align-items: center; + gap: 4px; + min-width: 0; + } + + [data-slot="comment-card-action"] { + display: none; + color: var(--v2-text-text-base); + } +} + +@media (hover: hover) { + [data-component="attachment-card"]:hover:has([data-slot="comment-card-action"]) [data-slot="comment-card-quote"] { + display: none; + } + + [data-component="attachment-card"]:hover [data-slot="comment-card-action"] { + display: flex; + } +} + +@media (hover: none) { + [data-component="attachment-card"]:has([data-slot="comment-card-action"]:not([data-commented])) + [data-slot="comment-card-quote"] { + display: none; + } + + [data-component="attachment-card"] [data-slot="comment-card-action"]:not([data-commented]) { + display: flex; + } +} + [data-color-scheme="dark"] [data-component="attachment-card"][data-surface="base"] { background: var(--v2-overlay-simple-overlay-hover); } diff --git a/packages/session-ui/src/message/comment-card.tsx b/packages/session-ui/src/message/comment-card.tsx index 8fc87f4586a..07050f5ac23 100644 --- a/packages/session-ui/src/message/comment-card.tsx +++ b/packages/session-ui/src/message/comment-card.tsx @@ -1,14 +1,39 @@ -import { createSignal, onCleanup, onMount, Show } from "solid-js" +import { createSignal, Match, onCleanup, onMount, Show, Switch } from "solid-js" import { FileIcon } from "@opencode/ui/file-icon" import { Icon } from "@opencode/ui/icon" +import { useI18n } from "@opencode/ui/context/i18n" import { getFilenameTruncated } from "@opencode/util/path" import { Tooltip } from "@opencode/ui/tooltip" import { AttachmentCard } from "./attachment-card" -/** What a comment is about: lines of a file, or a labelled subject such as an element picked in a page. */ +/** What a comment is about: lines of a file, a labelled subject such as an element picked in a page, or quoted text. */ export type CommentCardTarget = | { type: "file"; path: string; selection?: { startLine: number; endLine: number } } | { type: "note"; label: string; icon: string } + | { type: "quote"; text: string } + +export function commentCardTarget( + comment: + | { type?: "file"; path: string; selection?: { startLine: number; endLine: number } } + | { type: "note"; label: string; icon: string } + | { type: "quote"; text: string }, +): CommentCardTarget { + if (comment.type === "note") return { type: "note", label: comment.label, icon: comment.icon } + + if (comment.type === "quote") return { type: "quote", text: comment.text } + + return { type: "file", path: comment.path, selection: comment.selection } +} + +const QUOTE_PREVIEW_LENGTH = 200 + +const QUOTE_TOOLTIP_LENGTH = 600 + +export function quoteTooltip(quote: { text: string; comment?: string }) { + const text = quote.text.length > QUOTE_TOOLTIP_LENGTH ? `${quote.text.slice(0, QUOTE_TOOLTIP_LENGTH)}…` : quote.text + + return quote.comment ? `${quote.comment}\n\n${text}` : text +} export function CommentCard(props: { comment: string @@ -19,8 +44,12 @@ export function CommentCard(props: { wide?: boolean onClick?: () => void }) { + const i18n = useI18n() let title: HTMLSpanElement | undefined const [truncated, setTruncated] = createSignal(false) + const quote = () => (props.target.type === "quote" ? props.target.text.slice(0, QUOTE_PREVIEW_LENGTH) : undefined) + const heading = () => props.comment || (quote() ?? "") + const tooltipDisabled = () => !props.tooltip || (!truncated() && !(props.target.type === "quote" && props.comment)) onMount(() => { const element = title @@ -39,13 +68,13 @@ export function CommentCard(props: { - - {(file) => ( - <> - - - {getFilenameTruncated(file().path, 14)} - - {(sel) => - sel().startLine === sel().endLine - ? `:${sel().startLine}` - : `:${sel().startLine}-${sel().endLine}` - } - + + + {(file) => ( + <> + + + {getFilenameTruncated(file().path, 14)} + + {(sel) => + sel().startLine === sel().endLine ? `:${sel().startLine}` : `:${sel().startLine}-${sel().endLine}` + } + + + + )} + + + {(note) => ( + <> + + + {note().label} + + + )} + + + {(text) => ( + <> + + + + {props.comment ? text() : i18n.t("ui.commentCard.quote")} - - )} - - } - > - {(note) => ( - <> - - - {note().label} - - - )} -
+ + + + + + {props.comment ? i18n.t("ui.commentCard.editComment") : i18n.t("ui.commentCard.addComment")} + + + + + )} + + ) diff --git a/packages/session-ui/src/message/message-content.tsx b/packages/session-ui/src/message/message-content.tsx index 04766c75404..bb0bc869815 100644 --- a/packages/session-ui/src/message/message-content.tsx +++ b/packages/session-ui/src/message/message-content.tsx @@ -18,7 +18,7 @@ import { Markdown } from "../components/markdown" import { ImagePreview } from "@opencode/ui/image-preview" import { getFilename } from "@opencode/util/path" import { AttachmentCard } from "./attachment-card" -import { CommentCard } from "./comment-card" +import { CommentCard, commentCardTarget, quoteTooltip } from "./comment-card" import { TimelineSeparator } from "../components/timeline-separator" import { Tooltip } from "@opencode/ui/tooltip" import { IconButton } from "@opencode/ui/icon-button" @@ -236,13 +236,9 @@ function UserMessageComments(props: { comments: SessionUserComment[]; bounded: b {(comment) => ( diff --git a/packages/ui/src/data-display/line-comment/line-comment.tsx b/packages/ui/src/data-display/line-comment/line-comment.tsx index ce9cb8c2d4a..935c3733eff 100644 --- a/packages/ui/src/data-display/line-comment/line-comment.tsx +++ b/packages/ui/src/data-display/line-comment/line-comment.tsx @@ -74,6 +74,8 @@ export interface LineCommentEditorProps extends Omit, "chi cancelLabel?: string submitLabel?: string autofocus?: boolean + /** Submit an empty value too, such as to clear a comment that exists (default: false). */ + allowEmpty?: boolean mention?: LineCommentEditorMention } @@ -106,13 +108,14 @@ export function LineCommentEditor(props: LineCommentEditorProps) { "cancelLabel", "submitLabel", "autofocus", + "allowEmpty", "mention", "class", "classList", ]) const heading = () => local.heading ?? i18n.t("ui.lineComment.submit") - const canSubmit = () => local.value.trim().length > 0 + const canSubmit = () => !!local.allowEmpty || local.value.trim().length > 0 const closeMention = () => { setMentionOpen(false) @@ -199,7 +202,7 @@ export function LineCommentEditor(props: LineCommentEditorProps) { const submit = () => { const v = local.value.trim() - if (!v) return + if (!v && !local.allowEmpty) return local.onSubmit(v) } diff --git a/packages/ui/src/i18n/en.ts b/packages/ui/src/i18n/en.ts index d3087d9bbd4..2af67fcb6bb 100644 --- a/packages/ui/src/i18n/en.ts +++ b/packages/ui/src/i18n/en.ts @@ -55,6 +55,10 @@ const source = { "ui.lineComment.submit": "Comment", "ui.lineComment.cancel": "Cancel", + "ui.commentCard.quote": "Quote", + "ui.commentCard.addComment": "Add comment", + "ui.commentCard.editComment": "Edit comment", + "ui.sessionTurn.steps.show": "Show steps", "ui.sessionTurn.steps.hide": "Hide steps", "ui.sessionTurn.summary.response": "Response", diff --git a/packages/ui/src/icons/catalog.ts b/packages/ui/src/icons/catalog.ts index 369ca4340cd..aae5c1154ba 100644 --- a/packages/ui/src/icons/catalog.ts +++ b/packages/ui/src/icons/catalog.ts @@ -190,6 +190,10 @@ const icons = { viewBox: "0 0 16 16", body: ``, }, + "outline-quote": { + viewBox: "0 0 16 16", + body: ``, + }, "outline-arrow-left": { viewBox: "0 0 16 16", body: ``,