Skip to content
TypeScript

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

Antonyf08d8dd0a5a3
diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
index 39c57012999..72482811543 100644
--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
@@ -47,7 +47,11 @@ import { useLocalStorage } from "~/hooks/useLocalStorage";
import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";
import { useRenderedAppearance } from "~/hooks/useTheme";
import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse";
-import { pullRequestFindingKey, type PullRequestFinding } from "./pullRequestDetail.logic";
+import {
+ pullRequestFindingKey,
+ type PullRequestChatSubject,
+ type PullRequestFinding,
+} from "./pullRequestDetail.logic";
import {
canEditPullRequestComment,
canResolvePullRequestThread,
@@ -338,6 +342,7 @@ function PullRequestCodeTab({
pendingFinding,
fixFindingLabel = "Fix in a thread",
onFixFinding,
+ onAddToChat,
onAddToAgentSelection,
onRefresh,
refreshToken = 0,
@@ -353,6 +358,8 @@ function PullRequestCodeTab({
pendingFinding?: string | null;
fixFindingLabel?: string;
onFixFinding?: (finding: PullRequestFinding) => void;
+ /** Absent where there is no composer beside the panel to add a conversation to. */
+ onAddToChat?: (subject: PullRequestChatSubject) => void;
onAddToAgentSelection?: (input: PullRequestAgentSelectionInput) => void;
onRefresh: () => void;
refreshToken?: number;
@@ -967,6 +974,9 @@ function PullRequestCodeTab({
fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}
fixLabel={fixFindingLabel}
{...(onFixFinding ? { onFix: () => onFixFinding({ kind: "thread", thread }) } : {})}
+ {...(onAddToChat
+ ? { onAddToChat: (loaded) => onAddToChat({ kind: "thread", thread: loaded }) }
+ : {})}
onLoadMore={async (cursor): Promise<PullRequestThreadCommentsResult | null> => {
const result = await loadThreadComments({
environmentId,
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
index f272c2df81d..a517cf1ce7c 100644
--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
@@ -117,6 +117,8 @@ import {
buildExplainPullRequestHandoff,
buildFixFindingHandoff,
buildFixFindingsHandoff,
+ buildPullRequestCommentContext,
+ buildPullRequestContext,
buildResolveConflictsPrompt,
latestPullRequestReviewOutcomes,
loadingPullRequestCheckoutCommand,
@@ -137,6 +139,7 @@ import {
isPullRequestConflicting,
resolveBaseFreshness,
resolvePullRequestMergeMethod,
+ type PullRequestChatSubject,
type PullRequestFinding,
shouldRefreshPullRequestActivity,
} from "./pullRequestDetail.logic";
@@ -1013,6 +1016,43 @@ export function PullRequestDetailPanel({
);
};
+ /**
+ * Brings a remark into the composer beside this panel, with the pull request it belongs to,
+ * and nothing else: what to ask about it is the reader's to write. A remark on a line travels
+ * as its whole conversation, the way fixing one does.
+ */
+ const addCommentToChat = (subject: PullRequestChatSubject) => {
+ if (!detail || attachTarget === null) return;
+ const thread =
+ subject.kind === "comment"
+ ? detail.reviewThreads.find((candidate) =>
+ candidate.comments.some((comment) => comment.id === subject.comment.id),
+ )
+ : undefined;
+ const comment = buildPullRequestCommentContext(
+ detail,
+ thread === undefined ? subject : { kind: "thread", thread },
+ );
+ if (comment === null) return;
+ const store = useComposerDraftStore.getState();
+ const reference = buildPullRequestContext({
+ number: detail.number,
+ title: detail.title,
+ url: detail.url,
+ headBranch: detail.headBranch,
+ baseBranch: detail.baseBranch,
+ state: detail.state,
+ isDraft: detail.isDraft,
+ });
+ const hasReference = (store.getComposerDraft(attachTarget)?.reviewComments ?? []).some(
+ (existing) => existing.pullRequest?.url === detail.url,
+ );
+ // The active editor may be answering a provider question rather than editing this draft.
+ if (!hasReference) store.addReviewComment(attachTarget, reference, { insertAtCaret: false });
+ store.addReviewComment(attachTarget, comment, { insertAtCaret: false });
+ toastManager.add({ type: "success", title: "Added to the composer" });
+ };
+
const startCheckout = (mode: "worktree" | "local") => {
if (!handoffSummary) return;
void startHandoff(`checkout:${mode}`, null, mode);
@@ -1717,6 +1757,7 @@ export function PullRequestDetailPanel({
fixFindingLabel={handoffLabels.fixFinding}
fixCheckLabel={handoffLabels.fixCheck}
{...(canFixFindings ? { onFixFinding: startFixFinding } : {})}
+ {...(attachTarget === null ? {} : { onAddToChat: addCommentToChat })}
onRefresh={refreshDetail}
onRefreshChecks={refreshFromHost}
/>
@@ -1774,6 +1815,7 @@ export function PullRequestDetailPanel({
reference={reference}
order={timelineOrder}
onOpenCommit={openCommit}
+ {...(attachTarget === null ? {} : { onAddToChat: addCommentToChat })}
onRefresh={refreshDetail}
/>
)}
@@ -1797,6 +1839,7 @@ export function PullRequestDetailPanel({
pendingFinding={handoff}
fixFindingLabel={handoffLabels.fixFinding}
{...(canFixFindings ? { onFixFinding: startFixFinding } : {})}
+ {...(attachTarget === null ? {} : { onAddToChat: addCommentToChat })}
onRefresh={refreshDetail}
refreshToken={refreshToken}
backgroundRefreshToken={turnRefresh ?? 0}
diff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx
index a98a660cdbc..2fe3f96431b 100644
--- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx
@@ -7,7 +7,7 @@ import type {
PullRequestThreadCommentsResult,
PullRequestThreadComment,
} from "@t3tools/contracts";
-import { HammerIcon, MessageSquareIcon, Trash2Icon } from "lucide-react";
+import { HammerIcon, MessageSquareIcon, MessageSquarePlusIcon, Trash2Icon } from "lucide-react";
import { Circle, CircleCheck } from "lucide";
import { useRef, useState } from "react";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
@@ -23,6 +23,7 @@ import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
import {
editPullRequestThreadComment,
mergePullRequestThreadComments,
+ visibleBody,
} from "./pullRequestDetail.logic";
import { PullRequestActorLabel } from "./pullRequestPresentation";
import { PullRequestMarkdown } from "./PullRequestMarkdown";
@@ -121,6 +122,7 @@ export function ReviewThreadCard({
fixPending,
fixLabel = "Fix in a thread",
onFix,
+ onAddToChat,
onReply,
onLoadMore,
canEditComment,
@@ -140,6 +142,11 @@ export function ReviewThreadCard({
fixPending?: boolean;
fixLabel?: string;
onFix?: () => void;
+ /**
+ * Absent where there is no composer beside the panel to add the conversation to. Handed the
+ * thread with every comment the reader has loaded, not only the first page.
+ */
+ onAddToChat?: (thread: PullRequestReviewThread) => void;
onReply: (body: string) => Promise<boolean>;
onLoadMore: (cursor: string) => Promise<PullRequestThreadCommentsResult | null>;
canEditComment: (comment: PullRequestThreadComment) => boolean;
@@ -253,11 +260,22 @@ export function ReviewThreadCard({
{fixPending ? "Preparing..." : fixLabel}
</Button>
) : null}
- {canResolve ? (
+ {onAddToChat && comments.some((comment) => visibleBody(comment.body) !== null) ? (
<Button
size="xs"
variant="ghost"
className={onFix ? undefined : "ml-auto"}
+ onClick={() => onAddToChat({ ...thread, comments })}
+ >
+ <MessageSquarePlusIcon className="size-3" />
+ Add to chat
+ </Button>
+ ) : null}
+ {canResolve ? (
+ <Button
+ size="xs"
+ variant="ghost"
+ className={onFix || onAddToChat ? undefined : "ml-auto"}
disabled={pending}
onClick={onToggleResolved}
>
diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
index 617aa887080..03e014a47a0 100644
--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
@@ -18,6 +18,7 @@ import {
ChevronRightIcon,
HammerIcon,
ListFilterIcon,
+ MessageSquarePlusIcon,
TagIcon,
UsersIcon,
} from "lucide-react";
@@ -68,6 +69,7 @@ import {
pullRequestFindingKey,
pullRequestReviewOutcome,
visibleBody,
+ type PullRequestChatSubject,
type PullRequestConversationItem,
type PullRequestFinding,
} from "./pullRequestDetail.logic";
@@ -218,6 +220,34 @@ function CommentBody({
);
}
+/**
+ * What Add to chat hands over for a remark: a remark on a line goes as its whole conversation,
+ * the way fixing one does. Null when there are no words in it to talk about.
+ */
+function chatSubject(
+ comment: PullRequestComment,
+ thread: PullRequestReviewThread | undefined,
+): PullRequestChatSubject | null {
+ if (thread !== undefined) {
+ return thread.comments.some((entry) => visibleBody(entry.body) !== null)
+ ? { kind: "thread", thread }
+ : null;
+ }
+ return visibleBody(comment.body) === null ? null : { kind: "comment", comment };
+}
+
+function AddToChatButton({ onClick }: { onClick: () => void }) {
+ return (
+ <Button size="xs" variant="ghost" className="shrink-0" onClick={onClick}>
+ {/* Wrapped like Fix's label so both sit on the header's baseline. */}
+ <span className="inline-flex items-baseline gap-1">
+ <MessageSquarePlusIcon className="size-3 self-center" />
+ <span>Add to chat</span>
+ </span>
+ </Button>
+ );
+}
+
function CollapsedComment({
comment,
editing,
@@ -229,6 +259,7 @@ function CollapsedComment({
replyCount = 0,
replies = null,
moreReplies = null,
+ onAddToChat,
}: {
comment: PullRequestComment;
editing: CommentEditing;
@@ -240,6 +271,7 @@ function CollapsedComment({
replyCount?: number;
replies?: ReactNode;
moreReplies?: ReactNode;
+ onAddToChat?: (() => void) | undefined;
}) {
const [open, setOpen] = useState(false);
const statusTriggerRef = useRef<HTMLButtonElement>(null);
@@ -264,6 +296,7 @@ function CollapsedComment({
className={cn("size-3.5 transition-transform", open && "rotate-180")}
/>
</CollapsibleTrigger>
+ {onAddToChat ? <AddToChatButton onClick={onAddToChat} /> : null}
{reactionBar}
</div>
<CommentLocation comment={comment} thread={thread} />
@@ -401,6 +434,7 @@ export function PullRequestSummaryTab({
fixFindingLabel = "Fix in a thread",
fixCheckLabel = "Fix",
onFixFinding,
+ onAddToChat,
onRefresh,
onRefreshChecks = onRefresh,
}: {
@@ -416,6 +450,8 @@ export function PullRequestSummaryTab({
fixFindingLabel?: string;
fixCheckLabel?: string;
onFixFinding?: (finding: PullRequestFinding) => void;
+ /** Absent where there is no composer beside the panel to add a remark to. */
+ onAddToChat?: (subject: PullRequestChatSubject) => void;
onRefresh: () => void;
onRefreshChecks?: () => void;
}) {
@@ -605,6 +641,8 @@ export function PullRequestSummaryTab({
? null
: { kind: "comment", comment }
: { kind: "thread", thread };
+ // A reply goes with its conversation, from the card that heads it.
+ const chat = reply ? null : chatSubject(comment, thread);
return (
<article
key={`${detail.url}:${comment.id}`}
@@ -637,6 +675,9 @@ export function PullRequestSummaryTab({
</span>
</Button>
) : null}
+ {onAddToChat && chat !== null ? (
+ <AddToChatButton onClick={() => onAddToChat(chat)} />
+ ) : null}
{reactionBarFor(comment)}
</div>
{reply ? null : (
@@ -663,6 +704,7 @@ export function PullRequestSummaryTab({
const moreReplies =
item.kind === "thread" && item.hasMoreReplies ? <PullRequestMoreReplies {...item} /> : null;
if (isPullRequestCommentFinished(comment, thread)) {
+ const chat = chatSubject(comment, thread);
return (
<CollapsedComment
key={`${detail.url}:${item.kind}:${item.id}`}
@@ -675,6 +717,7 @@ export function PullRequestSummaryTab({
replyCount={item.kind === "thread" ? item.replies.length + item.moreReplies : 0}
replies={replies}
moreReplies={moreReplies}
+ onAddToChat={onAddToChat && chat !== null ? () => onAddToChat(chat) : undefined}
reactionBar={reactionBarFor(comment)}
/>
);
diff --git a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
index 88f14347ab1..60357c75712 100644
--- a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
@@ -18,6 +18,7 @@ import {
FileCode2Icon,
GitCommitHorizontalIcon,
MessageSquareIcon,
+ MessageSquarePlusIcon,
} from "lucide-react";
import { useState, type ReactNode } from "react";
@@ -38,6 +39,7 @@ import {
isPullRequestVerdictStale,
newestPullRequestCommitAt,
pullRequestReviewOutcome,
+ type PullRequestChatSubject,
type PullRequestReviewOutcome,
type PullRequestTimelineEvent,
type PullRequestTimelineThread,
@@ -65,6 +67,8 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react";
interface ReactionSurface {
readonly canReact: boolean;
+ /** Absent where there is no composer beside the panel to add a remark to. */
+ readonly onAddToChat?: ((comment: PullRequestComment) => void) | undefined;
readonly environmentId: EnvironmentId;
readonly threadRef: ScopedThreadRef | null;
readonly reference: PullRequestRef;
@@ -172,6 +176,34 @@ function ReviewStateBadge({ state }: { state: string }) {
);
}
+function AddToChatButton({
+ comment,
+ reactions,
+}: {
+ comment: PullRequestComment;
+ reactions: ReactionSurface;
+}) {
+ const onAddToChat = reactions.onAddToChat;
+ return onAddToChat === undefined ? null : (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ size="icon-xs"
+ variant="ghost-muted"
+ className="-mt-1 shrink-0"
+ aria-label="Add to chat"
+ onClick={() => onAddToChat(comment)}
+ />
+ }
+ >
+ <MessageSquarePlusIcon className="size-3" />
+ </TooltipTrigger>
+ <TooltipPopup>Add to chat</TooltipPopup>
+ </Tooltip>
+ );
+}
+
function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: (url: string) => void }) {
return url === null ? null : (
<Button
@@ -193,6 +225,7 @@ function ConversationCard({
onOpen,
reactions,
showPath = true,
+ reply = false,
}: {
event: PullRequestTimelineEvent;
editable: PullRequestComment | null;
@@ -200,6 +233,8 @@ function ConversationCard({
onOpen: (url: string) => void;
reactions: ReactionSurface;
showPath?: boolean;
+ /** A reply goes with its conversation, from the card that heads it. */
+ reply?: boolean;
}) {
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
@@ -248,6 +283,9 @@ function ConversationCard({
{editable !== null && !editing ? (
<PullRequestEditButton aria-label="Edit comment" onClick={() => setEditing(true)} />
) : null}
+ {event.body && event.comment && !reply ? (
+ <AddToChatButton comment={event.comment} reactions={reactions} />
+ ) : null}
{reactions.canReact || event.reactions.length > 0 ? (
<PullRequestReactionBar
className="ml-auto justify-end"
@@ -456,6 +494,7 @@ function ReviewThreadEvent({
onOpen={onOpen}
reactions={reactions}
showPath={false}
+ reply
/>
))}
</div>
@@ -606,6 +645,9 @@ function ReviewVerdictEvent({
</PullRequestMetaLine>
</div>
</div>
+ {event.body && event.comment ? (
+ <AddToChatButton comment={event.comment} reactions={reactions} />
+ ) : null}
{reactions.canReact || event.reactions.length > 0 ? (
<PullRequestReactionBar
className="ml-auto justify-end"
@@ -640,6 +682,7 @@ export function PullRequestTimelineTab({
reference,
order,
onOpenCommit,
+ onAddToChat,
onRefresh,
}: {
scrollerRef: (node: HTMLElement | null) => void;
@@ -649,6 +692,7 @@ export function PullRequestTimelineTab({
reference: PullRequestRef;
order: "newest" | "oldest";
onOpenCommit: (oid: string) => void;
+ onAddToChat?: (subject: PullRequestChatSubject) => void;
onRefresh: () => void;
}) {
const events = buildPullRequestTimeline(detail);
@@ -656,6 +700,7 @@ export function PullRequestTimelineTab({
const newestCommitAt = newestPullRequestCommitAt(detail.commits);
const reactions: ReactionSurface = {
canReact: detail.capabilities.reactions === true,
+ onAddToChat: onAddToChat && ((comment) => onAddToChat({ kind: "comment", comment })),
environmentId,
threadRef,
reference,
diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
index f760aa560cf..d23c4fdfae4 100644
--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
@@ -15,7 +15,11 @@ import {
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { formatInlineContextReference } from "~/lib/composerContextReferences";
-import { buildMessageContext, reviewCommentContextReference } from "~/lib/composerContextRecords";
+import {
+ buildMessageContext,
+ reviewCommentContextLabel,
+ reviewCommentContextReference,
+} from "~/lib/composerContextRecords";
import {
buildAddSelectionToAgentHandoff,
@@ -23,6 +27,7 @@ import {
buildExplainPullRequestHandoff,
buildResolveConflictsPrompt,
resolveThreadPanelPullRequestAction,
+ buildPullRequestCommentContext,
buildPullRequestReferenceContext,
buildFixFindingHandoff,
canDeletePullRequestBranch,
@@ -1005,6 +1010,173 @@ describe("asking about a change rather than working on it", () => {
});
});
+describe("adding a remark to the chat", () => {
+ const pullRequest = { number: 42, url: "https://github.com/pingdotgg/t3code/pull/42" };
+ const remark = (id: string, body: string): PullRequestComment => ({
+ id,
+ kind: "issue-comment",
+ author: { login: "octocat", name: null, avatarUrl: null },
+ body,
+ createdAt: "2026-07-03T00:00:00Z",
+ url: null,
+ path: null,
+ reviewState: null,
+ });
+
+ it("reads as the remark's author rather than as the pull request itself", () => {
+ const context = buildPullRequestCommentContext(pullRequest, {
+ kind: "comment",
+ comment: remark("c1", "Why not reuse the existing parser?"),
+ });
+
+ expect(context && reviewCommentContextLabel(context)).toBe("#42 @octocat comment");
+ expect(context?.text).toBe("octocat: Why not reuse the existing parser?");
+ });
+
+ it("keeps every added remark when a later hand-off lands", () => {
+ const added = ["c1", "c2"].flatMap(
+ (id) =>
+ buildPullRequestCommentContext(pullRequest, {
+ kind: "comment",
+ comment: remark(id, "why?"),
+ }) ?? [],
+ );
+ const handedOff = buildAskAboutPullRequestHandoff({
+ number: 42,
+ title: "Add the pull requests page",
+ url: "https://github.com/pingdotgg/t3code/pull/42",
+ headBranch: "feature",
+ baseBranch: "main",
+ state: "open",
+ isDraft: false,
+ });
+
+ expect(
+ appendHandoff({ prompt: "", reviewComments: added }, handedOff).reviewComments.map(
+ (comment) => comment.id,
+ ),
+ ).toEqual([
+ "pr-comment:https://github.com/pingdotgg/t3code/pull/42:comment:c1",
+ "pr-comment:https://github.com/pingdotgg/t3code/pull/42:comment:c2",
+ "pull-request-context:https://github.com/pingdotgg/t3code/pull/42",
+ ]);
+ });
+
+ it("drops a bot's bookkeeping so it cannot crowd the remark out of the bound", () => {
+ const context = buildPullRequestCommentContext(pullRequest, {
+ kind: "comment",
+ comment: remark(
+ "c1",
+ `<!-- ${"state".repeat(400)} -->\nThis leaks the token.\n\n\`\`\`html\n<!-- kept -->\n\`\`\``,
+ ),
+ });
+
+ expect(context?.text).toBe("octocat: This leaks the token.\n\n```html\n<!-- kept -->\n```");
+ });
+
+ it("keeps comments inside a quoted fence as code", () => {
+ const context = buildPullRequestCommentContext(pullRequest, {
+ kind: "comment",
+ comment: remark("c1", "> ```html\n> <!-- open\n> ```\n> Quoted. <!-- bot -->\nMine."),
+ });
+
+ expect(context?.text).toBe("octocat: > ```html\n> <!-- open\n> ```\n> Quoted. \nMine.");
+ });
+
+ it("holds a fence open over a deeper quoted fence and closes it with its blockquote", () => {
+ const nested = buildPullRequestCommentContext(pullRequest, {
+ kind: "comment",
+ comment: remark("c1", "```md\n> ```\n<!-- kept -->\n```\nMine. <!-- bot -->"),
+ });
+ const unquoted = buildPullRequestCommentContext(pullRequest, {
+ kind: "comment",
+ comment: remark("c2", "> ```\n> code\nMine. <!-- bot -->"),
+ });
+
+ expect(nested?.text).toBe("octocat: ```md\n> ```\n<!-- kept -->\n```\nMine.");
+ expect(unquoted?.text).toBe("octocat: > ```\n> code\nMine.");
+ });
+
+ it("keeps a fence written inside a hidden comment hidden", () => {
+ const context = buildPullRequestCommentContext(pullRequest, {
+ kind: "comment",
+ comment: remark("c1", '<!-- state\n```json\n{"secret": 1}\n```\n-->\nLooks good.'),
+ });
+
+ expect(context?.text).toBe("octocat: Looks good.");
+ });
+
+ it("closes a fence written with CRLF line endings", () => {
+ const context = buildPullRequestCommentContext(pullRequest, {
+ kind: "comment",
+ comment: remark("c1", "```ts\r\nconst x = 1;\r\n```\r\n<!-- bot -->\r\nRename x."),
+ });
+
+ expect(context?.text).toBe("octocat: ```ts\nconst x = 1;\n```\nRename x.");
+ });
+
+ it("reads inline code at the start of a line as prose, not as a fence", () => {
+ const context = buildPullRequestCommentContext(pullRequest, {
+ kind: "comment",
+ comment: remark("c1", "```x``` is unused <!-- bot -->\nRemove it."),
+ });
+
+ expect(context?.text).toBe("octocat: ```x``` is unused \nRemove it.");
+ });
+
+ it("keeps remarks from two repositories apart when their host ids match", () => {
+ const other = { number: 42, url: "https://github.com/octocat/fork/pull/42" };
+ const ids = [pullRequest, other].map(
+ (target) =>
+ buildPullRequestCommentContext(target, { kind: "comment", comment: remark("c1", "why?") })
+ ?.id,
+ );
+
+ expect(new Set(ids).size).toBe(2);
+ });
+
+ it("brings nothing for a remark an unfinished comment hides", () => {
+ expect(
+ buildPullRequestCommentContext(pullRequest, {
+ kind: "comment",
+ comment: remark("c1", "<!-- bot state left open"),
+ }),
+ ).toBeNull();
+ });
+
+ it("brings nothing for a remark with no words in it", () => {
+ expect(
+ buildPullRequestCommentContext(pullRequest, {
+ kind: "comment",
+ comment: remark("c1", "<!-- bot bookkeeping -->"),
+ }),
+ ).toBeNull();
+ });
+
+ it("brings nothing for a conversation with no words in it", () => {
+ const {
+ kind: _kind,
+ path: _path,
+ reviewState: _reviewState,
+ ...bookkeeping
+ } = remark("tc1", "<!-- bot bookkeeping -->");
+ expect(
+ buildPullRequestCommentContext(pullRequest, {
+ kind: "thread",
+ thread: {
+ id: "t1",
+ path: "src/app.ts",
+ line: 3,
+ side: "right",
+ isResolved: false,
+ isOutdated: false,
+ comments: [bookkeeping],
+ },
+ }),
+ ).toBeNull();
+ });
+});
+
describe("a second handoff into the same composer", () => {
const chip = (id: string): ReviewCommentContext => ({
id,
diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
index e6dc041ac3b..bcc46b63a04 100644
--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
@@ -1,4 +1,6 @@
import { stripInlineContextReferences } from "~/lib/composerContextReferences";
+import type { Nodes as MdastNodes } from "mdast";
+import { fromMarkdown } from "mdast-util-from-markdown";
import {
capitalizeTerm,
sourceControlClients,
@@ -238,9 +240,10 @@ export function threadPullRequestPanelTarget(thread: {
}
export function pullRequestHandoffLabels(inThisThread: boolean) {
+ // Beside a composer a remark's Fix shares its header with Add to chat.
return inThisThread
? {
- fixFinding: "Fix in this thread",
+ fixFinding: "Fix",
fixCheck: "Fix in this thread",
fixFindings: "Fix findings in this thread",
}
@@ -651,6 +654,42 @@ export function pagePullRequestConversationItems(
return { shown, hidden: items.length - shown.length };
}
+/**
+ * A body as it reads, for text sent to the agent under a length bound. A bot's HTML-comment
+ * bookkeeping would otherwise use up the bound before the remark got any of it. Comments in code
+ * are source the remark is showing, so they stay. Null for a body with no words.
+ */
+function readableBody(raw: string): string | null {
+ if (visibleBody(raw) === null) return null;
+ const body = raw.replace(/\r\n?/gu, "\n");
+ const cuts: Array<[number, number]> = [];
+ const visit = (node: MdastNodes) => {
+ if (node.type === "html" && node.position?.start.offset !== undefined) {
+ cuts.push([node.position.start.offset, node.position.end.offset ?? body.length]);
+ }
+ if ("children" in node) for (const child of node.children) visit(child);
+ };
+ visit(fromMarkdown(body));
+ let readable = "";
+ let from = 0;
+ for (const [start, end] of cuts) {
+ readable += body.slice(from, start);
+ // An HTML block can carry markup around its comment; only the comment itself is hidden.
+ const html = body.slice(start, end).replace(/<!--[\s\S]*?(?:-->|$)/gu, "");
+ // A line that was all comment is dropped rather than left as a blank one.
+ const ownLine = /(?:^|\n)[ \t>]*$/u.test(readable) && /^[ \t]*(?:\n|$)/u.test(body.slice(end));
+ if (ownLine && html.trim() === "") {
+ readable = readable.replace(/[ \t>]*$/u, "");
+ from = end + (/^[ \t]*\n/u.exec(body.slice(end))?.[0].length ?? 0);
+ } else {
+ readable += html;
+ from = end;
+ }
+ }
+ readable = (readable + body.slice(from)).trim();
+ return readable === "" ? null : readable;
+}
+
/**
* Merged wins over closed: GitHub sets both timestamps on a merge, and reporting "closed" for a
* merged pull request would misstate what happened.
@@ -794,7 +833,7 @@ function reviewThreadContext(
text: bounded(
thread.comments
.flatMap((comment) => {
- const body = visibleBody(comment.body);
+ const body = readableBody(comment.body);
return body === null ? [] : [`${comment.author?.login ?? "ghost"}: ${body}`];
})
.join("\n"),
@@ -1087,6 +1126,50 @@ export function buildPullRequestReferenceContext(
return { ...comment, id: `pr-reference:${input.url}` };
}
+/** The pull request chip a fix hand-off attaches, so the two dedupe in one draft. */
+export function buildPullRequestContext(input: PullRequestContextMetadata): ReviewCommentContext {
+ return pullRequestContextComment(input, []);
+}
+
+/** A remark the reader can bring into the chat: a conversation on a line, or one comment. */
+export type PullRequestChatSubject = Extract<PullRequestFinding, { kind: "thread" | "comment" }>;
+
+/**
+ * A remark or conversation brought into the chat to talk about, not to fix. Its id carries the
+ * URL because host ids are only unique within a repository. Null when there are no words in it.
+ */
+export function buildPullRequestCommentContext(
+ pullRequest: { readonly number: number; readonly url: string },
+ subject: PullRequestChatSubject,
+): ReviewCommentContext | null {
+ const pullRequestNumber = pullRequest.number;
+ if (subject.kind === "thread") {
+ const context = reviewThreadContext(subject.thread, pullRequestNumber);
+ return context.text === ""
+ ? null
+ : { ...context, id: `pr-comment:${pullRequest.url}:thread:${subject.thread.id}` };
+ }
+ const comment = subject.comment;
+ const body = readableBody(comment.body);
+ if (body === null) return null;
+ const author = comment.author?.login ?? "ghost";
+ return {
+ id: `pr-comment:${pullRequest.url}:comment:${comment.id}`,
+ sectionId: `pull-request:${pullRequestNumber}`,
+ sectionTitle: `PR #${pullRequestNumber} conversation`,
+ // The chip wears `filePath rangeLabel`: the file a remark names, or who wrote one that names none.
+ filePath: comment.path ?? `@${author}`,
+ startIndex: 0,
+ endIndex: 0,
+ rangeLabel: "comment",
+ text: bounded(`${author}: ${body}`),
+ diff: "",
+ ...(comment.path === null
+ ? {}
+ : { fenceLanguage: inferReviewCommentFenceLanguage(comment.path) }),
+ };
+}
+
const ANSWER_INSTRUCTIONS = [
"Answer the question asked in this message. Do not change any code, and do not check anything out unless asked to.",
];