feat(context): preserve references across copy paste and stash #10235
Closedchrisdeeming(GitHub profile, opens in a new tab)wants to merge 60 commits into
main fromrefs/pull/10235/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
- apps/mobile/src/features/threads/ThreadFeed.tsx line 1682Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1676,4 +1677,5 @@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);apps/web/src/components/chat/ChatComposer.tsx lines 3038 to 3079Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2568,3 +2748,20 @@2568- syncTerminalContextsByIds(composerTerminalContexts, terminalContextIds),2748+ composerTerminalContexts.filter((context) => referenced.has(context.id)),25692749 );25702750 }2751+ for (const comment of composerReviewComments) {2752+ if (!referenced.has(reviewCommentContextId(comment.id))) {2753+ removeComposerDraftReviewComment(composerDraftTarget, comment.id);2754+ }2755+ }2756+ for (const annotation of composerPreviewAnnotations) {2757+ if (!referenced.has(previewAnnotationContextId(annotation.id))) {2758+ releaseAttachmentUpload(annotation.id);2759+ removeComposerDraftPreviewAnnotation(composerDraftTarget, annotation.id);2760+ }2761+ }2762+ // Files live only as chips; images stay on the shelf when their chip goes.2763+ for (const file of composerFiles) {2764+ if (!referenced.has(file.id)) {2765+ removeComposerFileFromDraft(file.id);2766+ }2767+ }apps/web/src/components/chat/ChatComposer.tsx lines 4095 to 4101Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -3557,6 +3769,14 @@35573769 });35583770 }355937713560- // Terminal and preview context stays behind because the stash cannot restore it.3772+ // Everything the entry carries leaves the draft with it.35613773 promptRef.current = "";35623774 clearComposerDraftPromptAndImages(stashTarget);3775+ clearComposerDraftTerminalContexts(stashTarget);3776+ for (const comment of composerReviewComments) {3777+ removeComposerDraftReviewComment(stashTarget, comment.id);3778+ }3779+ for (const annotation of composerPreviewAnnotations) {3780+ releaseAttachmentUpload(annotation.id);3781+ removeComposerDraftPreviewAnnotation(stashTarget, annotation.id);3782+ }apps/web/src/components/chat/ChatComposer.tsx lines 4972 to 4982Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -4329,4 +4580,20 @@43294580 };4330458143314582 const removeComposerImage = (imageId: string) => {4332- removeComposerImageFromDraft(imageId);4583+ const referenced = collectInlineContextIds(promptRef.current).includes(imageId);4584+ if (!referenced) {4585+ removeComposerImageFromDraft(imageId);4586+ return;4587+ }4588+ const image = composerImagesRef.current.find((candidate) => candidate.id === imageId);4589+ const confirmation = requestConfirmDialog(4590+ `Remove ${image?.name ?? "this image"} from the message?\nIt is referenced in your text; removing it also removes every reference.`,4591+ { variant: "destructive" },4592+ );4593+ if (!confirmation) {4594+ removeComposerImageFromDraft(imageId);4595+ return;4596+ }4597+ void confirmation.then((confirmed) => {4598+ if (confirmed) removeComposerImageFromDraft(imageId);4599+ });apps/web/src/components/chat/MessagesTimeline.tsx lines 1433 to 1444Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1339,0 +1334,21 @@1334+ collectComposerContextReferences(resolvedContext.text).flatMap((occurrence) => {1335+ const record = asKnownContextRecord(resolvedContext.recordsById.get(occurrence.contextId));1336+ return record?.kind === "file" || record?.kind === "image" ? [record.attachmentId] : [];1337+ }),1338+ );1339+ const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id));1340+ const annotationRecordIds = resolvedContext.records1341+ .filter((record) => record.kind === "preview-annotation")1342+ .map((record) => record.contextId);1343+ const contextClipboardFragment =1344+ resolvedContext.records.length === 01345+ ? null1346+ : encodeComposerContextFragment({1347+ version: 1,1348+ source: {1349+ environmentId: ctx.activeThreadEnvironmentId,1350+ ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),1351+ messageId: row.message.id,1352+ },1353+ records: resolvedContext.records,1354+ });apps/web/src/composerDraftStore.ts lines 1904 to 1906Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -1926,6 +1856,6 @@19261856 draftCandidate.interactionMode === "plan" || draftCandidate.interactionMode === "default"19271857 ? draftCandidate.interactionMode19281858 : null;1929- const prompt = ensureInlineTerminalContextPlaceholders(1930- promptCandidate,1931- terminalContexts.length,1859+ const prompt = ensureInlineContextReferences(1860+ migrateLegacyTerminalContextPlaceholders(promptCandidate, terminalContexts),1861+ terminalContexts.map((context) => terminalContextReference({ ...context, text: "" })),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/components/chat/ChatComposer.tsx line 2379OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -2246,0 +2359,21 @@2359+ name: record.name,2360+ mimeType: file.type,2361+ sizeBytes: file.size,2362+ file,2363+ },2364+ ]);2365+ }2366+ },2367+ [addComposerFilesToDraft, addComposerImage, createAssetUrl],2368+ );2369+ /**2370+ * Brings records into this draft (paste, stash restore). Binaries are transferred only2371+ * when `sourceEnvironmentId` is given; the stash restores its own images and files.2372+ */2373+ const importContextRecords = useCallback(2374+ (2375+ records: ReadonlyArray<ComposerContextRecord>,2376+ sourceEnvironmentId: EnvironmentId | null,2377+ ): ReadonlyMap<string, string> => {2378+ const rewritten = new Map<string, string>();2379+ if (!activeThread) return rewritten;apps/web/src/components/chat/MessagesTimeline.tsx line 1425Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1328,12 +1328,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- ];1328+ const resolvedContext = resolveUserMessageContext(row.message);13371329 const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));13381330 const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));13391331 const revertTurnCount = row.revertTurnCount;1332+ // Files with a chip in the prose need no row; older messages keep their rows.1333+ const chippedAttachmentIds = new Set(1334+ collectComposerContextReferences(resolvedContext.text).flatMap((occurrence) => {1335+ const record = asKnownContextRecord(resolvedContext.recordsById.get(occurrence.contextId));1336+ return record?.kind === "file" || record?.kind === "image" ? [record.attachmentId] : [];1337+ }),1338+ );1339+ const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id));packages/shared/src/composerContextLegacy.ts line 344OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +324,21 @@324+ let body = rest.replace(reviewTokenPattern, (_whole, index: string) =>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] ?? ""))
- apps/web/src/components/chat/ChatComposer.tsx line 4637OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -4327,6 +4618,20 @@43274618 }43284619 }4620+ return insertedAny;4621+ };4622+4623+ /**4624+ * Chips for freshly attached files land at the caret; when the editor cannot take4625+ * input (approval, pending questions) they are appended so the file is never invisible.4626+ */4627+ const insertAttachmentReferences = (references: ReadonlyArray<ComposerContextReference>) => {4628+ if (references.length === 0) return;4629+ const text = references.map(formatInlineContextReference).join(" ");4630+ const inserted = insertComposerText(`${text} `, "cursor", { ensureLeadingBoundary: true });4631+ if (!inserted) {4632+ setPrompt(ensureInlineContextReferences(promptRef.current, references));4633+ }43294634 };4330463543314636 const removeComposerImage = (imageId: string) => {4332- removeComposerImageFromDraft(imageId);4637+ const referenced = collectInlineContextIds(promptRef.current).includes(imageId);apps/web/src/components/chat/MessagesTimeline.tsx line 1390OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -1339,0 +1370,21 @@1370+ for (const element of container.querySelectorAll("[data-markdown-copy]")) {1371+ copiedMarkdown.push(element.getAttribute("data-markdown-copy") ?? "");1372+ }1373+ }1374+ const selectedIds = new Set(1375+ collectComposerContextReferences(copiedMarkdown.join("\n")).map((o) => o.contextId),1376+ );1377+ const records = resolvedContext.records.filter((record) => selectedIds.has(record.contextId));1378+ if (records.length === 0) return;1379+ const fragment = encodeComposerContextFragment({1380+ version: 1,1381+ source: {1382+ environmentId: ctx.activeThreadEnvironmentId,1383+ ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),1384+ messageId: row.message.id,1385+ },1386+ records,1387+ });1388+ if (fragment) event.clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment);1389+ };1390+ const renderContextReference = (reference: ChatMarkdownContextReference) => {apps/web/src/components/composerContextPresentation.tsx lines 117 to 124Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +97,21 @@97+ }98+ return records;99+}100+101+function ContextChip(props: {102+ icon: ReactElement;103+ label: string;104+ kindLabel: string;105+ tooltip: string;106+}) {107+ return (108+ <Tooltip>109+ <TooltipTrigger110+ render={111+ <span112+ className={COMPOSER_INLINE_CHIP_CLASS_NAME}113+ aria-label={`${props.kindLabel}, ${props.label}`}114+ >115+ {props.icon}116+ <span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{props.label}</span>117+ </span>apps/web/src/composerDraftStore.ts lines 1884 to 1885OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -1931,0 +1865,21 @@1865+ const contextIds = new Map<string, string>();1866+ for (const [kind, entries] of [1867+ ["image", attachments],1868+ ["file", files],1869+ ["terminal", terminalContexts],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,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);
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 $17.48, 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/composerDraftStore.tsapps/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.