Skip to content

Commit dc20ec0

Browse files
committed
fix(web): show Bitbucket mention names without changing editable source
1 parent 54084ae commit dc20ec0

18 files changed

Lines changed: 450 additions & 17 deletions

‎apps/server/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,13 @@
3333
"effect": "catalog:",
3434
"jose": "catalog:",
3535
"node-pty": "^1.2.0-beta.15",
36+
"parse5": "^8.0.1",
3637
"proper-lockfile": "4.1.2",
38+
"remark-gfm": "^4.0.1",
39+
"remark-parse": "^11.0.0",
3740
"stream-chain": "^4.2.5",
3841
"stream-json": "3.6.0",
42+
"unified": "^11.0.5",
3943
"yaml": "catalog:",
4044
"yauzl": "^3.4.0"
4145
},

‎apps/server/src/pullRequest/BitbucketPullRequestProvider.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,7 @@ export const make = Effect.gen(function* () {
208208
deletions: diffStat.deletions,
209209
changedFiles: diffStat.changedFiles,
210210
body: pullRequest.body,
211+
displayBody: pullRequest.displayBody,
211212
mergedAt: null,
212213
closedAt: null,
213214
reviewers: pullRequest.reviewers,

‎apps/server/src/pullRequest/PullRequestProvider.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ export interface ProviderChangeRequestStat {
213213

214214
export interface ProviderChangeRequestDetail extends ProviderChangeRequest {
215215
readonly body: string;
216+
readonly displayBody?: string | undefined;
216217
readonly changedFiles: number;
217218
readonly mergedAt: string | null;
218219
readonly closedAt: string | null;

‎apps/server/src/pullRequest/PullRequestService.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1662,6 +1662,7 @@ export const make = Effect.gen(function* () {
16621662
number: changeRequest.number,
16631663
title: changeRequest.title,
16641664
body: changeRequest.body,
1665+
displayBody: changeRequest.displayBody,
16651666
url: changeRequest.url,
16661667
author: changeRequest.author,
16671668
state: changeRequest.state,
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
import remarkParse from "remark-parse";
3+
import { unified } from "unified";
4+
5+
import { bitbucketMentionDisplayBody } from "./bitbucketMentions.ts";
6+
7+
const id = "712020:11111111-2222-4333-8444-555555555555";
8+
const token = `@{${id}}`;
9+
const mention = (label = "@Alex Smith", accountId = id) =>
10+
`<span class="ap-mention" data-atlassian-id="${accountId}">${label}</span>`;
11+
12+
describe("Bitbucket mention display", () => {
13+
it("replaces repeated prose mentions without reformatting Markdown", () => {
14+
const body = `## Review\n\n**Thanks ${token}**\n\n> ${token}, looks good.`;
15+
expect(bitbucketMentionDisplayBody(body, mention())).toBe(
16+
"## Review\n\n**Thanks @Alex Smith**\n\n> @Alex Smith, looks good.",
17+
);
18+
});
19+
20+
it("keeps code, escaped tokens and authored links unchanged", () => {
21+
const literals = [
22+
`\`${token}\``,
23+
`\`\`\`text\n${token}\n\`\`\``,
24+
` ${token}`,
25+
`\\${token}`,
26+
`[${token}](https://example.com/${token})`,
27+
`https://example.com/${token}`,
28+
`<span>${token}</span>`,
29+
];
30+
for (const literal of literals) {
31+
const body = `${token}\n\n${literal}`;
32+
expect(bitbucketMentionDisplayBody(body, mention())).toBe(`@Alex Smith\n\n${literal}`);
33+
}
34+
});
35+
36+
it("decodes entities and escapes mention labels as literal Markdown", () => {
37+
expect(bitbucketMentionDisplayBody(token, mention("@A_[B]*`\\ &amp; &lt;name&gt;"))).toBe(
38+
"@A\\_\\[B\\]\\*\\`\\\\ \\& \\<name\\>",
39+
);
40+
expect(bitbucketMentionDisplayBody(token, mention("@<strong>Alex</strong> Smith"))).toBe(
41+
"@Alex Smith",
42+
);
43+
});
44+
45+
it.each([
46+
[`${token} <br> thanks`, "@Alex Smith <br> thanks"],
47+
[`Thanks <strong>everyone</strong> ${token}`, "Thanks <strong>everyone</strong> @Alex Smith"],
48+
[`${token} <!-- note --> thanks`, "@Alex Smith <!-- note --> thanks"],
49+
[`${token} <span>${token}</span> ${token}`, `@Alex Smith <span>${token}</span> @Alex Smith`],
50+
[
51+
`${token} <span><em>${token}</em></span> ${token}`,
52+
`@Alex Smith <span><em>${token}</em></span> @Alex Smith`,
53+
],
54+
[
55+
`${token} <span title="${token}">literal</span>`,
56+
`@Alex Smith <span title="${token}">literal</span>`,
57+
],
58+
[`\`<span>\` ${token} <br> thanks`, "`<span>` @Alex Smith <br> thanks"],
59+
[`${token} <span>${token}`, `@Alex Smith <span>${token}`],
60+
])("resolves prose beside HTML while preserving contained literals: %s", (body, expected) => {
61+
expect(bitbucketMentionDisplayBody(body, mention())).toBe(expected);
62+
});
63+
64+
it("preserves literal entity text in a resolved name", () => {
65+
const display = bitbucketMentionDisplayBody(token, mention("@A &amp;copy;"));
66+
expect(unified().use(remarkParse).parse(display!).children).toMatchObject([
67+
{ type: "paragraph", children: [{ type: "text", value: "@A &copy;" }] },
68+
]);
69+
});
70+
71+
it("supports UUID mention identifiers", () => {
72+
const uuid = "11111111-2222-4333-8444-555555555555";
73+
expect(bitbucketMentionDisplayBody(`@{${uuid}}`, mention("@Alex Smith", uuid))).toBe(
74+
"@Alex Smith",
75+
);
76+
});
77+
78+
it("keeps unresolved mentions when HTML is absent or has no matching mention", () => {
79+
for (const html of [
80+
undefined,
81+
null,
82+
"",
83+
"<p>@Alex Smith</p>",
84+
mention("@Alex Smith", "another-id"),
85+
]) {
86+
expect(bitbucketMentionDisplayBody(token, html)).toBeUndefined();
87+
}
88+
expect(bitbucketMentionDisplayBody(`${token} @{unknown}`, mention())).toBe(
89+
"@Alex Smith @{unknown}",
90+
);
91+
});
92+
93+
it("ignores empty, conflicting or code-only mention metadata", () => {
94+
for (const html of [
95+
mention(""),
96+
mention("@"),
97+
mention("Alex"),
98+
`<code>${mention()}</code>`,
99+
mention() + mention("@Someone Else"),
100+
]) {
101+
expect(bitbucketMentionDisplayBody(token, html)).toBeUndefined();
102+
}
103+
});
104+
105+
it("tolerates malformed HTML and ignores unrelated markup", () => {
106+
expect(bitbucketMentionDisplayBody(token, `<p>${mention()}<p>Unclosed`)).toBe("@Alex Smith");
107+
expect(bitbucketMentionDisplayBody("No mentions", mention())).toBeUndefined();
108+
});
109+
});
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
import { parseFragment, type DefaultTreeAdapterTypes } from "parse5";
2+
import remarkGfm from "remark-gfm";
3+
import remarkParse from "remark-parse";
4+
import { unified } from "unified";
5+
6+
const markdownParser = unified().use(remarkParse).use(remarkGfm).freeze();
7+
const mentionPattern = /@\{([^{}\s]+)\}/gu;
8+
const ignoredMarkdownNodes = new Set([
9+
"code",
10+
"inlineCode",
11+
"html",
12+
"link",
13+
"linkReference",
14+
"image",
15+
"imageReference",
16+
]);
17+
18+
type MarkdownNode = {
19+
type: string;
20+
position?:
21+
| { start: { offset?: number | undefined }; end: { offset?: number | undefined } }
22+
| undefined;
23+
children?: MarkdownNode[] | undefined;
24+
};
25+
26+
function htmlContentRanges(body: string, tree: MarkdownNode) {
27+
const fragments: string[] = [];
28+
let cursor = 0;
29+
const collect = (node: MarkdownNode) => {
30+
const start = node.position?.start.offset;
31+
const end = node.position?.end.offset;
32+
if (node.type === "html" && start !== undefined && end !== undefined) {
33+
fragments.push(" ".repeat(start - cursor), body.slice(start, end));
34+
cursor = end;
35+
} else {
36+
node.children?.forEach(collect);
37+
}
38+
};
39+
collect(tree);
40+
const ranges: { start: number; end: number }[] = [];
41+
if (fragments.length === 0) return ranges;
42+
fragments.push(" ".repeat(body.length - cursor));
43+
const visit = (node: DefaultTreeAdapterTypes.Node) => {
44+
const location = "tagName" in node ? node.sourceCodeLocation : undefined;
45+
const start = location?.startTag?.endOffset;
46+
const end = location?.endTag?.startOffset ?? location?.endOffset;
47+
if (start !== undefined && end !== undefined && end > start) {
48+
ranges.push({ start, end });
49+
return;
50+
}
51+
if ("childNodes" in node) node.childNodes.forEach(visit);
52+
};
53+
visit(parseFragment(fragments.join(""), { sourceCodeLocationInfo: true }));
54+
return ranges;
55+
}
56+
57+
function mentionLabels(html: string) {
58+
const labels = new Map<string, string>();
59+
const conflicts = new Set<string>();
60+
const text = (node: DefaultTreeAdapterTypes.Node): string =>
61+
"value" in node ? node.value : "childNodes" in node ? node.childNodes.map(text).join("") : "";
62+
const visit = (node: DefaultTreeAdapterTypes.Node) => {
63+
if ("tagName" in node) {
64+
if (["pre", "code", "script", "style"].includes(node.tagName)) return;
65+
const attribute = (name: string) => node.attrs.find((entry) => entry.name === name)?.value;
66+
const id = attribute("data-atlassian-id");
67+
if (id && attribute("class")?.split(/\s+/u).includes("ap-mention")) {
68+
const label = text(node).replace(/\s+/gu, " ").trim();
69+
if (label.startsWith("@") && label.length > 1) {
70+
if (labels.has(id) && labels.get(id) !== label) conflicts.add(id);
71+
labels.set(id, label);
72+
}
73+
}
74+
}
75+
if ("childNodes" in node) node.childNodes.forEach(visit);
76+
};
77+
visit(parseFragment(html));
78+
conflicts.forEach((id) => labels.delete(id));
79+
return labels;
80+
}
81+
82+
/** Resolves prose mentions for display without changing the Markdown used for edits. */
83+
export function bitbucketMentionDisplayBody(body: string, html: unknown) {
84+
if (typeof html !== "string" || !html || !body.includes("@{")) return undefined;
85+
const labels = mentionLabels(html);
86+
if (labels.size === 0) return undefined;
87+
const tree = markdownParser.parse(body);
88+
const htmlRanges = htmlContentRanges(body, tree);
89+
const replacements: { start: number; end: number; label: string }[] = [];
90+
const visit = (node: MarkdownNode) => {
91+
if (ignoredMarkdownNodes.has(node.type)) return;
92+
const start = node.position?.start.offset;
93+
const end = node.position?.end.offset;
94+
if (node.type === "text" && start !== undefined && end !== undefined) {
95+
const source = body.slice(start, end);
96+
for (const match of source.matchAll(mentionPattern)) {
97+
if (
98+
htmlRanges.some(
99+
(range) => start + match.index >= range.start && start + match.index < range.end,
100+
)
101+
)
102+
continue;
103+
let escapes = 0;
104+
for (let index = match.index - 1; index >= 0 && source[index] === "\\"; index--) escapes++;
105+
if (escapes % 2 !== 0) continue;
106+
const label = labels.get(match[1]!);
107+
if (label === undefined) continue;
108+
replacements.push({
109+
start: start + match.index,
110+
end: start + match.index + match[0].length,
111+
label: label.replace(/[\\`*_{}[\]()<>!#|~&]/gu, "\\$&"),
112+
});
113+
}
114+
}
115+
node.children?.forEach(visit);
116+
};
117+
visit(tree);
118+
if (replacements.length === 0) return undefined;
119+
let displayBody = body;
120+
for (const replacement of replacements.toReversed()) {
121+
displayBody =
122+
displayBody.slice(0, replacement.start) +
123+
replacement.label +
124+
displayBody.slice(replacement.end);
125+
}
126+
return displayBody === body ? undefined : displayBody;
127+
}

‎apps/server/src/pullRequest/bitbucketPullRequestJson.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as Result from "effect/Result";
22
import { describe, expect, it } from "vite-plus/test";
33

44
import {
5+
buildReviewThreads,
56
decodeCommentsJson,
67
decodeCommitsJson,
78
decodeConflictsJson,
@@ -375,3 +376,71 @@ describe("repository permission decoding", () => {
375376
expect(expectSuccess(decodeRepositoryPermissionJson(page([])))).toBe(true);
376377
});
377378
});
379+
380+
describe("mention display bodies", () => {
381+
const token = "@{712020:11111111-2222-4333-8444-555555555555}";
382+
const html =
383+
'<p><span class="ap-mention" data-atlassian-id="712020:11111111-2222-4333-8444-555555555555">@Alex Smith</span> thanks.</p>';
384+
it("preserves editable source in descriptions, comments and inline threads", () => {
385+
const body = `${token} thanks.`;
386+
const pr = expectSuccess(
387+
decodePullRequestJson(
388+
JSON.stringify(pullRequest({ description: body, rendered: { description: { html } } })),
389+
),
390+
);
391+
expect(pr).toMatchObject({ body, displayBody: "@Alex Smith thanks." });
392+
const pageResult = expectSuccess(
393+
decodeCommentsJson(
394+
page([
395+
{
396+
id: 1,
397+
content: { raw: body, html },
398+
created_on: "2026-10-02T00:00:00Z",
399+
inline: { path: "src/search.ts", to: 1 },
400+
},
401+
]),
402+
),
403+
);
404+
expect(pageResult.comments[0]).toMatchObject({ body, displayBody: "@Alex Smith thanks." });
405+
expect(buildReviewThreads(pageResult.entries)[0]?.comments[0]).toMatchObject({
406+
body,
407+
displayBody: "@Alex Smith thanks.",
408+
});
409+
});
410+
it("keeps raw descriptions when rendered HTML is missing", () => {
411+
const pr = expectSuccess(
412+
decodePullRequestJson(JSON.stringify(pullRequest({ description: token }))),
413+
);
414+
expect(pr.body).toBe(token);
415+
expect(pr.displayBody).toBeUndefined();
416+
});
417+
418+
it.each([42, "invalid", { description: 42 }, { description: { html: 42 } }])(
419+
"keeps valid pull requests when rendered metadata is malformed: %j",
420+
(rendered) => {
421+
const input = pullRequest({ description: token, rendered });
422+
const pr = expectSuccess(decodePullRequestJson(JSON.stringify(input)));
423+
expect(pr.body).toBe(token);
424+
expect(pr.displayBody).toBeUndefined();
425+
expect(expectSuccess(decodePullRequestPageJson(page([input]))).items).toHaveLength(1);
426+
},
427+
);
428+
429+
it("keeps comments and inline threads when optional HTML has the wrong type", () => {
430+
const result = expectSuccess(
431+
decodeCommentsJson(
432+
page([
433+
{
434+
id: 1,
435+
content: { raw: token, html: 42 },
436+
created_on: "2026-10-02T00:00:00Z",
437+
inline: { path: "src/search.ts", to: 1 },
438+
},
439+
]),
440+
),
441+
);
442+
expect(result.comments[0]).toMatchObject({ body: token });
443+
expect(result.comments[0]?.displayBody).toBeUndefined();
444+
expect(buildReviewThreads(result.entries)[0]?.comments[0]).toMatchObject({ body: token });
445+
});
446+
});

0 commit comments

Comments
 (0)