@devries-cameron20 / t3code Mirror · read-only / commits / f08d8dd0a5
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 03:15 UTC

feat(web): add pull request comments to the chat (#30579)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com>

Antony committed Nov 6, 2026 at 02:29 UTC f08d8dd0a5a3269da8aac7cfcbaa9f559110247c
7 files changed +420 -6
apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+11 -1
@@ -47,7 +47,11 @@ import { useLocalStorage } from "~/hooks/useLocalStorage";
47 import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";
48 import { useRenderedAppearance } from "~/hooks/useTheme";
49 import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse";
50 -import { pullRequestFindingKey, type PullRequestFinding } from "./pullRequestDetail.logic";
50 +import {
51 + pullRequestFindingKey,
52 + type PullRequestChatSubject,
53 + type PullRequestFinding,
54 +} from "./pullRequestDetail.logic";
55 import {
56 canEditPullRequestComment,
57 canResolvePullRequestThread,
@@ -338,6 +342,7 @@ function PullRequestCodeTab({
342 pendingFinding,
343 fixFindingLabel = "Fix in a thread",
344 onFixFinding,
345 + onAddToChat,
346 onAddToAgentSelection,
347 onRefresh,
348 refreshToken = 0,
@@ -353,6 +358,8 @@ function PullRequestCodeTab({
358 pendingFinding?: string | null;
359 fixFindingLabel?: string;
360 onFixFinding?: (finding: PullRequestFinding) => void;
361 + /** Absent where there is no composer beside the panel to add a conversation to. */
362 + onAddToChat?: (subject: PullRequestChatSubject) => void;
363 onAddToAgentSelection?: (input: PullRequestAgentSelectionInput) => void;
364 onRefresh: () => void;
365 refreshToken?: number;
@@ -967,6 +974,9 @@ function PullRequestCodeTab({
974 fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}
975 fixLabel={fixFindingLabel}
976 {...(onFixFinding ? { onFix: () => onFixFinding({ kind: "thread", thread }) } : {})}
977 + {...(onAddToChat
978 + ? { onAddToChat: (loaded) => onAddToChat({ kind: "thread", thread: loaded }) }
979 + : {})}
980 onLoadMore={async (cursor): Promise<PullRequestThreadCommentsResult | null> => {
981 const result = await loadThreadComments({
982 environmentId,
apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+43
@@ -117,6 +117,8 @@ import {
117 buildExplainPullRequestHandoff,
118 buildFixFindingHandoff,
119 buildFixFindingsHandoff,
120 + buildPullRequestCommentContext,
121 + buildPullRequestContext,
122 buildResolveConflictsPrompt,
123 latestPullRequestReviewOutcomes,
124 loadingPullRequestCheckoutCommand,
@@ -137,6 +139,7 @@ import {
139 isPullRequestConflicting,
140 resolveBaseFreshness,
141 resolvePullRequestMergeMethod,
142 + type PullRequestChatSubject,
143 type PullRequestFinding,
144 shouldRefreshPullRequestActivity,
145 } from "./pullRequestDetail.logic";
@@ -1013,6 +1016,43 @@ export function PullRequestDetailPanel({
1016 );
1017 };
1018
1019 + /**
1020 + * Brings a remark into the composer beside this panel, with the pull request it belongs to,
1021 + * and nothing else: what to ask about it is the reader's to write. A remark on a line travels
1022 + * as its whole conversation, the way fixing one does.
1023 + */
1024 + const addCommentToChat = (subject: PullRequestChatSubject) => {
1025 + if (!detail || attachTarget === null) return;
1026 + const thread =
1027 + subject.kind === "comment"
1028 + ? detail.reviewThreads.find((candidate) =>
1029 + candidate.comments.some((comment) => comment.id === subject.comment.id),
1030 + )
1031 + : undefined;
1032 + const comment = buildPullRequestCommentContext(
1033 + detail,
1034 + thread === undefined ? subject : { kind: "thread", thread },
1035 + );
1036 + if (comment === null) return;
1037 + const store = useComposerDraftStore.getState();
1038 + const reference = buildPullRequestContext({
1039 + number: detail.number,
1040 + title: detail.title,
1041 + url: detail.url,
1042 + headBranch: detail.headBranch,
1043 + baseBranch: detail.baseBranch,
1044 + state: detail.state,
1045 + isDraft: detail.isDraft,
1046 + });
1047 + const hasReference = (store.getComposerDraft(attachTarget)?.reviewComments ?? []).some(
1048 + (existing) => existing.pullRequest?.url === detail.url,
1049 + );
1050 + // The active editor may be answering a provider question rather than editing this draft.
1051 + if (!hasReference) store.addReviewComment(attachTarget, reference, { insertAtCaret: false });
1052 + store.addReviewComment(attachTarget, comment, { insertAtCaret: false });
1053 + toastManager.add({ type: "success", title: "Added to the composer" });
1054 + };
1055 +
1056 const startCheckout = (mode: "worktree" | "local") => {
1057 if (!handoffSummary) return;
1058 void startHandoff(`checkout:${mode}`, null, mode);
@@ -1717,6 +1757,7 @@ export function PullRequestDetailPanel({
1757 fixFindingLabel={handoffLabels.fixFinding}
1758 fixCheckLabel={handoffLabels.fixCheck}
1759 {...(canFixFindings ? { onFixFinding: startFixFinding } : {})}
1760 + {...(attachTarget === null ? {} : { onAddToChat: addCommentToChat })}
1761 onRefresh={refreshDetail}
1762 onRefreshChecks={refreshFromHost}
1763 />
@@ -1774,6 +1815,7 @@ export function PullRequestDetailPanel({
1815 reference={reference}
1816 order={timelineOrder}
1817 onOpenCommit={openCommit}
1818 + {...(attachTarget === null ? {} : { onAddToChat: addCommentToChat })}
1819 onRefresh={refreshDetail}
1820 />
1821 )}
@@ -1797,6 +1839,7 @@ export function PullRequestDetailPanel({
1839 pendingFinding={handoff}
1840 fixFindingLabel={handoffLabels.fixFinding}
1841 {...(canFixFindings ? { onFixFinding: startFixFinding } : {})}
1842 + {...(attachTarget === null ? {} : { onAddToChat: addCommentToChat })}
1843 onRefresh={refreshDetail}
1844 refreshToken={refreshToken}
1845 backgroundRefreshToken={turnRefresh ?? 0}
apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx
+20 -2
@@ -7,7 +7,7 @@ import type {
7 PullRequestThreadCommentsResult,
8 PullRequestThreadComment,
9 } from "@t3tools/contracts";
10 -import { HammerIcon, MessageSquareIcon, Trash2Icon } from "lucide-react";
10 +import { HammerIcon, MessageSquareIcon, MessageSquarePlusIcon, Trash2Icon } from "lucide-react";
11 import { Circle, CircleCheck } from "lucide";
12 import { useRef, useState } from "react";
13 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
@@ -23,6 +23,7 @@ import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
23 import {
24 editPullRequestThreadComment,
25 mergePullRequestThreadComments,
26 + visibleBody,
27 } from "./pullRequestDetail.logic";
28 import { PullRequestActorLabel } from "./pullRequestPresentation";
29 import { PullRequestMarkdown } from "./PullRequestMarkdown";
@@ -121,6 +122,7 @@ export function ReviewThreadCard({
122 fixPending,
123 fixLabel = "Fix in a thread",
124 onFix,
125 + onAddToChat,
126 onReply,
127 onLoadMore,
128 canEditComment,
@@ -140,6 +142,11 @@ export function ReviewThreadCard({
142 fixPending?: boolean;
143 fixLabel?: string;
144 onFix?: () => void;
145 + /**
146 + * Absent where there is no composer beside the panel to add the conversation to. Handed the
147 + * thread with every comment the reader has loaded, not only the first page.
148 + */
149 + onAddToChat?: (thread: PullRequestReviewThread) => void;
150 onReply: (body: string) => Promise<boolean>;
151 onLoadMore: (cursor: string) => Promise<PullRequestThreadCommentsResult | null>;
152 canEditComment: (comment: PullRequestThreadComment) => boolean;
@@ -253,11 +260,22 @@ export function ReviewThreadCard({
260 {fixPending ? "Preparing..." : fixLabel}
261 </Button>
262 ) : null}
256 - {canResolve ? (
263 + {onAddToChat && comments.some((comment) => visibleBody(comment.body) !== null) ? (
264 <Button
265 size="xs"
266 variant="ghost"
267 className={onFix ? undefined : "ml-auto"}
268 + onClick={() => onAddToChat({ ...thread, comments })}
269 + >
270 + <MessageSquarePlusIcon className="size-3" />
271 + Add to chat
272 + </Button>
273 + ) : null}
274 + {canResolve ? (
275 + <Button
276 + size="xs"
277 + variant="ghost"
278 + className={onFix || onAddToChat ? undefined : "ml-auto"}
279 disabled={pending}
280 onClick={onToggleResolved}
281 >
apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
+43
@@ -18,6 +18,7 @@ import {
18 ChevronRightIcon,
19 HammerIcon,
20 ListFilterIcon,
21 + MessageSquarePlusIcon,
22 TagIcon,
23 UsersIcon,
24 } from "lucide-react";
@@ -68,6 +69,7 @@ import {
69 pullRequestFindingKey,
70 pullRequestReviewOutcome,
71 visibleBody,
72 + type PullRequestChatSubject,
73 type PullRequestConversationItem,
74 type PullRequestFinding,
75 } from "./pullRequestDetail.logic";
@@ -218,6 +220,34 @@ function CommentBody({
220 );
221 }
222
223 +/**
224 + * What Add to chat hands over for a remark: a remark on a line goes as its whole conversation,
225 + * the way fixing one does. Null when there are no words in it to talk about.
226 + */
227 +function chatSubject(
228 + comment: PullRequestComment,
229 + thread: PullRequestReviewThread | undefined,
230 +): PullRequestChatSubject | null {
231 + if (thread !== undefined) {
232 + return thread.comments.some((entry) => visibleBody(entry.body) !== null)
233 + ? { kind: "thread", thread }
234 + : null;
235 + }
236 + return visibleBody(comment.body) === null ? null : { kind: "comment", comment };
237 +}
238 +
239 +function AddToChatButton({ onClick }: { onClick: () => void }) {
240 + return (
241 + <Button size="xs" variant="ghost" className="shrink-0" onClick={onClick}>
242 + {/* Wrapped like Fix's label so both sit on the header's baseline. */}
243 + <span className="inline-flex items-baseline gap-1">
244 + <MessageSquarePlusIcon className="size-3 self-center" />
245 + <span>Add to chat</span>
246 + </span>
247 + </Button>
248 + );
249 +}
250 +
251 function CollapsedComment({
252 comment,
253 editing,
@@ -229,6 +259,7 @@ function CollapsedComment({
259 replyCount = 0,
260 replies = null,
261 moreReplies = null,
262 + onAddToChat,
263 }: {
264 comment: PullRequestComment;
265 editing: CommentEditing;
@@ -240,6 +271,7 @@ function CollapsedComment({
271 replyCount?: number;
272 replies?: ReactNode;
273 moreReplies?: ReactNode;
274 + onAddToChat?: (() => void) | undefined;
275 }) {
276 const [open, setOpen] = useState(false);
277 const statusTriggerRef = useRef<HTMLButtonElement>(null);
@@ -264,6 +296,7 @@ function CollapsedComment({
296 className={cn("size-3.5 transition-transform", open && "rotate-180")}
297 />
298 </CollapsibleTrigger>
299 + {onAddToChat ? <AddToChatButton onClick={onAddToChat} /> : null}
300 {reactionBar}
301 </div>
302 <CommentLocation comment={comment} thread={thread} />
@@ -401,6 +434,7 @@ export function PullRequestSummaryTab({
434 fixFindingLabel = "Fix in a thread",
435 fixCheckLabel = "Fix",
436 onFixFinding,
437 + onAddToChat,
438 onRefresh,
439 onRefreshChecks = onRefresh,
440 }: {
@@ -416,6 +450,8 @@ export function PullRequestSummaryTab({
450 fixFindingLabel?: string;
451 fixCheckLabel?: string;
452 onFixFinding?: (finding: PullRequestFinding) => void;
453 + /** Absent where there is no composer beside the panel to add a remark to. */
454 + onAddToChat?: (subject: PullRequestChatSubject) => void;
455 onRefresh: () => void;
456 onRefreshChecks?: () => void;
457 }) {
@@ -605,6 +641,8 @@ export function PullRequestSummaryTab({
641 ? null
642 : { kind: "comment", comment }
643 : { kind: "thread", thread };
644 + // A reply goes with its conversation, from the card that heads it.
645 + const chat = reply ? null : chatSubject(comment, thread);
646 return (
647 <article
648 key={`${detail.url}:${comment.id}`}
@@ -637,6 +675,9 @@ export function PullRequestSummaryTab({
675 </span>
676 </Button>
677 ) : null}
678 + {onAddToChat && chat !== null ? (
679 + <AddToChatButton onClick={() => onAddToChat(chat)} />
680 + ) : null}
681 {reactionBarFor(comment)}
682 </div>
683 {reply ? null : (
@@ -663,6 +704,7 @@ export function PullRequestSummaryTab({
704 const moreReplies =
705 item.kind === "thread" && item.hasMoreReplies ? <PullRequestMoreReplies {...item} /> : null;
706 if (isPullRequestCommentFinished(comment, thread)) {
707 + const chat = chatSubject(comment, thread);
708 return (
709 <CollapsedComment
710 key={`${detail.url}:${item.kind}:${item.id}`}
@@ -675,6 +717,7 @@ export function PullRequestSummaryTab({
717 replyCount={item.kind === "thread" ? item.replies.length + item.moreReplies : 0}
718 replies={replies}
719 moreReplies={moreReplies}
720 + onAddToChat={onAddToChat && chat !== null ? () => onAddToChat(chat) : undefined}
721 reactionBar={reactionBarFor(comment)}
722 />
723 );
apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
+45
@@ -18,6 +18,7 @@ import {
18 FileCode2Icon,
19 GitCommitHorizontalIcon,
20 MessageSquareIcon,
21 + MessageSquarePlusIcon,
22 } from "lucide-react";
23 import { useState, type ReactNode } from "react";
24
@@ -38,6 +39,7 @@ import {
39 isPullRequestVerdictStale,
40 newestPullRequestCommitAt,
41 pullRequestReviewOutcome,
42 + type PullRequestChatSubject,
43 type PullRequestReviewOutcome,
44 type PullRequestTimelineEvent,
45 type PullRequestTimelineThread,
@@ -65,6 +67,8 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react";
67
68 interface ReactionSurface {
69 readonly canReact: boolean;
70 + /** Absent where there is no composer beside the panel to add a remark to. */
71 + readonly onAddToChat?: ((comment: PullRequestComment) => void) | undefined;
72 readonly environmentId: EnvironmentId;
73 readonly threadRef: ScopedThreadRef | null;
74 readonly reference: PullRequestRef;
@@ -172,6 +176,34 @@ function ReviewStateBadge({ state }: { state: string }) {
176 );
177 }
178
179 +function AddToChatButton({
180 + comment,
181 + reactions,
182 +}: {
183 + comment: PullRequestComment;
184 + reactions: ReactionSurface;
185 +}) {
186 + const onAddToChat = reactions.onAddToChat;
187 + return onAddToChat === undefined ? null : (
188 + <Tooltip>
189 + <TooltipTrigger
190 + render={
191 + <Button
192 + size="icon-xs"
193 + variant="ghost-muted"
194 + className="-mt-1 shrink-0"
195 + aria-label="Add to chat"
196 + onClick={() => onAddToChat(comment)}
197 + />
198 + }
199 + >
200 + <MessageSquarePlusIcon className="size-3" />
201 + </TooltipTrigger>
202 + <TooltipPopup>Add to chat</TooltipPopup>
203 + </Tooltip>
204 + );
205 +}
206 +
207 function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: (url: string) => void }) {
208 return url === null ? null : (
209 <Button
@@ -193,6 +225,7 @@ function ConversationCard({
225 onOpen,
226 reactions,
227 showPath = true,
228 + reply = false,
229 }: {
230 event: PullRequestTimelineEvent;
231 editable: PullRequestComment | null;
@@ -200,6 +233,8 @@ function ConversationCard({
233 onOpen: (url: string) => void;
234 reactions: ReactionSurface;
235 showPath?: boolean;
236 + /** A reply goes with its conversation, from the card that heads it. */
237 + reply?: boolean;
238 }) {
239 const [editing, setEditing] = useState(false);
240 const [saving, setSaving] = useState(false);
@@ -248,6 +283,9 @@ function ConversationCard({
283 {editable !== null && !editing ? (
284 <PullRequestEditButton aria-label="Edit comment" onClick={() => setEditing(true)} />
285 ) : null}
286 + {event.body && event.comment && !reply ? (
287 + <AddToChatButton comment={event.comment} reactions={reactions} />
288 + ) : null}
289 {reactions.canReact || event.reactions.length > 0 ? (
290 <PullRequestReactionBar
291 className="ml-auto justify-end"
@@ -456,6 +494,7 @@ function ReviewThreadEvent({
494 onOpen={onOpen}
495 reactions={reactions}
496 showPath={false}
497 + reply
498 />
499 ))}
500 </div>
@@ -606,6 +645,9 @@ function ReviewVerdictEvent({
645 </PullRequestMetaLine>
646 </div>
647 </div>
648 + {event.body && event.comment ? (
649 + <AddToChatButton comment={event.comment} reactions={reactions} />
650 + ) : null}
651 {reactions.canReact || event.reactions.length > 0 ? (
652 <PullRequestReactionBar
653 className="ml-auto justify-end"
@@ -640,6 +682,7 @@ export function PullRequestTimelineTab({
682 reference,
683 order,
684 onOpenCommit,
685 + onAddToChat,
686 onRefresh,
687 }: {
688 scrollerRef: (node: HTMLElement | null) => void;
@@ -649,6 +692,7 @@ export function PullRequestTimelineTab({
692 reference: PullRequestRef;
693 order: "newest" | "oldest";
694 onOpenCommit: (oid: string) => void;
695 + onAddToChat?: (subject: PullRequestChatSubject) => void;
696 onRefresh: () => void;
697 }) {
698 const events = buildPullRequestTimeline(detail);
@@ -656,6 +700,7 @@ export function PullRequestTimelineTab({
700 const newestCommitAt = newestPullRequestCommitAt(detail.commits);
701 const reactions: ReactionSurface = {
702 canReact: detail.capabilities.reactions === true,
703 + onAddToChat: onAddToChat && ((comment) => onAddToChat({ kind: "comment", comment })),
704 environmentId,
705 threadRef,
706 reference,
apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
+173 -1
@@ -15,7 +15,11 @@ import {
15 } from "@t3tools/contracts";
16 import { describe, expect, it } from "vite-plus/test";
17 import { formatInlineContextReference } from "~/lib/composerContextReferences";
18 -import { buildMessageContext, reviewCommentContextReference } from "~/lib/composerContextRecords";
18 +import {
19 + buildMessageContext,
20 + reviewCommentContextLabel,
21 + reviewCommentContextReference,
22 +} from "~/lib/composerContextRecords";
23
24 import {
25 buildAddSelectionToAgentHandoff,
@@ -23,6 +27,7 @@ import {
27 buildExplainPullRequestHandoff,
28 buildResolveConflictsPrompt,
29 resolveThreadPanelPullRequestAction,
30 + buildPullRequestCommentContext,
31 buildPullRequestReferenceContext,
32 buildFixFindingHandoff,
33 canDeletePullRequestBranch,
@@ -1005,6 +1010,173 @@ describe("asking about a change rather than working on it", () => {
1010 });
1011 });
1012
1013 +describe("adding a remark to the chat", () => {
1014 + const pullRequest = { number: 42, url: "https://github.com/pingdotgg/t3code/pull/42" };
1015 + const remark = (id: string, body: string): PullRequestComment => ({
1016 + id,
1017 + kind: "issue-comment",
1018 + author: { login: "octocat", name: null, avatarUrl: null },
1019 + body,
1020 + createdAt: "2026-07-03T00:00:00Z",
1021 + url: null,
1022 + path: null,
1023 + reviewState: null,
1024 + });
1025 +
1026 + it("reads as the remark's author rather than as the pull request itself", () => {
1027 + const context = buildPullRequestCommentContext(pullRequest, {
1028 + kind: "comment",
1029 + comment: remark("c1", "Why not reuse the existing parser?"),
1030 + });
1031 +
1032 + expect(context && reviewCommentContextLabel(context)).toBe("#42 @octocat comment");
1033 + expect(context?.text).toBe("octocat: Why not reuse the existing parser?");
1034 + });
1035 +
1036 + it("keeps every added remark when a later hand-off lands", () => {
1037 + const added = ["c1", "c2"].flatMap(
1038 + (id) =>
1039 + buildPullRequestCommentContext(pullRequest, {
1040 + kind: "comment",
1041 + comment: remark(id, "why?"),
1042 + }) ?? [],
1043 + );
1044 + const handedOff = buildAskAboutPullRequestHandoff({
1045 + number: 42,
1046 + title: "Add the pull requests page",
1047 + url: "https://github.com/pingdotgg/t3code/pull/42",
1048 + headBranch: "feature",
1049 + baseBranch: "main",
1050 + state: "open",
1051 + isDraft: false,
1052 + });
1053 +
1054 + expect(
1055 + appendHandoff({ prompt: "", reviewComments: added }, handedOff).reviewComments.map(
1056 + (comment) => comment.id,
1057 + ),
1058 + ).toEqual([
1059 + "pr-comment:https://github.com/pingdotgg/t3code/pull/42:comment:c1",
1060 + "pr-comment:https://github.com/pingdotgg/t3code/pull/42:comment:c2",
1061 + "pull-request-context:https://github.com/pingdotgg/t3code/pull/42",
1062 + ]);
1063 + });
1064 +
1065 + it("drops a bot's bookkeeping so it cannot crowd the remark out of the bound", () => {
1066 + const context = buildPullRequestCommentContext(pullRequest, {
1067 + kind: "comment",
1068 + comment: remark(
1069 + "c1",
1070 + `<!-- ${"state".repeat(400)} -->\nThis leaks the token.\n\n\`\`\`html\n<!-- kept -->\n\`\`\``,
1071 + ),
1072 + });
1073 +
1074 + expect(context?.text).toBe("octocat: This leaks the token.\n\n```html\n<!-- kept -->\n```");
1075 + });
1076 +
1077 + it("keeps comments inside a quoted fence as code", () => {
1078 + const context = buildPullRequestCommentContext(pullRequest, {
1079 + kind: "comment",
1080 + comment: remark("c1", "> ```html\n> <!-- open\n> ```\n> Quoted. <!-- bot -->\nMine."),
1081 + });
1082 +
1083 + expect(context?.text).toBe("octocat: > ```html\n> <!-- open\n> ```\n> Quoted. \nMine.");
1084 + });
1085 +
1086 + it("holds a fence open over a deeper quoted fence and closes it with its blockquote", () => {
1087 + const nested = buildPullRequestCommentContext(pullRequest, {
1088 + kind: "comment",
1089 + comment: remark("c1", "```md\n> ```\n<!-- kept -->\n```\nMine. <!-- bot -->"),
1090 + });
1091 + const unquoted = buildPullRequestCommentContext(pullRequest, {
1092 + kind: "comment",
1093 + comment: remark("c2", "> ```\n> code\nMine. <!-- bot -->"),
1094 + });
1095 +
1096 + expect(nested?.text).toBe("octocat: ```md\n> ```\n<!-- kept -->\n```\nMine.");
1097 + expect(unquoted?.text).toBe("octocat: > ```\n> code\nMine.");
1098 + });
1099 +
1100 + it("keeps a fence written inside a hidden comment hidden", () => {
1101 + const context = buildPullRequestCommentContext(pullRequest, {
1102 + kind: "comment",
1103 + comment: remark("c1", '<!-- state\n```json\n{"secret": 1}\n```\n-->\nLooks good.'),
1104 + });
1105 +
1106 + expect(context?.text).toBe("octocat: Looks good.");
1107 + });
1108 +
1109 + it("closes a fence written with CRLF line endings", () => {
1110 + const context = buildPullRequestCommentContext(pullRequest, {
1111 + kind: "comment",
1112 + comment: remark("c1", "```ts\r\nconst x = 1;\r\n```\r\n<!-- bot -->\r\nRename x."),
1113 + });
1114 +
1115 + expect(context?.text).toBe("octocat: ```ts\nconst x = 1;\n```\nRename x.");
1116 + });
1117 +
1118 + it("reads inline code at the start of a line as prose, not as a fence", () => {
1119 + const context = buildPullRequestCommentContext(pullRequest, {
1120 + kind: "comment",
1121 + comment: remark("c1", "```x``` is unused <!-- bot -->\nRemove it."),
1122 + });
1123 +
1124 + expect(context?.text).toBe("octocat: ```x``` is unused \nRemove it.");
1125 + });
1126 +
1127 + it("keeps remarks from two repositories apart when their host ids match", () => {
1128 + const other = { number: 42, url: "https://github.com/octocat/fork/pull/42" };
1129 + const ids = [pullRequest, other].map(
1130 + (target) =>
1131 + buildPullRequestCommentContext(target, { kind: "comment", comment: remark("c1", "why?") })
1132 + ?.id,
1133 + );
1134 +
1135 + expect(new Set(ids).size).toBe(2);
1136 + });
1137 +
1138 + it("brings nothing for a remark an unfinished comment hides", () => {
1139 + expect(
1140 + buildPullRequestCommentContext(pullRequest, {
1141 + kind: "comment",
1142 + comment: remark("c1", "<!-- bot state left open"),
1143 + }),
1144 + ).toBeNull();
1145 + });
1146 +
1147 + it("brings nothing for a remark with no words in it", () => {
1148 + expect(
1149 + buildPullRequestCommentContext(pullRequest, {
1150 + kind: "comment",
1151 + comment: remark("c1", "<!-- bot bookkeeping -->"),
1152 + }),
1153 + ).toBeNull();
1154 + });
1155 +
1156 + it("brings nothing for a conversation with no words in it", () => {
1157 + const {
1158 + kind: _kind,
1159 + path: _path,
1160 + reviewState: _reviewState,
1161 + ...bookkeeping
1162 + } = remark("tc1", "<!-- bot bookkeeping -->");
1163 + expect(
1164 + buildPullRequestCommentContext(pullRequest, {
1165 + kind: "thread",
1166 + thread: {
1167 + id: "t1",
1168 + path: "src/app.ts",
1169 + line: 3,
1170 + side: "right",
1171 + isResolved: false,
1172 + isOutdated: false,
1173 + comments: [bookkeeping],
1174 + },
1175 + }),
1176 + ).toBeNull();
1177 + });
1178 +});
1179 +
1180 describe("a second handoff into the same composer", () => {
1181 const chip = (id: string): ReviewCommentContext => ({
1182 id,
apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
+85 -2
@@ -1,4 +1,6 @@
1 import { stripInlineContextReferences } from "~/lib/composerContextReferences";
2 +import type { Nodes as MdastNodes } from "mdast";
3 +import { fromMarkdown } from "mdast-util-from-markdown";
4 import {
5 capitalizeTerm,
6 sourceControlClients,
@@ -238,9 +240,10 @@ export function threadPullRequestPanelTarget(thread: {
240 }
241
242 export function pullRequestHandoffLabels(inThisThread: boolean) {
243 + // Beside a composer a remark's Fix shares its header with Add to chat.
244 return inThisThread
245 ? {
243 - fixFinding: "Fix in this thread",
246 + fixFinding: "Fix",
247 fixCheck: "Fix in this thread",
248 fixFindings: "Fix findings in this thread",
249 }
@@ -651,6 +654,42 @@ export function pagePullRequestConversationItems(
654 return { shown, hidden: items.length - shown.length };
655 }
656
657 +/**
658 + * A body as it reads, for text sent to the agent under a length bound. A bot's HTML-comment
659 + * bookkeeping would otherwise use up the bound before the remark got any of it. Comments in code
660 + * are source the remark is showing, so they stay. Null for a body with no words.
661 + */
662 +function readableBody(raw: string): string | null {
663 + if (visibleBody(raw) === null) return null;
664 + const body = raw.replace(/\r\n?/gu, "\n");
665 + const cuts: Array<[number, number]> = [];
666 + const visit = (node: MdastNodes) => {
667 + if (node.type === "html" && node.position?.start.offset !== undefined) {
668 + cuts.push([node.position.start.offset, node.position.end.offset ?? body.length]);
669 + }
670 + if ("children" in node) for (const child of node.children) visit(child);
671 + };
672 + visit(fromMarkdown(body));
673 + let readable = "";
674 + let from = 0;
675 + for (const [start, end] of cuts) {
676 + readable += body.slice(from, start);
677 + // An HTML block can carry markup around its comment; only the comment itself is hidden.
678 + const html = body.slice(start, end).replace(/<!--[\s\S]*?(?:-->|$)/gu, "");
679 + // A line that was all comment is dropped rather than left as a blank one.
680 + const ownLine = /(?:^|\n)[ \t>]*$/u.test(readable) && /^[ \t]*(?:\n|$)/u.test(body.slice(end));
681 + if (ownLine && html.trim() === "") {
682 + readable = readable.replace(/[ \t>]*$/u, "");
683 + from = end + (/^[ \t]*\n/u.exec(body.slice(end))?.[0].length ?? 0);
684 + } else {
685 + readable += html;
686 + from = end;
687 + }
688 + }
689 + readable = (readable + body.slice(from)).trim();
690 + return readable === "" ? null : readable;
691 +}
692 +
693 /**
694 * Merged wins over closed: GitHub sets both timestamps on a merge, and reporting "closed" for a
695 * merged pull request would misstate what happened.
@@ -794,7 +833,7 @@ function reviewThreadContext(
833 text: bounded(
834 thread.comments
835 .flatMap((comment) => {
797 - const body = visibleBody(comment.body);
836 + const body = readableBody(comment.body);
837 return body === null ? [] : [`${comment.author?.login ?? "ghost"}: ${body}`];
838 })
839 .join("\n"),
@@ -1087,6 +1126,50 @@ export function buildPullRequestReferenceContext(
1126 return { ...comment, id: `pr-reference:${input.url}` };
1127 }
1128
1129 +/** The pull request chip a fix hand-off attaches, so the two dedupe in one draft. */
1130 +export function buildPullRequestContext(input: PullRequestContextMetadata): ReviewCommentContext {
1131 + return pullRequestContextComment(input, []);
1132 +}
1133 +
1134 +/** A remark the reader can bring into the chat: a conversation on a line, or one comment. */
1135 +export type PullRequestChatSubject = Extract<PullRequestFinding, { kind: "thread" | "comment" }>;
1136 +
1137 +/**
1138 + * A remark or conversation brought into the chat to talk about, not to fix. Its id carries the
1139 + * URL because host ids are only unique within a repository. Null when there are no words in it.
1140 + */
1141 +export function buildPullRequestCommentContext(
1142 + pullRequest: { readonly number: number; readonly url: string },
1143 + subject: PullRequestChatSubject,
1144 +): ReviewCommentContext | null {
1145 + const pullRequestNumber = pullRequest.number;
1146 + if (subject.kind === "thread") {
1147 + const context = reviewThreadContext(subject.thread, pullRequestNumber);
1148 + return context.text === ""
1149 + ? null
1150 + : { ...context, id: `pr-comment:${pullRequest.url}:thread:${subject.thread.id}` };
1151 + }
1152 + const comment = subject.comment;
1153 + const body = readableBody(comment.body);
1154 + if (body === null) return null;
1155 + const author = comment.author?.login ?? "ghost";
1156 + return {
1157 + id: `pr-comment:${pullRequest.url}:comment:${comment.id}`,
1158 + sectionId: `pull-request:${pullRequestNumber}`,
1159 + sectionTitle: `PR #${pullRequestNumber} conversation`,
1160 + // The chip wears `filePath rangeLabel`: the file a remark names, or who wrote one that names none.
1161 + filePath: comment.path ?? `@${author}`,
1162 + startIndex: 0,
1163 + endIndex: 0,
1164 + rangeLabel: "comment",
1165 + text: bounded(`${author}: ${body}`),
1166 + diff: "",
1167 + ...(comment.path === null
1168 + ? {}
1169 + : { fenceLanguage: inferReviewCommentFenceLanguage(comment.path) }),
1170 + };
1171 +}
1172 +
1173 const ANSWER_INSTRUCTIONS = [
1174 "Answer the question asked in this message. Do not change any code, and do not check anything out unless asked to.",
1175 ];