feat(web): unify context chip presentation and previews #10236
Closedchrisdeeming(GitHub profile, opens in a new tab)wants to merge 78 commits into
main fromrefs/pull/10236/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/components/chat/MessagesTimeline.tsx line 2418OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2260,4 +2401,18 @@2401+ tabIndex={props.tooltip ? 0 : undefined}2402+ >2403+ {props.icon}2404+ <span className={CHAT_INLINE_CHIP_LABEL_CLASS_NAME}>{props.label}</span>2405+ </span>2406+ );2407+ if (!props.tooltip) return chip;2408+ return (2409+ <Tooltip>2410+ <TooltipTrigger render={chip} />2411+ <TooltipPopup side="top" className="max-w-96 whitespace-pre-wrap leading-tight">2412+ {props.tooltip}2413+ </TooltipPopup>2414+ </Tooltip>2415+ );2416+}226024172261- return <TerminalContextInlineChip label={props.context.header} tooltipText={tooltipText} />;2262- },2263-);2418+function UserMessageContextPopover(props: {apps/web/src/components/chat/ExpandedImageDialog.tsx lines 149 to 151OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -145,14 +145,7 @@145- {preview.images.length > 1 && (146- <Button147- type="button"148- size="icon"149- variant="ghost"150- className="absolute left-2 top-1/2 z-20 -translate-y-1/2 text-white/90 hover:bg-white/10 hover:text-white sm:left-6"151- aria-label="Previous image"152- onClick={() => navigateImage(-1)}153- >154- <ChevronLeftIcon className="size-5" />155- </Button>156- )}157- <MediaActions source={actionsSource}>158- <div className="relative isolate z-10 max-h-[92vh] max-w-[92vw]">145+ <DialogPopup146+ {...composerFloatingLayerProps}147+ showCloseButton={false}148+ bottomStickOnMobile={false}149+ backdropClassName="z-[60] bg-black/75! backdrop-blur-none!"150+ viewportClassName="z-[60] grid-rows-1 place-items-center px-4 py-6 [-webkit-app-region:no-drag]"151+ className="row-start-1 max-h-[92vh] w-auto max-w-[92vw] overflow-visible rounded-none! border-transparent! bg-transparent! p-0 shadow-none! before:hidden"
- apps/web/src/components/chat/TerminalContextInlineChip.tsx line 46OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -17,2 +27,20 @@1727 export function TerminalContextInlineChip(props: TerminalContextInlineChipProps) {18- const { label, tooltipText, expired = false } = props;28+ const { label, terminalLabel, lineStart, lineEnd, text, detailsMode, expired = false } = props;29+30+ const content = (31+ <>32+ <TerminalIcon33+ className={cn(34+ COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,35+ CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES.terminal,36+ "size-3.5",37+ expired && "opacity-100",38+ )}39+ />40+ <span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{label}</span>41+ </>42+ );43+44+ if (!expired && text.length > 0 && detailsMode === "popover") {45+ return (46+ <Popover>
- apps/web/src/components/chat/MessagesTimeline.tsx line 2393OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2263,8 +2380,14 @@2263-);2264-2265-const UserMessageElementContextChip = memo(function UserMessageElementContextChip(props: {2266- context: ParsedElementContextEntry;2380+function UserMessageContextChip(props: {2381+ icon: ReactNode;2382+ label: string;2383+ kindLabel?: string;2384+ copyMarkdown: string;2385+ tooltip?: string;2386+ toneClassName?: string;2387+ interactive?: boolean;2388+ unresolved?: boolean;22672389 }) {2268- const tooltipText = props.context.body2269- ? `${props.context.header}\n${props.context.body}`2270- : props.context.header;2390+ const chip = (2391+ <span2392+ className={cn(2393+ CHAT_INLINE_CHIP_CLASS_NAME,
- apps/web/src/components/chat/MessagesTimeline.tsx line 2637OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2341,0 +2617,21 @@2617+ {2618+ kind: "file",2619+ canRender: (record, context) =>2620+ record.kind === "file" &&2621+ context.attachment !== null &&2622+ isFileAttachment(context.attachment),2623+ render: (record, context) => {2624+ if (2625+ record.kind !== "file" ||2626+ context.attachment === null ||2627+ !isFileAttachment(context.attachment)2628+ ) {2629+ return <UnavailableUserMessageContextChip {...context} />;2630+ }2631+ const attachment = context.attachment;2632+ const isVideo = isVideoAttachment(attachment);2633+ const disabled =2634+ attachment.downloadable === false && (!isVideo || attachment.previewUrl === undefined);2635+ const size = formatAttachmentSize(record.sizeBytes);2636+ return (2637+ <Tooltip>
- apps/web/src/components/chat/TerminalContextInlineChip.tsx lines 84 to 119OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -30,16 +108,12 @@108+ tabIndex={0}30109 >31- <TerminalIcon32- className={cn(33- COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,34- "size-3.5",35- expired && "opacity-100",36- )}37- />38- <span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{label}</span>110+ {content}39111 </span>40112 }41113 />42114 <TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">43- {tooltipText}115+ {expired116+ ? `Terminal context expired. Remove and re-add ${label} to include it in your message.`117+ : text}44118 </TooltipPopup>45119 </Tooltip>
- apps/server/src/orchestration/Normalizer.ts line 290Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -253,3 +256,5 @@253256 }),254257 ),255258 );259+ if (attachment.id !== undefined) {260+ finalAttachmentIdByClientId.set(attachment.id, attachmentId);apps/web/src/components/chat/ChatComposer.tsx lines 3065 to 3106Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2568,3 +2780,20 @@2568- syncTerminalContextsByIds(composerTerminalContexts, terminalContextIds),2780+ composerTerminalContexts.filter((context) => referenced.has(context.id)),25692781 );25702782 }2783+ for (const comment of composerReviewComments) {2784+ if (!referenced.has(reviewCommentContextId(comment.id))) {2785+ removeComposerDraftReviewComment(composerDraftTarget, comment.id);2786+ }2787+ }2788+ for (const annotation of composerPreviewAnnotations) {2789+ if (!referenced.has(previewAnnotationContextId(annotation.id))) {2790+ releaseAttachmentUpload(annotation.id);2791+ removeComposerDraftPreviewAnnotation(composerDraftTarget, annotation.id);2792+ }2793+ }2794+ // Files live only as chips; images stay on the shelf when their chip goes.2795+ for (const file of composerFiles) {2796+ if (!referenced.has(file.id)) {2797+ removeComposerFileFromDraft(file.id);2798+ }2799+ }apps/web/src/components/chat/TerminalContextInlineChip.tsx lines 18 to 24Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -5,10 +6,19 @@6+ CHAT_INLINE_CHIP_CLASS_NAME,57 COMPOSER_INLINE_CHIP_CLASS_NAME,68 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,79 COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,10+ CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES,11+ CONTEXT_INLINE_CHIP_INTERACTIVE_CLASS_NAME,12+ CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES,813 } from "../composerInlineChip";9-import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";14+import { ContextChipPopover, ContextChipShell } from "../contextChipParts";10151116 interface TerminalContextInlineChipProps {1217 label: string;13- tooltipText: string;18+ terminalLabel: string;19+ lineStart: number;20+ lineEnd: number;21+ text: string;22+ detailsMode: ContextPresentationCapability["details"];1423 expired?: boolean;24+ surface?: "composer" | "transcript";apps/web/src/lib/composerContextRecords.ts lines 218 to 220Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +176,21 @@176+): PreviewAnnotationContextRecord {177+ const elements = annotation.elements.flatMap((target): ElementContextDetails[] => {178+ const element = normalizeElementContextSelection(target.element);179+ return element ? [element] : [];180+ });181+ return {182+ version: 1,183+ contextId: previewAnnotationContextId(annotation.id),184+ kind: "preview-annotation",185+ label: sanitizeComposerContextLabel(186+ previewAnnotationContextLabel(annotation),187+ "preview-annotation",188+ ),189+ annotationId: annotation.id,190+ pageUrl: annotation.pageUrl,191+ pageTitle: annotation.pageTitle,192+ comment: annotation.comment.trim(),193+ targetSummary: previewAnnotationTargetSummary(annotation),194+ styleChanges: annotation.styleChanges.map(195+ (change) => `${change.property}: ${change.previousValue || "(unset)"} → ${change.value}`,196+ ),apps/web/src/reviewCommentContext.test.ts line 4OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1,13 +1,4 @@11 import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";22 import { describe, expect, it } from "vite-plus/test";334-import {5- appendReviewCommentsToPrompt,6- buildDiffReviewComment,7- buildFileReviewComment,8- buildReviewCommentRenderablePatch,9- formatReviewCommentContext,10- inferReviewCommentFenceLanguage,11- parseReviewCommentMessageSegments,12- restoreDiffReviewCommentRange,13-} from "./reviewCommentContext";4+import { buildDiffReviewComment, restoreDiffReviewCommentRange } from "./reviewCommentContext";@@ -109,3 +116,13 @@109116 Send `/compact` in an existing conversation to reduce context usage when the110117 provider supports it. Web and desktop also offer compaction from the context meter.111118119+## Context in your message120+121+Context you attach lands where your cursor is, as a chip inside your text: a terminal excerpt,122+a review comment from a diff or file, a preview annotation, or a file. You can type before and123+after a chip, move it by cutting and pasting, and delete it like a character. Hover a chip for124+its brief details. Select a terminal excerpt to open its captured output, or select a review125+comment, picked element, or preview annotation to open its full details. Chips read as "Terminal126+excerpt, Terminal 1 lines 3-4" and similar to screen readers.127+128+A pull request appears as its icon and number. Its colour reflects whether it was open, draft,packages/shared/src/composerContextClipboard.ts line 14OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +1,14 @@1+import {2+ COMPOSER_CONTEXT_CLIPBOARD_MIME,3+ ComposerContextClipboardFragment,4+} from "@t3tools/contracts";5+import * as Option from "effect/Option";6+import * as Schema from "effect/Schema";7+8+export { COMPOSER_CONTEXT_CLIPBOARD_MIME };9+10+const MAX_FRAGMENT_CHARS = 2_000_000;11+const decodeFragment = Schema.decodeUnknownOption(ComposerContextClipboardFragment);12+13+export function encodeComposerContextFragment(fragment: ComposerContextClipboardFragment): string {14+ return JSON.stringify(fragment);packages/shared/src/composerContextLegacy.ts lines 96 to 106Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +82,21 @@82+ const header = /^(.*?) (?:line (\d+)|lines (\d+)-(\d+))$/.exec(entry.header);83+ if (!header) return null;84+ const terminalLabel = header[1]!.trim();85+ if (!terminalLabel) return null;86+ const lineStart = Number(header[2] ?? header[3]);87+ const lineEnd = Number(header[2] ?? header[4]);88+ const text = entry.body89+ .split("\n")90+ .map((line) => line.replace(/^\d+ \| ?/, ""))91+ .join("\n");92+ return {93+ version: 1,94+ contextId: legacyId("terminal", index),95+ kind: "terminal",96+ label: entry.header,97+ terminalId: terminalLabel.toLowerCase().replace(/\s+/g, "-"),98+ terminalLabel,99+ lineStart,100+ lineEnd,101+ text,102+ };packages/shared/src/composerContextReferences.ts line 22Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +2,21 @@2+ COMPOSER_CONTEXT_LABEL_MAX_CHARS,3+ type ComposerContextId,4+ type ComposerContextKind,5+ type ComposerContextRecord,6+ type ElementContextDetails,7+ type KnownComposerContextRecord,8+} from "@t3tools/contracts";9+10+/**11+ * Canonical inline reference: `[label](t3-context://v1/<kind>/<contextId>)`, or the image12+ * form ``. The link carries position and identity only; the payload lives in the13+ * message's context records. Labels are display text and never identity.14+ */15+16+const CONTEXT_PROTOCOL = "t3-context:";17+const COMPOSER_CONTEXT_HREF_PREFIX = `${CONTEXT_PROTOCOL}//v1/`;18+const CONTEXT_KIND_PATTERN = /^[a-z][a-z0-9-]{0,39}$/;19+const CONTEXT_ID_PATTERN = /^[a-z0-9_-]{1,128}$/i;20+const MAX_LINK_LABEL_LENGTH = 512;21+const CONTEXT_LINK = new RegExp(22+ String.raw`(!?)\[([^\]\n]{0,${MAX_LINK_LABEL_LENGTH}})\]\((${COMPOSER_CONTEXT_HREF_PREFIX}[^\s)]{1,200})\)`,
- apps/web/src/components/chat/ChatComposer.tsx lines 2565 to 2590Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -2248,0 +2377,21 @@2377+ addComposerImage({2378+ type: "image",2379+ id: localId,2380+ name: record.name,2381+ mimeType: file.type,2382+ sizeBytes: file.size,2383+ previewUrl: URL.createObjectURL(file),2384+ file,2385+ });2386+ } else {2387+ addComposerFilesToDraft([2388+ {2389+ type: "file",2390+ id: localId,2391+ name: record.name,2392+ mimeType: file.type,2393+ sizeBytes: file.size,2394+ file,2395+ },2396+ ]);2397+ }apps/web/src/components/chat/ChatComposer.tsx line 2411OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -2248,0 +2391,21 @@2391+ name: record.name,2392+ mimeType: file.type,2393+ sizeBytes: file.size,2394+ file,2395+ },2396+ ]);2397+ }2398+ },2399+ [addComposerFilesToDraft, addComposerImage, createAssetUrl],2400+ );2401+ /**2402+ * Brings records into this draft (paste, stash restore). Binaries are transferred only2403+ * when `sourceEnvironmentId` is given; the stash restores its own images and files.2404+ */2405+ const importContextRecords = useCallback(2406+ (2407+ records: ReadonlyArray<ComposerContextRecord>,2408+ sourceEnvironmentId: EnvironmentId | null,2409+ ): ReadonlyMap<string, string> => {2410+ const rewritten = new Map<string, string>();2411+ if (!activeThread) return rewritten;apps/web/src/components/chat/composerPromptHistory.ts line 131OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -127,18 +127,5 @@127127 continue;128128 }129- const previewAnnotation = extractTrailingPreviewAnnotation(prompt);130- if (previewAnnotation.annotation) {131- prompt = previewAnnotation.promptText;132- continue;133- }134- const elementContexts = extractTrailingElementContexts(prompt);135- if (elementContexts.contextCount > 0) {136- prompt = elementContexts.promptText;137- continue;138- }139- const terminalContexts = extractTrailingTerminalContexts(prompt);140- if (terminalContexts.contextCount > 0) {141- prompt = stripInlineTerminalLabels(142- terminalContexts.promptText,143- terminalContexts.contexts.map((context) => context.header),144- );129+ const legacy = TRAILING_LEGACY_CONTEXT.exec(prompt);130+ if (legacy) {131+ if (legacy[1] === "preview_annotation" && legacy[2]!.includes("<preview_annotation>")) break;apps/web/src/components/chat/MessagesTimeline.tsx lines 1441 to 1450Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1328,12 +1351,12 @@1328- if (!extracted.annotation) break;1329- previewAnnotations.unshift(extracted.annotation);1330- visibleText = extracted.promptText;1331- }1332- const elementContextState = extractTrailingElementContexts(visibleText);1333- const elementContexts = [1334- ...displayedUserMessage.elementContexts,1335- ...elementContextState.contexts,1336- ];1351+ const resolvedContext = resolveUserMessageContext(row.message);13371352 const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));13381353 const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));13391354 const revertTurnCount = row.revertTurnCount;1355+ // Files with a chip in the prose need no row; older messages keep their rows.1356+ const chippedAttachmentIds = new Set(1357+ collectComposerContextReferences(resolvedContext.text).flatMap((occurrence) => {1358+ const record = asKnownContextRecord(resolvedContext.recordsById.get(occurrence.contextId));1359+ return record?.kind === "file" || record?.kind === "image" ? [record.attachmentId] : [];1360+ }),1361+ );1362+ const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id));apps/web/src/components/chat/MessagesTimeline.tsx line 1500Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -1339,0 +1388,21 @@1388+ const container = document.createElement("div");1389+ container.appendChild(selection.getRangeAt(index).cloneContents());1390+ for (const element of container.querySelectorAll("[data-markdown-copy]")) {1391+ copiedMarkdown.push(element.getAttribute("data-markdown-copy") ?? "");1392+ }1393+ }1394+ const selectedIds = new Set(1395+ collectComposerContextReferences(copiedMarkdown.join("\n")).map((o) => o.contextId),1396+ );1397+ const records = resolvedContext.records.filter((record) => selectedIds.has(record.contextId));1398+ if (records.length === 0) return;1399+ const fragment = encodeComposerContextFragment({1400+ version: 1,1401+ source: {1402+ environmentId: ctx.activeThreadEnvironmentId,1403+ ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),1404+ messageId: row.message.id,1405+ },1406+ records,1407+ });1408+ if (fragment) event.clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment);apps/web/src/lib/composerContextRecords.ts line 338OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +318,21 @@318+ // The folded id is itself a valid producer id, so it folds to itself again.319+ id: record.contextId,320+ sectionId: record.sectionId,321+ sectionTitle: record.sectionTitle,322+ filePath: record.filePath,323+ startIndex: record.startIndex,324+ endIndex: record.endIndex,325+ rangeLabel: record.rangeLabel,326+ text: record.text,327+ diff: record.diff,328+ ...(record.fenceLanguage !== undefined ? { fenceLanguage: record.fenceLanguage } : {}),329+ ...(record.pullRequest !== undefined ? { pullRequest: record.pullRequest } : {}),330+ };331+}332+333+/** Lossy on purpose: geometry and screenshot do not travel; the agent-facing detail does. */334+export function previewAnnotationFromRecord(335+ record: PreviewAnnotationContextRecord,336+): PreviewAnnotationPayload {337+ return {338+ id: record.annotationId || record.contextId,
- apps/web/src/components/chat/ChatComposer.tsx lines 4669 to 4673OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -4329,4 +4654,20 @@4654+4655+ /**4656+ * Chips for freshly attached files land at the caret; when the editor cannot take4657+ * input (approval, pending questions) they are appended so the file is never invisible.4658+ */4659+ const insertAttachmentReferences = (references: ReadonlyArray<ComposerContextReference>) => {4660+ if (references.length === 0) return;4661+ const text = references.map(formatInlineContextReference).join(" ");4662+ const inserted = insertComposerText(`${text} `, "cursor", { ensureLeadingBoundary: true });4663+ if (!inserted) {4664+ setPrompt(ensureInlineContextReferences(promptRef.current, references));4665+ }43294666 };4330466743314668 const removeComposerImage = (imageId: string) => {4332- removeComposerImageFromDraft(imageId);4669+ const referenced = collectInlineContextIds(promptRef.current).includes(imageId);4670+ if (!referenced) {4671+ removeComposerImageFromDraft(imageId);4672+ return;4673+ }apps/web/src/composerDraftStore.ts line 3372OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -3406,3 +3369,4 @@34063369 if (accepted.length === 0 && replacements.size === 0) {34073370 return state;34083371 }3372+ acceptedIds = [...accepted, ...replacements.values()].map((file) => file.id);
- packages/shared/src/composerContextLegacy.ts line 63OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +43,21 @@43+ header: string;44+ body: string;45+}46+47+function parseEntries(block: string): ParsedEntry[] {48+ const entries: ParsedEntry[] = [];49+ let current: { header: string; bodyLines: string[] } | null = null;50+ const commit = () => {51+ if (!current) return;52+ entries.push({ header: current.header, body: current.bodyLines.join("\n").trimEnd() });53+ current = null;54+ };55+ for (const line of block.split("\n")) {56+ const headerMatch = /^- (.+):$/.exec(line);57+ if (headerMatch) {58+ commit();59+ current = { header: headerMatch[1]!, bodyLines: [] };60+ continue;61+ }62+ if (current && line.startsWith(" ")) current.bodyLines.push(line.slice(2));63+ else if (line.trim().length > 0) return [];
juliusmarminge closed this
Sign in to join this conversation.
Macroscope skipped reviewing this pull request. Per-review cost limit exceeded (workspace setting).
This review would cost an estimated $21.44, which exceeds your per-review limit of $15.00.
The top 3 files driving up this estimate:
apps/web/src/components/chat/ChatComposer.tsxapps/web/src/components/chat/MessagesTimeline.tsxapps/web/src/composerDraftStore.tsTip
To get this pull request reviewed, you can:
@macroscope-appon this PR to request a manual review (monthly spend limits still apply)..macroscope/ignore.md— note that creating this file replaces Macroscope's built-in default ignores rather than extending them.