feat(web): move composer context into inline references #10234
Closedchrisdeeming(GitHub profile, opens in a new tab)wants to merge 46 commits into
main fromrefs/pull/10234/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 2510Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2337,3 +2376,17 @@23372376 );23382377 }233923782379+/** One inline context chip in a sent message: label always, details by hover or click. */2380+function UserMessageContextReferenceChip(props: {2381+ reference: ChatMarkdownContextReference;2382+ record: KnownComposerContextRecord | undefined;2383+ annotationImage: ChatImageAttachment | null;2384+ attachment: ChatImageAttachment | ChatFileAttachment | null;2385+ onExpandImage: (image: ChatImageAttachment) => void;2386+ onOpenFile: (file: ChatFileAttachment) => void;2387+}) {2388+ const { reference, record, attachment } = props;2389+ const iconClassName = cn(COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, "size-3.5");2390+ if (record?.kind === "image" && attachment && isImageAttachment(attachment)) {2391+ return (2392+ <button
- apps/web/src/components/composerContextPresentation.tsx line 152Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +121,21 @@121+122+function attachmentTooltip(123+ attachment: ComposerImageAttachment | ComposerFileAttachment,124+ upload: AttachmentUploadState | undefined,125+): string {126+ const lines = [attachment.name, formatAttachmentSize(attachment.sizeBytes)];127+ if (upload?.status === "failed") lines.push("", upload.reason);128+ return lines.join("\n");129+}130+131+function ImageContextChip(props: {132+ record: ComposerImageAttachment;133+ upload: AttachmentUploadState | undefined;134+}) {135+ const actions = use(ComposerContextActionsContext);136+ const suffix = uploadStatusSuffix(props.upload);137+ return (138+ <Tooltip>139+ <TooltipTrigger140+ render={141+ <button
- apps/web/src/components/chat/ChatComposer.tsx lines 2762 to 2803Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2568,3 +2539,20 @@2568- syncTerminalContextsByIds(composerTerminalContexts, terminalContextIds),2539+ composerTerminalContexts.filter((context) => referenced.has(context.id)),25692540 );25702541 }2542+ for (const comment of composerReviewComments) {2543+ if (!referenced.has(reviewCommentContextId(comment.id))) {2544+ removeComposerDraftReviewComment(composerDraftTarget, comment.id);2545+ }2546+ }2547+ for (const annotation of composerPreviewAnnotations) {2548+ if (!referenced.has(previewAnnotationContextId(annotation.id))) {2549+ releaseAttachmentUpload(annotation.id);2550+ removeComposerDraftPreviewAnnotation(composerDraftTarget, annotation.id);2551+ }2552+ }2553+ // Files live only as chips; images stay on the shelf when their chip goes.2554+ for (const file of composerFiles) {2555+ if (!referenced.has(file.id)) {2556+ removeComposerFileFromDraft(file.id);2557+ }2558+ }apps/web/src/components/chat/composerPromptHistory.ts line 16OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -14,3 +12,5 @@14121513 const CLAUDE_ULTRATHINK_PREFIX = "Ultrathink:\n";1614 const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b[^>]*>[\s\S]*?<\/review_comment>/g;15+const TRAILING_LEGACY_CONTEXT =16+ /\n*<(terminal_context|element_context|preview_annotation)>\n((?:(?!<preview_annotation>)[\s\S])*?)\n<\/\1>\s*$/;apps/web/src/components/chat/MessagesTimeline.tsx lines 2408 to 2421Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2269,4 +2288,18 @@2288+ icon: ReactNode;2289+ label: string;2290+ tooltip?: string;2291+ unresolved?: boolean;22692292 }) {2270- const tooltipText = props.context.body2271- ? `${props.context.header}\n${props.context.body}`2272- : props.context.header;2293+ const chip = (2294+ <span2295+ className={cn(2296+ CHAT_INLINE_CHIP_CLASS_NAME,2297+ props.unresolved && "border-dashed text-muted-foreground",2298+ )}2299+ data-context-unresolved={props.unresolved ? "true" : undefined}2300+ >2301+ {props.icon}2302+ <span className={CHAT_INLINE_CHIP_LABEL_CLASS_NAME}>{props.label}</span>2303+ </span>2304+ );2305+ if (!props.tooltip) return chip;apps/web/src/components/ChatView.tsx lines 6971 to 6977Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -6485,14 +6484,9 @@6485- const composerElementContextsSnapshot = [...composerElementContexts];64866484 const composerPreviewAnnotationsSnapshot = [...composerPreviewAnnotations];64876485 const composerReviewCommentsSnapshot: ReviewCommentContext[] = [...composerReviewComments];6488- const messageTextWithContexts = appendElementContextsToPrompt(6489- appendTerminalContextsToPrompt(promptForSend, composerTerminalContextsSnapshot),6490- composerElementContextsSnapshot,6491- );6492- const messageTextWithPreviewAnnotations = composerPreviewAnnotationsSnapshot.reduce(6493- (text, annotation) => appendPreviewAnnotationPrompt(text, annotation),6494- messageTextWithContexts,6495- );6496- const messageTextForSend = appendReviewCommentsToPrompt(6497- messageTextWithPreviewAnnotations,6498- composerReviewCommentsSnapshot,6486+ // Expired terminal excerpts are not sent; their chips leave the text with them.6487+ const messageTextForSend = composerTerminalContexts6488+ .filter((context) => !composerTerminalContextsSnapshot.includes(context))6489+ .reduce(6490+ (text, context) => removeInlineContextReference(text, context.id).prompt,6491+ promptForSend,6492+ )apps/web/src/components/ChatView.tsx lines 7210 to 7213Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -6703,5 +6715,7 @@67036715 titleSeed = `File: ${composerFilesSnapshot[0].name}`;67046716 } else if (composerTerminalContextsSnapshot.length > 0) {67056717 titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);6706- } else if (composerElementContextsSnapshot.length > 0) {6707- titleSeed = formatElementContextLabel(composerElementContextsSnapshot[0]!);6718+ } else if (composerReviewCommentsSnapshot.length > 0) {6719+ titleSeed = `Review: ${reviewCommentContextLabel(composerReviewCommentsSnapshot[0]!)}`;6720+ } else if (composerPreviewAnnotationsSnapshot.length > 0) {6721+ titleSeed = previewAnnotationContextLabel(composerPreviewAnnotationsSnapshot[0]!);apps/web/src/composerDraftStore.ts lines 366 to 369Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -357 +344,21 @@357344 */345+/** Options for adding a context record and, independently, a reference to it. */346+export interface ComposerContextAddOptions {347+ /** `false` when the caller already placed the chip (paste, caret insertion). */348+ appendReference?: boolean;349+ /** `true` when this action intentionally adds another reference to an existing record. */350+ allowDuplicateReference?: boolean;351+ /** `false` to append synchronously instead of asking a mounted editor for its current caret. */352+ insertAtCaret?: boolean;353+}354+355+/**356+ * A mounted composer registers itself here so context produced by other panels (diff357+ * comments, preview picks) lands at its caret. Without a handler the store appends the358+ * reference to the prompt, which is where a draft with no composer open would show it.359+ * Runtime-only: never persisted.360+ */361+export type ComposerContextInsertionHandler = (362+ references: ReadonlyArray<ComposerContextReference>,363+) => boolean;364+const contextInsertionHandlers = new Map<string, ComposerContextInsertionHandler>();apps/web/src/composerDraftStore.ts lines 2963 to 2974Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2993,6 +2904,6 @@29932904 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();29942905 const nextDraft: ComposerThreadDraftState = {29952906 ...existing,2996- prompt: ensureInlineTerminalContextPlaceholders(2907+ prompt: ensureInlineContextReferences(29972908 existing.prompt,2998- normalizedContexts.length,2909+ normalizedContexts.map(terminalContextReference),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/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 line 342Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +270,21 @@270+ reviews.push(record);271+ return `${reviewToken}${reviews.length - 1}${reviewToken}`;272+ });273+274+ // Blocks were appended in send order (terminal, element, preview, review), so they peel275+ // off the end in reverse. Each peel exposes the next block as trailing.276+ // Only reviews that trailed the original text were appended by the old send path; a277+ // review that sat before other blocks keeps its place.278+ const trailingReviewTokens: number[] = [];279+ const tokens = trailingReviewTokenPattern.exec(rest);280+ if (tokens && tokens[0].length > 0) {281+ trailingReviewTokens.push(282+ ...Array.from(tokens[0].matchAll(reviewTokenPattern), (m) => Number(m[1])),283+ );284+ rest = rest.slice(0, tokens.index).replace(/\n+$/, "");285+ }286+ for (;;) {287+ const preview = stripTrailing(rest, TRAILING_PREVIEW);288+ if (preview) {289+ rest = preview.text;290+ previewBodies.unshift(preview.match[1] ?? "");packages/shared/src/composerContextLegacy.ts lines 397 to 403Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +320,21 @@320+321+ let body = rest.replace(reviewTokenPattern, (_whole, index: string) =>322+ formatComposerContextReference(reviews[Number(index)]!),323+ );324+325+ // Placeholders bind to terminal entries in order, like the old materialize step did.326+ let placeholderIndex = 0;327+ body = body.replace(new RegExp(PLACEHOLDER, "g"), () => {328+ const record = terminals[placeholderIndex];329+ placeholderIndex += 1;330+ return record ? formatComposerContextReference(record) : "";331+ });332+ // Sent messages carry the materialized `@terminal-1:509-514` label instead of the333+ // placeholder; each such label becomes the chip in place.334+ const placedTerminals = new Set(terminals.slice(0, placeholderIndex));335+ for (const record of terminals) {336+ if (placedTerminals.has(record)) continue;337+ const label = inlineTerminalLabel(record);338+ let at = body.indexOf(label);339+ while (at !== -1 && /[\d-]/.test(body[at + label.length] ?? "")) {340+ at = body.indexOf(label, at + 1);
- apps/web/src/components/chat/MessagesTimeline.tsx lines 1513 to 1514OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1501,5 +1510,5 @@15011510 {typeof revertTurnCount === "number" && (15021511 <RevertUserMessageButton turnCount={revertTurnCount} />15031512 )}1504- {displayedUserMessage.copyText && (1505- <MessageCopyButton text={displayedUserMessage.copyText} variant="ghost" />1513+ {resolvedContext.text && (1514+ <MessageCopyButton text={resolvedContext.text} variant="ghost" />apps/web/src/components/chat/MessagesTimeline.tsx line 2436OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -2341,0 +2416,21 @@2416+ return (2417+ <button2418+ type="button"2419+ disabled={disabled}2420+ className={cn(CHAT_INLINE_CHIP_CLASS_NAME, !disabled && "cursor-pointer hover:underline")}2421+ aria-label={`File attachment, ${record.name}`}2422+ onClick={() => props.onOpenFile(attachment)}2423+ >2424+ <FileIcon className={iconClassName} />2425+ <span className={CHAT_INLINE_CHIP_LABEL_CLASS_NAME}>{record.name}</span>2426+ </button>2427+ );2428+ }2429+ if (record?.kind === "terminal") {2430+ const tooltipText = record.text.length > 0 ? `${record.label}\n${record.text}` : record.label;2431+ return <TerminalContextInlineChip label={record.label} tooltipText={tooltipText} />;2432+ }2433+ if (record?.kind === "element") {2434+ const lines = [record.label, record.pageUrl];2435+ if (record.selector) lines.push(record.selector);2436+ if (record.htmlPreview.trim()) lines.push("", record.htmlPreview.trim().slice(0, 600));apps/web/src/composerDraftStore.ts line 3270OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3340,3 +3267,4 @@33403267 }33413268 const nextDraft: ComposerThreadDraftState = {33423269 ...current,3270+ prompt: removeInlineContextReference(current.prompt, imageId).prompt,apps/web/src/lib/composerContextRecords.ts lines 241 to 248Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +197,21 @@197+ };198+ return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" };199+}200+201+export function buildMessageContext(input: {202+ terminalContexts: ReadonlyArray<TerminalContextDraft>;203+ reviewComments: ReadonlyArray<ReviewCommentContext>;204+ previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;205+ attachments?: ReadonlyArray<BoundComposerAttachment>;206+}): OrchestrationMessageContext | undefined {207+ // An annotation's screenshot travels as the image attachment that reuses its id.208+ const attachmentIds = new Set((input.attachments ?? []).map((bound) => bound.attachment.id));209+ const records: ComposerContextRecord[] = [210+ ...input.terminalContexts.map(terminalContextRecord),211+ ...input.reviewComments.map(reviewCommentContextRecord),212+ ...input.previewAnnotations.map((annotation) =>213+ previewAnnotationContextRecord(annotation, {214+ screenshotContextId: attachmentIds.has(annotation.id) ? annotation.id : undefined,215+ }),216+ ),217+ ...(input.attachments ?? []).map(attachmentContextRecord),
- apps/web/src/components/chat/ChatComposer.tsx line 4362OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -4327,6 +4343,20 @@43274343 }43284344 }4345+ return insertedAny;4346+ };4347+4348+ /**4349+ * Chips for freshly attached files land at the caret; when the editor cannot take4350+ * input (approval, pending questions) they are appended so the file is never invisible.4351+ */4352+ const insertAttachmentReferences = (references: ReadonlyArray<ComposerContextReference>) => {4353+ if (references.length === 0) return;4354+ const text = references.map(formatInlineContextReference).join(" ");4355+ const inserted = insertComposerText(`${text} `, "cursor", { ensureLeadingBoundary: true });4356+ if (!inserted) {4357+ setPrompt(ensureInlineContextReferences(promptRef.current, references));4358+ }43294359 };4330436043314361 const removeComposerImage = (imageId: string) => {4332- removeComposerImageFromDraft(imageId);4362+ const referenced = collectInlineContextIds(promptRef.current).includes(imageId);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);apps/web/src/composerDraftStore.ts lines 3611 to 3619Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -3583,7 +3565,12 @@35833565 ...state.draftsByThreadKey,35843566 [threadKey]: {35853567 ...existing,3586- prompt: ensureInlineTerminalContextPlaceholders(3587- existing.prompt,3588- existing.terminalContexts.length + acceptedContexts.length,3589- ),3568+ prompt:3569+ options?.appendReference === false3570+ ? existing.prompt3571+ : ensureInlineContextReferences(3572+ existing.prompt,3573+ [...existing.terminalContexts, ...acceptedContexts].map(3574+ terminalContextReference,3575+ ),3576+ ),apps/web/src/lib/composerContextReferences.ts line 52OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +32,21 @@32+ * Producers mint ids in their own grammars (`pull-request-finding:42`,33+ * `file-comment-<ms>-<n>`). A context id must survive a Markdown link and the wire34+ * schema, so anything outside `[a-z0-9_-]` is folded into a readable slug plus a hash of35+ * the original. Deterministic, so the same producer id always maps to the same context id.36+ */37+export function toComposerContextId(producerId: string): ComposerContextId {38+ if (CONTEXT_ID_PATTERN.test(producerId)) return producerId as ComposerContextId;39+ const slug = producerId40+ .replace(/[^a-z0-9_-]+/gi, "-")41+ .replace(/^-+|-+$/g, "")42+ .slice(0, 48);43+ return `${slug || "ctx"}-${fnv1a32(producerId)}` as ComposerContextId;44+}45+46+/** Kind namespaces also survive import, where a record id becomes the new producer id. */47+export function toKindScopedComposerContextId(48+ kind: ComposerContextKind,49+ producerId: string,50+): ComposerContextId {51+ const prefix = `${kind}_`;52+ return toComposerContextId(producerId.startsWith(prefix) ? producerId : `${prefix}${producerId}`);
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 $15.04, which exceeds your per-review limit of $15.00.
The top 3 files driving up this estimate:
apps/web/src/composerDraftStore.tsapps/web/src/components/chat/ChatComposer.tsxapps/web/src/components/chat/MessagesTimeline.tsxTip
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.