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 defbf666d0e..01672308ede 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 bde7d860d51..2dd5539e535 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) => 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 7b1a3c87595..9832e8fdac6 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/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 8b06a8e3917..1ae11b4e3bc 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) => (