Open History to see the last commit
1import { mFallback, type Msg } from "gt-react-native";
2import { describe, expect, it } from "vite-plus/test";
3import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
4import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
5
6import { pullRequestComposerContext } from "../../lib/composerContext";
7
8import {
9 clearReviewCommentTarget,
10 completeReviewCommentRange,
11 formatReviewCommentContext,
12 formatReviewSelectedRangeLabel,
13 getReviewCommentSelection,
14 reviewCommentSelectionScope,
15 selectReviewCommentSelection,
16 setReviewCommentTarget,
17 startReviewCommentRange,
18 parseReviewCommentMessageSegments,
19 reviewCommentChipLabel,
20 reviewCommentComposerDraft,
21 parseReviewInlineComments,
22 type ReviewCommentTarget,
23} from "./reviewCommentSelection";
24import { buildReviewParsedDiff, type ReviewRenderableLineRow } from "./reviewModel";
25import { setReviewSelectedSectionId } from "./reviewState";
26
27function makeTarget(): ReviewCommentTarget {
28 return {
29 sectionId: "section-1",
30 sectionTitle: "Working tree",
31 filePath: "apps/demo/src/main.ts",
32 startIndex: 0,
33 endIndex: 1,
34 lines: [
35 {
36 kind: "line",
37 id: "line-1",
38 change: "delete",
39 oldLineNumber: 7,
40 newLineNumber: null,
41 oldPosition: 7,
42 newPosition: 7,
43 content: "const retryLimit = 2;",
44 additionTokenIndex: null,
45 deletionTokenIndex: 0,
46 comparison: null,
47 },
48 {
49 kind: "line",
50 id: "line-2",
51 change: "add",
52 oldLineNumber: null,
53 newLineNumber: 7,
54 oldPosition: 8,
55 newPosition: 7,
56 content: "const retryLimit = 4;",
57 additionTokenIndex: 0,
58 deletionTokenIndex: null,
59 comparison: null,
60 },
61 ],
62 };
63}
64
65describe("review comment serialization", () => {
66 it("excludes a linked pull request chip from draft review comments", () => {
67 const record = pullRequestComposerContext(
68 {
69 number: 42,
70 title: "Fix checkout",
71 url: "https://github.com/example/repo/pull/42",
72 headBranch: "fix-checkout",
73 baseBranch: "main",
74 state: "open",
75 isDraft: false,
76 },
77 "pr-42",
78 );
79
80 expect(
81 parseReviewInlineComments(formatComposerContextReference(record), {
82 version: 1,
83 records: [record],
84 }),
85 ).toEqual([]);
86 });
87
88 it("reads an added review comment after the composer upgrades it to a context chip", () => {
89 const upgraded = reviewCommentComposerDraft(makeTarget(), "Please keep this configurable.");
90 const comments = parseReviewInlineComments(upgraded.text, {
91 version: 1,
92 records: upgraded.records,
93 });
94
95 expect(comments).toEqual([
96 {
97 id: upgraded.records[0]!.contextId,
98 sectionId: "section-1",
99 sectionTitle: "Working tree",
100 filePath: "apps/demo/src/main.ts",
101 startIndex: 0,
102 endIndex: 1,
103 rangeLabel: "7",
104 text: "Please keep this configurable.",
105 diff: "@@ -7,1 +7,1 @@\n-const retryLimit = 2;\n+const retryLimit = 4;",
106 fenceLanguage: "diff",
107 },
108 ]);
109 });
110
111 it.each(["explain </review_comment> please", "Consider ``` here"])(
112 "keeps review markup in the note %j out of the chip's diff",
113 (note) => {
114 const upgraded = reviewCommentComposerDraft(makeTarget(), note);
115
116 expect(upgraded.records).toEqual([
117 expect.objectContaining({
118 text: note,
119 diff: "@@ -7,1 +7,1 @@\n-const retryLimit = 2;\n+const retryLimit = 4;",
120 }),
121 ]);
122 expect(upgraded.text).toBe(formatComposerContextReference(upgraded.records[0]!));
123 },
124 );
125
126 it("keeps legacy comments and counts a typed comment only while its chip is present", () => {
127 const upgraded = upgradeLegacyContextMessage(
128 formatReviewCommentContext(makeTarget(), "Typed comment"),
129 );
130 const context = { version: 1, records: upgraded.records } as const;
131 const legacy = formatReviewCommentContext(makeTarget(), "Legacy comment");
132 const comments = parseReviewInlineComments(
133 `${legacy}\n${upgraded.text}\n${upgraded.text}`,
134 context,
135 );
136
137 expect(comments.map((comment) => comment.text)).toEqual(["Legacy comment", "Typed comment"]);
138 expect(parseReviewInlineComments(legacy, context).map((comment) => comment.text)).toEqual([
139 "Legacy comment",
140 ]);
141 expect(parseReviewInlineComments("", context)).toEqual([]);
142 expect(
143 parseReviewInlineComments(upgraded.text.replace("/review-comment/", "/mention/"), context),
144 ).toEqual([]);
145 });
146
147 it("keeps closing-tag text inside a chip label within a real review body", () => {
148 const body = "Before [</review_comment>](t3-context://v1/mention/context-1) after";
149 const serialized = `<review_comment sectionId="s" filePath="app.ts" startIndex="0" endIndex="0">${body}</review_comment>`;
150 const segments = parseReviewCommentMessageSegments(`${serialized} tail`);
151 expect(segments).toEqual([
152 { kind: "review-comment", comment: expect.objectContaining({ text: body }) },
153 { kind: "text", id: `review-comment-text:${serialized.length}`, text: " tail" },
154 ]);
155 });
156
157 it("treats legacy markup inside a context label as opaque text", () => {
158 const text =
159 '[<review_comment sectionId="s" filePath="app.ts" startIndex="0" endIndex="0">Review this</review_comment>](t3-context://v1/mention/context-1)';
160 expect(parseReviewCommentMessageSegments(text)).toEqual([
161 { kind: "text", id: "review-comment-text:0", text },
162 ]);
163 });
164
165 it("splits chat text into review comment segments", () => {
166 const serialized = `Before\n${formatReviewCommentContext(makeTarget(), "Please keep this configurable.")}\nAfter`;
167 const segments = parseReviewCommentMessageSegments(serialized);
168
169 expect(segments).toHaveLength(3);
170 expect(segments[0]).toEqual(expect.objectContaining({ kind: "text", text: "Before\n" }));
171 expect(segments[1]).toEqual(
172 expect.objectContaining({
173 kind: "review-comment",
174 comment: expect.objectContaining({
175 filePath: "apps/demo/src/main.ts",
176 text: "Please keep this configurable.",
177 diff: expect.stringContaining("+const retryLimit = 4;"),
178 }),
179 }),
180 );
181 expect(segments[2]).toEqual(expect.objectContaining({ kind: "text", text: "\nAfter" }));
182 });
183
184 it("parses source-language review comments created by the web file viewer", () => {
185 const [segment] = parseReviewCommentMessageSegments(
186 [
187 '<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
188 "Clarify this.",
189 "```md",
190 "# Plan",
191 "- Step one",
192 "```",
193 "</review_comment>",
194 ].join("\n"),
195 );
196
197 expect(segment).toEqual(
198 expect.objectContaining({
199 kind: "review-comment",
200 comment: expect.objectContaining({
201 filePath: "docs/plan.md",
202 fenceLanguage: "md",
203 diff: "# Plan\n- Step one",
204 }),
205 }),
206 );
207 });
208
209 it("shows a review comment's line range in the app language", () => {
210 // Like the real catalogue lookup: only a message object keeps the context its key needs.
211 const range = JSON.stringify([["start"], " to ", ["end"]]);
212 const french = ((message: string | Msg, values?: Record<string, unknown>) =>
213 typeof message !== "string" &&
214 message.context === "a range of lines in a file or diff" &&
215 JSON.stringify(message.tree) === range
216 ? `${String(message.values.start)} à ${String(message.values.end)}`
217 : mFallback(message, values)) as NonNullable<
218 Parameters<typeof parseReviewCommentMessageSegments>[1]
219 >;
220 const [segment] = parseReviewCommentMessageSegments(
221 [
222 '<review_comment sectionId="section-1" sectionTitle="Working tree" filePath="src/app.ts" startIndex="0" endIndex="1" rangeLabel="+12 to +13">',
223 "Rename this.",
224 "```diff",
225 "+one",
226 "+two",
227 "```",
228 "</review_comment>",
229 ].join("\n"),
230 french,
231 );
232
233 expect(segment).toEqual(
234 expect.objectContaining({
235 kind: "review-comment",
236 comment: expect.objectContaining({ rangeLabel: "+12 à +13" }),
237 }),
238 );
239 expect(reviewCommentChipLabel("app.ts +12 to +13", "+12 to +13", french)).toBe(
240 "app.ts +12 à +13",
241 );
242 });
243
244 it("keeps fenced examples in comment prose separate from the context fence", () => {
245 const [segment] = parseReviewCommentMessageSegments(
246 [
247 '<review_comment sectionId="section-1" sectionTitle="Working tree" filePath="src/app.ts" startIndex="0" endIndex="0" rangeLabel="+1">',
248 "Try this:",
249 "```ts",
250 "const value = 1;",
251 "```",
252 "Then retry.",
253 "```diff",
254 "@@ -0,0 +1,1 @@",
255 "+one",
256 "```",
257 "</review_comment>",
258 ].join("\n"),
259 );
260
261 expect(segment).toEqual(
262 expect.objectContaining({
263 kind: "review-comment",
264 comment: expect.objectContaining({
265 text: ["Try this:", "```ts", "const value = 1;", "```", "Then retry."].join("\n"),
266 diff: "@@ -0,0 +1,1 @@\n+one",
267 }),
268 }),
269 );
270 });
271
272 it("round-trips greater-than signs in review attributes", () => {
273 const serialized = formatReviewCommentContext(
274 { ...makeTarget(), sectionTitle: "Changes > 5" },
275 "Check this.",
276 );
277 const [comment] = parseReviewInlineComments(serialized);
278
279 expect(serialized).toContain('sectionTitle="Changes > 5"');
280 expect(comment?.sectionTitle).toBe("Changes > 5");
281 });
282});
283
284describe("review comment excerpt", () => {
285 it("starts a new hunk header where a selection skips unloaded lines", () => {
286 const parsed = buildReviewParsedDiff(
287 [
288 "diff --git a/notes.txt b/notes.txt",
289 "--- a/notes.txt",
290 "+++ b/notes.txt",
291 "@@ -1,3 +1,3 @@",
292 " Line 1",
293 "-Line 2",
294 "+First change",
295 " Line 3",
296 "@@ -21,3 +21,3 @@",
297 " Line 21",
298 "-Line 22",
299 "+Second change",
300 " Line 23",
301 ].join("\n"),
302 "review-comment-across-hunks",
303 );
304 if (parsed.kind !== "files") throw new Error("Expected a parsed diff");
305 const lines = parsed.files[0]!.rows.filter(
306 (row): row is ReviewRenderableLineRow => row.kind === "line",
307 );
308 const formatted = formatReviewCommentContext(
309 { ...makeTarget(), lines, startIndex: 2, endIndex: 6 },
310 "Review both.",
311 );
312
313 expect(parseReviewInlineComments(formatted)[0]?.diff).toBe(
314 [
315 "@@ -3,1 +2,2 @@",
316 "+First change",
317 " Line 3",
318 "@@ -21,2 +21,2 @@",
319 " Line 21",
320 "-Line 22",
321 "+Second change",
322 ].join("\n"),
323 );
324 });
325});
326
327describe("review selected range label", () => {
328 it("falls back to line count when unified endpoints decrease across old and new numbers", () => {
329 expect(
330 formatReviewSelectedRangeLabel({
331 ...makeTarget(),
332 lines: [
333 {
334 kind: "line",
335 id: "line-1",
336 change: "context",
337 oldLineNumber: 10,
338 newLineNumber: 13,
339 oldPosition: 10,
340 newPosition: 13,
341 content: "line 10 of the original file",
342 additionTokenIndex: null,
343 deletionTokenIndex: null,
344 comparison: null,
345 },
346 {
347 kind: "line",
348 id: "line-2",
349 change: "delete",
350 oldLineNumber: 11,
351 newLineNumber: null,
352 oldPosition: 11,
353 newPosition: 14,
354 content: "line 11 of the original file",
355 additionTokenIndex: null,
356 deletionTokenIndex: 0,
357 comparison: null,
358 },
359 ],
360 }),
361 ).toBe("2 lines");
362 });
363});
364
365describe("review comment selection store", () => {
366 const changes = { id: "git:branch-range", content: "hash-1" };
367 const scope = reviewCommentSelectionScope(1, "env:thread", changes)!;
368 const otherScope = reviewCommentSelectionScope(1, "env:thread", {
369 id: "turn:2",
370 content: "diff",
371 })!;
372 const target = makeTarget();
373 const pending = {
374 sectionId: target.sectionId,
375 sectionTitle: target.sectionTitle,
376 filePath: target.filePath,
377 lines: target.lines,
378 lineIndex: 0,
379 rowId: "row-1",
380 };
381
382 it("keeps a long-pressed range start when replacing an earlier target", () => {
383 setReviewCommentTarget(scope, target);
384 startReviewCommentRange(scope, pending);
385
386 expect(getReviewCommentSelection()).toEqual({ scope, target: null, pending });
387 });
388
389 it("keeps the range start after a same-line range end and drops it on a plain tap", () => {
390 startReviewCommentRange(scope, pending);
391 const sameLine = { ...target, startIndex: 0, endIndex: 0 };
392 completeReviewCommentRange(scope, sameLine);
393 expect(getReviewCommentSelection().pending).toEqual(pending);
394
395 setReviewCommentTarget(scope, sameLine);
396 expect(getReviewCommentSelection().pending).toBeNull();
397 });
398
399 it("clears the target and the range start together", () => {
400 startReviewCommentRange(scope, pending);
401 clearReviewCommentTarget();
402
403 expect(getReviewCommentSelection()).toEqual({ scope: null, target: null, pending: null });
404 });
405
406 it("reads as empty from another thread or section", () => {
407 setReviewCommentTarget(scope, target);
408
409 expect(selectReviewCommentSelection(getReviewCommentSelection(), scope).target).toBe(target);
410 expect(selectReviewCommentSelection(getReviewCommentSelection(), otherScope).target).toBeNull();
411 expect(selectReviewCommentSelection(getReviewCommentSelection(), null).target).toBeNull();
412 });
413
414 it("reads as empty in a reopened review sheet", () => {
415 setReviewCommentTarget(scope, target);
416 const reopenedScope = reviewCommentSelectionScope(2, "env:thread", changes);
417
418 expect(
419 selectReviewCommentSelection(getReviewCommentSelection(), reopenedScope).target,
420 ).toBeNull();
421 });
422
423 it("reads as empty when the section disappears and comes back over a different diff", () => {
424 setReviewCommentTarget(scope, target);
425 // The working tree went clean, so the default showed; the section later returns.
426 const returned = reviewCommentSelectionScope(1, "env:thread", {
427 ...changes,
428 content: "hash-2",
429 });
430 const unchanged = reviewCommentSelectionScope(1, "env:thread", { ...changes });
431
432 expect(selectReviewCommentSelection(getReviewCommentSelection(), returned).target).toBeNull();
433 expect(selectReviewCommentSelection(getReviewCommentSelection(), unchanged).target).toBe(
434 target,
435 );
436 });
437
438 it("drops the selection when the section changes, so switching back starts empty", () => {
439 setReviewCommentTarget(scope, target);
440 setReviewSelectedSectionId("env:thread", "turn:2");
441 setReviewSelectedSectionId("env:thread", "git:branch-range");
442
443 expect(selectReviewCommentSelection(getReviewCommentSelection(), scope).target).toBeNull();
444 });
445});