feat(web): autocomplete repository pull request references #10237
Closedchrisdeeming(GitHub profile, opens in a new tab)wants to merge 80 commits into
main fromrefs/pull/10237/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/ExpandedImageDialog.tsx line 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/MessagesTimeline.tsx line 2549Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2264,3 +2433,19 @@2433+ aria-label={`${props.accessibleLabel}. Show details`}2434+ />2435+ }2436+ >2437+ {props.chip}2438+ </PopoverTrigger>2439+ <PopoverPopup2440+ side="top"2441+ className="w-[min(36rem,calc(100vw-2rem))]"2442+ viewportClassName="overflow-x-auto p-2"2443+ >2444+ <PopoverTitle className="sr-only">{props.accessibleLabel}</PopoverTitle>2445+ {props.children}2446+ </PopoverPopup>2447+ </Popover>2448+ );2449+}226424502265-const UserMessageElementContextChip = memo(function UserMessageElementContextChip(props: {2266- context: ParsedElementContextEntry;2451+function UserMessagePullRequestContextChip(props: {
- apps/web/src/components/PullRequestContextDetails.tsx line 13OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +1,13 @@1+import type { PullRequestContextMetadata } from "@t3tools/contracts";2+import { ArrowRightIcon, GitPullRequestIcon } from "lucide-react";3+4+import { cn } from "~/lib/utils";5+6+type PullRequestDisplayState = "open" | "draft" | "merged" | "closed";7+8+function displayState(metadata: PullRequestContextMetadata): PullRequestDisplayState {9+ return metadata.state === "open" && metadata.isDraft ? "draft" : metadata.state;10+}11+12+const STATE_PRESENTATION = {13+ open: {
- apps/web/src/components/composerContextPresentation.tsx line 263Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +226,21 @@226+ );227+}228+229+function previewAnnotationTooltip(annotation: PreviewAnnotationPayload): string {230+ const lines = [annotation.pageTitle?.trim() || annotation.pageUrl];231+ if (annotation.comment.trim()) lines.push("", annotation.comment.trim());232+ const targets: string[] = [];233+ const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;234+ if (annotation.elements.length > 0) targets.push(plural(annotation.elements.length, "element"));235+ if (annotation.regions.length > 0) targets.push(plural(annotation.regions.length, "region"));236+ if (annotation.strokes.length > 0) targets.push(plural(annotation.strokes.length, "drawing"));237+ if (annotation.styleChanges.length > 0) {238+ targets.push(plural(annotation.styleChanges.length, "style change"));239+ }240+ if (targets.length > 0) lines.push("", targets.join(", "));241+ return lines.join("\n");242+}243+244+function ComposerReviewCommentDetails({ comment }: { comment: ReviewCommentContext }) {245+ return (246+ <div className="space-y-2 overflow-hidden rounded-lg border border-border/70 bg-background/70 p-3">
- apps/mobile/src/features/threads/ThreadFeed.tsx lines 1681 to 1682OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -1676,4 +1677,6 @@16761677 readonly linkHandlers: MarkdownLinkHandlers;16771678 readonly renderImage: MarkdownImageRenderer;16781679 }) {1679- const segments = parseReviewCommentMessageSegments(props.text);1680+ // Inline context references render as their labels until mobile grows chips for them.1681+ const text = replaceComposerContextReferences(props.text, (occurrence) => occurrence.label);1682+ const segments = parseReviewCommentMessageSegments(text);apps/web/src/components/chat/ChatComposer.tsx lines 3218 to 3288Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2568,3 +2962,20 @@2568- syncTerminalContextsByIds(composerTerminalContexts, terminalContextIds),2962+ composerTerminalContexts.filter((context) => referenced.has(context.id)),25692963 );25702964 }2965+ for (const comment of composerReviewComments) {2966+ if (!referenced.has(reviewCommentContextId(comment.id))) {2967+ removeComposerDraftReviewComment(composerDraftTarget, comment.id);2968+ }2969+ }2970+ for (const annotation of composerPreviewAnnotations) {2971+ if (!referenced.has(previewAnnotationContextId(annotation.id))) {2972+ releaseAttachmentUpload(annotation.id);2973+ removeComposerDraftPreviewAnnotation(composerDraftTarget, annotation.id);2974+ }2975+ }2976+ // Files live only as chips; images stay on the shelf when their chip goes.2977+ for (const file of composerFiles) {2978+ if (!referenced.has(file.id)) {2979+ removeComposerFileFromDraft(file.id);2980+ }2981+ }apps/web/src/components/ComposerCitationNode.tsx line 127Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -117,3 +102,4 @@117102 >118103 <AssistantCitationChip119104 citation={props.citation}105+ composerapps/web/src/components/contextChipParts.tsx lines 231 to 235Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +212,21 @@212+ props.unresolved && "border-dashed text-foreground",213+ props.error && "border-destructive/35 bg-destructive/8 text-destructive",214+ );215+ const content = <FileChipContent {...props} />;216+ const attributes = {217+ className,218+ "aria-label": props.accessibleLabel,219+ "data-markdown-copy": props.copyMarkdown,220+ "data-context-unresolved": props.unresolved ? "true" : undefined,221+ };222+ return (223+ <Tooltip>224+ <TooltipTrigger225+ render={226+ props.onOpen ? (227+ <button type="button" disabled={props.disabled} onClick={props.onOpen} {...attributes}>228+ {content}229+ </button>230+ ) : (231+ <span {...attributes}>{content}</span>232+ )apps/web/src/composerDraftStore.ts lines 3853 to 3856OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -3944,4 +3850,7 @@39443850 }39453851 const nextDraft: ComposerThreadDraftState = {39463852 ...current,3947- prompt: ensureInlineTerminalContextPlaceholders("", current.terminalContexts.length),3853+ prompt: ensureInlineContextReferences(3854+ "",3855+ current.terminalContexts.map(terminalContextReference),3856+ ),apps/web/src/hooks/useCopyToClipboard.ts lines 113 to 120Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -96,3 +100,16 @@96100 }9710198102 try {103+ // Custom flavors need ClipboardItem; when it is missing or refuses the type, plain text104+ // still lands so the copy never silently fails.105+ if (extraFlavors && typeof ClipboardItem !== "undefined" && navigator.clipboard.write) {106+ try {107+ await navigator.clipboard.write([108+ new ClipboardItem({109+ "text/plain": new Blob([value], { type: "text/plain" }),110+ ...Object.fromEntries(111+ Object.entries(extraFlavors).map(([type, data]) => [112+ type,113+ new Blob([data], { type }),114+ ]),115+ ),apps/web/src/lib/terminalContext.ts line 32OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -32,11 +21,12 @@32- /**33- * Element-context entries extracted from the trailing `<element_context>`34- * block (if any). Stripped from `visibleText` so the raw block doesn't35- * leak into the user's bubble.36- */37- elementContexts: ParsedElementContextEntry[];21+export interface TerminalContextReferenceSource {22+ id: string;23+ terminalLabel: string;24+ lineStart: number;25+ lineEnd: number;3826 }392740-export interface ParsedTerminalContextEntry {41- header: string;42- body: string;28+/** The canonical inline link that stands for this context in the prompt. */29+export function formatTerminalContextReference(context: TerminalContextReferenceSource): string {30+ return formatComposerContextReference({31+ kind: "terminal",32+ contextId: context.id as ComposerContextId,packages/shared/src/composerContextLegacy.ts lines 312 to 318OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +298,21 @@298+ elementEntries.unshift(...entries);299+ continue;300+ }301+ const terminal = stripTrailing(rest, TRAILING_TERMINAL);302+ if (terminal) {303+ const entries = parseEntries(terminal.match[1] ?? "");304+ if (entries.length === 0 || entries.some((entry) => terminalRecord(entry, 1) === null)) break;305+ rest = terminal.text;306+ terminalEntries.unshift(...entries);307+ continue;308+ }309+ break;310+ }311+312+ const terminals = terminalEntries313+ .map((entry, index) => terminalRecord(entry, index + 1))314+ .filter((record) => record !== null);315+ const elements = elementEntries316+ .map((entry, index) => elementRecord(entry, index + 1))317+ .filter((record) => record !== null);318+ const previews = previewBodies.map((body, index) => previewRecord(body, index + 1));
- apps/web/src/components/chat/MessagesTimeline.tsx lines 1441 to 1450Resolvedby chrisdeeming(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 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 2585OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -2341,0 +2565,21 @@2565+}2566+2567+function UnavailableUserMessageContextChip(props: UserMessageContextRenderContext) {2568+ return (2569+ <UnresolvedChip2570+ label={props.reference.label}2571+ className={CHAT_INLINE_CHIP_CLASS_NAME}2572+ labelClassName={CHAT_INLINE_CHIP_LABEL_CLASS_NAME}2573+ copyMarkdown={props.copyMarkdown}2574+ tooltip="This context is no longer available."2575+ tooltipClassName="max-w-96 whitespace-pre-wrap leading-tight"2576+ />2577+ );2578+}2579+2580+const userMessageContextPresentationRegistry = createContextPresentationRegistry<2581+ KnownComposerContextRecord,2582+ UserMessageContextRenderContext,2583+ ReactNode2584+>({2585+ requiredKinds: ["image", "file", "terminal", "element", "review-comment", "preview-annotation"],packages/shared/src/composerContextLegacy.ts lines 398 to 402Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +325,21 @@325+ formatComposerContextReference(reviews[Number(index)]!),326+ );327+328+ // Placeholders bind to terminal entries in order, like the old materialize step did.329+ let placeholderIndex = 0;330+ body = body.replace(new RegExp(PLACEHOLDER, "g"), () => {331+ const record = terminals[placeholderIndex];332+ placeholderIndex += 1;333+ return record ? formatComposerContextReference(record) : "";334+ });335+ // Sent messages carry the materialized `@terminal-1:509-514` label instead of the336+ // placeholder; each such label becomes the chip in place.337+ const placedTerminals = new Set(terminals.slice(0, placeholderIndex));338+ for (const record of terminals) {339+ if (placedTerminals.has(record)) continue;340+ const label = inlineTerminalLabel(record);341+ let at = body.indexOf(label);342+ while (343+ at !== -1 &&344+ (/[\w@.-]/.test(body[at - 1] ?? "") || /[\d-]/.test(body[at + label.length] ?? ""))345+ ) {
- apps/web/src/components/chat/ChatComposer.tsx lines 4883 to 4887OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -4329,4 +4868,20 @@4868+4869+ /**4870+ * Chips for freshly attached files land at the caret; when the editor cannot take4871+ * input (approval, pending questions) they are appended so the file is never invisible.4872+ */4873+ const insertAttachmentReferences = (references: ReadonlyArray<ComposerContextReference>) => {4874+ if (references.length === 0) return;4875+ const text = references.map(formatInlineContextReference).join(" ");4876+ const inserted = insertComposerText(`${text} `, "cursor", { ensureLeadingBoundary: true });4877+ if (!inserted) {4878+ setPrompt(ensureInlineContextReferences(promptRef.current, references));4879+ }43294880 };4330488143314882 const removeComposerImage = (imageId: string) => {4332- removeComposerImageFromDraft(imageId);4883+ const referenced = collectInlineContextIds(promptRef.current).includes(imageId);4884+ if (!referenced) {4885+ removeComposerImageFromDraft(imageId);4886+ return;4887+ }apps/web/src/components/composerContextPresentation.tsx lines 286 to 296OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +276,21 @@276+}277+278+function ComposerPreviewAnnotationDetails({279+ annotation,280+}: {281+ annotation: PreviewAnnotationPayload;282+}) {283+ const summary = previewAnnotationTooltip(annotation);284+ return (285+ <div className="overflow-hidden rounded-lg border border-border/70 bg-background/70">286+ {annotation.screenshot ? (287+ <img288+ src={annotation.screenshot.dataUrl}289+ alt="Annotated preview crop"290+ className="max-h-64 w-full border-border/70 border-b bg-muted object-contain"291+ />292+ ) : (293+ <div className="border-border/70 border-b bg-muted/40 px-3 py-2 text-secondary-label text-xs">294+ Screenshot unavailable295+ </div>296+ )}apps/web/src/composerDraftStore.ts lines 1897 to 1903Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -1931,0 +1870,21 @@1870+ ["review-comment", reviewComments],1871+ ["preview-annotation", previewAnnotations],1872+ ] as const) {1873+ for (const entry of entries) {1874+ const contextId = toKindScopedComposerContextId(kind, entry.id);1875+ contextIds.set(`${kind}/${entry.id}`, contextId);1876+ contextIds.set(`${kind}/${toComposerContextId(entry.id)}`, contextId);1877+ if (kind === "preview-annotation") {1878+ contextIds.set(`${kind}/${toComposerContextId(`annotation-${entry.id}`)}`, contextId);1879+ }1880+ }1881+ }1882+ // Older drafts used producer ids (including dots and colons) directly in links.1883+ // Rewrite only links backed by this draft, before appending any missing references.1884+ const migratedPrompt = promptCandidate.replace(1885+ /\[([^\]\r\n]*)\]\(t3-context:\/\/v1\/([a-z-]+)\/([^/()\r\n]+)\)/g,1886+ (source, label: string, kind: string, id: string) => {1887+ const contextId = contextIds.get(`${kind}/${id}`);1888+ return contextId ? formatInlineContextReference({ kind, contextId, label }) : source;1889+ },1890+ );
- apps/web/src/components/chat/ChatComposer.tsx lines 2490 to 2496OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2239,0 +2476,21 @@2476+ .map((annotation) =>2477+ previewAnnotationContextRecord(annotation, {2478+ screenshotContextId: composerImages.some((image) => image.id === annotation.id)2479+ ? annotation.id2480+ : undefined,2481+ }),2482+ ),2483+ ...[...composerImages, ...composerFiles]2484+ .filter((attachment) =>2485+ wanted.has(toKindScopedComposerContextId(attachment.type, attachment.id)),2486+ )2487+ .map((attachment) => {2488+ // A hydrated file already lives on the server under its upload id.2489+ const upload = uploadsByImageId[attachment.id];2490+ const uploadId =2491+ attachment.type === "file" && attachment.uploadedAttachmentId !== undefined2492+ ? attachment.uploadedAttachmentId2493+ : upload?.status === "ready"2494+ ? upload.attachmentId2495+ : undefined;2496+ return attachmentContextRecord({ attachment, attachmentId: uploadId ?? attachment.id });apps/web/src/lib/composerContextRecords.ts line 262OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +242,21 @@242+ const { attachment, attachmentId } = bound;243+ const base = {244+ version: 1 as const,245+ contextId: toKindScopedComposerContextId(attachment.type, attachment.id),246+ label: sanitizeComposerContextLabel(attachment.name, attachment.type),247+ attachmentId,248+ name: attachment.name,249+ mimeType: attachment.mimeType,250+ sizeBytes: attachment.sizeBytes,251+ };252+ return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" };253+}254+255+export function buildMessageContext(input: {256+ terminalContexts: ReadonlyArray<TerminalContextDraft>;257+ reviewComments: ReadonlyArray<ReviewCommentContext>;258+ previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;259+ attachments?: ReadonlyArray<BoundComposerAttachment>;260+}): OrchestrationMessageContext | undefined {261+ // An annotation's screenshot travels as the image attachment that reuses its id.262+ const attachmentIds = new Set((input.attachments ?? []).map((bound) => bound.attachment.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 $22.32, 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.