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(plan): inline comment threads in the statement editor and review timeline (#21386)
boojackb472886b03af
diff --git a/frontend/scripts/ui-guideline-legacy-debt.json b/frontend/scripts/ui-guideline-legacy-debt.jsonindex b6ef1ab749..44f71d317d 100644--- a/frontend/scripts/ui-guideline-legacy-debt.json+++ b/frontend/scripts/ui-guideline-legacy-debt.json@@ -652,7 +652,7 @@"path": "src/components/MarkdownEditor/MarkdownEditor.tsx","rule": "no-native-control","token": "button",- "count": 3+ "count": 1},{"path": "src/components/MatchedDatabaseView.tsx",diff --git a/frontend/src/assets/css/github-markdown-style.css b/frontend/src/assets/css/github-markdown-style.cssindex a420625ccf..80d5a6aa08 100644--- a/frontend/src/assets/css/github-markdown-style.css+++ b/frontend/src/assets/css/github-markdown-style.css@@ -537,7 +537,7 @@margin-top: 0 !important;}-.markdown-body > p:last-of-type {+.markdown-body > :last-child {margin-bottom: 0 !important;}diff --git a/frontend/src/components/MarkdownEditor/MarkdownEditor.css b/frontend/src/components/MarkdownEditor/MarkdownEditor.cssnew file mode 100644index 0000000000..ace6c435bb--- /dev/null+++ b/frontend/src/components/MarkdownEditor/MarkdownEditor.css@@ -0,0 +1,7 @@+/* Monaco's unlayered button:focus rule also matches React controls hosted in+ an editor view zone. Tabs own their focus styling: a keyboard-only background+ with the selected underline, without a second editor-colored outline. */+.bb-markdown-editor [role="tab"]:focus,+.monaco-editor.standalone .bb-markdown-editor [role="tab"]:focus {+ outline: none;+}diff --git a/frontend/src/components/MarkdownEditor/MarkdownEditor.test.tsx b/frontend/src/components/MarkdownEditor/MarkdownEditor.test.tsxindex 218bb3ff5e..ca737b44b0 100644--- a/frontend/src/components/MarkdownEditor/MarkdownEditor.test.tsx+++ b/frontend/src/components/MarkdownEditor/MarkdownEditor.test.tsx@@ -1,9 +1,13 @@+import { readFileSync } from "node:fs";import type { ReactElement } from "react";import { act } from "react";import { createRoot } from "react-dom/client";import { describe, expect, test, vi } from "vitest";import { MarkdownEditor } from "./MarkdownEditor";+// Vitest stubs CSS imports; load the actual stylesheet from the frontend test root.+const markdownStyles = readFileSync("src/assets/css/github-markdown-style.css", "utf8");+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -32,6 +36,57 @@ const renderIntoContainer = (element: ReactElement) => {};describe("MarkdownEditor", () => {+ test.each([+ { content: "2222", lastTag: "P" },+ { content: "First paragraph\n\nLast paragraph", lastTag: "P" },+ { content: "Introduction\n\n- Item", lastTag: "UL" },+ { content: "Introduction\n\n```sql\nSELECT 1;\n```", lastTag: "PRE" },+ { content: "Introduction\n\n## Heading", lastTag: "H2" },+ ])("removes the final $lastTag margin while preserving spacing between blocks", ({ content, lastTag }) => {+ const stylesheet = document.createElement("style");+ stylesheet.textContent = markdownStyles;+ document.head.append(stylesheet);+ const { container, render, unmount } = renderIntoContainer(+ <MarkdownEditor content={content} mode="preview" />+ );+ document.body.append(container);+ try {+ render();+ const body = container.querySelector(".markdown-body")!;+ const last = body.lastElementChild!;+ expect(last.tagName).toBe(lastTag);+ expect(Number.parseFloat(getComputedStyle(last).marginBottom)).toBe(0);+ if (body.firstElementChild !== last) {+ expect(Number.parseFloat(getComputedStyle(body.firstElementChild!).marginBottom)).toBe(16);+ }+ } finally {+ unmount();+ container.remove();+ stylesheet.remove();+ }+ });++ test("switches between accessible tabs without losing the draft", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MarkdownEditor content="**draft**" onChange={vi.fn()} />+ );+ render();+ const tabs = container.querySelectorAll<HTMLButtonElement>('[role="tab"]');+ expect(tabs).toHaveLength(2);+ expect(tabs[0].getAttribute("aria-selected")).toBe("true");++ act(() => tabs[1].click());+ expect(tabs[1].getAttribute("aria-selected")).toBe("true");+ expect(container.querySelector('[role="tabpanel"] strong')?.textContent).toBe(+ "draft"+ );++ act(() => tabs[0].click());+ expect(tabs[0].getAttribute("aria-selected")).toBe("true");+ expect(container.querySelector("textarea")?.value).toBe("**draft**");+ unmount();+ });+test("opens rendered markdown links in a new tab", () => {const { container, render, unmount } = renderIntoContainer(<MarkdownEditor@@ -52,3 +107,16 @@ describe("MarkdownEditor", () => {unmount();});});+++test("focuses the input when autofocus is requested", () => {+ const {container, render, unmount} = renderIntoContainer(<MarkdownEditor autoFocus compact content="" onChange={vi.fn()} />);+ document.body.append(container);+ try {+ render();+ expect(document.activeElement).toBe(container.querySelector("textarea"));+ } finally {+ unmount();+ container.remove();+ }+});diff --git a/frontend/src/components/MarkdownEditor/MarkdownEditor.tsx b/frontend/src/components/MarkdownEditor/MarkdownEditor.tsxindex 765c81f7db..01b5f5d7fd 100644--- a/frontend/src/components/MarkdownEditor/MarkdownEditor.tsx+++ b/frontend/src/components/MarkdownEditor/MarkdownEditor.tsx@@ -3,7 +3,9 @@ import { Bold, Code2, Hash, Heading1, Link2 } from "lucide-react";import MarkdownIt from "markdown-it";import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";+import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";import { Textarea } from "@/components/ui/textarea";+import "./MarkdownEditor.css";import { cn } from "@/lib/utils";const markdown = new MarkdownIt({@@ -12,10 +14,13 @@ const markdown = new MarkdownIt({});const editorBoxClassName =- "min-h-34 w-full rounded-xs border border-control-border bg-transparent px-3 py-2 text-sm";+ "w-full rounded-xs border border-control-border bg-transparent px-3 py-2 text-sm";type CommonProps = {content: string;+ autoFocus?: boolean;+ /** Start with three lines while still growing to fit the draft. */+ compact?: boolean;placeholder?: string;maxLength?: number;transform?: (raw: string) => string;@@ -38,6 +43,8 @@ type Props = EditorProps | PreviewProps;export function MarkdownEditor({content,+ autoFocus = false,+ compact = false,onChange,onSubmit,placeholder,@@ -47,6 +54,10 @@ export function MarkdownEditor({maxHeight,}: Props) {const { t } = useTranslation();+ const boxClassName = cn(+ editorBoxClassName,+ compact ? "min-h-20" : "min-h-34"+ );const textareaRef = useRef<HTMLTextAreaElement>(null);const [tab, setTab] = useState<"write" | "preview">(mode === "preview" ? "preview" : "write"@@ -68,12 +79,17 @@ export function MarkdownEditor({if (!textareaRef.current) {return;}- textareaRef.current.style.height = "auto";- textareaRef.current.style.height = `${Math.max(- textareaRef.current.scrollHeight,- 112- )}px`;- }, [content, tab]);+ const textarea = textareaRef.current;+ textarea.style.height = "auto";+ // Let rows and the CSS minimum define the initial height. scrollHeight+ // includes padding but not borders; account for both when growing.+ const borderHeight = textarea.offsetHeight - textarea.clientHeight;+ textarea.style.height = `${textarea.scrollHeight + borderHeight}px`;+ }, [compact, content, tab]);++ useEffect(() => {+ if (autoFocus) textareaRef.current?.focus({ preventScroll: true });+ }, [autoFocus, tab]);const insertTemplate = (template: string, cursorOffset: number) => {const textarea = textareaRef.current;@@ -107,36 +123,30 @@ export function MarkdownEditor({}return (- <div>- <div className="mb-2 flex items-center justify-between pb-1">- <div className="flex gap-x-4">- <button- className={cn(- "relative px-1 pb-1 text-sm transition-colors",- tab === "write"- ? "text-accent after:absolute after:inset-x-0 after:-bottom-px after:h-0.5 after:bg-accent"- : "text-control-light hover:text-control"- )}- onClick={() => setTab("write")}- type="button"+ <Tabs+ className="bb-markdown-editor"+ value={tab}+ onValueChange={(value) => {+ if (value === "write" || value === "preview") setTab(value);+ }}+ >+ <div className="mb-2 flex flex-wrap items-center justify-between gap-2 pb-1">+ <TabsList className="border-0">+ <TabsTrigger+ className="pb-1 font-normal focus-visible:bg-control-bg focus-visible:ring-0 focus-visible:ring-offset-0"+ value="write">{t("issue.comment-editor.write")}- </button>- <button- className={cn(- "relative px-1 pb-1 text-sm transition-colors",- tab === "preview"- ? "text-accent after:absolute after:inset-x-0 after:-bottom-px after:h-0.5 after:bg-accent"- : "text-control-light hover:text-control"- )}- onClick={() => setTab("preview")}- type="button"+ </TabsTrigger>+ <TabsTrigger+ className="pb-1 font-normal focus-visible:bg-control-bg focus-visible:ring-0 focus-visible:ring-offset-0"+ value="preview">{t("issue.comment-editor.preview")}- </button>- </div>+ </TabsTrigger>+ </TabsList>{tab === "write" && (- <div className="flex items-center gap-x-2">+ <div className="flex flex-wrap items-center gap-2"><ToolbarButtonicon={<Heading1 className="h-4 w-4" />}label={t("issue.comment-editor.toolbar.header")}@@ -166,61 +176,63 @@ export function MarkdownEditor({)}</div>- {tab === "preview" ? (- <PreviewBody- className={cn(editorBoxClassName, "markdown-body")}- html={previewHtml}- />- ) : (- <Textarea- className={editorBoxClassName}- maxLength={maxLength}- onChange={(e) => onChange?.(e.target.value)}- onKeyDown={(e) => {- const listContinuation = applyMarkdownListContinuation(- content,- e.currentTarget.selectionStart,- e.currentTarget.selectionEnd- );- if (- e.key === "Enter" &&- !e.nativeEvent.isComposing &&- !e.metaKey &&- !e.ctrlKey &&- listContinuation- ) {- e.preventDefault();- onChange?.(listContinuation.content);- window.requestAnimationFrame(() => {- const target = textareaRef.current;- if (!target) {- return;- }- target.focus();- target.setSelectionRange(- listContinuation.cursor,- listContinuation.cursor- );- });- return;- }- if (- e.key === "Enter" &&- !e.nativeEvent.isComposing &&- (e.metaKey || e.ctrlKey)- ) {- e.preventDefault();- onSubmit?.();- }- }}- placeholder={placeholder ?? t("issue.leave-a-comment")}- ref={textareaRef}- rows={4}- style={{ maxHeight }}- value={content}- />- )}- </div>+ <TabsPanel className="mt-0" value={tab}>+ {tab === "preview" ? (+ <PreviewBody+ className={cn(boxClassName, "markdown-body")}+ html={previewHtml}+ />+ ) : (+ <Textarea+ className={boxClassName}+ maxLength={maxLength}+ onChange={(e) => onChange?.(e.target.value)}+ onKeyDown={(e) => {+ const listContinuation = applyMarkdownListContinuation(+ content,+ e.currentTarget.selectionStart,+ e.currentTarget.selectionEnd+ );+ if (+ e.key === "Enter" &&+ !e.nativeEvent.isComposing &&+ !e.metaKey &&+ !e.ctrlKey &&+ listContinuation+ ) {+ e.preventDefault();+ onChange?.(listContinuation.content);+ window.requestAnimationFrame(() => {+ const target = textareaRef.current;+ if (!target) {+ return;+ }+ target.focus();+ target.setSelectionRange(+ listContinuation.cursor,+ listContinuation.cursor+ );+ });+ return;+ }+ if (+ e.key === "Enter" &&+ !e.nativeEvent.isComposing &&+ (e.metaKey || e.ctrlKey)+ ) {+ e.preventDefault();+ onSubmit?.();+ }+ }}+ placeholder={placeholder ?? t("issue.leave-a-comment")}+ ref={textareaRef}+ rows={compact ? 3 : 4}+ style={{ maxHeight }}+ value={content}+ />+ )}+ </TabsPanel>+ </Tabs>);}@@ -237,15 +249,16 @@ function sanitizePreviewHtml(html: string) {function PreviewBody({ className, html }: { className: string; html: string }) {const { t } = useTranslation();+ if (html) {+ return (+ <div className={className} dangerouslySetInnerHTML={{ __html: html }} />+ );+ }return (<div className={className}>- {html ? (- <div dangerouslySetInnerHTML={{ __html: html }} />- ) : (- <span className="italic text-control-placeholder">- {t("issue.comment-editor.nothing-to-preview")}- </span>- )}+ <span className="italic text-control-placeholder">+ {t("issue.comment-editor.nothing-to-preview")}+ </span></div>);}diff --git a/frontend/src/components/UserAvatar.tsx b/frontend/src/components/UserAvatar.tsxindex 2f425b986a..ccf3be23ad 100644--- a/frontend/src/components/UserAvatar.tsx+++ b/frontend/src/components/UserAvatar.tsx@@ -9,6 +9,12 @@ const AVATAR_COLORS = ["#EF4444",];+const AVATAR_SIZES = {+ xs: "size-5 text-xs",+ sm: "size-7 text-xs",+ md: "size-9 text-sm",+};+export function getAvatarColor(name: string) {let hash = 0;for (let i = 0; i < name.length; i++)@@ -34,15 +40,14 @@ export function UserAvatar({title: string;/** Stable string for color derivation (e.g. email). Defaults to title. */colorSeed?: string;- size?: "sm" | "md";+ size?: "xs" | "sm" | "md";className?: string;}) {- const dim = size === "sm" ? "h-7 w-7 text-xs" : "h-9 w-9 text-sm";return (<divclassName={cn("rounded-full flex items-center justify-center text-white font-medium shrink-0",- dim,+ AVATAR_SIZES[size],className)}style={{ backgroundColor: getAvatarColor(colorSeed ?? title) }}diff --git a/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx b/frontend/src/components/issue-activity/IssueCommentActivity.test.tsxindex 2fceac5a3e..c819aacc9e 100644--- a/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx+++ b/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx@@ -20,7 +20,7 @@ import {getIssueCommentType,IssueCommentType,} from "@/stores/app/issueComment";-import { IssueCommentRow } from "./IssueCommentActivity";+import { canEditIssueComment, IssueCommentRow } from "./IssueCommentActivity";vi.mock("react-i18next", async (importOriginal) => ({...(await importOriginal<typeof import("react-i18next")>()),@@ -37,6 +37,15 @@ vi.mock("react-i18next", async (importOriginal) => ({}),}));+const mocks = vi.hoisted(() => ({+ hasPermission: vi.fn((_project: unknown, _permission: unknown) => false),+}));+vi.mock("@/utils/iam/permission", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/utils/iam/permission")>()),+ hasProjectPermissionV2: (project: unknown, permission: unknown) =>+ mocks.hasPermission(project, permission),+}));+vi.mock("@/stores/app", () => ({useAppStore: (selector: (state: unknown) => unknown) =>selector({@@ -116,6 +125,33 @@ const changeSpec = ({},});+describe("canEditIssueComment", () => {+ const project = { name: "projects/p1" } as Parameters<typeof canEditIssueComment>[1];+ const own = create(IssueCommentSchema, {+ name: "projects/p1/issues/1/issueComments/9",+ creator: "users/[email protected]",+ comment: "mine",+ });++ test("authoring a comment grants no edit without the update permission", () => {+ mocks.hasPermission.mockImplementation(+ (_project: unknown, permission: unknown) =>+ permission === "bb.issueComments.create"+ );+ expect(canEditIssueComment(own, project)).toBe(false);+ });++ test("the update permission allows editing a user comment", () => {+ mocks.hasPermission.mockImplementation(+ (_project: unknown, permission: unknown) =>+ permission === "bb.issueComments.update"+ );+ expect(canEditIssueComment(own, project)).toBe(true);+ expect(canEditIssueComment(reviewSubmission, project)).toBe(false);+ expect(canEditIssueComment(own, undefined)).toBe(false);+ });+});+describe("IssueCommentRow", () => {test("shows who bypassed review and created the rollout", () => {const issue = create(IssueSchema, {@@ -224,7 +260,7 @@ describe("IssueCommentRow", () => {expect(link).toHaveClass("text-main","hover:text-accent",- "hover:underline"+ "hover:no-underline");expect(link).not.toHaveAttribute("data-prevent-scroll-reset");});diff --git a/frontend/src/components/issue-activity/IssueCommentActivity.tsx b/frontend/src/components/issue-activity/IssueCommentActivity.tsxindex fa1900eb6a..c994d819e1 100644--- a/frontend/src/components/issue-activity/IssueCommentActivity.tsx+++ b/frontend/src/components/issue-activity/IssueCommentActivity.tsx@@ -23,13 +23,13 @@ import { UserAvatar } from "@/components/UserAvatar";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";+import { useUserByIdentifier } from "@/hooks/useAppState";import {diffEntryKey,diffPlanSpecsForEvent,type SpecDiffEntry,} from "@/lib/plan/diffPlanSpecs";import { cn } from "@/lib/utils";-import { extractUserEmail } from "@/stores";import { useAppStore } from "@/stores/app";import {getIssueCommentType,@@ -95,11 +95,10 @@ function isDoneRolloutComment(}// Whether the current user may edit a comment: only user comments and approval-// decisions that carry a note are editable, and only by their author or someone-// with the update permission. Shared so both activity surfaces gate edits alike.+// decisions that carry a note are editable, and only with the update+// permission. Shared so every activity surface gates edits alike.export function canEditIssueComment(comment: IssueComment,- currentUserEmail: string,project: Parameters<typeof hasProjectPermissionV2>[0] | undefined): boolean {if (!project) {@@ -112,30 +111,23 @@ export function canEditIssueComment(if (!editable) {return false;}- if (currentUserEmail === extractUserEmail(comment.creator)) {- return true;- }+ // Edits go through UpdateIssueComment, which the server gates on the update+ // permission alone; authorship grants nothing there.return hasProjectPermissionV2(project, "bb.issueComments.update");}-// The timeline row shell shared by every activity item: the connector line, the-// left icon gutter, and a body that is a bordered card when present or a-// borderless inline header when absent. This is the single source of the-// activity-item layout for both the issue-detail list and the review timeline.-export function ActivityRowShell({- body,- header,+// The timeline row frame shared by every activity item: the connector line+// and the left icon gutter around an arbitrary body.+export function ActivityRowFrame({+ children,icon,id,isLast,- subjectSuffix,}: {- body?: ReactNode;- header: ReactNode;+ children: ReactNode;icon: ReactNode;id?: string;isLast: boolean;- subjectSuffix?: ReactNode;}) {return (<li>@@ -148,33 +140,60 @@ export function ActivityRowShell({)}<div className="relative flex items-start"><div className="pt-1.5">{icon}</div>- <div className="min-w-0 flex-1">- <div- className={cn(- "overflow-hidden rounded-sm border",- body- ? "ml-3 border-block-border bg-background"- : "ml-1 border-transparent"- )}- >- <div className={cn("px-3 py-2", body && "bg-control-bg/50")}>- <div className="flex items-center justify-between">- <div className="flex min-w-0 flex-wrap items-center gap-x-2 text-sm">- {header}- </div>- {subjectSuffix}- </div>- </div>- {body && (- <div className="wrap-break-word border-block-border border-t px-3 py-2 text-control text-sm [&_.markdown-body>div>:first-child]:mt-0 [&_.markdown-body>div>:last-child]:mb-0">- {body}- </div>- )}+ <div className="min-w-0 flex-1">{children}</div>+ </div>+ </div>+ </li>+ );+}++// The timeline row shell shared by every activity item: the frame plus a+// body that is a bordered card when present or a borderless inline header+// when absent. This is the single source of the activity-item layout for+// both the issue-detail list and the review timeline.+export function ActivityRowShell({+ body,+ header,+ icon,+ id,+ isLast,+ subjectSuffix,+}: {+ body?: ReactNode;+ header: ReactNode;+ icon: ReactNode;+ id?: string;+ isLast: boolean;+ subjectSuffix?: ReactNode;+}) {+ return (+ <ActivityRowFrame icon={icon} id={id} isLast={isLast}>+ <div+ className={cn(+ "overflow-hidden rounded-sm border",+ body+ ? "ml-3 border-block-border bg-background"+ : "ml-1 border-transparent"+ )}+ >+ <div className={cn("px-3 py-2", body && "flex flex-col gap-y-2")}>+ <div+ className={cn(+ "flex items-center justify-between gap-x-2",+ body && "min-h-6"+ )}+ >+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 text-sm">+ {header}</div>+ {subjectSuffix}</div>+ {body && (+ <div className="wrap-break-word text-control text-sm">{body}</div>+ )}</div></div>- </li>+ </ActivityRowFrame>);}@@ -197,10 +216,8 @@ function IssueCommentHeader({similarCount,}: ActivityProps & { similarCount?: number }) {const { t } = useTranslation();- const creatorUser = useAppStore((state) =>- state.getUserByIdentifier(comment.creator)- );- const creator = creatorUser ?? unknownUser(comment.creator);+ const creator =+ useUserByIdentifier(comment.creator) ?? unknownUser(comment.creator);const createdTs = getTimeForPbTimestampProtoEs(comment.createTime, 0);const updatedTs = getTimeForPbTimestampProtoEs(comment.updateTime, 0);const isEdited =@@ -223,7 +240,10 @@ function IssueCommentHeader({</Badge>)}{comment.createTime && (- <HumanizeTs className="text-control-light" ts={createdTs / 1000} />+ <HumanizeTs+ className="text-xs text-control-light"+ ts={createdTs / 1000}+ />)}{isEdited && (<span className="text-control-light text-xs">@@ -276,10 +296,6 @@ export function IssueCommentRow({}function IssueCommentActionIcon({ issue, plan, comment }: ActivityProps) {- const creatorUser = useAppStore((state) =>- state.getUserByIdentifier(comment.creator)- );- const user = creatorUser ?? unknownUser(comment.creator);const commentType = getIssueCommentType(comment);if (@@ -345,10 +361,17 @@ function IssueCommentActionIcon({ issue, plan, comment }: ActivityProps) {return <ActivityBadge spec={PLAN_CHANGE_ICON.edited} />;}+ return <ActivityUserIcon principal={comment.creator} />;+}++// The avatar badge of a user-authored activity row.+export function ActivityUserIcon({ principal }: { principal: string }) {+ const user = useUserByIdentifier(principal) ?? unknownUser(principal);return (<div className="relative pl-0.5"><div className="flex size-7 items-center justify-center rounded-full bg-background ring-4 ring-background"><UserAvatar+ colorSeed={user.email}className="font-medium"size="sm"title={user.title || user.email}@@ -588,7 +611,7 @@ function IssueCommentActionSentence({);}- return <span className="wrap-break-word min-w-0 text-control" />;+ return null;}function SpecDiffRow({@@ -824,7 +847,7 @@ function SpecChangeRow({{children}{" "}{specRoute != null ? (<RouterLink- className="inline-flex min-w-0 items-center gap-1 text-main transition-colors hover:text-accent hover:underline focus-visible:text-accent focus-visible:underline focus-visible:outline-hidden"+ className="inline-flex min-w-0 items-center gap-1 text-main no-underline transition-colors hover:text-accent hover:no-underline focus-visible:text-accent"to={specRoute}>{chip}diff --git a/frontend/src/components/monaco/MonacoViewZone.test.tsx b/frontend/src/components/monaco/MonacoViewZone.test.tsxnew file mode 100644index 0000000000..ab6472d48c--- /dev/null+++ b/frontend/src/components/monaco/MonacoViewZone.test.tsx@@ -0,0 +1,147 @@+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, test, vi } from "vitest";+import { MonacoViewZone } from "./MonacoViewZone";+import type { IStandaloneCodeEditor } from "./types";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++function fakeEditor() {+ const zones = new Map<+ string,+ {+ afterLineNumber: number;+ domNode: HTMLElement;+ onDomNodeTop?: (top: number) => void;+ }+ >();+ let nextId = 0;+ const widgets = new Set<{ getDomNode: () => HTMLElement }>();+ const editor = {+ addOverlayWidget: (widget: { getDomNode: () => HTMLElement }) => {+ widgets.add(widget);+ },+ removeOverlayWidget: (widget: { getDomNode: () => HTMLElement }) => {+ widgets.delete(widget);+ },+ getLayoutInfo: () => ({+ contentLeft: 52,+ width: 800,+ verticalScrollbarWidth: 14,+ minimap: { minimapWidth: 0 },+ }),+ onDidLayoutChange: () => ({ dispose: vi.fn() }),+ getModel: () => ({}),+ changeViewZones: (+ callback: (accessor: {+ addZone: (zone: {+ afterLineNumber: number;+ domNode: HTMLElement;+ onDomNodeTop?: (top: number) => void;+ }) => string;+ removeZone: (id: string) => void;+ layoutZone: (id: string) => void;+ }) => void+ ) =>+ callback({+ addZone: (zone) => {+ const id = `zone-${nextId++}`;+ zones.set(id, zone);+ return id;+ },+ removeZone: (id) => {+ zones.delete(id);+ },+ layoutZone: vi.fn(),+ }),+ };+ return { editor: editor as unknown as IStandaloneCodeEditor, widgets, zones };+}++describe("MonacoViewZone", () => {+ test("reserves a zone after the line, hosts the content in an overlay widget, and removes both on unmount", () => {+ const { editor, widgets, zones } = fakeEditor();+ const container = document.createElement("div");+ const root = createRoot(container);++ act(() => {+ root.render(+ <MonacoViewZone afterLineNumber={4} editor={editor}>+ <span data-testid="content">hello</span>+ </MonacoViewZone>+ );+ });+ expect(zones.size).toBe(1);+ const [zone] = Array.from(zones.values());+ expect(zone.afterLineNumber).toBe(4);+ // The zone only reserves space; the content lives in the overlay widget.+ expect(zone.domNode.querySelector("[data-testid='content']")).toBeNull();+ expect(widgets.size).toBe(1);+ const widgetNode = Array.from(widgets)[0].getDomNode();+ expect(widgetNode.querySelector("[data-testid='content']")?.textContent).toBe(+ "hello"+ );+ expect(widgetNode.style.left).toBe("52px");+ expect(widgetNode.style.width).toBe("734px");+ zone.onDomNodeTop?.(120);+ expect(widgetNode.style.top).toBe("120px");++ act(() => {+ root.render(+ <MonacoViewZone afterLineNumber={9} editor={editor}>+ <span data-testid="content">hello</span>+ </MonacoViewZone>+ );+ });+ expect(zones.size).toBe(1);+ expect(Array.from(zones.values())[0].afterLineNumber).toBe(9);++ act(() => root.unmount());+ expect(zones.size).toBe(0);+ expect(widgets.size).toBe(0);+ });+});+++afterEach(() => vi.unstubAllGlobals());++test.each([+ { name: "already visible", top: 150, height: 100, expected: undefined },+ { name: "below the viewport", top: 480, height: 120, expected: 208 },+ { name: "above the viewport", top: 50, height: 120, expected: 42 },+ { name: "taller than the viewport", top: 450, height: 600, expected: 442 },+])("reveals $name with minimal editor scrolling", ({top, height, expected}) => {+ const frames = new Map<number, FrameRequestCallback>();+ let nextFrame = 0;+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { frames.set(++nextFrame, callback); return nextFrame; });+ vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));+ const runFrame = () => { const queued = [...frames.values()]; frames.clear(); act(() => queued.forEach(callback => callback(0))); };+ const host = document.createElement("div");+ host.getBoundingClientRect = () => new DOMRect(0, 100, 800, 400);+ const target = document.createElement("div");+ target.getBoundingClientRect = () => new DOMRect(0, top, 700, height);+ const revealTarget = {current: target};+ const {editor} = fakeEditor();+ const scroll = vi.fn();+ Object.assign(editor, {getDomNode: () => host, getScrollTop: () => 100, setScrollTop: scroll});+ const root = createRoot(document.createElement("div"));+ const render = (key: string, text = "comment") => act(() => root.render(<MonacoViewZone afterLineNumber={4} editor={editor} revealKey={key} revealTarget={revealTarget}>{text}</MonacoViewZone>));+ render("first");+ runFrame();+ expect(scroll).not.toHaveBeenCalled();+ runFrame();+ if (expected === undefined) expect(scroll).not.toHaveBeenCalled();+ else expect(scroll).toHaveBeenCalledExactlyOnceWith(expected);+ // Typing/rerendering the same comment must not pull the reader back.+ scroll.mockClear();+ render("first", "longer comment");+ runFrame(); runFrame();+ expect(scroll).not.toHaveBeenCalled();+ render("second");+ runFrame();+ act(() => root.unmount());+ runFrame();+ expect(scroll).not.toHaveBeenCalled();+});diff --git a/frontend/src/components/monaco/MonacoViewZone.tsx b/frontend/src/components/monaco/MonacoViewZone.tsxnew file mode 100644index 0000000000..cf6da16d11--- /dev/null+++ b/frontend/src/components/monaco/MonacoViewZone.tsx@@ -0,0 +1,147 @@+import {+ createContext,+ type ReactNode,+ type RefObject,+ useCallback,+ useLayoutEffect,+ useMemo,+ useRef,+} from "react";+import { createPortal } from "react-dom";+import type { IStandaloneCodeEditor } from "./types";++export const MonacoViewZoneRevealContext = createContext<+ ((target: HTMLElement) => void) | undefined+>(undefined);++// Hosts interactive React content between two editor lines the way VS Code's+// ZoneWidget does: a view zone reserves the vertical space (the zone layer+// sits under the text layer, so it cannot take clicks), and an overlay widget+// pinned to the zone's top carries the real content. The content wrapper is+// measured with a ResizeObserver and the zone re-laid out to match.+export function MonacoViewZone({+ afterLineNumber,+ children,+ editor,+ revealKey,+ revealTarget,+}: {+ afterLineNumber: number;+ children: ReactNode;+ editor: IStandaloneCodeEditor;+ // Reveal once on opening/changing content, never on every resize or keystroke.+ revealKey?: unknown;+ revealTarget?: RefObject<HTMLElement | null>;+}) {+ const widgetNode = useMemo(() => {+ const node = document.createElement("div");+ node.style.pointerEvents = "auto";+ return node;+ }, []);+ const contentRef = useRef<HTMLDivElement>(null);+ const revealFrame = useRef<number | undefined>(undefined);++ useLayoutEffect(() => {+ const content = contentRef.current;+ const zoneNode = document.createElement("div");+ const zone = {+ afterLineNumber,+ domNode: zoneNode,+ heightInPx: 1,+ onDomNodeTop: (top: number) => {+ widgetNode.style.top = `${top}px`;+ },+ };+ let zoneId = "";+ editor.changeViewZones((accessor) => {+ zoneId = accessor.addZone(zone);+ });+ const widget = {+ getId: () => `bytebase.view-zone.${zoneId}`,+ getDomNode: () => widgetNode,+ getPosition: () => null,+ };+ editor.addOverlayWidget(widget);++ // Span the content column: after the gutter, before the scrollbar.+ const layout = () => {+ const info = editor.getLayoutInfo();+ widgetNode.style.left = `${info.contentLeft}px`;+ widgetNode.style.width = `${Math.max(+ 0,+ info.width -+ info.contentLeft -+ info.verticalScrollbarWidth -+ info.minimap.minimapWidth+ )}px`;+ };+ layout();+ const layoutSubscription = editor.onDidLayoutChange(layout);++ const fit = () => {+ const next = content?.offsetHeight ?? 0;+ if (!next || next === zone.heightInPx) return;+ zone.heightInPx = next;+ editor.changeViewZones((accessor) => accessor.layoutZone(zoneId));+ };+ // The content is only measurable once the widget is in the editor's DOM+ // and has its column width. Size the zone now, before the editor's next+ // render, so the first frame never shows the content over the lines+ // below it at a placeholder height.+ fit();+ const observer = new ResizeObserver(fit);+ if (content) observer.observe(content);++ return () => {+ observer.disconnect();+ layoutSubscription.dispose();+ // The editor may already be disposed when the host unmounts.+ if (!editor.getModel()) return;+ editor.removeOverlayWidget(widget);+ editor.changeViewZones((accessor) => accessor.removeZone(zoneId));+ };+ }, [afterLineNumber, editor, widgetNode]);++ const reveal = useCallback(+ (target: HTMLElement) => {+ if (revealFrame.current !== undefined)+ cancelAnimationFrame(revealFrame.current);+ // Wait for the zone height to include newly opened forms.+ revealFrame.current = requestAnimationFrame(() => {+ revealFrame.current = requestAnimationFrame(() => {+ const host = editor.getDomNode();+ if (!host || !editor.getModel()) return;+ const bounds = target.getBoundingClientRect();+ const viewport = host.getBoundingClientRect();+ if (!bounds.height || !viewport.height) return;+ const top = viewport.top + 8;+ const bottom = viewport.bottom - 8;+ const delta =+ bounds.height > bottom - top || bounds.top < top+ ? bounds.top - top+ : Math.max(0, bounds.bottom - bottom);+ if (delta) editor.setScrollTop(editor.getScrollTop() + delta);+ });+ });+ },+ [editor]+ );++ useLayoutEffect(() => {+ const target = revealTarget?.current ?? contentRef.current;+ if (revealKey !== undefined && target) reveal(target);+ return () => {+ if (revealFrame.current !== undefined)+ cancelAnimationFrame(revealFrame.current);+ };+ }, [reveal, revealKey, revealTarget]);++ return createPortal(+ <div data-testid="monaco-view-zone" ref={contentRef}>+ <MonacoViewZoneRevealContext value={reveal}>+ {children}+ </MonacoViewZoneRevealContext>+ </div>,+ widgetNode+ );+}diff --git a/frontend/src/components/monaco/core.ts b/frontend/src/components/monaco/core.tsindex 7d0c8c6bf0..ba569e80f2 100644--- a/frontend/src/components/monaco/core.ts+++ b/frontend/src/components/monaco/core.ts@@ -72,6 +72,18 @@ export const loadMonacoEditor = async (): Promise<typeof MonacoType> => {return monacoModule;};+// Tokenizes `text` with Monaco's language support and the active theme and+// returns HTML, one `<br/>`-separated line per input line. For code excerpts+// rendered outside an editor that must still match the editor's colors.+export const colorizeStatement = async (+ text: string,+ language: MonacoType.languages.ILanguageExtensionPoint["id"] = "sql"+): Promise<string> => {+ await initialize();+ const monaco = await loadMonacoEditor();+ return monaco.editor.colorize(text, language, { tabSize: 2 });+};+export const getMonacoEditor = async (): Promise<typeof MonacoType> => {return monacoLoadDefer.promise;};diff --git a/frontend/src/components/monaco/index.ts b/frontend/src/components/monaco/index.tsindex 36dc5b4e1f..3c7f6fd930 100644--- a/frontend/src/components/monaco/index.ts+++ b/frontend/src/components/monaco/index.ts@@ -5,3 +5,4 @@ export * from "./ReadonlyMonaco";export * from "./ReadonlyDiffMonaco";export * from "./types";export * from "./utils";+export * from "./MonacoViewZone";diff --git a/frontend/src/hooks/useInViewOnce.test.tsx b/frontend/src/hooks/useInViewOnce.test.tsxnew file mode 100644index 0000000000..2110fe6ebb--- /dev/null+++ b/frontend/src/hooks/useInViewOnce.test.tsx@@ -0,0 +1,46 @@+import { act, cleanup, render } from "@testing-library/react";+import { afterEach, describe, expect, test, vi } from "vitest";+import { useInViewOnce } from "./useInViewOnce";++type Callback = (entries: { isIntersecting: boolean }[]) => void;+class FakeObserver {+ static instances: FakeObserver[] = [];+ observe = vi.fn();+ disconnect = vi.fn();+ constructor(readonly callback: Callback) {+ FakeObserver.instances.push(this);+ }+}++function Probe() {+ const { ref, inView } = useInViewOnce<HTMLDivElement>();+ return <div data-inview={inView} data-testid="probe" ref={ref} />;+}++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ FakeObserver.instances = [];+});++describe("useInViewOnce", () => {+ test("latches true the first time the element intersects, then stops observing", () => {+ vi.stubGlobal("IntersectionObserver", FakeObserver);+ const { getByTestId } = render(<Probe />);+ expect(getByTestId("probe").getAttribute("data-inview")).toBe("false");+ const [observer] = FakeObserver.instances;+ expect(observer.observe).toHaveBeenCalledWith(getByTestId("probe"));+ act(() => observer.callback([{ isIntersecting: false }]));+ expect(getByTestId("probe").getAttribute("data-inview")).toBe("false");+ act(() => observer.callback([{ isIntersecting: true }]));+ expect(getByTestId("probe").getAttribute("data-inview")).toBe("true");+ expect(observer.disconnect).toHaveBeenCalled();+ expect(FakeObserver.instances).toHaveLength(1);+ });++ test("reports in view right away without IntersectionObserver", () => {+ vi.stubGlobal("IntersectionObserver", undefined);+ const { getByTestId } = render(<Probe />);+ expect(getByTestId("probe").getAttribute("data-inview")).toBe("true");+ });+});diff --git a/frontend/src/hooks/useInViewOnce.ts b/frontend/src/hooks/useInViewOnce.tsnew file mode 100644index 0000000000..0ef598bc20--- /dev/null+++ b/frontend/src/hooks/useInViewOnce.ts@@ -0,0 +1,28 @@+import { type RefObject, useEffect, useRef, useState } from "react";++// Whether an element has ever come near the viewport, for work a page should+// defer until the reader gets there. Latches true and stops observing; an+// environment without IntersectionObserver reports true right away.+export function useInViewOnce<T extends Element>(+ rootMargin = "200px"+): { ref: RefObject<T | null>; inView: boolean } {+ const ref = useRef<T>(null);+ const [inView, setInView] = useState(+ () => typeof IntersectionObserver === "undefined"+ );+ useEffect(() => {+ const element = ref.current;+ if (inView || !element) return;+ const observer = new IntersectionObserver(+ (entries) => {+ if (!entries.some((entry) => entry.isIntersecting)) return;+ setInView(true);+ observer.disconnect();+ },+ { rootMargin }+ );+ observer.observe(element);+ return () => observer.disconnect();+ }, [inView, rootMargin]);+ return { ref, inView };+}diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex fe05ea4f28..7979dfccaa 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1783,6 +1783,36 @@"guidance-suffix": "without changes","re-request-review": "re-request review","title": "Rejected by {{user}}"+ },+ "thread": {+ "add-comment": "Add comment",+ "add-comment-on-line": "Add a comment on line {{line}}",+ "add-comment-on-lines": "Add a comment on lines {{startLine}} to {{endLine}}",+ "anchor": {+ "line_one": "Line {{range}}",+ "line_other": "Lines {{range}}",+ "outdated": "Outdated",+ "statement-unavailable": "Statement unavailable",+ "unavailable-change": "Deleted change",+ "view-in-statement": "View in Statement"+ },+ "comment-on-lines": "Comment on lines",+ "comment-required": "Enter a comment before submitting.",+ "n-replies-hidden_one": "{{count}} reply hidden",+ "n-replies-hidden_other": "{{count}} replies hidden",+ "n-replies_one": "{{count}} reply",+ "n-replies_other": "{{count}} replies",+ "publish": "Publish",+ "reopen-with-comment": "Reopen with comment",+ "reply": "Reply",+ "reply-placeholder": "Reply...",+ "reply-posted-status-failed": "Reply posted, but the thread status could not be updated. Retry the status action.",+ "resolve": "Resolve",+ "resolve-with-comment": "Resolve with comment",+ "resolved": "Resolved",+ "threads-on-line_one": "{{count}} thread on this line",+ "threads-on-line_other": "{{count}} threads on this line",+ "write-comment": "Write a comment..."}},"rollback": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 4a57edcdd8..3a3cbb6493 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1783,6 +1783,36 @@"guidance-suffix": "sin cambios","re-request-review": "vuelve a solicitar la revisión","title": "Rechazado por {{user}}"+ },+ "thread": {+ "add-comment": "Añadir comentario",+ "add-comment-on-line": "Añadir un comentario en la línea {{line}}",+ "add-comment-on-lines": "Añadir un comentario en las líneas {{startLine}} a {{endLine}}",+ "anchor": {+ "line_one": "Línea {{range}}",+ "line_other": "Líneas {{range}}",+ "outdated": "Obsoleto",+ "statement-unavailable": "Sentencia no disponible",+ "unavailable-change": "Cambio eliminado",+ "view-in-statement": "Ver en la sentencia"+ },+ "comment-on-lines": "Comentar las líneas",+ "comment-required": "Escribe un comentario antes de enviarlo.",+ "n-replies-hidden_one": "{{count}} respuesta oculta",+ "n-replies-hidden_other": "{{count}} respuestas ocultas",+ "n-replies_one": "{{count}} respuesta",+ "n-replies_other": "{{count}} respuestas",+ "publish": "Publicar",+ "reopen-with-comment": "Reabrir con comentario",+ "reply": "Responder",+ "reply-placeholder": "Responder...",+ "reply-posted-status-failed": "La respuesta se publicó, pero no se pudo actualizar el estado del hilo. Vuelve a intentar cambiar el estado.",+ "resolve": "Resolver",+ "resolve-with-comment": "Resolver con comentario",+ "resolved": "Resuelto",+ "threads-on-line_one": "{{count}} hilo en esta línea",+ "threads-on-line_other": "{{count}} hilos en esta línea",+ "write-comment": "Escribe un comentario..."}},"rollback": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex bd94f7e281..a707c84659 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1783,6 +1783,36 @@"guidance-suffix": "こともできます","re-request-review": "レビューを再依頼する","title": "{{user}} に却下されました"+ },+ "thread": {+ "add-comment": "コメントを追加",+ "add-comment-on-line": "{{line}} 行目にコメントを追加",+ "add-comment-on-lines": "{{startLine}}~{{endLine}} 行目にコメントを追加",+ "anchor": {+ "line_one": "{{range}} 行目",+ "line_other": "{{range}} 行",+ "outdated": "最新ではありません",+ "statement-unavailable": "ステートメントは利用できません",+ "unavailable-change": "削除された変更",+ "view-in-statement": "ステートメントで表示"+ },+ "comment-on-lines": "選択行にコメント",+ "comment-required": "送信する前にコメントを入力してください。",+ "n-replies-hidden_one": "{{count}} 件の返信が非表示",+ "n-replies-hidden_other": "{{count}} 件の返信が非表示",+ "n-replies_one": "{{count}} 件の返信",+ "n-replies_other": "{{count}} 件の返信",+ "publish": "公開",+ "reopen-with-comment": "コメントして再開",+ "reply": "返信",+ "reply-placeholder": "返信...",+ "reply-posted-status-failed": "返信は投稿されましたが、スレッドの状態を更新できませんでした。状態の変更を再試行してください。",+ "resolve": "解決",+ "resolve-with-comment": "コメントして解決",+ "resolved": "解決済み",+ "threads-on-line_one": "この行に {{count}} 件のスレッド",+ "threads-on-line_other": "この行に {{count}} 件のスレッド",+ "write-comment": "コメントを書く..."}},"rollback": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 8b153f580d..d929a33f27 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1783,6 +1783,36 @@"guidance-suffix": "mà không thay đổi","re-request-review": "yêu cầu xét duyệt lại","title": "Bị {{user}} từ chối"+ },+ "thread": {+ "add-comment": "Thêm bình luận",+ "add-comment-on-line": "Thêm bình luận vào dòng {{line}}",+ "add-comment-on-lines": "Thêm bình luận vào các dòng từ {{startLine}} đến {{endLine}}",+ "anchor": {+ "line_one": "Dòng {{range}}",+ "line_other": "Dòng {{range}}",+ "outdated": "Đã lỗi thời",+ "statement-unavailable": "Câu lệnh không khả dụng",+ "unavailable-change": "Thay đổi đã xóa",+ "view-in-statement": "Xem trong câu lệnh"+ },+ "comment-on-lines": "Bình luận các dòng đã chọn",+ "comment-required": "Nhập bình luận trước khi gửi.",+ "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",+ "publish": "Đăng",+ "reopen-with-comment": "Mở lại kèm bình luận",+ "reply": "Trả lời",+ "reply-placeholder": "Trả lời...",+ "reply-posted-status-failed": "Đã đăng phản hồi nhưng không thể cập nhật trạng thái chủ đề. Hãy thử lại thao tác cập nhật trạng thái.",+ "resolve": "Giải quyết",+ "resolve-with-comment": "Giải quyết kèm bình luận",+ "resolved": "Đã giải quyết",+ "threads-on-line_one": "{{count}} chủ đề trên dòng này",+ "threads-on-line_other": "{{count}} chủ đề trên dòng này",+ "write-comment": "Viết bình luận..."}},"rollback": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 18fecd99ee..02c4f24e58 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1783,6 +1783,36 @@"guidance-suffix": "(不做修改)","re-request-review": "重新发起审批","title": "被 {{user}} 拒绝"+ },+ "thread": {+ "add-comment": "添加评论",+ "add-comment-on-line": "在第 {{line}} 行添加评论",+ "add-comment-on-lines": "在第 {{startLine}} 至 {{endLine}} 行添加评论",+ "anchor": {+ "line_one": "第 {{range}} 行",+ "line_other": "第 {{range}} 行",+ "outdated": "已过期",+ "statement-unavailable": "语句不可用",+ "unavailable-change": "已删除的变更",+ "view-in-statement": "在语句中查看"+ },+ "comment-on-lines": "评论所选行",+ "comment-required": "请先填写评论再提交。",+ "n-replies-hidden_one": "已隐藏 {{count}} 条回复",+ "n-replies-hidden_other": "已隐藏 {{count}} 条回复",+ "n-replies_one": "{{count}} 条回复",+ "n-replies_other": "{{count}} 条回复",+ "publish": "发布",+ "reopen-with-comment": "回复并重新打开",+ "reply": "回复",+ "reply-placeholder": "回复...",+ "reply-posted-status-failed": "回复已发布,但讨论状态更新失败。请重试状态操作。",+ "resolve": "解决",+ "resolve-with-comment": "回复并解决",+ "resolved": "已解决",+ "threads-on-line_one": "此行有 {{count}} 个讨论",+ "threads-on-line_other": "此行有 {{count}} 个讨论",+ "write-comment": "撰写评论..."}},"rollback": {diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsxindex b3facea997..34d2586e65 100644--- a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx@@ -19,6 +19,7 @@ import { useProjectByName } from "@/hooks/useProjectByName";import { collectPlanUpdateSpecs } from "@/lib/plan/diffPlanSpecs";import { pushNotification } from "@/stores";import { useAppStore } from "@/stores/app";+import { isThreadReply } from "@/stores/app/issueComment";import { projectNamePrefix } from "@/stores/modules/v1/common";import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";import {@@ -75,9 +76,15 @@ export function IssueDetailCommentList() {const issueName = page.issue?.name || page.plan?.issue || "";// `getIssueComments` returns a stable empty array on miss, so reading it// inside the selector won't loop.- const issueComments = useAppStore((state) =>+ const cachedIssueComments = useAppStore((state) =>issueName ? state.getIssueComments(issueName) : EMPTY_ISSUE_COMMENTS);+ // Thread replies belong to the plan review surface; this list shows the+ // timeline entries only.+ const issueComments = useMemo(+ () => cachedIssueComments.filter((comment) => !isThreadReply(comment)),+ [cachedIssueComments]+ );const planUpdateSpecs = useMemo(() => collectPlanUpdateSpecs(issueComments),[issueComments]@@ -179,7 +186,7 @@ export function IssueDetailCommentList() {};const allowEditComment = (comment: IssueComment): boolean =>- canEditIssueComment(comment, currentUser.email, project);+ canEditIssueComment(comment, project);const startEditComment = (comment: IssueComment) => {setActiveCommentName(comment.name);diff --git a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsxindex c7954f70d1..3bed4b09d2 100644--- a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx+++ b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx@@ -23,6 +23,8 @@ import { PlanDetailDeployFuture } from "./components/PlanDetailDeployFuture";import { PlanDetailHeader } from "./components/PlanDetailHeader";import { PlanDetailHeaderDetails } from "./components/PlanDetailHeaderDetails";import { PlanReviewSection } from "./components/review/PlanReviewSection";+import { useIssueCommentThreadsSync } from "./hooks/useIssueCommentThreadsSync";+import { usePlacementSync } from "./hooks/usePlacementSync";import { PlanDetailStoreProvider } from "./shared/stores/PlanDetailStoreProvider";import { planPhaseAnchorId } from "./shell/focusPhase";import { usePlanDetailPage } from "./shell/hooks/usePlanDetailPage";@@ -106,6 +108,13 @@ function ProjectPlanDetailPageInner({stageId,taskId,});+ useIssueCommentThreadsSync(page.issue);+ usePlacementSync({+ issueName: page.issue?.name,+ projectId,+ ready: page.ready,+ specs: page.plan.specs,+ });const isGitOpsPlan = useMemo(() => isReleaseBackedPlan(page.plan.specs),[page.plan.specs]diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsxindex 2008d248b7..9d848c6052 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsx@@ -130,7 +130,7 @@ vi.mock("@/app/router", () => ({vi.mock("@/stores/app", () => {const getState = () => ({createSheet: vi.fn(),- fetchIssueCommentTimeline: vi.fn(),+ fetchIssueCommentThreads: vi.fn(),});return { useAppStore: { getState } };});diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsxindex 268083dcdb..605028ef89 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsx@@ -297,9 +297,8 @@ export function PlanDetailHeader() {// issue comments so the review timeline reflects it (like issue detail).await Promise.all([page.refreshState(),- useAppStore.getState().fetchIssueCommentTimeline({+ useAppStore.getState().fetchIssueCommentThreads({parent: issue.name,- pageSize: 1000,}),]);if (pageKeyRef.current !== actionPageKey) return;diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.tsxindex 008d47331f..d2f5641f79 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.tsx@@ -7,7 +7,12 @@ import {releaseServiceClientConnect,sheetServiceClientConnect,} from "@/api";-import { MonacoEditor, ReadonlyMonaco } from "@/components/monaco";+import {+ type IStandaloneCodeEditor,+ MonacoEditor,+ type MonacoModule,+ ReadonlyMonaco,+} from "@/components/monaco";import { ReleaseInfoCard } from "@/components/release/ReleaseInfoCard";import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";@@ -52,6 +57,26 @@ import {} from "../utils/localSheet";import { getSQLAdviceMarkers } from "../utils/sqlAdvice";import { SchemaEditorSheet } from "./SchemaEditorSheet";+import { StatementThreadsLayer } from "./threads/StatementThreadsLayer";+import { sheetSha256OfName } from "./threads/threadModel";++// Both modes reserve the same gutter so line numbers and SQL stay aligned+// when entering or leaving edit mode. Keep these options stable: MonacoEditor+// re-applies options on every new object.+const STATEMENT_EDITOR_OPTIONS = {+ glyphMargin: true,+ lineNumbersMinChars: 2,+ lineDecorationsWidth: 24,+ selectionHighlight: false,+ occurrencesHighlight: "off",+} as const;++// Sticky scroll would pin statement lines over the thread view zones.+const THREADS_EDITOR_OPTIONS = {+ ...STATEMENT_EDITOR_OPTIONS,+ selectOnLineNumbers: false,+ stickyScroll: { enabled: false },+} as const;export function PlanDetailStatementSection({className,@@ -93,6 +118,20 @@ export function PlanDetailStatementSection({const [draftStatement, setDraftStatement] = useState("");const [isSchemaEditorOpen, setIsSchemaEditorOpen] = useState(false);const inputRef = useRef<HTMLInputElement>(null);+ // The read-only editor instance, captured whenever one is created so the+ // threads layer can attach even if threads become enabled later. Editing,+ // an asynchronous sheet load, or an emptied statement unmounts and disposes+ // it; forget it whenever that happens so the layer never binds to a+ // disposed editor while the next one is still loading.+ const showsReadonlyEditor =+ !isLoading && !isEditing && Boolean(statement || draftStatement);+ const [readonlyEditor, setReadonlyEditor] = useState<{+ editor: IStandaloneCodeEditor;+ monaco: MonacoModule;+ }>();+ useEffect(() => {+ if (!showsReadonlyEditor) setReadonlyEditor(undefined);+ }, [showsReadonlyEditor]);const editingScope = useMemo(() => `statement:${spec.id}`, [spec.id]);const targetDatabaseName = useMemo(() => {@@ -443,6 +482,18 @@ export function PlanDetailStatementSection({const editorContent = page.isCreating ? statement : draftStatement;+ // Inline threads anchor to the saved sheet of a persisted spec, so they+ // need an issue, a content-addressed sheet, and the complete statement.+ const sheetSha256 = sheetSha256OfName(sheetName);+ const issue = page.issue;+ const threadsEnabled = Boolean(+ issue &&+ !page.isCreating &&+ !isPendingDraft &&+ sheetSha256 &&+ !isSheetOversize+ );+return (<div className={cn("flex flex-col gap-y-1", className)}><div className="flex items-start justify-between gap-2">@@ -549,7 +600,7 @@ export function PlanDetailStatementSection({<div className="rounded-sm border border-control-border bg-white px-4 py-3 text-sm text-control-light">{t("common.loading")}</div>- ) : statement || draftStatement || isEditing ? (+ ) : isEditing || showsReadonlyEditor ? (<div className="relative overflow-hidden rounded-sm border border-control-border">{isEditing ? (<MonacoEditor@@ -558,6 +609,7 @@ export function PlanDetailStatementSection({className="relative h-auto max-h-[600px] min-h-[120px]"content={editorContent}language={language}+ options={STATEMENT_EDITOR_OPTIONS}onChange={(nextStatement) => {if (page.isCreating) {updateLocalStatement(nextStatement);@@ -567,12 +619,32 @@ export function PlanDetailStatementSection({}}/>) : (- <ReadonlyMonaco- advices={markers}- className="relative h-auto max-h-[600px] min-h-[120px]"- content={statement}- language={language}- />+ <>+ <ReadonlyMonaco+ advices={markers}+ className="relative h-auto max-h-[600px] min-h-[120px]"+ content={statement}+ language={language}+ onReady={(monaco, editor) =>+ setReadonlyEditor({ editor, monaco })+ }+ options={+ threadsEnabled+ ? THREADS_EDITOR_OPTIONS+ : STATEMENT_EDITOR_OPTIONS+ }+ />+ {threadsEnabled && issue && sheetSha256 && readonlyEditor && (+ <StatementThreadsLayer+ editor={readonlyEditor.editor}+ issue={issue}+ key={sheetSha256}+ monaco={readonlyEditor.monaco}+ sheetSha256={sheetSha256}+ spec={spec}+ />+ )}+ </>)}</div>) : (diff --git a/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.test.tsx b/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.test.tsxindex 2777d0da90..d67d660681 100644--- a/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.test.tsx@@ -24,7 +24,7 @@ import { PlanReviewSection } from "./PlanReviewSection";const mocks = vi.hoisted(() => ({comments: [] as IssueComment[],getIssueComments: vi.fn((_issueName: string) => [] as IssueComment[]),- fetchIssueCommentTimeline: vi.fn(async () => ({ issueComments: [] })),+ fetchIssueCommentThreads: vi.fn(async () => []),getOrFetchProjectByName: vi.fn(async () => ({})),loadProjectIamPolicy: vi.fn(async () => ({})),getUserByIdentifier: vi.fn(() => undefined),@@ -89,7 +89,7 @@ vi.mock("@/stores/app", () => ({}),{getState: () => ({- fetchIssueCommentTimeline: mocks.fetchIssueCommentTimeline,+ fetchIssueCommentThreads: mocks.fetchIssueCommentThreads,getOrFetchProjectByName: mocks.getOrFetchProjectByName,loadProjectIamPolicy: mocks.loadProjectIamPolicy,getProjectByName: mocks.getProjectByName,diff --git a/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.tsx b/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.tsxindex 918cd039a9..e8dd9c6f95 100644--- a/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.tsx+++ b/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.tsx@@ -18,7 +18,6 @@ export function PlanReviewSection() {const page = usePlanDetailContext();const issue = page.issue;const issueName = issue?.name ?? "";- const issueUpdateKey = `${issue?.updateTime?.seconds ?? ""}:${issue?.updateTime?.nanos ?? ""}`;const loadProjectIamPolicy = useAppStore((state) => state.loadProjectIamPolicy);@@ -33,19 +32,6 @@ export function PlanReviewSection() {void loadProjectIamPolicy(projectName).catch(() => undefined);}, [loadProjectIamPolicy, page.projectId]);- // Refetch comments whenever the issue changes server-side (polling bumps- // updateTime) or after local actions refresh the issue.- useEffect(() => {- if (!issueName) return;- void useAppStore- .getState()- .fetchIssueCommentTimeline({- parent: issueName,- pageSize: 1000,- })- .catch(() => undefined);- }, [issueName, issueUpdateKey]);-const comments = useAppStore((state) =>issueName ? state.getIssueComments(issueName) : EMPTY_COMMENTS);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 2a1e53271d..bf79d06dc6 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@@ -4,8 +4,10 @@ import { createRoot } from "react-dom/client";import { describe, expect, test, vi } from "vitest";import {IssueComment_ReviewSubmissionSchema,+ IssueComment_ThreadState,IssueCommentSchema,IssueSchema,+ StatementAnchorSchema,} from "@/types/proto-es/v1/issue_service_pb";import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";@@ -20,6 +22,19 @@ vi.mock("react-i18next", () => ({}));vi.mock("@/components/issue-activity/IssueCommentActivity", () => ({+ ActivityRowFrame: ({+ children,+ icon,+ }: {+ children: ReactNode;+ icon: ReactNode;+ }) => (+ <li data-testid="thread-row">+ {icon}+ {children}+ </li>+ ),+ ActivityUserIcon: () => <span data-testid="user-icon" />,ActivityRowShell: ({header,icon,@@ -54,6 +69,11 @@ vi.mock("@/components/MarkdownEditor", () => ({vi.mock("@/hooks/useAppState", () => ({useCurrentUser: () => ({ email: "[email protected]" }),+ useUserByIdentifier: () => ({+ name: "users/[email protected]",+ email: "[email protected]",+ title: "Submitter",+ }),}));vi.mock("@/hooks/useProjectByName", () => ({@@ -69,11 +89,50 @@ vi.mock("@/stores/app", () => ({email: "[email protected]",title: "Submitter",}),+ sheetsByName: {},}),- { getState: () => ({}) }+ { getState: () => ({ getOrFetchSheetByName: async () => undefined }) }+ ),+}));++vi.mock("@/app/router", () => ({+ router: { push: vi.fn() },+}));++vi.mock("../../shared/stores/usePlanDetailStore", () => ({+ usePlanDetailStore: (selector: (state: unknown) => unknown) =>+ selector({+ selectedSpecId: undefined,+ placements: new Map(),+ placementTargets: new Map(),+ }),+ usePlanDetailStoreApi: () => ({+ getState: () => ({ requestThreadFocus: vi.fn() }),+ }),+}));++vi.mock("../threads/CommentThreadCard", () => ({+ CommentThreadCard: ({+ context,+ thread,+ }: {+ context: ReactNode;+ thread: { root: { name: string }; replies: { name: string }[] };+ }) => (+ <div+ data-replies={thread.replies.length}+ data-root={thread.root.name}+ data-testid="thread-card"+ >+ {context}+ </div>),}));+vi.mock("../threads/StatementAnchorContext", () => ({+ StatementAnchorContext: () => <div data-testid="anchor-context" />,+}));+vi.mock("@/stores", () => ({pushNotification: vi.fn(),}));@@ -162,4 +221,55 @@ describe("ReviewActivityTimeline", () => {act(() => root.unmount());});++ test("a thread root renders one card with its replies and never a reply row", () => {+ const issue = create(IssueSchema, {+ name: "projects/p1/issues/1",+ creator: "users/[email protected]",+ draft: false,+ });+ const plan = create(PlanSchema, { name: "projects/p1/plans/1" });+ const rootName = "projects/p1/issues/1/issueComments/root";+ const comments = [+ reviewSubmission("comments/submission"),+ create(IssueCommentSchema, {+ name: rootName,+ comment: "Root",+ creator: "users/[email protected]",+ threadState: IssueComment_ThreadState.OPEN,+ statementAnchor: create(StatementAnchorSchema, { spec: "spec-1" }),+ }),+ create(IssueCommentSchema, {+ name: "projects/p1/issues/1/issueComments/reply",+ comment: "Reply",+ creator: "users/[email protected]",+ root: rootName,+ }),+ create(IssueCommentSchema, {+ name: "projects/p1/issues/1/issueComments/general",+ comment: "General",+ creator: "users/[email protected]",+ }),+ ];+ const container = document.createElement("div");+ const root = createRoot(container);++ act(() => {+ root.render(+ <ReviewActivityTimeline comments={comments} issue={issue} plan={plan} />+ );+ });++ const card = container.querySelector("[data-testid='thread-card']");+ expect(card?.getAttribute("data-root")).toBe(rootName);+ expect(card?.getAttribute("data-replies")).toBe("1");+ expect(card?.querySelector("[data-testid='anchor-context']")).not.toBeNull();+ // submission row + thread row + general comment row+ expect(container.querySelectorAll("li")).toHaveLength(3);+ expect(+ container.querySelectorAll("[data-testid='comment-row']")+ ).toHaveLength(1);++ act(() => root.unmount());+ });});diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsxindex 1a03003035..4dd44096fa 100644--- a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx@@ -1,4 +1,4 @@-import { FileText, Loader2, Pencil } from "lucide-react";+import { FileText, Loader2, MessagesSquare, Pencil } from "lucide-react";import {type ReactNode,useCallback,@@ -8,8 +8,11 @@ import {useState,} from "react";import { useTranslation } from "react-i18next";+import { router } from "@/app/router";+import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/app/router/handles";import { HumanizeTs } from "@/components/HumanizeTs";import {+ ActivityRowFrame,ActivityRowShell,CommentCreator,CommentIconBadge,@@ -21,7 +24,6 @@ import {} from "@/components/issue-activity/IssueCommentActivity";import { MarkdownEditor } from "@/components/MarkdownEditor";import { Button } from "@/components/ui/button";-import { useCurrentUser } from "@/hooks/useAppState";import { useProjectByName } from "@/hooks/useProjectByName";import {collectPlanUpdateSpecs,@@ -32,6 +34,7 @@ import { useAppStore } from "@/stores/app";import {getIssueCommentType,IssueCommentType,+ isThreadRoot,} from "@/stores/app/issueComment";import { projectNamePrefix } from "@/stores/modules/v1/common";import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";@@ -39,8 +42,21 @@ import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";import type { Plan } from "@/types/proto-es/v1/plan_service_pb";import { hasProjectPermissionV2 } from "@/utils/iam/permission";import { usePlanChangeReferenceData } from "../../hooks/usePlanChangeReferenceData";+import { placementOf } from "../../shared/stores/placementSlice";+import {+ usePlanDetailStore,+ usePlanDetailStoreApi,+} from "../../shared/stores/usePlanDetailStore";+import { focusPlanPhase } from "../../shell/focusPhase";import { usePlanDetailContext } from "../../shell/PlanDetailContext";import { PlanSpecChangeReference } from "../PlanChangeReference";+import { CommentThreadCard } from "../threads/CommentThreadCard";+import { StatementAnchorContext } from "../threads/StatementAnchorContext";+import {+ type CommentThread,+ groupThreads,+ targetSha256OfSpec,+} from "../threads/threadModel";import { consolidateConsecutive } from "./consolidateTimeline";import { foldTimeline } from "./foldTimeline";import { ReviewCommentComposer } from "./ReviewCommentComposer";@@ -67,7 +83,14 @@ export function ReviewActivityTimeline({() => collectPlanUpdateSpecs(comments),[comments]);- const changeReferenceResources = usePlanChangeReferenceData(planUpdateSpecs);+ const threads = useMemo(() => groupThreads(comments), [comments]);+ // Anchored threads reference the plan's current specs; hydrate them once+ // here rather than once per card.+ const referenceSpecs = useMemo(+ () => [...planUpdateSpecs, ...plan.specs],+ [planUpdateSpecs, plan.specs]+ );+ const changeReferenceResources = usePlanChangeReferenceData(referenceSpecs);const renderPlanChangeReference = useCallback<PlanChangeReferenceRenderer>(({ siblings, spec }) => (<PlanSpecChangeReference@@ -141,6 +164,7 @@ export function ReviewActivityTimeline({key={item.entry.id}plan={plan}renderPlanChangeReference={renderPlanChangeReference}+ threads={threads}/>);})}@@ -190,11 +214,11 @@ function TornSeparator({className="group shrink-0 bg-background px-2 text-control-light hover:text-control"onClick={onShowAll}size="xs"- appearance="link"+ appearance="secondary">{t("plan.review.activity.n-hidden-events", { count })}<span className="mx-1 text-control-placeholder">·</span>- <span className="text-accent group-hover:underline">+ <span className="text-accent group-hover:text-accent-hover">{t("plan.review.activity.show-all")}</span></Button>@@ -209,14 +233,32 @@ function ActivityRow({isLast,plan,renderPlanChangeReference,+ threads,}: {entry: TimelineEntry;issue: Issue;isLast: boolean;plan: Plan;renderPlanChangeReference: PlanChangeReferenceRenderer;+ threads: CommentThread[];}) {const source = entry.source;+ if (source.type === "comment" && isThreadRoot(source.comment)) {+ const thread = threads.find(+ (candidate) => candidate.root.name === source.comment.name+ );+ if (thread) {+ return (+ <ThreadActivityRow+ isLast={isLast}+ issue={issue}+ plan={plan}+ renderPlanChangeReference={renderPlanChangeReference}+ thread={thread}+ />+ );+ }+ }if (source.type === "comment") {return (<ReviewCommentRow@@ -277,7 +319,7 @@ function SyntheticHeader({)}{source.time && (<HumanizeTs- className="text-control-light"+ className="text-xs text-control-light"ts={getTimeForPbTimestampProtoEs(source.time, 0) / 1000}/>)}@@ -309,7 +351,6 @@ function ReviewCommentRow({}) {const { t } = useTranslation();const page = usePlanDetailContext();- const currentUser = useCurrentUser();const project = useProjectByName(`${projectNamePrefix}${page.projectId}`);const [isEditing, setIsEditing] = useState(false);const [editContent, setEditContent] = useState(comment.comment);@@ -331,7 +372,7 @@ function ReviewCommentRow({}}, [comment.comment, isEditing]);- const allowEdit = canEditIssueComment(comment, currentUser.email, project);+ const allowEdit = canEditIssueComment(comment, project);const save = async () => {if (!editContent || editContent === comment.comment) {@@ -440,3 +481,90 @@ function ReviewCommentRow({/>);}++// A thread occupies one timeline entry at its root's position: the root with+// its statement anchor, the replies, and the thread footer, in one card.+function ThreadActivityRow({+ isLast,+ issue,+ plan,+ renderPlanChangeReference,+ thread,+}: {+ isLast: boolean;+ issue: Issue;+ plan: Plan;+ renderPlanChangeReference: PlanChangeReferenceRenderer;+ thread: CommentThread;+}) {+ const page = usePlanDetailContext();+ const project = useProjectByName(`${projectNamePrefix}${page.projectId}`);+ 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)+ ),+ [anchor?.spec, plan.specs]+ );+ const placement = usePlanDetailStore((s) =>+ anchor+ ? placementOf(s, thread.root.name, anchor.spec, targetSha256)+ : undefined+ );++ // Open the Changes phase on the anchored spec; the statement editor picks+ // up the focus request once it shows that spec.+ const viewInStatement = () => {+ const specId = anchor?.spec;+ if (!specId) return;+ storeApi.getState().requestThreadFocus({+ commentName: thread.root.name,+ specId,+ });+ focusPlanPhase("changes", page.expandPhase);+ if (selectedSpecId !== specId) {+ void router.push(+ {+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ params: { planId: page.planId, projectId: page.projectId, specId },+ },+ { preventScrollReset: true }+ );+ }+ };++ return (+ <ActivityRowFrame+ icon={+ <CommentIconBadge+ className="bg-control-bg text-control"+ icon={<MessagesSquare className="size-4" />}+ />+ }+ id={thread.root.name}+ isLast={isLast}+ >+ <CommentThreadCard+ className="ml-3"+ context={+ anchor && (+ <StatementAnchorContext+ anchor={anchor}+ onViewInStatement={viewInStatement}+ placement={placement}+ plan={plan}+ renderPlanChangeReference={renderPlanChangeReference}+ project={project}+ />+ )+ }+ issueName={issue.name}+ project={project}+ thread={thread}+ />+ </ActivityRowFrame>+ );+}diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewCommentComposer.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewCommentComposer.tsxindex 9985b3b587..1afd58cfdc 100644--- a/frontend/src/routes/project/plan-detail/components/review/ReviewCommentComposer.tsx+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewCommentComposer.tsx@@ -63,6 +63,7 @@ export function ReviewCommentComposer({ issueName }: { issueName: string }) {<div className="flex items-center gap-x-3"><div className="shrink-0 pl-0.5"><UserAvatar+ colorSeed={currentUser.email}size="sm"title={currentUser.title || currentUser.email}/>@@ -83,7 +84,11 @@ export function ReviewCommentComposer({ issueName }: { issueName: string }) {return (<div className="flex items-start gap-x-3"><div className="shrink-0 pl-0.5 pt-1">- <UserAvatar size="sm" title={currentUser.title || currentUser.email} />+ <UserAvatar+ colorSeed={currentUser.email}+ size="sm"+ title={currentUser.title || currentUser.email}+ /></div><div className="min-w-0 flex-1"><MarkdownEditordiff --git a/frontend/src/routes/project/plan-detail/components/review/timelineEvents.ts b/frontend/src/routes/project/plan-detail/components/review/timelineEvents.tsindex 626937de94..21b6279fd0 100644--- a/frontend/src/routes/project/plan-detail/components/review/timelineEvents.ts+++ b/frontend/src/routes/project/plan-detail/components/review/timelineEvents.ts@@ -3,6 +3,7 @@// card or a one-line system row is decided at render time by body presence,// so no weight/tier is stored here. Plan check results are never entries.import type { Timestamp } from "@bufbuild/protobuf/wkt";+import { isThreadReply } from "@/stores/app/issueComment";import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";export type TimelineSource =@@ -52,6 +53,8 @@ export function buildTimelineEntries(input: {});}for (const comment of input.comments) {+ // Replies render inside their thread's entry, never as their own row.+ if (isThreadReply(comment)) continue;if (comment.event.case === "reviewSubmission") {if (comment === reviewSubmission) {entries.push({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.tsxnew file mode 100644index 0000000000..0308e04144--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsx@@ -0,0 +1,526 @@+import { create } from "@bufbuild/protobuf";+import { TimestampSchema } from "@bufbuild/protobuf/wkt";+import { act, useState } from "react";+import { createRoot, type Root } from "react-dom/client";+import { MonacoViewZoneRevealContext } from "@/components/monaco/MonacoViewZone";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import {+ IssueComment_ThreadState,+ IssueCommentSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";++const mocks = vi.hoisted(() => ({+ createIssueComment: vi.fn(),+ notify: vi.fn(),+ updateIssueComment: vi.fn(),+ hasPermission: vi.fn((_project: unknown, _permission: unknown) => true),+}));++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({+ t: (key: string, options?: { count?: number }) =>+ options?.count !== undefined ? `${key}:${options.count}` : key,+ }),+}));++vi.mock("@/components/HumanizeTs", () => ({ HumanizeTs: () => null }));++// The activity module drags Monaco into the test; only the edit rule matters.+vi.mock("@/components/issue-activity/IssueCommentActivity", () => ({+ canEditIssueComment: () => true,+}));++vi.mock("@/components/MarkdownEditor", () => ({+ MarkdownEditor: ({+ content,+ autoFocus,+ mode,+ onChange,+ onSubmit,+ placeholder,+ }: {+ content: string;+ autoFocus?: boolean;+ mode?: string;+ onChange?: (value: string) => void;+ onSubmit?: () => void;+ placeholder?: string;+ }) =>+ mode === "preview" ? (+ <p data-testid="preview">{content}</p>+ ) : (+ <textarea+ autoFocus={autoFocus}+ onChange={(event) => onChange?.(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) onSubmit?.();+ }}+ placeholder={placeholder}+ value={content}+ />+ ),+}));++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],+ }),+}));++vi.mock("@/stores", () => ({+ pushNotification: mocks.notify,+ extractUserEmail: (identifier: string) => identifier.replace(/^users\//, ""),+}));++vi.mock("@/stores/app", () => ({+ useAppStore: Object.assign(+ (selector: (state: unknown) => unknown) =>+ selector({+ getUserByIdentifier: (principal: string) => ({+ name: principal,+ email: principal.replace(/^users\//, ""),+ title: principal.replace(/^users\//, "").split("@")[0],+ }),+ }),+ {+ getState: () => ({+ createIssueComment: mocks.createIssueComment,+ updateIssueComment: mocks.updateIssueComment,+ }),+ }+ ),+}));++vi.mock("@/utils/iam/permission", () => ({+ hasProjectPermissionV2: (project: unknown, permission: unknown) =>+ mocks.hasPermission(project, permission),+}));++import { CommentThreadCard } from "./CommentThreadCard";+import { groupThreads } from "./threadModel";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const ISSUE = "projects/p/issues/1";+const project = { name: "projects/p" } as Project;++const comment = (+ id: string,+ text: string,+ extra: { root?: string; resolved?: boolean; creator?: string } = {}+) =>+ create(IssueCommentSchema, {+ name: `${ISSUE}/issueComments/${id}`,+ comment: text,+ creator: extra.creator ?? "users/[email protected]",+ createTime: create(TimestampSchema, { seconds: BigInt(1) }),+ updateTime: create(TimestampSchema, { seconds: BigInt(1) }),+ root: extra.root,+ threadState:+ extra.root !== undefined+ ? undefined+ : extra.resolved+ ? IssueComment_ThreadState.RESOLVED+ : IssueComment_ThreadState.OPEN,+ });++const rootName = `${ISSUE}/issueComments/root`;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ HTMLElement.prototype.scrollIntoView = vi.fn();+ vi.clearAllMocks();+ mocks.hasPermission.mockReturnValue(true);+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ Reflect.deleteProperty(HTMLElement.prototype, "scrollIntoView");+});++const render = (ui: React.ReactElement) => act(() => root.render(ui));++const click = (element: Element | null | undefined) => {+ if (!element) throw new Error("element not found");+ act(() => {+ element.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+};++const buttonByText = (text: string) =>+ Array.from(container.querySelectorAll("button")).find((button) =>+ button.textContent?.includes(text)+ );++const chooseReplyAction = (action = "reply") => {+ click(container.querySelector('button[aria-label="common.actions"]'));+ const item = Array.from(document.querySelectorAll('[role="menuitem"]'))+ .find((el) => el.textContent === `plan.review.thread.${action}`);+ click(item);+ expect(mocks.createIssueComment).not.toHaveBeenCalled();+ expect(mocks.updateIssueComment).not.toHaveBeenCalled();+ click(buttonByText(`plan.review.thread.${action}`));+};++describe("CommentThreadCard", () => {+ test("places statement context above the root author as a separate full-width region", () => {+ const [thread] = groupThreads([comment("root", "Root question")]);+ render(+ <CommentThreadCard+ issueName={ISSUE}+ project={project}+ thread={thread}+ context={<div data-testid="anchor-context">SELECT 1;</div>}+ />+ );+ const card = container.querySelector("[data-testid='comment-thread']");+ const anchor = container.querySelector("[data-testid='anchor-context']");+ const rootComment = container.querySelector("[data-testid='thread-comment']");+ expect(card?.firstElementChild?.contains(anchor)).toBe(true);+ expect(rootComment?.contains(anchor)).toBe(false);+ expect(anchor?.compareDocumentPosition(rootComment!)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING+ );+ });++ test("renders the root and replies oldest first with the thread footer", () => {+ const [thread] = groupThreads([+ comment("root", "Root question"),+ comment("r2", "Second reply", { root: rootName }),+ comment("r1", "First reply", { root: rootName }),+ ]);+ render(+ <CommentThreadCard issueName={ISSUE} project={project} thread={thread} />+ );+ const bodies = Array.from(+ container.querySelectorAll("[data-testid='preview']")+ ).map((node) => node.textContent);+ expect(bodies).toEqual(["Root question", "First reply", "Second reply"]);+ expect(container.querySelector("[data-thread-state]")?.getAttribute("data-thread-state")).toBe("open");+ expect(buttonByText("plan.review.thread.resolve")).toBeDefined();+ expect(buttonByText("plan.review.thread.reply-placeholder")).toBeDefined();+ });++ test("a resolved thread collapses to a summary and expands in place", () => {+ const [thread] = groupThreads([+ comment("root", "Root", { resolved: true }),+ comment("r1", "Reply", { root: rootName, creator: "users/[email protected]" }),+ ]);+ render(+ <CommentThreadCard issueName={ISSUE} project={project} thread={thread} />+ );+ expect(container.textContent).toContain("plan.review.thread.n-replies:1");+ expect(container.querySelector("[data-testid='preview']")).toBeNull();++ click(buttonByText("plan.review.thread.resolved"));+ expect(+ container.querySelectorAll("[data-testid='preview']")+ ).toHaveLength(2);+ expect(buttonByText("common.reopen")).toBeDefined();+ expect(buttonByText("plan.review.thread.resolve")).toBeUndefined();+ });++ test("roots and replies share header avatars and a full-width body", () => {+ const [thread] = groupThreads([comment("root", "Root"), comment("r1", "Reply", { root: rootName })]);+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} />);+ const comments = container.querySelectorAll("[data-testid='thread-comment']");+ for (const comment of comments) {+ const content = comment.querySelector("[data-testid='comment-content']");+ const avatar = comment.querySelector("[data-testid='comment-avatar']");+ expect(content?.firstElementChild?.contains(avatar)).toBe(true);+ expect(content?.querySelector("[data-testid='preview']")).not.toBeNull();+ }+ expect(container.querySelector("[data-testid='reply-composer-avatar']")).toBeNull();+ click(buttonByText("plan.review.thread.reply-placeholder"));+ expect(container.querySelector("[data-testid='reply-composer-avatar']")).not.toBeNull();+ click(buttonByText("common.cancel"));+ expect(container.querySelector("[data-testid='reply-composer-avatar']")).toBeNull();+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} />);+ expect(container.querySelector("[data-testid='thread-comment'] [data-testid='comment-avatar']")).not.toBeNull();+ });++ test("new replies do not hide replies already visible in a short thread", () => {+ const replies = Array.from({ length: 6 }, (_, index) => comment(`r${index}`, `Reply ${index}`, { root: rootName }));+ const [short] = groupThreads([comment("root", "Root"), ...replies.slice(0, 4)]);+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={short} />);+ expect(container.querySelectorAll("[data-testid='preview']")).toHaveLength(5);+ const [long] = groupThreads([comment("root", "Root"), ...replies]);+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={long} />);+ expect(container.querySelectorAll("[data-testid='preview']")).toHaveLength(7);+ });++ test("folds long threads and shows the tail until expanded", () => {+ const replies = Array.from({ length: 6 }, (_, i) =>+ comment(`r${i}`, `Reply ${i}`, { root: rootName })+ );+ const [thread] = groupThreads([comment("root", "Root"), ...replies]);+ render(+ <CommentThreadCard issueName={ISSUE} project={project} thread={thread} />+ );+ const visible = () =>+ Array.from(container.querySelectorAll("[data-testid='preview']")).map(+ (node) => node.textContent+ );+ expect(visible()).toEqual(["Root", "Reply 4", "Reply 5"]);+ expect(container.textContent).toContain(+ "plan.review.thread.n-replies-hidden:4"+ );+ click(buttonByText("plan.review.activity.show-all"));+ expect(visible()).toHaveLength(7);+ });++ test("replying creates a reply on the root and resolving updates the thread state", async () => {+ const [thread] = groupThreads([comment("root", "Root")]);+ mocks.createIssueComment.mockResolvedValue(+ comment("new", "Sounds good", { root: rootName })+ );+ mocks.updateIssueComment.mockResolvedValue(+ comment("root", "Root", { resolved: true })+ );+ render(+ <CommentThreadCard issueName={ISSUE} project={project} thread={thread} />+ );++ click(buttonByText("plan.review.thread.reply-placeholder"));+ const textarea = container.querySelector("textarea");+ expect(textarea?.placeholder).toBe("plan.review.thread.reply-placeholder");+ act(() => {+ const setter = Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype,+ "value"+ )?.set;+ setter?.call(textarea, "Sounds good");+ textarea?.dispatchEvent(new Event("input", { bubbles: true }));+ });+ chooseReplyAction();+ await act(async () => {});+ expect(mocks.createIssueComment).toHaveBeenCalledWith({+ issueName: ISSUE,+ comment: "Sounds good",+ root: rootName,+ });+ // The reply box collapses after a successful post.+ expect(container.querySelector("textarea")).toBeNull();++ click(buttonByText("plan.review.thread.resolve"));+ await act(async () => {});+ expect(mocks.updateIssueComment).toHaveBeenCalledWith({+ issueCommentName: rootName,+ threadState: IssueComment_ThreadState.RESOLVED,+ });+ });++ test.each([false, true])("notifies the owner after a successful local state change: resolved=%s", async (resolved) => {+ const [thread] = groupThreads([comment("root", "Root", { resolved })]);+ const onThreadStateChanged = vi.fn();+ mocks.updateIssueComment.mockResolvedValue(comment("root", "Root", { resolved: !resolved }));+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} collapsible={false} onThreadStateChanged={onThreadStateChanged} />);+ click(buttonByText(resolved ? "common.reopen" : "plan.review.thread.resolve"));+ await act(async () => {});+ expect(onThreadStateChanged).toHaveBeenCalledExactlyOnceWith(!resolved);+ });++ test("does not advance on failure or a remote state refresh", async () => {+ const [thread] = groupThreads([comment("root", "Root")]);+ const onThreadStateChanged = vi.fn();+ mocks.updateIssueComment.mockRejectedValueOnce(new Error("offline"));+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} collapsible={false} onThreadStateChanged={onThreadStateChanged} />);+ click(buttonByText("plan.review.thread.resolve"));+ await act(async () => {});+ expect(onThreadStateChanged).not.toHaveBeenCalled();+ const [updated] = groupThreads([comment("root", "Root", {resolved: true})]);+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={updated} collapsible={false} onThreadStateChanged={onThreadStateChanged} />);+ expect(onThreadStateChanged).not.toHaveBeenCalled();+ expect(container.querySelector("[data-testid='preview']")).not.toBeNull();+ });++ test("does not advance if the user leaves the card before Resolve completes", async () => {+ const [thread] = groupThreads([comment("root", "Root")]);+ const onThreadStateChanged = vi.fn();+ let complete!: (value: ReturnType<typeof comment>) => void;+ mocks.updateIssueComment.mockReturnValueOnce(new Promise((resolve) => {complete = resolve;}));+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} collapsible={false} onThreadStateChanged={onThreadStateChanged} />);+ click(buttonByText("plan.review.thread.resolve"));+ render(<div />);+ await act(async () => {complete(comment("root", "Root", {resolved: true}));});+ expect(onThreadStateChanged).not.toHaveBeenCalled();+ });++ test.each([false, true])("posts the reply before changing status: initially resolved=%s", async (resolved) => {+ const [thread] = groupThreads([comment("root", "Root", {resolved})]);+ let finishReply!: (value: ReturnType<typeof comment>) => void;+ let finishState!: (value: ReturnType<typeof comment>) => void;+ mocks.createIssueComment.mockImplementationOnce(() => new Promise((resolve) => {finishReply = resolve;}));+ mocks.updateIssueComment.mockImplementationOnce(() => new Promise((resolve) => {finishState = resolve;}));+ const onReplyDraftChange = vi.fn();+ const onThreadStateChanged = vi.fn();+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} collapsible={false} replyDraft="Decision details" onReplyDraftChange={onReplyDraftChange} onThreadStateChanged={onThreadStateChanged} />);+ chooseReplyAction(resolved ? "reopen-with-comment" : "resolve-with-comment");+ expect(mocks.createIssueComment).toHaveBeenCalledExactlyOnceWith({issueName: ISSUE, root: rootName, comment: "Decision details"});+ expect(mocks.updateIssueComment).not.toHaveBeenCalled();+ await act(async () => {finishReply(comment("reply", "Decision details", {root: rootName}));});+ expect(onReplyDraftChange).toHaveBeenCalledWith(expect.any(Function));+ expect(mocks.updateIssueComment).toHaveBeenCalledExactlyOnceWith({issueCommentName: rootName, threadState: resolved ? IssueComment_ThreadState.OPEN : IssueComment_ThreadState.RESOLVED});+ expect(buttonByText(resolved ? "common.reopen" : "plan.review.thread.resolve")?.disabled).toBe(true);+ expect(onThreadStateChanged).not.toHaveBeenCalled();+ await act(async () => {finishState(comment("root", "Root", {resolved: !resolved}));});+ expect(onThreadStateChanged).toHaveBeenCalledExactlyOnceWith(!resolved);+ });++ test("reply failure preserves the draft and never changes status", async () => {+ const [thread] = groupThreads([comment("root", "Root")]);+ const onReplyDraftChange = vi.fn();+ mocks.createIssueComment.mockRejectedValueOnce(new Error("offline"));+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} replyDraft="Keep this draft" onReplyDraftChange={onReplyDraftChange} />);+ chooseReplyAction("resolve-with-comment");+ await act(async () => {});+ expect(mocks.updateIssueComment).not.toHaveBeenCalled();+ expect(onReplyDraftChange).not.toHaveBeenCalled();+ expect(container.querySelector("textarea")?.value).toBe("Keep this draft");+ });++ test("a failed status update can be retried without creating another reply", async () => {+ const [thread] = groupThreads([comment("root", "Root")]);+ const onThreadStateChanged = vi.fn();+ const onReplyDraftChange = vi.fn();+ mocks.createIssueComment.mockResolvedValueOnce(comment("reply", "Posted", {root: rootName}));+ mocks.updateIssueComment.mockRejectedValueOnce(new Error("status update failed"));+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} replyDraft="Posted" onReplyDraftChange={onReplyDraftChange} onThreadStateChanged={onThreadStateChanged} />);+ chooseReplyAction("resolve-with-comment");+ await act(async () => {});+ expect(onReplyDraftChange).toHaveBeenCalledWith(expect.any(Function));+ expect(onThreadStateChanged).not.toHaveBeenCalled();+ expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({title: "plan.review.thread.reply-posted-status-failed"}));+ expect(container.querySelector("textarea")).toBeNull();+ mocks.updateIssueComment.mockResolvedValueOnce(comment("root", "Root", {resolved: true}));+ click(buttonByText("plan.review.thread.resolve"));+ await act(async () => {});+ expect(mocks.createIssueComment).toHaveBeenCalledTimes(1);+ expect(mocks.updateIssueComment).toHaveBeenCalledTimes(2);+ expect(onThreadStateChanged).toHaveBeenCalledExactlyOnceWith(true);+ });++ test("without settle permission the submission menu only offers Reply", () => {+ mocks.hasPermission.mockImplementation((_project, permission) => permission === "bb.issueComments.create");+ const [thread] = groupThreads([comment("root", "Root")]);+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} replyDraft="Reply only" onReplyDraftChange={vi.fn()} />);+ click(container.querySelector('button[aria-label="common.actions"]'));+ expect(Array.from(document.querySelectorAll('[role="menuitem"]')).map((el) => el.textContent)).toEqual(["plan.review.thread.reply"]);+ });++ test("authoring the root grants no Resolve without the update permission", () => {+ mocks.hasPermission.mockImplementation(+ (_project: unknown, permission: unknown) =>+ permission === "bb.issueComments.create"+ );+ const [thread] = groupThreads([+ comment("root", "Root", { creator: "users/[email protected]" }),+ ]);+ render(+ <CommentThreadCard issueName={ISSUE} project={project} thread={thread} />+ );+ expect(buttonByText("plan.review.thread.resolve")).toBeUndefined();+ });++ test("hides Resolve from users who may neither update nor own the root", () => {+ mocks.hasPermission.mockImplementation(+ (_project: unknown, permission: unknown) =>+ permission === "bb.issueComments.create"+ );+ const [thread] = groupThreads([comment("root", "Root")]);+ render(+ <CommentThreadCard issueName={ISSUE} project={project} thread={thread} />+ );+ expect(buttonByText("plan.review.thread.reply-placeholder")).toBeDefined();+ expect(buttonByText("plan.review.thread.resolve")).toBeUndefined();+ });+});+++test.each(["ctrlKey", "metaKey"])("ignores %s+Enter while a reply is pending", async (modifier) => {+ const [thread] = groupThreads([comment("root", "Root question")]);+ let complete!: (value: ReturnType<typeof comment>) => void;+ mocks.createIssueComment.mockImplementationOnce(() => new Promise(resolve => {complete = resolve;}));+ const onReplyDraftChange = vi.fn();+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} replyDraft="My reply" onReplyDraftChange={onReplyDraftChange} />);+ chooseReplyAction();+ expect(mocks.createIssueComment).toHaveBeenCalledTimes(1);+ expect(buttonByText("plan.review.thread.reply")?.disabled).toBe(true);+ act(() => {container.querySelector("textarea")!.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", [modifier]: true, bubbles: true}));});+ expect(mocks.createIssueComment).toHaveBeenCalledTimes(1);+ await act(async () => {complete(comment("reply", "My reply", {root: rootName}));});+ expect(onReplyDraftChange).toHaveBeenCalledWith(expect.any(Function));+});+++test.each(["reply", "resolve-with-comment", "reopen-with-comment"])("validates an empty comment after clicking %s", (action) => {+ const [thread] = groupThreads([comment("root", "Root", {resolved: action === "reopen-with-comment"})]);+ const props = {issueName: ISSUE, project, thread, collapsible: false, onReplyDraftChange: vi.fn()};+ render(<CommentThreadCard {...props} replyDraft=" " />);+ expect(document.querySelector('[role="alert"]')).toBeNull();+ chooseReplyAction(action);+ expect(buttonByText(`plan.review.thread.${action}`)?.disabled).toBe(false);+ expect(document.querySelector('[role="alert"]')?.textContent).toBe("plan.review.thread.comment-required");+ expect(container.querySelector('[role="alert"]')).toBeNull();+ expect(mocks.createIssueComment).not.toHaveBeenCalled();+ expect(mocks.updateIssueComment).not.toHaveBeenCalled();+ render(<CommentThreadCard {...props} replyDraft="Now with a comment" />);+ expect(document.querySelector('[role="alert"]')).toBeNull();+ render(<CommentThreadCard {...props} replyDraft="" />);+ expect(document.querySelector('[role="alert"]')).toBeNull();+});+++test.each([+ { remount: true, nextDraft: "My next reply", expected: "My next reply" },+ { remount: true, nextDraft: "First reply", expected: "" },+ { remount: false, nextDraft: "My next reply", expected: "My next reply" },+])("clears only the submitted draft: $remount / $nextDraft", async ({remount, nextDraft, expected}) => {+ const [thread] = groupThreads([comment("root", "Root")]);+ let finish!: (value: ReturnType<typeof comment>) => void;+ let changeDraft!: (value: string) => void;+ mocks.createIssueComment.mockReturnValueOnce(new Promise(resolve => { finish = resolve; }));+ function DraftOwner({ visible }: { visible: boolean }) {+ const [draft, setDraft] = useState("First reply");+ changeDraft = setDraft;+ return visible ? <CommentThreadCard issueName={ISSUE} project={project} thread={thread} collapsible={false} replyDraft={draft} onReplyDraftChange={setDraft} /> : null;+ }+ render(<DraftOwner visible />);+ click(buttonByText("plan.review.thread.reply"));+ expect(mocks.createIssueComment).toHaveBeenCalledTimes(1);+ if (remount) {+ render(<DraftOwner visible={false} />);+ render(<DraftOwner visible />);+ }+ act(() => changeDraft(nextDraft));+ await act(async () => { finish(comment("posted", "First reply", {root:rootName})); });+ expect(container.querySelector("textarea")?.value).toBe(expected);+});+++test("focuses and reveals the reply footer once when opened in Monaco", () => {+ const [thread] = groupThreads([comment("root", "Root")]);+ const reveal = vi.fn();+ const view = (draft: string) => <MonacoViewZoneRevealContext value={reveal}><CommentThreadCard issueName={ISSUE} project={project} thread={thread} replyDraft={draft} onReplyDraftChange={vi.fn()} /></MonacoViewZoneRevealContext>;+ render(view(""));+ expect(reveal).not.toHaveBeenCalled();+ click(buttonByText("plan.review.thread.reply-placeholder"));+ expect(document.activeElement).toBe(container.querySelector("textarea"));+ expect(reveal).toHaveBeenCalledExactlyOnceWith(container.querySelector('[data-testid="thread-reply-footer"]'));+ expect(HTMLElement.prototype.scrollIntoView).not.toHaveBeenCalled();+ render(view("Typing a reply"));+ expect(reveal).toHaveBeenCalledTimes(1);+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsx b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsxnew file mode 100644index 0000000000..dd494a513c--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsx@@ -0,0 +1,486 @@+import {+ Check,+ ChevronDown,+ ChevronUp,+ CircleCheck,+ Loader2,+ RotateCcw,+} from "lucide-react";+import {+ type ReactNode,+ type SetStateAction,+ useContext,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { useTranslation } from "react-i18next";+import { HumanizeTs } from "@/components/HumanizeTs";+import { MarkdownEditor } from "@/components/MarkdownEditor";+import { MonacoViewZoneRevealContext } from "@/components/monaco/MonacoViewZone";+import { UserAvatar } from "@/components/UserAvatar";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Popover, PopoverContent } from "@/components/ui/popover";+import { useCurrentUser, useUserByIdentifier } from "@/hooks/useAppState";+import { cn } from "@/lib/utils";+import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";+import type { Project } from "@/types/proto-es/v1/project_service_pb";+import { ThreadComment } from "./ThreadComment";+import type { CommentThread } from "./threadModel";+import {+ canReplyToThread,+ canSettleThread,+ useThreadActions,+} from "./useThreadActions";++// A long thread keeps its tail visible and folds the middle behind a count.+const VISIBLE_TAIL_REPLIES = 2;+const FOLD_REPLIES_ABOVE = 4;+type ReplyAction = "reply" | "resolve" | "reopen";++// The same thread presentation for the statement editor and the Review+// Activity timeline: root and replies in one card, Reply and Resolve or Reopen+// in the footer. Resolved threads collapse to a summary row.+export function CommentThreadCard({+ className,+ collapsible = true,+ context,+ issueName,+ label,+ onClose,+ onThreadStateChanged,+ replyDraft: savedReplyDraft,+ onReplyDraftChange,+ project,+ thread,+}: {+ className?: string;+ // Whether a resolved thread may collapse to its summary row.+ collapsible?: boolean;+ // Full-width statement context above the root author and discussion.+ context?: ReactNode;+ issueName: string;+ // Extra header text after the timestamp (the anchored line range).+ label?: ReactNode;+ // Editor placement: closes the expanded thread back to its marker.+ onClose?: () => void;+ // Fired only after this card successfully changes state, never on refresh.+ onThreadStateChanged?: (resolved: boolean) => void;+ replyDraft?: string;+ onReplyDraftChange?: (draft: SetStateAction<string>) => void;+ project: Project | undefined;+ thread: CommentThread;+}) {+ const { t } = useTranslation();+ const currentUser = useCurrentUser();+ const actions = useThreadActions(issueName);+ const [collapsed, setCollapsed] = useState(collapsible && thread.resolved);+ const [showAllReplies, setShowAllReplies] = useState(+ () => thread.replies.length <= FOLD_REPLIES_ABOVE+ );+ const [replyOpen, setReplyOpen] = useState(Boolean(savedReplyDraft));+ const replyFooterRef = useRef<HTMLDivElement>(null);+ const revealInEditor = useContext(MonacoViewZoneRevealContext);+ useEffect(() => {+ if (!replyOpen || !replyFooterRef.current) return;+ if (revealInEditor) revealInEditor(replyFooterRef.current);+ else replyFooterRef.current.scrollIntoView({ block: "nearest" });+ }, [replyOpen, revealInEditor]);+ const [localReplyDraft, setLocalReplyDraft] = useState("");+ const replyDraft = savedReplyDraft ?? localReplyDraft;+ const setReplyDraft = onReplyDraftChange ?? setLocalReplyDraft;+ const [submitting, setSubmitting] = useState(false);+ const [replyAction, setReplyAction] = useState<ReplyAction>("reply");+ const [replyAttempted, setReplyAttempted] = useState(false);+ const replyButtonRef = useRef<HTMLButtonElement>(null);+ useEffect(() => {+ if (replyDraft.trim() || !replyOpen) setReplyAttempted(false);+ }, [replyDraft, replyOpen]);+ const submissionPending = useRef(false);+ const busy = actions.pending || submitting;+ const draftRef = useRef(replyDraft);+ useLayoutEffect(() => {+ draftRef.current = replyDraft;+ }, [replyDraft]);+ const mounted = useRef(false);+ const stateChanged = useRef(onThreadStateChanged);+ useLayoutEffect(() => {+ mounted.current = true;+ stateChanged.current = onThreadStateChanged;+ return () => {+ mounted.current = false;+ };+ }, [onThreadStateChanged]);++ const settleThread = async () => {+ if (busy || submissionPending.current) return;+ const resolved = !thread.resolved;+ const updated = await (resolved+ ? actions.resolve(thread.root.name)+ : actions.reopen(thread.root.name));+ if (updated && mounted.current) stateChanged.current?.(resolved);+ };++ // Resolving collapses the thread; reopening expands it again.+ useEffect(() => {+ if (!collapsible) return;+ setCollapsed(thread.resolved);+ }, [collapsible, thread.resolved]);++ const allowReply = canReplyToThread(project);+ const allowSettle = canSettleThread(project);+ const selectedAction =+ allowSettle && replyAction === (thread.resolved ? "reopen" : "resolve")+ ? replyAction+ : "reply";+ const replyActionLabel =+ selectedAction === "resolve"+ ? t("plan.review.thread.resolve-with-comment")+ : selectedAction === "reopen"+ ? t("plan.review.thread.reopen-with-comment")+ : t("plan.review.thread.reply");+ useEffect(() => {+ setReplyAction("reply");+ }, [thread.resolved, allowSettle]);++ const { hiddenCount, visibleReplies } = useMemo(() => {+ const replies = thread.replies;+ if (showAllReplies || replies.length <= FOLD_REPLIES_ABOVE) {+ return { hiddenCount: 0, visibleReplies: replies };+ }+ return {+ hiddenCount: replies.length - VISIBLE_TAIL_REPLIES,+ visibleReplies: replies.slice(replies.length - VISIBLE_TAIL_REPLIES),+ };+ }, [showAllReplies, thread.replies]);++ const submitReply = async (action: ReplyAction = "reply") => {+ if (busy || submissionPending.current) return;+ if (!allowReply || (action !== "reply" && !allowSettle)) return;+ if (!replyDraft.trim()) {+ setReplyAttempted(true);+ return;+ }+ submissionPending.current = true;+ setSubmitting(true);+ const submittedDraft = replyDraft;+ try {+ const created = await actions.reply(thread.root.name, submittedDraft);+ if (!created) return;+ setReplyAttempted(false);+ setReplyAction("reply");+ // Once published, this draft must never be sent again when retrying a+ // failed status update. Preserve any new text typed while publishing.+ setReplyDraft((current) => (current === submittedDraft ? "" : current));+ if (mounted.current && draftRef.current === submittedDraft) {+ setReplyOpen(false);+ }+ if (action === "reply") return;+ const failureTitle = t("plan.review.thread.reply-posted-status-failed");+ const resolved = action === "resolve";+ const updated = await (resolved+ ? actions.resolve(thread.root.name, failureTitle)+ : actions.reopen(thread.root.name, failureTitle));+ if (updated && mounted.current) stateChanged.current?.(resolved);+ } finally {+ submissionPending.current = false;+ setSubmitting(false);+ }+ };++ if (collapsed) {+ return (+ <div+ className={cn(+ "rounded-sm border border-block-border bg-background",+ className+ )}+ data-testid="comment-thread"+ data-thread-state="resolved"+ id={thread.root.name}+ >+ <ThreadSummary thread={thread} onExpand={() => setCollapsed(false)} />+ </div>+ );+ }++ return (+ <div+ className={cn(+ "@container/thread flex min-w-0 flex-col rounded-sm border border-block-border bg-background",+ className+ )}+ data-testid="comment-thread"+ data-thread-state={thread.resolved ? "resolved" : "open"}+ id={thread.root.name}+ >+ {context && (+ <div className="min-w-0 overflow-hidden rounded-t-sm border-b border-block-border">+ {context}+ </div>+ )}+ <ThreadComment+ actions={+ <>+ {thread.resolved && collapsible && (+ <Button+ aria-label={t("common.collapse")}+ onClick={() => setCollapsed(true)}+ size="xs"+ appearance="secondary"+ >+ <ChevronUp className="size-3.5" />+ </Button>+ )}+ {onClose && (+ <Button+ aria-label={t("common.close")}+ onClick={onClose}+ size="xs"+ appearance="secondary"+ >+ <ChevronUp className="size-3.5" />+ </Button>+ )}+ </>+ }+ comment={thread.root}+ onEdit={actions.edit}+ project={project}+ status={+ <>+ {label}+ {thread.resolved && (+ <Badge className="gap-x-1 px-2 text-xs" variant="success">+ <CircleCheck className="size-3" />+ {t("plan.review.thread.resolved")}+ </Badge>+ )}+ </>+ }+ />+ {hiddenCount > 0 && (+ <div className="flex justify-center border-t border-block-border bg-control-bg/50 py-1">+ <Button+ onClick={() => setShowAllReplies(true)}+ size="xs"+ appearance="link"+ >+ <ChevronDown className="size-3.5" />+ {t("plan.review.thread.n-replies-hidden", { count: hiddenCount })}+ <span className="text-control-placeholder">·</span>+ {t("plan.review.activity.show-all")}+ </Button>+ </div>+ )}+ {visibleReplies.map((reply) => (+ <ThreadComment+ className="border-t border-block-border"+ comment={reply}+ key={reply.name}+ onEdit={actions.edit}+ project={project}+ />+ ))}+ {(allowReply || allowSettle) && (+ <div+ className="flex flex-wrap items-center gap-2 border-t border-block-border bg-control-bg/50 px-2 py-2 sm:px-3"+ ref={replyFooterRef}+ data-testid="thread-reply-footer"+ >+ {allowReply && (+ <>+ {replyOpen && (+ <div+ className="hidden h-6 shrink-0 self-start items-center @xs/thread:flex"+ data-testid="reply-composer-avatar"+ >+ <UserAvatar+ colorSeed={currentUser.email}+ size="xs"+ title={currentUser.title || currentUser.email}+ />+ </div>+ )}+ {replyOpen ? (+ <div className="flex min-w-0 flex-1 flex-col gap-y-2">+ <MarkdownEditor+ autoFocus+ compact+ content={replyDraft}+ onChange={setReplyDraft}+ onSubmit={() => void submitReply(selectedAction)}+ placeholder={t("plan.review.thread.reply-placeholder")}+ />+ <div className="flex flex-wrap items-center justify-end gap-2">+ <Button+ onClick={() => setReplyOpen(false)}+ size="sm"+ appearance="secondary"+ >+ {t("common.cancel")}+ </Button>+ <div className="inline-flex items-center">+ <Button+ ref={replyButtonRef}+ size="sm"+ className="rounded-r-none"+ disabled={busy}+ onClick={() => void submitReply(selectedAction)}+ >+ {busy && <Loader2 className="size-4 animate-spin" />}+ {replyActionLabel}+ </Button>+ <Popover+ open={replyAttempted && !replyDraft.trim()}+ onOpenChange={(open) => {+ if (!open) setReplyAttempted(false);+ }}+ >+ <PopoverContent+ anchor={replyButtonRef}+ side="top"+ align="end"+ initialFocus={false}+ className="max-w-64 px-3 py-2 text-xs"+ >+ <p role="alert">+ {t("plan.review.thread.comment-required")}+ </p>+ </PopoverContent>+ </Popover>+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label={t("common.actions")}+ disabled={busy}+ render={+ <Button+ size="sm"+ className="rounded-l-none border-l border-accent-text/20"+ />+ }+ >+ <ChevronDown className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ disabled={busy}+ onClick={() => setReplyAction("reply")}+ >+ {t("plan.review.thread.reply")}+ </DropdownMenuItem>+ {allowSettle && (+ <DropdownMenuItem+ disabled={busy}+ onClick={() =>+ setReplyAction(+ thread.resolved ? "reopen" : "resolve"+ )+ }+ >+ {thread.resolved+ ? t("plan.review.thread.reopen-with-comment")+ : t("plan.review.thread.resolve-with-comment")}+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>+ </div>+ ) : (+ <Button+ appearance="outline"+ className="min-w-20 flex-1 justify-start bg-background text-control-placeholder"+ onClick={() => setReplyOpen(true)}+ size="sm"+ type="button"+ >+ {t("plan.review.thread.reply-placeholder")}+ </Button>+ )}+ </>+ )}+ {!allowReply && <span className="flex-1" />}+ {allowSettle && !replyOpen && (+ <Button+ appearance="outline"+ className="ml-auto shrink-0 bg-background"+ disabled={busy}+ onClick={() => void settleThread()}+ size="sm"+ >+ {thread.resolved ? (+ <RotateCcw className="size-3.5" />+ ) : (+ <Check className="size-3.5" />+ )}+ {thread.resolved+ ? t("common.reopen")+ : t("plan.review.thread.resolve")}+ </Button>+ )}+ </div>+ )}+ </div>+ );+}++function ThreadSummary({+ thread,+ onExpand,+}: {+ thread: CommentThread;+ onExpand: () => void;+}) {+ const { t } = useTranslation();+ const creator =+ useUserByIdentifier(thread.root.creator) ??+ unknownUser(thread.root.creator);+ const summary = thread.root.comment.split("\n")[0] ?? "";+ return (+ <Button+ appearance="secondary"+ className="w-full min-w-0 justify-start text-left font-normal"+ onClick={onExpand}+ size="md"+ >+ <UserAvatar+ colorSeed={creator.email}+ size="xs"+ title={creator.title || creator.email}+ />+ <span className="max-w-24 truncate font-medium text-main">+ {creator.title || creator.email}+ </span>+ <span className="min-w-0 flex-1 truncate text-control" title={summary}>+ {summary}+ </span>+ {thread.replies.length > 0 && (+ <span className="shrink-0 text-xs text-control-light">+ {t("plan.review.thread.n-replies", { count: thread.replies.length })}+ </span>+ )}+ {thread.root.createTime && (+ <HumanizeTs+ className="hidden shrink-0 text-xs text-control-light sm:inline"+ ts={getTimeForPbTimestampProtoEs(thread.root.createTime, 0) / 1000}+ />+ )}+ <Badge className="shrink-0 gap-x-1 px-2 text-xs" variant="success">+ <CircleCheck className="size-3" />+ {t("plan.review.thread.resolved")}+ </Badge>+ <ChevronDown className="size-4 shrink-0 text-control-light" />+ </Button>+ );+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/InlineThreadComposer.tsx b/frontend/src/routes/project/plan-detail/components/threads/InlineThreadComposer.tsxnew file mode 100644index 0000000000..f265121062--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/InlineThreadComposer.tsx@@ -0,0 +1,84 @@+import { Loader2, Send } from "lucide-react";+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { MarkdownEditor } from "@/components/MarkdownEditor";+import { UserAvatar } from "@/components/UserAvatar";+import { Button } from "@/components/ui/button";+import { useCurrentUser } from "@/hooks/useAppState";+import type { LineRange } from "./threadModel";++// The composer that opens below the last selected line. Publishing creates a+// root comment anchored to those lines; the draft survives a failed publish.+export function InlineThreadComposer({+ onCancel,+ onPublish,+ pending,+ range,+}: {+ onCancel: () => void;+ onPublish: (comment: string) => Promise<boolean>;+ pending: boolean;+ range: LineRange;+}) {+ const { t } = useTranslation();+ const currentUser = useCurrentUser();+ const [draft, setDraft] = useState("");+ const canPublish = !pending && draft.trim() !== "";++ const publish = async () => {+ if (!canPublish) return;+ const published = await onPublish(draft);+ if (published) setDraft("");+ };++ return (+ <div+ className="flex flex-col rounded-sm border border-block-border bg-background"+ data-testid="inline-thread-composer"+ >+ <div className="flex items-center gap-x-2 border-b border-block-border bg-control-bg/50 px-3 py-1.5 text-sm">+ <UserAvatar+ colorSeed={currentUser.email}+ size="xs"+ title={currentUser.title || currentUser.email}+ />+ <span className="min-w-0 font-medium text-main">+ {range.startLine === range.endLine+ ? t("plan.review.thread.add-comment-on-line", {+ line: range.startLine,+ })+ : t("plan.review.thread.add-comment-on-lines", {+ startLine: range.startLine,+ endLine: range.endLine,+ })}+ </span>+ </div>+ <div className="flex flex-col gap-y-2 px-3 py-2">+ <MarkdownEditor+ compact+ content={draft}+ onChange={setDraft}+ onSubmit={() => void publish()}+ placeholder={t("plan.review.thread.write-comment")}+ />+ <div className="flex items-center justify-end gap-x-2">+ <Button onClick={onCancel} size="sm" appearance="secondary">+ {t("common.cancel")}+ </Button>+ <Button+ disabled={!canPublish}+ onClick={() => void publish()}+ size="sm"+ >+ {pending ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <Send className="size-3.5" />+ )}+ {t("plan.review.thread.publish")}+ </Button>+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementAnchorContext.test.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementAnchorContext.test.tsxnew file mode 100644index 0000000000..12136e46af--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementAnchorContext.test.tsx@@ -0,0 +1,144 @@+import { create } from "@bufbuild/protobuf";+import { cleanup, render, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { Plan_ChangeDatabaseConfigSchema, Plan_SpecSchema, PlanSchema } from "@/types/proto-es/v1/plan_service_pb";+import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";+import { type Sheet, SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";+import { current, OUTDATED } from "./placement/place";+import { StatementAnchorContext } from "./StatementAnchorContext";+import { buildWholeLineAnchor } from "./threadModel";++const mocks = vi.hoisted(() => ({+ sheets: {} as Record<string, Sheet>,+ fetchSheet: vi.fn(),+ colorize: vi.fn(async (text: string) => text.split("\n").map((line) => `<span>${line}</span>`).join("<br/>")),+}));+vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({t: (key: string, options?: { count?: number; range: string }) =>+ options ? `${(options.count ?? 1) > 1 ? "Lines" : "Line"} ${options.range}` : key}),+}));+vi.mock("@/components/monaco/core", () => ({ colorizeStatement: (text: string) => mocks.colorize(text) }));+vi.mock("@/stores/app", () => ({+ useAppStore: Object.assign(+ (selector: (state: unknown) => unknown) => selector({ sheetsByName: mocks.sheets }),+ {+ getState: () => ({+ getSheetByName: (name: string) => mocks.sheets[name],+ getOrFetchSheetByName: mocks.fetchSheet,+ }),+ }+ ),+}));++const savedHash = "c".repeat(64);+const currentHash = "d".repeat(64);+const savedName = `projects/p/sheets/${savedHash}`;+const currentName = `projects/p/sheets/${currentHash}`;+const original = "/* original revision\ncomment line\ncomment line 2\n*/\nSELECT 1;\nSELECT 2;";+const project = create(ProjectSchema, { name: "projects/p" });+const plan = create(PlanSchema, { specs: [create(Plan_SpecSchema, {+ id: "spec",+ config: { case: "changeDatabaseConfig", value: create(Plan_ChangeDatabaseConfigSchema, { sheet: currentName }) },+})] });+const anchor = (startLine: number, endLine: number) => buildWholeLineAnchor({+ spec: "spec", sheetSha256: savedHash, startLine, endLine,+});+const props = {+ plan,+ project,+ onViewInStatement: vi.fn(),+ renderPlanChangeReference: () => <span>Change 1</span>,+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.sheets = {+ [savedName]: create(SheetSchema, { name: savedName, content: new TextEncoder().encode(original) }),+ [currentName]: create(SheetSchema, { name: currentName, content: new TextEncoder().encode("CURRENT REVISION") }),+ };+});+afterEach(cleanup);++describe("StatementAnchorContext", () => {+ test.each([+ { start: 1, end: 1, displayed: [1], selected: [1], label: "Line 1" },+ { start: 2, end: 2, displayed: [1, 2], selected: [2], label: "Line 2" },+ { start: 4, end: 5, displayed: [2, 3, 4, 5], selected: [4, 5], label: "Lines 4–5" },+ ])("adds at most two preceding lines to $label without expanding the anchor", async ({start, end, displayed, selected, label}) => {+ const { container, getByText } = render(<StatementAnchorContext {...props} anchor={anchor(start, end)} placement={OUTDATED} />);+ const numbers = (selector: string) => Array.from(container.querySelectorAll(selector)).map((el) => Number(el.getAttribute("data-line-number")));+ expect(numbers("[data-line-number]")).toEqual(displayed);+ expect(numbers('[data-selected="true"]')).toEqual(selected);+ expect(getByText(label)).toBeTruthy();+ // Colorized from the recorded revision, never the current one.+ await waitFor(() => expect(container.querySelector("code span")).not.toBeNull());+ expect(container.textContent).not.toContain("CURRENT REVISION");+ expect(container.textContent).not.toContain("SELECT 2;");+ });++ test("tokenizes a recorded revision once, from the document start, however many cards excerpt it", async () => {+ const hash = "e".repeat(64);+ const name = `projects/p/sheets/${hash}`;+ mocks.sheets[name] = create(SheetSchema, { name, content: new TextEncoder().encode(original) });+ const shared = buildWholeLineAnchor({ spec: "spec", sheetSha256: hash, startLine: 5, endLine: 5 });+ const { container } = render(+ <>+ <StatementAnchorContext {...props} anchor={shared} placement={OUTDATED} />+ <StatementAnchorContext {...props} anchor={shared} placement={OUTDATED} />+ </>+ );+ await waitFor(() => expect(container.querySelectorAll("code span").length).toBeGreaterThan(0));+ expect(mocks.colorize).toHaveBeenCalledTimes(1);+ // Only through the excerpt's last line, from the document start.+ expect(mocks.colorize).toHaveBeenCalledWith(+ `${original.split("\n").slice(0, 5).join("\n")}\n`+ );+ });++ test("mapped placements still render context from the recorded revision", () => {+ const { container, getByText } = render(<StatementAnchorContext {...props} anchor={anchor(4, 5)} placement={current(10, 11)} />);+ expect(getByText("Lines 4–5")).toBeTruthy();+ expect(container.textContent).toContain("comment line");+ expect(container.textContent).not.toContain("CURRENT REVISION");+ });++ test.each([+ { sheet: "complete", text: original, extra: 0, state: "CURRENT", action: true },+ { sheet: "truncated", text: original, extra: 1, state: "UNAVAILABLE", action: false },+ { sheet: "empty", text: "", extra: 0, state: "UNAVAILABLE", action: false },+ ])("a hash-matched anchor on a $sheet sheet is $state", ({ text, extra, state, action }) => {+ const content = new TextEncoder().encode(text);+ mocks.sheets[currentName] = create(SheetSchema, {+ name: currentName,+ content,+ contentSize: BigInt(content.byteLength + extra),+ });+ const onCurrent = buildWholeLineAnchor({ spec: "spec", sheetSha256: currentHash, startLine: 1, endLine: 1 });+ const { container, queryByText } = render(<StatementAnchorContext {...props} anchor={onCurrent} placement={undefined} />);+ expect(container.querySelector("[data-anchor-state]")?.getAttribute("data-anchor-state")).toBe(state);+ expect(queryByText("plan.review.thread.anchor.view-in-statement") !== null).toBe(action);+ });++ test("a hash-matched anchor stays pending until its sheet has loaded", async () => {+ const content = new TextEncoder().encode(original);+ const sheet = create(SheetSchema, { name: currentName, content, contentSize: BigInt(content.byteLength) });+ delete mocks.sheets[currentName];+ mocks.fetchSheet.mockResolvedValueOnce(sheet);+ const onCurrent = buildWholeLineAnchor({ spec: "spec", sheetSha256: currentHash, startLine: 1, endLine: 1 });+ const { container, queryByText } = render(<StatementAnchorContext {...props} anchor={onCurrent} placement={undefined} />);+ const state = () => container.querySelector("[data-anchor-state]")?.getAttribute("data-anchor-state");+ expect(state()).toBe("PENDING");+ expect(queryByText("plan.review.thread.anchor.view-in-statement")).toBeNull();+ await waitFor(() => expect(state()).toBe("CURRENT"));+ expect(queryByText("plan.review.thread.anchor.view-in-statement")).not.toBeNull();+ });++ test("fetches a missing recorded revision instead of using the current SQL", async () => {+ delete mocks.sheets[savedName];+ const { container } = render(<StatementAnchorContext {...props} anchor={anchor(4, 5)} placement={OUTDATED} />);+ await waitFor(() => expect(mocks.fetchSheet).toHaveBeenCalledWith(savedName));+ expect(container.querySelector("[data-line-number]")).toBeNull();+ expect(container.textContent).not.toContain("CURRENT REVISION");+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementAnchorContext.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementAnchorContext.tsxnew file mode 100644index 0000000000..7383a41010--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementAnchorContext.tsx@@ -0,0 +1,271 @@+import { Ban, ExternalLink, History } from "lucide-react";+import { useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import type { PlanChangeReferenceRenderer } from "@/components/issue-activity/IssueCommentActivity";+import { colorizeStatement } from "@/components/monaco/core";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { useInViewOnce } from "@/hooks/useInViewOnce";+import { useSheetStatement } from "@/hooks/useSheetStatement";+import { cn } from "@/lib/utils";+import type { StatementAnchor } from "@/types/proto-es/v1/issue_service_pb";+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";+import { tokenizeLines } from "./placement/lineTokens";+import type { Placement } from "./placement/place";+import {+ type AnchorState,+ anchorLineRange,+ excerptLines,+ type LineRange,+ lineRangeLabel,+ resolveAnchorState,+ sheetNameOfSha256,+ targetSha256OfSpec,+} from "./threadModel";++// The recorded context of an anchored comment in the Review Activity+// timeline: the change, the originally selected lines, the placement state,+// and the SQL excerpt of the recorded sheet revision. The editor never+// renders this block; there the anchor is a gutter marker and a line+// highlight at the comment's current placement.+export function StatementAnchorContext({+ anchor,+ onViewInStatement,+ placement,+ plan,+ project,+ renderPlanChangeReference,+}: {+ anchor: StatementAnchor;+ onViewInStatement?: () => void;+ placement: Placement | undefined;+ plan: Plan;+ project: Project | undefined;+ renderPlanChangeReference: PlanChangeReferenceRenderer;+}) {+ const { t } = useTranslation();+ const range = anchorLineRange(anchor);+ const spec = plan.specs.find((candidate) => candidate.id === anchor.spec);+ const sheetName = project+ ? sheetNameOfSha256(project.name, anchor.sheetSha256)+ : "";+ // The recorded revision is downloaded only once the card nears the+ // viewport, so a long timeline fetches sheets as the reader reaches them+ // rather than all at once when the fold opens.+ const { ref, inView } = useInViewOnce<HTMLDivElement>();+ const enabled = sheetName !== "" && inView;+ const { statement, isLoading, isTruncated } = useSheetStatement({+ enabled,+ sheetName,+ });+ const loaded = enabled && !isLoading;+ // The editor mounts its thread layer only for a complete, non-empty+ // statement. An anchor on the spec's current sheet is CURRENT by hash+ // alone, so that sheet must be loaded and pass those checks before the+ // card offers to show it; until then it is pending, and a truncated or+ // empty sheet makes it unavailable rather than a dead "view" action. A+ // diff-mapped CURRENT anchor needs none of this: its target is complete.+ const resolved = resolveAnchorState(anchor, plan, placement);+ const onCurrentSheet = anchor.sheetSha256 === targetSha256OfSpec(spec);+ const state = ((): AnchorState => {+ if (resolved !== "CURRENT" || !onCurrentSheet) return resolved;+ if (!loaded) return "PENDING";+ return isTruncated || statement === "" ? "UNAVAILABLE" : "CURRENT";+ })();++ return (+ <div+ ref={ref}+ className="@container/anchor flex min-w-0 flex-col"+ data-anchor-state={state}+ data-testid="statement-anchor"+ >+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b border-block-border bg-control-bg/50 px-3 py-1.5 text-xs">+ <div className="flex min-w-0 flex-1 basis-full @sm/anchor:basis-0">+ {spec ? (+ renderPlanChangeReference({ siblings: plan.specs, spec })+ ) : (+ <span className="truncate font-medium text-control-light">+ {t("plan.review.thread.anchor.unavailable-change")}+ </span>+ )}+ </div>+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1.5">+ {range && (+ <span className="shrink-0 text-control-light">+ {lineRangeLabel(t, range)}+ </span>+ )}+ <AnchorStatePill+ onViewInStatement={onViewInStatement}+ state={state}+ />+ </div>+ </div>+ {!isLoading && statement && range && (+ <SqlExcerpt+ sheetName={sheetName}+ dimmed={state === "OUTDATED" || state === "UNAVAILABLE"}+ statement={statement}+ range={range}+ />+ )}+ </div>+ );+}++function AnchorStatePill({+ onViewInStatement,+ state,+}: {+ onViewInStatement?: () => void;+ state: AnchorState;+}) {+ const { t } = useTranslation();+ if (state === "CURRENT") {+ if (!onViewInStatement) return null;+ return (+ <Button+ className="h-auto shrink-0 p-0 text-xs"+ onClick={onViewInStatement}+ size="xs"+ appearance="link"+ >+ {t("plan.review.thread.anchor.view-in-statement")}+ <ExternalLink className="size-3" />+ </Button>+ );+ }+ if (state === "OUTDATED") {+ return (+ <Badge className="gap-x-1 px-2 text-xs" variant="warning">+ <History className="size-3" />+ {t("plan.review.thread.anchor.outdated")}+ </Badge>+ );+ }+ // The diff has not settled the comment yet; show nothing rather than a+ // state that may flip in a moment.+ if (state === "PENDING") return null;+ return (+ <Badge className="gap-x-1 px-2 text-xs" variant="default">+ <Ban className="size-3" />+ {t("plan.review.thread.anchor.statement-unavailable")}+ </Badge>+ );+}++const CONTEXT_LINES_BEFORE = 2;++// Sheets are immutable and content-addressed, so each is tokenized once per+// page however many cards excerpt it, and only through the deepest line a+// card needs rather than the whole sheet. Tokenizing from the document start+// keeps a snippet that begins inside a multiline comment or string in the+// same lexical state as the editor. A few sheets are kept; a plan rarely+// excerpts more revisions than that at once.+const COLORIZED_SHEET_LIMIT = 8;+const colorizedSheets = new Map<+ string,+ { throughLine: number; lines: Promise<string[]> }+>();+const colorizedLinesOf = (+ sheetName: string,+ statement: string,+ throughLine: number+): Promise<string[]> => {+ const cached = colorizedSheets.get(sheetName);+ if (cached && cached.throughLine >= throughLine) return cached.lines;+ const prefix = tokenizeLines(statement).slice(0, throughLine).join("");+ const lines = colorizeStatement(prefix).then((html) =>+ html.split(/<br\s*\/?>/)+ );+ colorizedSheets.delete(sheetName);+ colorizedSheets.set(sheetName, { throughLine, lines });+ for (const key of colorizedSheets.keys()) {+ if (colorizedSheets.size <= COLORIZED_SHEET_LIMIT) break;+ colorizedSheets.delete(key);+ }+ return lines;+};++function SqlExcerpt({+ dimmed,+ sheetName,+ statement,+ range,+}: {+ dimmed: boolean;+ sheetName: string;+ statement: string;+ range: LineRange;+}) {+ const startLine = Math.max(1, range.startLine - CONTEXT_LINES_BEFORE);+ const lines = useMemo(+ () => excerptLines(statement, { startLine, endLine: range.endLine }),+ [range.endLine, startLine, statement]+ );+ const [colorized, setColorized] = useState<{+ sheetName: string;+ lines: string[];+ }>();+ useEffect(() => {+ let cancelled = false;+ void colorizedLinesOf(sheetName, statement, range.endLine).then((html) => {+ if (!cancelled) setColorized({ sheetName, lines: html });+ });+ return () => {+ cancelled = true;+ };+ }, [range.endLine, sheetName, statement]);+ const htmlLines =+ colorized?.sheetName === sheetName ? colorized.lines : undefined;+ if (lines.length === 0) return null;+ return (+ <pre+ className={cn(+ "m-0 overflow-x-auto bg-background font-mono text-sm leading-6",+ dimmed && "opacity-60"+ )}+ >+ <div className="w-max min-w-full">+ {lines.map((line, index) => {+ const lineNumber = startLine + index;+ const selected =+ lineNumber >= range.startLine && lineNumber <= range.endLine;+ const html = htmlLines?.[lineNumber - 1];+ return (+ <div+ className={cn(+ "flex items-start gap-x-3 px-3",+ selected && "bg-accent/12"+ )}+ data-line-number={lineNumber}+ data-selected={selected || undefined}+ key={lineNumber}+ >+ <span+ className="shrink-0 select-none text-right text-control-placeholder"+ style={{+ width: `${Math.max(2, String(range.endLine).length)}ch`,+ }}+ >+ {lineNumber}+ </span>+ {html === undefined ? (+ <code className="min-w-0 flex-1 whitespace-pre text-main">+ {line}+ </code>+ ) : (+ <code+ className="min-w-0 flex-1 whitespace-pre text-main"+ dangerouslySetInnerHTML={{ __html: html }}+ />+ )}+ </div>+ );+ })}+ </div>+ </pre>+ );+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsxnew file mode 100644index 0000000000..1feba37889--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsx@@ -0,0 +1,745 @@+import { create } from "@bufbuild/protobuf";+import { TimestampSchema } from "@bufbuild/protobuf/wkt";+import type * as monaco from "monaco-editor";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import type {+ IStandaloneCodeEditor,+ MonacoModule,+} from "@/components/monaco/types";+import { PositionSchema } from "@/types/proto-es/v1/common_pb";+import {+ IssueComment_ThreadState,+ IssueCommentSchema,+ IssueSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import {+ Plan_ChangeDatabaseConfigSchema,+ Plan_SpecSchema,+ PlanSchema,+} from "@/types/proto-es/v1/plan_service_pb";+import { StatementAnchorSchema } from "@/types/proto-es/v1/issue_service_pb";++const SHA = "c".repeat(64);+const ISSUE = "projects/p/issues/1";++const mocks = vi.hoisted(() => ({+ comments: [] as unknown[],+ createIssueComment: vi.fn(),+ threadFocus: undefined as+ | { commentName: string; specId: string; nonce: number }+ | undefined,+ clearThreadFocus: vi.fn(),+ placements: new Map<string, unknown>(),+ placementTargets: new Map<string, string>(),+ hasPermission: vi.fn((_project: unknown, _permission: unknown) => true),+}));++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({+ t: (key: string, options?: { count?: number }) =>+ options?.count !== undefined ? `${key}:${options.count}` : key,+ }),+}));++vi.mock("@/hooks/useProjectByName", () => ({+ useProjectByName: () => ({ name: "projects/p" }),+}));++vi.mock("@/stores", () => ({+ pushNotification: vi.fn(),+ extractUserEmail: (identifier: string) => identifier.replace(/^users\//, ""),+}));++vi.mock("@/stores/app", () => ({+ useAppStore: Object.assign(+ (selector: (state: unknown) => unknown) =>+ selector({ getIssueComments: () => mocks.comments }),+ {+ getState: () => ({ createIssueComment: mocks.createIssueComment }),+ }+ ),+}));++vi.mock("@/utils/iam/permission", () => ({+ hasProjectPermissionV2: (project: unknown, permission: unknown) =>+ mocks.hasPermission(project, permission),+}));++vi.mock("../../hooks/usePlanChangeReferenceData", () => ({+ usePlanChangeReferenceData: () => ({}),+}));++vi.mock("../../shared/stores/usePlanDetailStore", () => ({+ usePlanDetailStore: (selector: (state: unknown) => unknown) =>+ selector({+ threadFocus: mocks.threadFocus,+ clearThreadFocus: mocks.clearThreadFocus,+ placements: mocks.placements,+ placementTargets: mocks.placementTargets,+ }),+}));++vi.mock("../../shell/PlanDetailContext", () => ({+ usePlanDetailContext: () => ({+ projectId: "p",+ plan: create(PlanSchema, {+ specs: [+ create(Plan_SpecSchema, {+ id: "spec-1",+ config: {+ case: "changeDatabaseConfig",+ value: create(Plan_ChangeDatabaseConfigSchema, {+ sheet: `projects/p/sheets/${"c".repeat(64)}`,+ }),+ },+ }),+ ],+ }),+ }),+}));++vi.mock("../PlanChangeReference", () => ({+ PlanSpecChangeReference: () => <span>hr-prod</span>,+}));++vi.mock("./CommentThreadCard", () => ({+ CommentThreadCard: ({+ onClose,+ thread,+ }: {+ onClose: () => void;+ thread: { root: { name: string } };+ }) => (+ <div data-testid="thread-card" data-root={thread.root.name}>+ <button data-testid="close-thread" onClick={onClose} type="button" />+ </div>+ ),+}));++vi.mock("./InlineThreadComposer", () => ({+ InlineThreadComposer: ({+ onCancel,+ onPublish,+ range,+ }: {+ onCancel: () => void;+ onPublish: (comment: string) => Promise<boolean>;+ range: { startLine: number; endLine: number };+ }) => (+ <div data-testid="composer" data-range={`${range.startLine}-${range.endLine}`}>+ <button data-testid="cancel-composer" onClick={onCancel} type="button" />+ <button+ data-testid="publish"+ onClick={() => void onPublish("No LIMIT")}+ type="button"+ />+ </div>+ ),+}));++vi.mock("./ThreadStack", () => ({+ ThreadStack: ({+ onExpand,+ onCollapse,+ replyDrafts,+ onReplyDraftChange,+ expandedRoots,+ threads,+ }: {+ onExpand: (rootName: string) => void;+ onCollapse: (rootName: string) => void;+ replyDrafts: Record<string, string>;+ onReplyDraftChange: (rootName: string, draft: string | ((current: string) => string)) => void;+ expandedRoots: ReadonlySet<string>;+ threads: { thread: { root: { name: string } } }[];+ }) => threads.length === 1 && expandedRoots.has(threads[0].thread.root.name) ? (+ <div data-testid="thread-card" data-root={threads[0].thread.root.name}>+ <button data-testid="close-thread" onClick={() => onCollapse(threads[0].thread.root.name)} type="button" />+ <button data-testid="save-draft" onClick={() => onReplyDraftChange(threads[0].thread.root.name, "unfinished reply")} type="button" />+ <button data-testid="clear-submitted-draft" onClick={() => onReplyDraftChange(threads[0].thread.root.name, current => current === "unfinished reply" ? "" : current)} type="button" />+ <input data-testid="saved-draft" readOnly value={replyDrafts[threads[0].thread.root.name] ?? ""} />+ </div>+ ) : (+ <ul data-testid="thread-picker">+ {threads.map((entry) => (+ <li key={entry.thread.root.name}>+ <button+ data-testid="pick-thread"+ data-expanded={expandedRoots.has(entry.thread.root.name)}+ onClick={() => onExpand(entry.thread.root.name)}+ type="button"+ >+ {entry.thread.root.name}+ </button>+ {expandedRoots.has(entry.thread.root.name) && (+ <button data-testid="close-thread" onClick={() => onCollapse(entry.thread.root.name)} type="button" />+ )}+ </li>+ ))}+ </ul>+ ),+}));++import { StatementThreadsLayer } from "./StatementThreadsLayer";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++type MouseHandler = (e: monaco.editor.IEditorMouseEvent) => void;++class FakeRange {+ constructor(+ public startLineNumber: number,+ public startColumn: number,+ public endLineNumber: number,+ public endColumn: number+ ) {}+}++const MouseTargetType = {+ GUTTER_GLYPH_MARGIN: 2,+ GUTTER_LINE_NUMBERS: 3,+ GUTTER_LINE_DECORATIONS: 4,+ CONTENT_TEXT: 6,+ CONTENT_EMPTY: 7,+};++const fakeMonaco = {+ Range: FakeRange,+ editor: {+ TrackedRangeStickiness: { NeverGrowsWhenTypingAtEdges: 1 },+ MouseTargetType,+ GlyphMarginLane: { Center: 2 },+ },+} as unknown as MonacoModule;++function createFakeEditor(lineMaxColumn = 20) {+ const handlers: Record<string, MouseHandler[]> = {+ move: [],+ down: [],+ up: [],+ leave: [],+ };+ const zones = new Map<string, { afterLineNumber: number; domNode: HTMLElement }>();+ const widgets = new Set<{ getDomNode: () => HTMLElement }>();+ let zoneSeq = 0;+ // The DOM hit test used by the drag; tests set the line the pointer is on.+ const pointer = { line: undefined as number | undefined };+ let selection: monaco.Selection | null = null;+ const selectionListeners = new Set<() => void>();+ const setSelection = (range: FakeRange) => {+ if (selection?.startLineNumber === range.startLineNumber &&+ selection.startColumn === range.startColumn &&+ selection.endLineNumber === range.endLineNumber &&+ selection.endColumn === range.endColumn) return;+ selection = { ...range, isEmpty: () => range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn } as monaco.Selection;+ for (const listener of selectionListeners) listener();+ };+ const decorations = { current: [] as monaco.editor.IModelDeltaDecoration[] };+ const domNode = document.createElement("div");+ document.body.append(domNode);+ domNode.scrollIntoView = vi.fn();+ const subscribe = (key: string) => (handler: MouseHandler) => {+ handlers[key].push(handler);+ return {+ dispose: () => {+ handlers[key] = handlers[key].filter((h) => h !== handler);+ },+ };+ };+ const editor = {+ focus: vi.fn(),+ addAction: vi.fn(() => ({ dispose: vi.fn() })),+ addOverlayWidget: (widget: { getDomNode: () => HTMLElement }) => {+ widgets.add(widget);+ },+ removeOverlayWidget: (widget: { getDomNode: () => HTMLElement }) => {+ widgets.delete(widget);+ },+ getLayoutInfo: () => ({+ contentLeft: 52,+ width: 800,+ verticalScrollbarWidth: 14,+ minimap: { minimapWidth: 0 },+ }),+ getTargetAtClientPoint: () =>+ pointer.line === undefined+ ? null+ : { type: MouseTargetType.CONTENT_TEXT, position: { lineNumber: pointer.line, column: 1 }, range: null },+ onDidLayoutChange: () => ({ dispose: vi.fn() }),+ changeViewZones: (+ callback: (accessor: {+ addZone: (zone: { afterLineNumber: number; domNode: HTMLElement }) => string;+ removeZone: (id: string) => void;+ layoutZone: (id: string) => void;+ }) => void+ ) =>+ callback({+ addZone: (zone) => {+ const id = `z${zoneSeq++}`;+ zones.set(id, zone);+ return id;+ },+ removeZone: (id) => {+ zones.delete(id);+ },+ layoutZone: () => {},+ }),+ createDecorationsCollection: () => ({+ set: (next: monaco.editor.IModelDeltaDecoration[]) => {+ decorations.current = next;+ },+ clear: () => {+ decorations.current = [];+ },+ }),+ getDomNode: () => domNode,+ getModel: () => ({ getLineMaxColumn: () => lineMaxColumn }),+ getSelection: () => selection,+ setSelection,+ setPosition: ({ lineNumber, column }: { lineNumber: number; column: number }) =>+ setSelection(new FakeRange(lineNumber, column, lineNumber, column)),+ onDidChangeCursorSelection: (listener: () => void) => {+ selectionListeners.add(listener);+ return { dispose: () => selectionListeners.delete(listener) };+ },+ onMouseDown: subscribe("down"),+ onMouseLeave: subscribe("leave"),+ onMouseMove: subscribe("move"),+ onMouseUp: subscribe("up"),+ revealLineInCenter: vi.fn(),+ };+ const fire = (key: string, line: number | undefined, type: number, detail?: Record<string, unknown>) => {+ const event = {+ event: { leftButton: true, preventDefault: vi.fn(), stopPropagation: vi.fn() },+ target: {+ type,+ detail,+ position: line === undefined ? null : { lineNumber: line, column: 1 },+ range: null,+ },+ } as unknown as monaco.editor.IEditorMouseEvent;+ act(() => {+ for (const handler of [...handlers[key]]) handler(event);+ });+ return event;+ };+ // Drag steps arrive through the document, not the editor's mouse events.+ const dragTo = (line: number) => {+ pointer.line = line;+ act(() => {+ document.dispatchEvent(new MouseEvent("mousemove", { bubbles: true }));+ });+ };+ const release = () => {+ act(() => {+ document.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));+ });+ };+ return {+ editor: editor as unknown as IStandaloneCodeEditor,+ decorations,+ pressEscape: () => act(() => {+ domNode.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));+ }),+ dragTo,+ fire,+ release,+ widgets,+ zones,+ };+}++const at = (seconds: number) =>+ create(TimestampSchema, { seconds: BigInt(seconds) });++const threadRoot = (+ id: string,+ startLine: number,+ endLine: number,+ extra: { createdAt?: number; resolved?: boolean } = {}+) =>+ create(IssueCommentSchema, {+ name: `${ISSUE}/issueComments/${id}`,+ comment: id,+ createTime: at(extra.createdAt ?? 1),+ threadState: extra.resolved+ ? IssueComment_ThreadState.RESOLVED+ : IssueComment_ThreadState.OPEN,+ statementAnchor: create(StatementAnchorSchema, {+ spec: "spec-1",+ sheetSha256: SHA,+ startPosition: create(PositionSchema, { line: startLine, column: 0 }),+ endPosition: create(PositionSchema, { line: endLine, column: 0 }),+ }),+ });++const issue = create(IssueSchema, { name: ISSUE });+const spec = create(Plan_SpecSchema, { id: "spec-1" });++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ vi.clearAllMocks();+ mocks.threadFocus = undefined;+ mocks.hasPermission.mockReturnValue(true);+ container = document.createElement("div");+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ document.body.replaceChildren();+});++const mount = (editor: IStandaloneCodeEditor) =>+ act(() =>+ root.render(+ <StatementThreadsLayer+ editor={editor}+ issue={issue}+ monaco={fakeMonaco}+ sheetSha256={SHA}+ spec={spec}+ />+ )+ );++const zoneAfter = (zones: Map<string, { afterLineNumber: number; domNode: HTMLElement }>) =>+ Array.from(zones.values()).map((zone) => zone.afterLineNumber);++const hosted = (+ widgets: Set<{ getDomNode: () => HTMLElement }>,+ selector: string+) =>+ Array.from(widgets)+ .map((widget) => widget.getDomNode().querySelector(selector))+ .find(Boolean) ?? null;++const cardRoot = (widgets: Set<{ getDomNode: () => HTMLElement }>) =>+ hosted(widgets, "[data-testid='thread-card']")?.getAttribute("data-root");++const classesOf = (+ decorations: monaco.editor.IModelDeltaDecoration[],+ line: number+) =>+ decorations+ .filter((d) => d.range.startLineNumber === line)+ .map(+ (d) => d.options.className ?? d.options.glyphMarginClassName ?? d.options.linesDecorationsClassName ?? ""+ );++describe("StatementThreadsLayer", () => {+ test("decorates current anchors and expands the earliest unresolved thread", () => {+ mocks.comments = [+ threadRoot("later", 6, 9, { createdAt: 5 }),+ threadRoot("first", 3, 4, { createdAt: 2 }),+ threadRoot("resolved", 1, 1, { createdAt: 1, resolved: true }),+ threadRoot("also-on-9", 8, 9, { createdAt: 7 }),+ ];+ const fake = createFakeEditor();+ mount(fake.editor);++ expect(classesOf(fake.decorations.current, 3)).toEqual(["bb-thread-line"]);+ expect(classesOf(fake.decorations.current, 8)).toEqual(["bb-thread-line--passive"]);+ expect(classesOf(fake.decorations.current, 4)).toContain("bb-thread-glyph bb-thread-glyph--active");+ expect(classesOf(fake.decorations.current, 1)).toContain(+ "bb-thread-glyph bb-thread-glyph--resolved"+ );+ expect(classesOf(fake.decorations.current, 9)).toContain(+ "bb-thread-glyph bb-thread-glyph--count-2"+ );+ expect(zoneAfter(fake.zones)).toEqual([4]);+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/first`);+ });++ test("distinguishes the current range from non-stacking passive ranges", () => {+ mocks.comments = [threadRoot("single", 2, 2), threadRoot("multi", 1, 2, { createdAt: 2, resolved: true })];+ const fake = createFakeEditor();+ mount(fake.editor);+ const highlighted = () => fake.decorations.current.filter((d) => d.options.className === "bb-thread-line").map((d) => d.range.startLineNumber);+ expect(highlighted()).toEqual([2]);+ expect(classesOf(fake.decorations.current, 1)).toContain("bb-thread-line--passive");+ expect(fake.decorations.current.filter((d) => d.options.isWholeLine && d.range.startLineNumber === 2)).toHaveLength(1);+ fake.fire("move", 1, MouseTargetType.GUTTER_LINE_NUMBERS);+ expect(highlighted()).toEqual([2]);+ const picker = hosted(fake.widgets, "[data-testid='thread-picker']");+ act(() => picker?.querySelectorAll("[data-testid='pick-thread']")[1].dispatchEvent(new MouseEvent("click", { bubbles: true })));+ expect(highlighted()).toEqual([1, 2]);+ act(() => hosted(fake.widgets, "[data-testid='close-thread']")?.dispatchEvent(new MouseEvent("click", { bubbles: true })));+ expect(highlighted()).toEqual([]);+ expect(fake.decorations.current.filter((d) => d.options.className === "bb-thread-line--passive").map((d) => d.range.startLineNumber)).toEqual([1, 2]);+ expect(fake.decorations.current.filter((d) => d.options.glyphMarginClassName?.includes("bb-thread-glyph--count-2"))).toHaveLength(1);+ });++ test("creation ranges replace the reading highlight and cancellation restores it", () => {+ mocks.comments = [threadRoot("single", 2, 2)];+ const fake = createFakeEditor(1);+ mount(fake.editor);+ const lines = (className: string) => fake.decorations.current.filter((d) => d.options.className === className).map((d) => d.range.startLineNumber);+ fake.fire("down", 1, MouseTargetType.GUTTER_LINE_NUMBERS);+ fake.dragTo(2);+ fake.release();+ expect(lines("bb-thread-line")).toEqual([]);+ expect(lines("bb-thread-line--selecting")).toEqual([1, 2]);+ fake.pressEscape();+ expect(lines("bb-thread-line")).toEqual([2]);+ expect(lines("bb-thread-line--selecting")).toEqual([]);+ fake.fire("down", 3, MouseTargetType.GUTTER_LINE_NUMBERS);+ fake.release();+ fake.fire("down", 3, MouseTargetType.GUTTER_LINE_DECORATIONS);+ expect(lines("bb-thread-line")).toEqual([]);+ expect(lines("bb-thread-line--selecting")).toEqual([3]);+ expect(lines("bb-thread-line--passive")).toEqual([2]);+ expect(fake.decorations.current.find((d) => d.options.className === "bb-thread-line--passive")?.options.linesDecorationsClassName).toBeUndefined();+ act(() => hosted(fake.widgets, "[data-testid='cancel-composer']")?.dispatchEvent(new MouseEvent("click", { bubbles: true })));+ expect(lines("bb-thread-line")).toEqual([2]);+ expect(lines("bb-thread-line--selecting")).toEqual([]);+ });++ test("a marker opens its thread, a combined marker offers a picker, and closing returns to markers", () => {+ mocks.comments = [+ threadRoot("first", 3, 4, { createdAt: 2 }),+ threadRoot("a", 6, 9, { createdAt: 5 }),+ threadRoot("b", 8, 9, { createdAt: 7 }),+ ];+ const fake = createFakeEditor();+ mount(fake.editor);+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/first`);++ // Moving onto an occupied line must not replace its marker with creation.+ fake.fire("move", 9, MouseTargetType.GUTTER_GLYPH_MARGIN);+ expect(classesOf(fake.decorations.current, 9)).toContain("bb-thread-add-glyph");+ fake.fire("down", 9, MouseTargetType.GUTTER_GLYPH_MARGIN);+ expect(hosted(fake.widgets, "[data-testid='composer']")).toBeNull();+ expect(zoneAfter(fake.zones)).toEqual([9]);+ const picker = hosted(fake.widgets, "[data-testid='thread-picker']");+ const pick = picker?.querySelectorAll("[data-testid='pick-thread']");+ expect(Array.from(pick ?? []).map((node) => node.textContent)).toEqual([+ `${ISSUE}/issueComments/a`,+ `${ISSUE}/issueComments/b`,+ ]);+ act(() => {+ pick?.[1].dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ expect(zoneAfter(fake.zones)).toEqual([9]);+ expect(pick?.[1].getAttribute("data-expanded")).toBe("true");++ // The marker of the expanded thread toggles it closed.+ fake.fire("down", 4, MouseTargetType.GUTTER_GLYPH_MARGIN);+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/first`);+ fake.fire("down", 4, MouseTargetType.GUTTER_GLYPH_MARGIN);+ expect(fake.zones.size).toBe(0);+ });++ test("selecting lines reveals the add action, which opens and publishes a whole-line anchor", async () => {+ mocks.comments = [];+ mocks.createIssueComment.mockResolvedValue(+ create(IssueCommentSchema, { name: `${ISSUE}/issueComments/new` })+ );+ const fake = createFakeEditor();+ mount(fake.editor);++ fake.fire("move", 2, MouseTargetType.GUTTER_LINE_NUMBERS);+ expect(classesOf(fake.decorations.current, 2)).toEqual([+ "bb-thread-add-glyph",+ ]);+ fake.fire("move", 2, MouseTargetType.CONTENT_TEXT);+ expect(classesOf(fake.decorations.current, 2)).toEqual(["bb-thread-add-glyph"]);+ fake.fire("leave", undefined, MouseTargetType.CONTENT_TEXT);+ expect(classesOf(fake.decorations.current, 2)).toEqual([]);++ const down = fake.fire("down", 2, MouseTargetType.GUTTER_LINE_NUMBERS);+ expect(down.event.preventDefault).toHaveBeenCalled();+ fake.dragTo(4);+ fake.release();+ expect(fake.zones.size).toBe(0);+ expect(classesOf(fake.decorations.current, 4)).toContain("bb-thread-add-glyph");+ fake.fire("down", 4, MouseTargetType.GUTTER_LINE_DECORATIONS);+ expect(classesOf(fake.decorations.current, 3)).toEqual([+ "bb-thread-line--selecting",+ ]);++ expect(zoneAfter(fake.zones)).toEqual([4]);+ const composer = hosted(fake.widgets, "[data-testid='composer']");+ expect(composer?.getAttribute("data-range")).toBe("2-4");++ await act(async () => {+ hosted(fake.widgets, "[data-testid='publish']")?.dispatchEvent(+ new MouseEvent("click", { bubbles: true })+ );+ });+ expect(mocks.createIssueComment).toHaveBeenCalledTimes(1);+ const request = mocks.createIssueComment.mock.calls[0][0];+ expect(request).toMatchObject({ issueName: ISSUE, comment: "No LIMIT" });+ expect(request.statementAnchor).toMatchObject({+ spec: "spec-1",+ sheetSha256: SHA,+ startPosition: { line: 2, column: 0 },+ endPosition: { line: 4, column: 0 },+ });+ expect(fake.zones.size).toBe(0);+ });++ test("a press on the line numbers also selects comment lines", () => {+ mocks.comments = [];+ const fake = createFakeEditor();+ mount(fake.editor);+ fake.fire("down", 5, MouseTargetType.GUTTER_LINE_NUMBERS);+ fake.dragTo(3);+ fake.release();+ expect(fake.zones.size).toBe(0);+ fake.fire("down", 5, MouseTargetType.GUTTER_LINE_DECORATIONS);+ expect(zoneAfter(fake.zones)).toEqual([5]);+ expect(+ hosted(fake.widgets, "[data-testid='composer']")?.getAttribute("data-range")+ ).toBe("3-5");+ });++ test("creation from an occupied line preserves the selected range", () => {+ mocks.comments = [threadRoot("existing", 4, 4)];+ const fake = createFakeEditor();+ mount(fake.editor);+ fake.fire("down", 2, MouseTargetType.GUTTER_LINE_NUMBERS);+ fake.dragTo(4);+ fake.release();+ expect(classesOf(fake.decorations.current, 4)).toContain("bb-thread-add-glyph");+ expect(fake.decorations.current.filter((d) => d.range.startLineNumber === 4 && d.options.glyphMarginClassName)).toHaveLength(1);+ fake.fire("down", 4, MouseTargetType.GUTTER_LINE_DECORATIONS);+ expect(hosted(fake.widgets, "[data-testid='composer']")?.getAttribute("data-range")).toBe("2-4");+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/existing`);+ });++ test("Escape releases the pinned creation action without replacing the count", () => {+ mocks.comments = [threadRoot("a", 4, 4), threadRoot("b", 4, 4)];+ const fake = createFakeEditor(1);+ mount(fake.editor);+ fake.fire("move", 4, MouseTargetType.GUTTER_GLYPH_MARGIN);+ expect(classesOf(fake.decorations.current, 4)).toContain("bb-thread-add-glyph");+ fake.fire("down", 4, MouseTargetType.GUTTER_LINE_NUMBERS);+ fake.release();+ expect(classesOf(fake.decorations.current, 4)).toContain("bb-thread-add-glyph");+ expect(classesOf(fake.decorations.current, 4)).toContain("bb-thread-glyph bb-thread-glyph--count-2 bb-thread-glyph--active");+ fake.pressEscape();+ expect(classesOf(fake.decorations.current, 4)).not.toContain("bb-thread-add-glyph");+ expect(classesOf(fake.decorations.current, 4)).toContain("bb-thread-glyph bb-thread-glyph--count-2 bb-thread-glyph--active");+ expect(hosted(fake.widgets, "[data-testid='composer']")).toBeNull();+ });++ test("whole-line hover exposes creation beside stable thread markers", () => {+ mocks.comments = [threadRoot("a", 4, 4), threadRoot("b", 4, 4)];+ const fake = createFakeEditor();+ mount(fake.editor);+ fake.fire("move", 4, MouseTargetType.CONTENT_TEXT);+ const marker = fake.decorations.current.find((d) => d.options.glyphMarginClassName);+ expect(marker?.options.glyphMarginClassName).toContain("bb-thread-glyph--count-2");+ const add = fake.decorations.current.find((d) => d.options.linesDecorationsClassName === "bb-thread-add-glyph");+ expect(add?.range.startLineNumber).toBe(4);+ expect(add?.options.glyphMarginClassName).toBeUndefined();+ fake.fire("down", 4, MouseTargetType.GUTTER_GLYPH_MARGIN);+ expect(fake.zones.size).toBe(0);+ expect(hosted(fake.widgets, "[data-testid='composer']")).toBeNull();+ fake.fire("down", 4, MouseTargetType.GUTTER_LINE_DECORATIONS);+ expect(hosted(fake.widgets, "[data-testid='composer']")?.getAttribute("data-range")).toBe("4-4");+ });++ test("selection pins the action to its last line and the glyph remains a viewing action", () => {+ mocks.comments = [threadRoot("a", 4, 4)];+ const fake = createFakeEditor();+ mount(fake.editor);+ fake.fire("down", 2, MouseTargetType.GUTTER_LINE_NUMBERS);+ fake.dragTo(4);+ fake.release();+ fake.fire("move", 7, MouseTargetType.CONTENT_TEXT);+ expect(fake.decorations.current.find((d) => d.options.linesDecorationsClassName === "bb-thread-add-glyph")?.range.startLineNumber).toBe(4);+ fake.fire("down", 4, MouseTargetType.GUTTER_GLYPH_MARGIN);+ expect(fake.decorations.current.filter((d) => d.options.className === "bb-thread-line--selecting")).toHaveLength(0);+ expect(hosted(fake.widgets, "[data-testid='composer']")).toBeNull();+ });++ test("blank line hover offers creation but space after the file does not", () => {+ mocks.comments = [];+ const fake = createFakeEditor();+ mount(fake.editor);+ fake.fire("move", 4, MouseTargetType.CONTENT_EMPTY, { isAfterLines: false });+ expect(classesOf(fake.decorations.current, 4)).toContain("bb-thread-add-glyph");+ fake.fire("move", 4, MouseTargetType.CONTENT_EMPTY, { isAfterLines: true });+ expect(classesOf(fake.decorations.current, 4)).toEqual([]);+ });++ test("an all-resolved group keeps its count and resolved state", () => {+ mocks.comments = [threadRoot("a", 2, 4, { resolved: true }), threadRoot("b", 4, 4, { resolved: true })];+ const fake = createFakeEditor();+ mount(fake.editor);+ const marker = fake.decorations.current.find((d) => d.options.glyphMarginClassName);+ expect(marker?.options.glyphMarginClassName).toBe("bb-thread-glyph bb-thread-glyph--count-2 bb-thread-glyph--resolved");+ expect(marker?.options.glyphMarginHoverMessage).toEqual({value: "plan.review.thread.threads-on-line:2"});+ });++ test("without create permission the gutter offers no affordance", () => {+ mocks.comments = [];+ mocks.hasPermission.mockReturnValue(false);+ const fake = createFakeEditor();+ mount(fake.editor);+ fake.fire("move", 2, MouseTargetType.GUTTER_LINE_NUMBERS);+ expect(fake.decorations.current).toEqual([]);+ fake.fire("down", 2, MouseTargetType.GUTTER_GLYPH_MARGIN);+ fake.release();+ expect(fake.zones.size).toBe(0);+ expect(+ (fake.editor as unknown as { addAction: ReturnType<typeof vi.fn> }).addAction+ ).not.toHaveBeenCalled();+ });++ test("status refreshes do not switch or close the automatically expanded thread", () => {+ mocks.comments = [threadRoot("first", 3, 4), threadRoot("other", 6, 9)];+ const fake = createFakeEditor();+ mount(fake.editor);+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/first`);+ mocks.comments = [threadRoot("first", 3, 4, { resolved: true }), threadRoot("other", 6, 9)];+ mount(fake.editor);+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/first`);+ mocks.comments = [threadRoot("first", 3, 4, { resolved: true }), threadRoot("other", 6, 9, { resolved: true })];+ mount(fake.editor);+ expect(zoneAfter(fake.zones)).toEqual([4]);+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/first`);+ });++ test("keeps reply drafts when the entire gutter group closes and reopens", () => {+ mocks.comments = [threadRoot("first", 3, 4)];+ const fake = createFakeEditor();+ mount(fake.editor);+ act(() => hosted(fake.widgets, "[data-testid='save-draft']")?.dispatchEvent(new MouseEvent("click", {bubbles: true})));+ fake.fire("down", 4, MouseTargetType.GUTTER_GLYPH_MARGIN);+ expect(fake.zones.size).toBe(0);+ fake.fire("down", 4, MouseTargetType.GUTTER_GLYPH_MARGIN);+ expect((hosted(fake.widgets, "[data-testid='saved-draft']") as HTMLInputElement)?.value).toBe("unfinished reply");+ act(() => hosted(fake.widgets, "[data-testid='clear-submitted-draft']")?.dispatchEvent(new MouseEvent("click", {bubbles: true})));+ expect((hosted(fake.widgets, "[data-testid='saved-draft']") as HTMLInputElement)?.value).toBe("");+ });++ test("a focus request expands the thread, reveals its line, and is cleared", () => {+ mocks.comments = [+ threadRoot("first", 3, 4, { createdAt: 2 }),+ threadRoot("target", 10, 12, { createdAt: 5 }),+ ];+ mocks.threadFocus = {+ commentName: `${ISSUE}/issueComments/target`,+ specId: "spec-1",+ nonce: 7,+ };+ const fake = createFakeEditor();+ mount(fake.editor);+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/target`);+ expect(+ (fake.editor as unknown as { revealLineInCenter: ReturnType<typeof vi.fn> })+ .revealLineInCenter+ ).toHaveBeenCalledWith(10);+ expect(mocks.clearThreadFocus).toHaveBeenCalledWith(7);+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsxnew file mode 100644index 0000000000..7cfd7518fb--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx@@ -0,0 +1,556 @@+import type * as monaco from "monaco-editor";+import {+ type SetStateAction,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { useTranslation } from "react-i18next";+import { MonacoViewZone } from "@/components/monaco/MonacoViewZone";+import type {+ IStandaloneCodeEditor,+ MonacoModule,+} from "@/components/monaco/types";+import { useProjectByName } from "@/hooks/useProjectByName";+import { useAppStore } from "@/stores/app";+import { projectNamePrefix } from "@/stores/modules/v1/common";+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";+import { placementsForSheet } from "../../shared/stores/placementSlice";+import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";+import { usePlanDetailContext } from "../../shell/PlanDetailContext";+import { InlineThreadComposer } from "./InlineThreadComposer";+import "./statementThreads.css";+import { ThreadStack } from "./ThreadStack";+import {+ buildWholeLineAnchor,+ defaultExpandedThread,+ type EditorThread,+ groupMarkersByLine,+ groupThreads,+ type LineRange,+ lineRangeLabel,+ selectEditorThreads,+ selectionLineRange,+} from "./threadModel";+import { canReplyToThread, useThreadActions } from "./useThreadActions";++// The thread to expand when a line opens: its first unresolved thread, or+// its first thread when all are resolved.+const firstToExpand = (threads: EditorThread[] | undefined): string[] => {+ const entry = threads && (defaultExpandedThread(threads) ?? threads[0]);+ return entry ? [entry.thread.root.name] : [];+};++// Binds comment threads to the read-only statement editor with Monaco's own+// primitives, the way VS Code's comment controller does: glyph-margin+// decorations for markers and the comment affordance, whole-line decorations+// for highlights, and view zones for the composer and the expanded threads.+//+// Creation is a two-step gesture. Selecting lines (a press or drag in the+// gutter, or a text selection) shows the comment action on the last selected+// line. The creation action sits between the line numbers and SQL; thread+// markers stay in the glyph lane and always open the existing discussions.+export function StatementThreadsLayer({+ editor,+ issue,+ monaco: monacoModule,+ sheetSha256,+ spec,+}: {+ editor: IStandaloneCodeEditor;+ issue: Issue;+ monaco: MonacoModule;+ sheetSha256: string;+ spec: Plan_Spec;+}) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const project = useProjectByName(`${projectNamePrefix}${page.projectId}`);+ const comments = useAppStore((state) => state.getIssueComments(issue.name));+ // Placements computed for another revision of this spec say nothing about+ // the displayed one; until the run for this sheet lands, only the no-diff+ // rule applies.+ const placements = usePlanDetailStore((s) =>+ placementsForSheet(s, spec.id, sheetSha256)+ );+ const actions = useThreadActions(issue.name);+ const canCreate = canReplyToThread(project);++ const editorThreads = useMemo(+ () =>+ selectEditorThreads(+ groupThreads(comments),+ { specId: spec.id, sheetSha256 },+ placements+ ),+ [comments, placements, sheetSha256, spec.id]+ );+ const markersByLine = useMemo(+ () => groupMarkersByLine(editorThreads),+ [editorThreads]+ );++ // A union of commented lines, so overlapping threads never darken a line.+ const commentedLines = useMemo(() => {+ const lines = new Set<number>();+ for (const { range } of editorThreads) {+ for (let line = range.startLine; line <= range.endLine; line++)+ lines.add(line);+ }+ return [...lines].sort((a, b) => a - b);+ }, [editorThreads]);++ // Which line's threads are open, and which of them are expanded. By+ // default the first line with an unresolved thread opens with its first+ // unresolved thread expanded and the others collapsed; the user's choices+ // win once they open or close anything.+ const [openLine, setOpenLine] = useState<number | undefined>();+ const [expandedRoots, setExpandedRoots] = useState<ReadonlySet<string>>(+ () => new Set()+ );+ const expandedThreadRef = useRef<HTMLDivElement>(null);+ const initialExpansionAppliedRef = useRef(false);+ useEffect(() => {+ if (initialExpansionAppliedRef.current) return;+ const line = defaultExpandedThread(editorThreads)?.range.endLine;+ if (line === undefined) return;+ initialExpansionAppliedRef.current = true;+ setOpenLine(line);+ setExpandedRoots(new Set(firstToExpand(markersByLine.get(line))));+ }, [editorThreads, markersByLine]);++ const openThreads = useCallback(+ (line: number | undefined, roots: Iterable<string>) => {+ initialExpansionAppliedRef.current = true;+ setOpenLine(line);+ setExpandedRoots(new Set(roots));+ },+ []+ );++ // Keep drafts across card collapses and closing/reopening a gutter group.+ const [replyDrafts, setReplyDrafts] = useState<Record<string, string>>({});+ const updateReplyDraft = useCallback(+ (root: string, update: SetStateAction<string>) => {+ setReplyDrafts((previous) => {+ const draft =+ typeof update === "function" ? update(previous[root] ?? "") : update;+ if (previous[root] === draft) return previous;+ const next = { ...previous };+ if (draft) next[root] = draft;+ else delete next[root];+ return next;+ });+ },+ []+ );++ const [hoveredLine, setHoveredLine] = useState<number | undefined>();+ const [selection, setSelection] = useState<LineRange | undefined>();+ const dragRef = useRef<LineRange | undefined>(undefined);+ const [composerRange, setComposerRange] = useState<LineRange | undefined>();++ // The line that carries the comment action: the end of the selection, or+ // the hovered line when nothing is selected.+ const actionLine = canCreate+ ? (selection?.endLine ?? hoveredLine)+ : undefined;++ // "View in Statement" from the timeline.+ const threadFocus = usePlanDetailStore((s) => s.threadFocus);+ const clearThreadFocus = usePlanDetailStore((s) => s.clearThreadFocus);+ useEffect(() => {+ if (!threadFocus || threadFocus.specId !== spec.id) return;+ const target = editorThreads.find(+ (entry) => entry.thread.root.name === threadFocus.commentName+ );+ if (!target) {+ // Anchors are current only for the saved version; a thread that is not+ // placed here has nothing to reveal.+ if (comments.length > 0) clearThreadFocus(threadFocus.nonce);+ return;+ }+ openThreads(target.range.endLine, [target.thread.root.name]);+ editor.revealLineInCenter(target.range.startLine);+ editor+ .getDomNode()+ ?.scrollIntoView({ behavior: "smooth", block: "center" });+ clearThreadFocus(threadFocus.nonce);+ }, [+ clearThreadFocus,+ comments.length,+ editor,+ editorThreads,+ openThreads,+ spec.id,+ threadFocus,+ ]);++ // Track the editor's selection as a line range (empty = none).+ useEffect(() => {+ const read = () => {+ const current = editor.getSelection();+ if (!current || current.isEmpty()) {+ setSelection(undefined);+ return;+ }+ setSelection(selectionLineRange(current));+ };+ read();+ const subscription = editor.onDidChangeCursorSelection(read);+ return () => subscription.dispose();+ }, [editor]);++ // Decorations: highlights, markers, the comment action, the composer range.+ useEffect(() => {+ const collection = editor.createDecorationsCollection();+ const decorations: monaco.editor.IModelDeltaDecoration[] = [];+ const stickiness =+ monacoModule.editor.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges;+ // Exactly one background per line: passive, current, or creation.+ // Higher-priority states replace the base instead of layering over it.+ const lineClasses = new Map<number, string>(+ commentedLines.map((line) => [line, "bb-thread-line--passive"])+ );+ const activeThread = editorThreads.find(+ (entry) =>+ entry.range.endLine === openLine &&+ expandedRoots.has(entry.thread.root.name)+ );+ const creationRange = composerRange ?? (canCreate ? selection : undefined);+ const range = creationRange ?? activeThread?.range;+ if (range) {+ for (let line = range.startLine; line <= range.endLine; line++) {+ lineClasses.set(+ line,+ creationRange ? "bb-thread-line--selecting" : "bb-thread-line"+ );+ }+ }+ for (const [line, className] of [...lineClasses].sort(+ ([a], [b]) => a - b+ )) {+ decorations.push({+ range: new monacoModule.Range(line, 1, line, 1),+ options: {+ isWholeLine: true,+ className,+ stickiness,+ },+ });+ }+ for (const [line, threads] of markersByLine) {+ const count = threads.length;+ const classes = ["bb-thread-glyph"];+ if (count > 1) {+ classes.push(+ count > 9+ ? "bb-thread-glyph--count-many"+ : `bb-thread-glyph--count-${count}`+ );+ }+ if (threads.every((entry) => entry.thread.resolved)) {+ classes.push("bb-thread-glyph--resolved");+ }+ if (line === openLine) classes.push("bb-thread-glyph--active");+ decorations.push({+ range: new monacoModule.Range(line, 1, line, 1),+ options: {+ glyphMarginClassName: classes.join(" "),+ glyphMargin: { position: monacoModule.editor.GlyphMarginLane.Center },+ glyphMarginHoverMessage: {+ value: t("plan.review.thread.threads-on-line", { count }),+ },+ stickiness,+ },+ });+ }+ if (actionLine !== undefined && !composerRange) {+ const actionRange = selection ?? {+ startLine: actionLine,+ endLine: actionLine,+ };+ decorations.push({+ range: new monacoModule.Range(actionLine, 1, actionLine, 1),+ options: {+ linesDecorationsClassName: "bb-thread-add-glyph",+ linesDecorationsTooltip: `${t("plan.review.thread.add-comment")} · ${lineRangeLabel(t, actionRange)}`,+ stickiness,+ },+ });+ }+ collection.set(decorations);+ return () => {+ collection.clear();+ };+ }, [+ actionLine,+ canCreate,+ commentedLines,+ composerRange,+ editor,+ editorThreads,+ expandedRoots,+ markersByLine,+ monacoModule,+ openLine,+ selection,+ t,+ ]);++ const openComposer = useCallback(+ (range: LineRange) => {+ setComposerRange(range);+ // The composer range takes over the highlight; drop the text selection.+ editor.setPosition({ lineNumber: range.startLine, column: 1 });+ // Empty-line gutter selections may already have this cursor position,+ // so Monaco won't emit a selection-change event to clear our range.+ setSelection(undefined);+ setHoveredLine(undefined);+ },+ [editor]+ );++ // Gutter interaction. A press in the gutter selects lines (drag to extend)+ // through the editor's own selection; the drag follows the pointer with+ // the editor's hit test so it keeps working past the gutter and the+ // editor's edge.+ useEffect(() => {+ const GutterTypes = new Set<monaco.editor.MouseTargetType>([+ monacoModule.editor.MouseTargetType.GUTTER_GLYPH_MARGIN,+ monacoModule.editor.MouseTargetType.GUTTER_LINE_NUMBERS,+ monacoModule.editor.MouseTargetType.GUTTER_LINE_DECORATIONS,+ ]);+ const HoverTypes = new Set([+ ...GutterTypes,+ monacoModule.editor.MouseTargetType.CONTENT_TEXT,+ monacoModule.editor.MouseTargetType.CONTENT_EMPTY,+ ]);+ const lineOf = (target: monaco.editor.IMouseTarget | null) =>+ target?.position?.lineNumber ??+ (target?.range ? target.range.startLineNumber : undefined);+ const selectLines = (range: LineRange) => {+ const start = Math.min(range.startLine, range.endLine);+ const end = Math.max(range.startLine, range.endLine);+ const model = editor.getModel();+ const endColumn = model ? model.getLineMaxColumn(end) : 1;+ editor.focus();+ editor.setSelection(new monacoModule.Range(start, 1, end, endColumn));+ // An empty line has an empty Monaco text selection, but a deliberate+ // gutter selection must still offer creation for that whole line.+ setSelection({ startLine: start, endLine: end });+ };++ const onDragMove = (event: MouseEvent) => {+ const current = dragRef.current;+ if (!current) return;+ const line = lineOf(+ editor.getTargetAtClientPoint(event.clientX, event.clientY)+ );+ if (line === undefined || current.endLine === line) return;+ dragRef.current = { startLine: current.startLine, endLine: line };+ selectLines(dragRef.current);+ };+ const finishDrag = () => {+ dragRef.current = undefined;+ };++ // Escape clears the explicit gutter selection while this editor owns focus.+ const node = editor.getDomNode();+ const cancelSelection = (event: KeyboardEvent) => {+ if (+ event.key !== "Escape" ||+ !selection ||+ !(event.target instanceof Node) ||+ !node?.contains(event.target)+ )+ return;+ event.preventDefault();+ event.stopPropagation();+ const current = editor.getSelection();+ if (current) {+ editor.setPosition({+ lineNumber: current.endLineNumber,+ column: current.endColumn,+ });+ }+ dragRef.current = undefined;+ setSelection(undefined);+ setHoveredLine(undefined);+ };+ node?.addEventListener("keydown", cancelSelection, true);++ const subscriptions = [+ editor.onMouseMove((e) => {+ if (dragRef.current) return;+ const line = lineOf(e.target);+ setHoveredLine(+ line !== undefined &&+ HoverTypes.has(e.target.type) &&+ !(+ e.target.type ===+ monacoModule.editor.MouseTargetType.CONTENT_EMPTY &&+ e.target.detail?.isAfterLines+ )+ ? line+ : undefined+ );+ }),+ editor.onMouseLeave(() => {+ if (!dragRef.current) setHoveredLine(undefined);+ }),+ editor.onMouseDown((e) => {+ if (!GutterTypes.has(e.target.type) || !e.event.leftButton) return;+ const line = lineOf(e.target);+ if (line === undefined) return;+ const isGlyph =+ e.target.type ===+ monacoModule.editor.MouseTargetType.GUTTER_GLYPH_MARGIN;+ const isCreationAction =+ e.target.type ===+ monacoModule.editor.MouseTargetType.GUTTER_LINE_DECORATIONS;+ if (isCreationAction && actionLine === line && !composerRange) {+ e.event.preventDefault();+ openComposer(selection ?? { startLine: line, endLine: line });+ return;+ }+ const threads = isGlyph ? markersByLine.get(line) : undefined;+ if (threads) {+ e.event.preventDefault();+ editor.setPosition({ lineNumber: line, column: 1 });+ setSelection(undefined);+ if (openLine === line) {+ openThreads(undefined, []);+ } else {+ openThreads(line, firstToExpand(threads));+ }+ return;+ }+ if (!canCreate) return;+ // Keeps the browser from starting a text selection during the drag.+ e.event.preventDefault();+ dragRef.current = { startLine: line, endLine: line };+ selectLines(dragRef.current);+ setHoveredLine(undefined);+ }),+ ];+ document.addEventListener("mousemove", onDragMove);+ document.addEventListener("mouseup", finishDrag);+ return () => {+ node?.removeEventListener("keydown", cancelSelection, true);+ document.removeEventListener("mousemove", onDragMove);+ document.removeEventListener("mouseup", finishDrag);+ for (const subscription of subscriptions) subscription.dispose();+ };+ }, [+ actionLine,+ canCreate,+ composerRange,+ editor,+ markersByLine,+ monacoModule,+ openComposer,+ openLine,+ openThreads,+ selection,+ ]);++ // Keyboard and context-menu path: comment on the selected lines.+ useEffect(() => {+ if (!canCreate) return;+ const action = editor.addAction({+ id: "bytebase.comment-on-lines",+ label: t("plan.review.thread.comment-on-lines"),+ contextMenuGroupId: "navigation",+ contextMenuOrder: 0,+ run: () => {+ const current = editor.getSelection();+ if (!current) return;+ openComposer(selectionLineRange(current));+ },+ });+ return () => action.dispose();+ }, [canCreate, editor, openComposer, t]);++ useEffect(() => {+ const node = editor.getDomNode();+ if (!node) return;+ node.classList.toggle("bb-thread-creatable", canCreate);+ return () => node.classList.remove("bb-thread-creatable");+ }, [canCreate, editor]);++ const publish = useCallback(+ async (comment: string) => {+ if (!composerRange) return false;+ const created = await actions.publish(+ comment,+ buildWholeLineAnchor({+ spec: spec.id,+ sheetSha256,+ startLine: composerRange.startLine,+ endLine: composerRange.endLine,+ })+ );+ if (!created) return false;+ setComposerRange(undefined);+ openThreads(composerRange.endLine, [created.name]);+ return true;+ },+ [actions, composerRange, openThreads, sheetSha256, spec.id]+ );++ const openEntries: EditorThread[] =+ openLine !== undefined ? (markersByLine.get(openLine) ?? []) : [];++ return (+ <>+ {openLine !== undefined && openEntries.length > 0 && (+ <MonacoViewZone+ afterLineNumber={openLine}+ editor={editor}+ revealKey={expandedRoots.size > 0 ? expandedRoots : undefined}+ revealTarget={expandedThreadRef}+ >+ <div className="py-2 pr-2 sm:pr-4">+ <ThreadStack+ key={openLine}+ expandedRoots={expandedRoots}+ expandedThreadRef={expandedThreadRef}+ issueName={issue.name}+ onCollapse={(rootName) =>+ openThreads(+ openLine,+ Array.from(expandedRoots).filter((r) => r !== rootName)+ )+ }+ onExpand={(rootName) => openThreads(openLine, [rootName])}+ replyDrafts={replyDrafts}+ onReplyDraftChange={updateReplyDraft}+ project={project}+ threads={openEntries}+ />+ </div>+ </MonacoViewZone>+ )}+ {composerRange && (+ <MonacoViewZone+ afterLineNumber={composerRange.endLine}+ editor={editor}+ revealKey={`${composerRange.startLine}-${composerRange.endLine}`}+ >+ <div className="py-2 pr-2 sm:pr-4">+ <InlineThreadComposer+ onCancel={() => setComposerRange(undefined)}+ onPublish={publish}+ pending={actions.pending}+ range={composerRange}+ />+ </div>+ </MonacoViewZone>+ )}+ </>+ );+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.tsx b/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.tsxnew file mode 100644index 0000000000..885b5224b9--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.tsx@@ -0,0 +1,159 @@+import { Loader2, Pencil } from "lucide-react";+import { type ReactNode, useEffect, useState } from "react";+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 type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";++// 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.+export function ThreadComment({+ actions,+ className,+ comment,+ onEdit,+ project,+ status,+}: {+ // Header actions after the edit button (thread collapse or close).+ actions?: ReactNode;+ className?: string;+ comment: IssueComment;+ onEdit: (issueCommentName: string, comment: string) => Promise<unknown>;+ project: Project | undefined;+ // Thread status shown after the timestamp (resolved).+ status?: ReactNode;+}) {+ const { t } = useTranslation();+ const creator =+ useUserByIdentifier(comment.creator) ?? unknownUser(comment.creator);+ const createdTs = getTimeForPbTimestampProtoEs(comment.createTime, 0);+ const updatedTs = getTimeForPbTimestampProtoEs(comment.updateTime, 0);+ const isEdited = createdTs !== updatedTs;+ const [isEditing, setIsEditing] = useState(false);+ const [draft, setDraft] = useState(comment.comment);+ const [saving, setSaving] = useState(false);+ const allowEdit = canEditIssueComment(comment, project);++ useEffect(() => {+ if (!isEditing) setDraft(comment.comment);+ }, [comment.comment, isEditing]);++ const save = async () => {+ if (!draft.trim() || draft === comment.comment) {+ setIsEditing(false);+ return;+ }+ setSaving(true);+ const updated = await onEdit(comment.name, draft);+ setSaving(false);+ if (updated) setIsEditing(false);+ };++ return (+ <div+ className={cn(+ "@container/comment flex items-start gap-x-2 px-2 py-2 sm:px-3",+ className+ )}+ data-testid="thread-comment"+ id={comment.name}+ >+ <div+ className="flex min-w-0 flex-1 flex-col gap-y-2"+ data-testid="comment-content"+ >+ <div className="flex min-h-6 items-center gap-x-2">+ <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}+ />+ </div>+ <span+ className="min-w-0 truncate text-sm font-medium text-main"+ title={creator.title || creator.email}+ >+ {creator.title || creator.email}+ </span>+ </div>+ {comment.createTime && (+ <HumanizeTs+ className="hidden shrink-0 whitespace-nowrap text-xs text-control-light @2xs/comment:inline"+ ts={createdTs / 1000}+ />+ )}+ {isEdited && (+ <span className="hidden shrink-0 whitespace-nowrap text-xs text-control-light @2xs/comment:inline">+ ({t("common.edited")})+ </span>+ )}+ {status}+ </div>+ <div className="flex shrink-0 items-center gap-x-1">+ {allowEdit && !isEditing && (+ <Button+ aria-label={t("common.edit")}+ onClick={() => {+ setDraft(comment.comment);+ setIsEditing(true);+ }}+ size="xs"+ appearance="secondary"+ >+ <Pencil className="size-3.5" />+ </Button>+ )}+ {actions}+ </div>+ </div>+ {isEditing ? (+ <div className="flex flex-col gap-y-2">+ <MarkdownEditor+ content={draft}+ onChange={setDraft}+ onSubmit={() => void save()}+ />+ <div className="flex items-center justify-end gap-x-2">+ <Button+ onClick={() => setIsEditing(false)}+ size="xs"+ appearance="secondary"+ >+ {t("common.cancel")}+ </Button>+ <Button+ disabled={+ saving ||+ draft.trim().length === 0 ||+ draft === comment.comment+ }+ onClick={() => void save()}+ size="xs"+ >+ {saving && <Loader2 className="size-3.5 animate-spin" />}+ {t("common.save")}+ </Button>+ </div>+ </div>+ ) : (+ comment.comment && (+ <div className="wrap-break-word text-sm text-control">+ <MarkdownEditor content={comment.comment} mode="preview" />+ </div>+ )+ )}+ </div>+ </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.tsxnew file mode 100644index 0000000000..f425a229f3--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.test.tsx@@ -0,0 +1,144 @@+import { create } from "@bufbuild/protobuf";+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 } from "@/types/proto-es/v1/issue_service_pb";+import type { EditorThread } from "./threadModel";+import { ThreadStack } from "./ThreadStack";++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("@/components/HumanizeTs", () => ({ HumanizeTs: () => <span>17h</span> }));+vi.mock("@/stores/app", () => ({+ useAppStore: (selector: (state: unknown) => unknown) =>+ selector({ getUserByIdentifier: () => ({ email: "[email protected]", title: "Aurora" }) }),+}));+vi.mock("./CommentThreadCard", () => ({+ CommentThreadCard: ({ thread, onThreadStateChanged, replyDraft, onReplyDraftChange }: {+ thread: EditorThread["thread"];+ onThreadStateChanged: (resolved: boolean) => void;+ replyDraft: string;+ onReplyDraftChange: (draft: string) => void;+ }) => (+ <div data-thread-name={thread.root.name} data-resolved={String(thread.resolved)}>+ <input aria-label="Reply draft" value={replyDraft} onChange={(e) => onReplyDraftChange(e.target.value)} />+ <button onClick={() => onThreadStateChanged(!thread.resolved)}>Change state</button>+ </div>+ ),+}));++afterEach(() => { cleanup(); vi.clearAllMocks(); });++const entry = (name: string, resolved: boolean, seconds: number): EditorThread => ({+ range: { startLine: 2, endLine: 2 },+ thread: {+ root: create(IssueCommentSchema, {+ name,+ creator: "[email protected]",+ comment: `${name} summary\nsecond line`,+ createTime: create(TimestampSchema, { seconds: BigInt(seconds) }),+ }),+ replies: [],+ resolved,+ },+});+const props = {+ issueName: "projects/p/issues/1",+ project: undefined,+ onCollapse: vi.fn(),+ onExpand: vi.fn(),+ expandedRoots: new Set<string>(),+ replyDrafts: {},+ onReplyDraftChange: vi.fn(),+};+const order = (container: HTMLElement) =>+ Array.from(container.querySelectorAll("[data-thread-name]")).map((el) => el.getAttribute("data-thread-name"));++describe("ThreadStack", () => {+ test("keeps order and mounted drafts on status updates, then regroups on reopening", () => {+ const threads = [entry("resolved", true, 1), entry("open-a", false, 2), entry("open-b", false, 3)];+ const expandedRoots = new Set(["open-a"]);+ const { container, rerender } = render(<ThreadStack {...props} expandedRoots={expandedRoots} threads={threads} key="first-open" />);+ expect(order(container)).toEqual(["open-a", "open-b", "resolved"]);+ expect(container.querySelectorAll('[role="none"]')).toHaveLength(0);+ const draft = container.querySelector("input");+ const changed = [entry("resolved", false, 1), entry("open-a", true, 2), entry("open-b", false, 3)];+ rerender(<ThreadStack {...props} expandedRoots={expandedRoots} threads={changed} key="first-open" />);+ expect(order(container)).toEqual(["open-a", "open-b", "resolved"]);+ expect(container.querySelector("input")).toBe(draft);+ expect(container.querySelector('[data-thread-name="open-a"]')?.getAttribute("data-resolved")).toBe("true");+ rerender(<ThreadStack {...props} expandedRoots={expandedRoots} threads={changed} key="reopened" />);+ expect(order(container)).toEqual(["resolved", "open-b", "open-a"]);+ });++ test.each([false, true])("omits the separator for a single status group: %s", (resolved) => {+ const { container } = render(<ThreadStack {...props} threads={[entry("a", resolved, 1), entry("b", resolved, 2)]} />);+ expect(container.querySelectorAll('[role="none"]')).toHaveLength(0);+ expect(order(container)).toEqual(["a", "b"]);+ });++ test.each([+ { current: "a", states: [false, true, false], next: "c" },+ { current: "c", states: [false, true, false], next: "a" },+ { current: "a", states: [false, true, true], next: undefined },+ ])("advances after resolving $current, skipping resolved and wrapping within the stack", ({ current, states, next }) => {+ const threads = states.map((resolved, index) => entry(["a", "b", "c"][index], resolved, index));+ const { getByText } = render(<ThreadStack {...props} expandedRoots={new Set([current])} threads={threads} />);+ fireEvent.click(getByText("Change state"));+ if (next) expect(props.onExpand).toHaveBeenCalledWith(next);+ else {+ expect(props.onCollapse).toHaveBeenCalledWith(current);+ expect(props.onExpand).not.toHaveBeenCalled();+ }+ });++ test("reopens the current thread in place", () => {+ const { getByText } = render(<ThreadStack {...props} expandedRoots={new Set(["a"])} threads={[entry("a", true, 1), entry("b", false, 2)]} />);+ fireEvent.click(getByText("Change state"));+ expect(props.onExpand).toHaveBeenCalledWith("a");+ expect(props.onCollapse).not.toHaveBeenCalled();+ });++ test("preserves a reply draft when advancing and returning to a collapsed thread", () => {+ function Harness() {+ const [expanded, setExpanded] = useState(new Set(["a"]));+ const [drafts, setDrafts] = useState<Record<string, string>>({});+ return <ThreadStack {...props}+ threads={[entry("a", false, 1), entry("b", false, 2)]}+ expandedRoots={expanded}+ onExpand={(name) => setExpanded(new Set([name]))}+ onCollapse={() => setExpanded(new Set())}+ replyDrafts={drafts}+ onReplyDraftChange={(name, draft) => setDrafts((previous) => ({...previous, [name]: typeof draft === "function" ? draft(previous[name] ?? "") : draft}))}+ />;+ }+ const { container, getByLabelText, getByText } = render(<Harness />);+ fireEvent.change(getByLabelText("Reply draft"), { target: { value: "unfinished reply" } });+ fireEvent.click(getByText("Change state"));+ expect(container.querySelector('[data-thread-name="b"] input')).not.toBeNull();+ fireEvent.click(container.querySelector('[data-thread-name="a"]')!);+ expect((getByLabelText("Reply draft") as HTMLInputElement).value).toBe("unfinished reply");+ });++ test("shows new threads and removes missing ones without remounting retained rows", () => {+ const { container, rerender } = render(<ThreadStack {...props} threads={[entry("a", false, 1), entry("b", true, 2)]} />);+ const first = container.querySelector('[data-thread-name="a"]');+ rerender(<ThreadStack {...props} threads={[entry("a", true, 1), entry("c", false, 3), entry("d", true, 4)]} />);+ expect(order(container)).toEqual(["a", "c", "d"]);+ expect(container.querySelector('[data-thread-name="a"]')).toBe(first);+ expect(container.textContent).not.toContain("second line");+ });+});+++test("exposes the expanded card for editor reveal", () => {+ const ref = createRef<HTMLDivElement>();+ const threads = [entry("a", false, 1), entry("b", false, 2)];+ const {rerender} = render(<ThreadStack {...props} threads={threads} expandedRoots={new Set(["a"])} expandedThreadRef={ref} />);+ expect(ref.current?.querySelector('[data-thread-name="a"]')).not.toBeNull();+ rerender(<ThreadStack {...props} threads={threads} expandedRoots={new Set(["b"])} expandedThreadRef={ref} />);+ expect(ref.current?.querySelector('[data-thread-name="b"]')).not.toBeNull();+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsx b/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsxnew file mode 100644index 0000000000..7eec1d23ea--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsx@@ -0,0 +1,227 @@+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 { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";+import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";+import { CommentThreadCard } from "./CommentThreadCard";+import {+ compareByCreateTime,+ type EditorThread,+ formatLineRange,+ lineRangeLabel,+} from "./threadModel";++type ThreadGroups = { open: string[]; resolved: string[] };++// Capture group membership when a thread first appears in this open stack.+// Live status changes update the content, never the current reading order.+function includeNewThreads(+ groups: ThreadGroups,+ threads: EditorThread[]+): ThreadGroups {+ const known = new Set([...groups.open, ...groups.resolved]);+ const added = threads+ .filter((entry) => !known.has(entry.thread.root.name))+ .sort((a, b) => compareByCreateTime(a.thread.root, b.thread.root));+ if (added.length === 0) return groups;+ return {+ open: [+ ...groups.open,+ ...added+ .filter((entry) => !entry.thread.resolved)+ .map((entry) => entry.thread.root.name),+ ],+ resolved: [+ ...groups.resolved,+ ...added+ .filter((entry) => entry.thread.resolved)+ .map((entry) => entry.thread.root.name),+ ],+ };+}++// A mount is one viewing session. Reopening the gutter or switching lines+// remounts the stack, sorting Open before Resolved using the latest state.+export function ThreadStack({+ expandedRoots,+ expandedThreadRef,+ issueName,+ onCollapse,+ onExpand,+ replyDrafts,+ onReplyDraftChange,+ project,+ threads,+}: {+ expandedRoots: ReadonlySet<string>;+ expandedThreadRef?: Ref<HTMLDivElement>;+ issueName: string;+ onCollapse: (rootName: string) => void;+ onExpand: (rootName: string) => void;+ replyDrafts: Readonly<Record<string, string>>;+ onReplyDraftChange: (rootName: string, draft: SetStateAction<string>) => void;+ project: Project | undefined;+ threads: EditorThread[];+}) {+ const { t } = useTranslation();+ const [groups, setGroups] = useState(() =>+ includeNewThreads({ open: [], resolved: [] }, threads)+ );+ const nextGroups = includeNewThreads(groups, threads);+ if (nextGroups !== groups) setGroups(nextGroups);+ const byName = new Map(+ threads.map((entry) => [entry.thread.root.name, entry])+ );+ const currentEntries = (names: string[]) =>+ names.flatMap((name) => {+ const entry = byName.get(name);+ return entry ? [entry] : [];+ });+ const open = currentEntries(nextGroups.open);+ const resolved = currentEntries(nextGroups.resolved);+ const ordered = [...open, ...resolved];+ const handleStateChanged = (name: string, resolved: boolean) => {+ if (!expandedRoots.has(name)) return;+ if (!resolved) {+ onExpand(name);+ return;+ }+ const index = ordered.findIndex((entry) => entry.thread.root.name === name);+ const next = [...ordered.slice(index + 1), ...ordered.slice(0, index)].find(+ (entry) => entry.thread.root.name !== name && !entry.thread.resolved+ );+ if (next) onExpand(next.thread.root.name);+ else onCollapse(name);+ };+ // Threads ending on the same line may cover different ranges; label each+ // with its range only when they differ.+ const showRanges =+ new Set(threads.map((entry) => formatLineRange(entry.range))).size > 1;+ const rangeLabel = (entry: EditorThread) =>+ showRanges ? (+ <span className="shrink-0 text-xs text-control-light">+ {lineRangeLabel(t, entry.range)}+ </span>+ ) : undefined;+ return (+ <div+ className="@container flex min-w-0 flex-col gap-y-2"+ data-testid="thread-stack"+ >+ {ordered.map((entry) => (+ <div+ key={entry.thread.root.name}+ ref={+ expandedRoots.has(entry.thread.root.name)+ ? expandedThreadRef+ : undefined+ }+ >+ {expandedRoots.has(entry.thread.root.name) ? (+ <CommentThreadCard+ className="shadow-sm"+ collapsible={false}+ issueName={issueName}+ label={rangeLabel(entry)}+ onClose={() => onCollapse(entry.thread.root.name)}+ onThreadStateChanged={(resolved) =>+ handleStateChanged(entry.thread.root.name, resolved)+ }+ replyDraft={replyDrafts[entry.thread.root.name] ?? ""}+ onReplyDraftChange={(draft) =>+ onReplyDraftChange(entry.thread.root.name, draft)+ }+ project={project}+ thread={entry.thread}+ />+ ) : (+ <CollapsedThreadRow+ comment={entry.thread.root}+ label={rangeLabel(entry)}+ onSelect={() => onExpand(entry.thread.root.name)}+ replyCount={entry.thread.replies.length}+ resolved={entry.thread.resolved}+ />+ )}+ </div>+ ))}+ </div>+ );+}++function CollapsedThreadRow({+ comment,+ label,+ onSelect,+ replyCount,+ resolved,+}: {+ comment: IssueComment;+ label?: ReactNode;+ onSelect: () => void;+ replyCount: number;+ resolved: boolean;+}) {+ const { t } = useTranslation();+ const creator =+ useUserByIdentifier(comment.creator) ?? unknownUser(comment.creator);+ const firstLine = comment.comment.split("\n")[0] ?? "";+ return (+ <Button+ appearance="secondary"+ className="w-full min-w-0 justify-start rounded-sm border border-block-border bg-background text-left font-normal hover:bg-control-bg"+ data-testid="thread-row"+ data-thread-name={comment.name}+ aria-expanded={false}+ onClick={onSelect}+ size="md"+ >+ <UserAvatar+ colorSeed={creator.email}+ size="xs"+ title={creator.title || creator.email}+ />+ <span+ className="max-w-24 truncate font-medium text-main"+ title={creator.title || creator.email}+ >+ {creator.title || creator.email}+ </span>+ <span className="min-w-0 flex-1 truncate text-control" title={firstLine}>+ {firstLine}+ </span>+ {label}+ {replyCount > 0 && (+ <span+ className="flex shrink-0 items-center gap-x-1 text-xs text-control-light"+ title={t("plan.review.thread.n-replies", { count: replyCount })}+ >+ <MessageSquare className="size-3.5" />+ <span aria-hidden="true">{replyCount}</span>+ <span className="sr-only">+ {t("plan.review.thread.n-replies", { count: replyCount })}+ </span>+ </span>+ )}+ {comment.createTime && (+ <HumanizeTs+ className="hidden shrink-0 text-xs text-control-light @xl:inline"+ ts={getTimeForPbTimestampProtoEs(comment.createTime, 0) / 1000}+ />+ )}+ {resolved && (+ <Badge className="shrink-0 gap-x-1 px-2 text-xs" variant="success">+ <CircleCheck className="size-3" />+ {t("plan.review.thread.resolved")}+ </Badge>+ )}+ <ChevronDown className="size-4 shrink-0 text-control-light" />+ </Button>+ );+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/budgets.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/budgets.tsnew file mode 100644index 0000000000..eefa08d144--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/budgets.ts@@ -0,0 +1,36 @@+// Fixed limits for computing placements in the browser. Fetching is bounded+// before it starts and the diff is bounded while it runs; anything past a limit+// is UNAVAILABLE, never a partial answer.+//+// The values are provisional placeholders until page-load measurements on+// representative plans set them (design open question 3). Keep them fixed in+// code rather than configurable so results are reproducible.+export interface PlacementBudgets {+ // Distinct sheets one run may download, and again the distinct sheets one+ // run may hand to the worker, cached or not.+ readonly maxSheets: number;+ // Upper bound on a single sheet's content size in bytes.+ readonly maxBytesPerSheet: number;+ // Upper bound on the bytes downloaded by one run, sources and targets, and+ // again on the bytes one run hands to the worker.+ readonly maxTotalBytes: number;+ // Upper bound on the lines of one tokenized sheet.+ readonly maxLinesPerSheet: number;+ // Diff frontier steps plus token comparisons for one saved/current pair.+ readonly maxWorkPerPair: number;+ // The same unit, summed over every pair in one run.+ readonly maxWorkPerRun: number;+ // Wall-clock limit for the worker; the worker is terminated when it expires.+ readonly workerDeadlineMs: number;+}++export const PLACEMENT_BUDGETS: PlacementBudgets = Object.freeze({+ maxSheets: 16,+ // Matches the backend preview cutoff (common.MaxSheetSize).+ maxBytesPerSheet: 2 * 1024 * 1024,+ maxTotalBytes: 8 * 1024 * 1024,+ maxLinesPerSheet: 50_000,+ maxWorkPerPair: 5_000_000,+ maxWorkPerRun: 20_000_000,+ workerDeadlineMs: 5_000,+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/concurrency.test.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/concurrency.test.tsnew file mode 100644index 0000000000..1ff10245a9--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/concurrency.test.ts@@ -0,0 +1,42 @@+import { describe, expect, test } from "vitest";+import { runWithConcurrency } from "./concurrency";++describe("runWithConcurrency", () => {+ test("never runs more than the limit at once and keeps result order", async () => {+ let inFlight = 0;+ let peak = 0;+ const release: (() => void)[] = [];+ const pending = runWithConcurrency([1, 2, 3, 4, 5], 2, (item) => {+ inFlight++;+ peak = Math.max(peak, inFlight);+ return new Promise<number>((resolve) => {+ release.push(() => {+ inFlight--;+ resolve(item * 10);+ });+ });+ });+ await Promise.resolve();+ expect(inFlight).toBe(2);+ while (release.length) {+ release.shift()?.();+ await Promise.resolve();+ await Promise.resolve();+ }+ expect(await pending).toEqual([10, 20, 30, 40, 50]);+ expect(peak).toBe(2);+ });++ test("records a rejection as undefined without stopping the rest", async () => {+ const results = await runWithConcurrency(["a", "b", "c"], 3, async (x) => {+ if (x === "b") throw new Error("boom");+ return x.toUpperCase();+ });+ expect(results).toEqual(["A", undefined, "C"]);+ });++ test("handles an empty list and a limit larger than the list", async () => {+ expect(await runWithConcurrency([], 4, async (x) => x)).toEqual([]);+ expect(await runWithConcurrency([1], 4, async (x) => x)).toEqual([1]);+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/concurrency.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/concurrency.tsnew file mode 100644index 0000000000..f259f3605e--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/concurrency.ts@@ -0,0 +1,25 @@+// Runs `task` over `items` with at most `limit` in flight, preserving order in+// the result. Rejections are collected as `undefined` so one failed sheet+// fetch does not abort the others.+export async function runWithConcurrency<T, R>(+ items: readonly T[],+ limit: number,+ task: (item: T) => Promise<R>+): Promise<(R | undefined)[]> {+ const results: (R | undefined)[] = new Array(items.length);+ let next = 0;+ const worker = async () => {+ while (next < items.length) {+ const index = next++;+ try {+ results[index] = await task(items[index]);+ } catch {+ results[index] = undefined;+ }+ }+ };+ await Promise.all(+ Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, worker)+ );+ return results;+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/lineTokens.test.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/lineTokens.test.tsnew file mode 100644index 0000000000..2687dc1007--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/lineTokens.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest";+import { tokenizeLines } from "./lineTokens";++describe("tokenizeLines", () => {+ it("always emits a final token", () => {+ expect(tokenizeLines("")).toEqual([""]);+ expect(tokenizeLines("A")).toEqual(["A"]);+ expect(tokenizeLines("A\n")).toEqual(["A\n", ""]);+ });++ it("treats CRLF, LF, and lone CR as line breaks and keeps terminators", () => {+ expect(tokenizeLines("A\r\nB\r")).toEqual(["A\r\n", "B\r", ""]);+ expect(tokenizeLines("A\rB\nC\r\nD")).toEqual(["A\r", "B\n", "C\r\n", "D"]);+ expect(tokenizeLines("\n\n")).toEqual(["\n", "\n", ""]);+ expect(tokenizeLines("\r\r\n")).toEqual(["\r", "\r\n", ""]);+ });++ it("never merges a CR with a later LF that is not adjacent", () => {+ expect(tokenizeLines("A\r \nB")).toEqual(["A\r", " \n", "B"]);+ });++ it("reproduces the input when concatenated", () => {+ for (const text of [+ "",+ "x",+ "a\nb",+ "a\r\nb\rc\n",+ "\r\n\r\n",+ "é\n漢字\r\n",+ ]) {+ expect(tokenizeLines(text).join("")).toBe(text);+ }+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/lineTokens.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/lineTokens.tsnew file mode 100644index 0000000000..ece59737af--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/lineTokens.ts@@ -0,0 +1,22 @@+// Splits raw sheet content into editor lines the way the design's placement+// rule expects: CRLF, LF, and a lone CR each end a line, every token keeps its+// own terminator, and the final token is always emitted even when empty, so+// "A\n" has two lines like it does in the editor. Concatenating the tokens+// reproduces the input byte for byte. Token index + 1 is the editor line.+export function tokenizeLines(text: string): string[] {+ const tokens: string[] = [];+ let start = 0;+ for (let i = 0; i < text.length; i++) {+ const code = text.charCodeAt(i);+ if (code === 10) {+ tokens.push(text.slice(start, i + 1));+ start = i + 1;+ } else if (code === 13) {+ if (text.charCodeAt(i + 1) === 10) i++;+ tokens.push(text.slice(start, i + 1));+ start = i + 1;+ }+ }+ tokens.push(text.slice(start));+ return tokens;+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/myersDiff.test.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/myersDiff.test.tsnew file mode 100644index 0000000000..0b5cec9f20--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/myersDiff.test.ts@@ -0,0 +1,160 @@+import { describe, expect, it } from "vitest";+import { diffLines, type Hunk } from "./myersDiff";++// Applies `hunks` to `saved`, taking replacement lines from `current`; used by+// tests to prove a hunk list is a faithful edit script.+function applyHunks(+ saved: readonly string[],+ current: readonly string[],+ hunks: readonly Hunk[]+): string[] {+ const out: string[] = [];+ let sPos = 1;+ let cPos = 1;+ for (const hunk of hunks) {+ while (sPos < hunk.sStart) {+ out.push(saved[sPos - 1]);+ sPos++;+ cPos++;+ }+ for (let i = 0; i < hunk.cLen; i++) out.push(current[cPos - 1 + i]);+ sPos += hunk.sLen;+ cPos += hunk.cLen;+ }+ while (sPos <= saved.length) {+ out.push(saved[sPos - 1]);+ sPos++;+ }+ return out;+}++const diff = (a: string[], b: string[], budget = 1_000_000): Hunk[] => {+ const result = diffLines(a, b, budget);+ if (!result.complete) throw new Error("diff did not complete");+ // Every pinned hunk list must also be a correct edit script.+ expect(applyHunks(a, b, result.hunks)).toEqual(b);+ return result.hunks;+};++describe("diffLines", () => {+ it("returns no hunks for identical or empty inputs", () => {+ expect(diff([], [])).toEqual([]);+ expect(diff(["A"], ["A"])).toEqual([]);+ expect(diff(["A", "B", "C"], ["A", "B", "C"])).toEqual([]);+ });++ it("reports a whole-document insertion or deletion", () => {+ expect(diff([], ["A", "B"])).toEqual([{ sStart: 1, sLen: 0, cLen: 2 }]);+ expect(diff(["A", "B"], [])).toEqual([{ sStart: 1, sLen: 2, cLen: 0 }]);+ });++ it("places pure insertions at the saved line they precede", () => {+ expect(diff(["B", "C"], ["A", "B", "C"])).toEqual([+ { sStart: 1, sLen: 0, cLen: 1 },+ ]);+ expect(diff(["A", "C"], ["A", "B", "C"])).toEqual([+ { sStart: 2, sLen: 0, cLen: 1 },+ ]);+ expect(diff(["A", "B"], ["A", "B", "C"])).toEqual([+ { sStart: 3, sLen: 0, cLen: 1 },+ ]);+ });++ it("reports deletions at the first removed saved line", () => {+ expect(diff(["A", "B", "C"], ["B", "C"])).toEqual([+ { sStart: 1, sLen: 1, cLen: 0 },+ ]);+ expect(diff(["A", "B", "C"], ["A", "C"])).toEqual([+ { sStart: 2, sLen: 1, cLen: 0 },+ ]);+ expect(diff(["A", "B", "C"], ["A", "B"])).toEqual([+ { sStart: 3, sLen: 1, cLen: 0 },+ ]);+ });++ it("merges an adjacent delete and insert into one replacement hunk", () => {+ expect(diff(["A", "B", "C"], ["A", "X", "C"])).toEqual([+ { sStart: 2, sLen: 1, cLen: 1 },+ ]);+ expect(diff(["A", "B", "C", "D"], ["A", "X", "Y", "Z", "D"])).toEqual([+ { sStart: 2, sLen: 2, cLen: 3 },+ ]);+ });++ it("keeps separate hunks separated by unchanged lines", () => {+ expect(diff(["A", "B", "C", "D", "E"], ["A", "X", "C", "D", "Y"])).toEqual([+ { sStart: 2, sLen: 1, cLen: 1 },+ { sStart: 5, sLen: 1, cLen: 1 },+ ]);+ });++ // Pinned alignment for repeated lines: the design accepts whichever+ // occurrence the fixed implementation keeps. Changing this expectation+ // moves comments and needs a deliberate decision.+ it("pins which duplicate survives when one of two copies is removed", () => {+ // [A, X, B, X, C] -> [A, X, C]: the first X is kept, B and the second X+ // are deleted as one hunk.+ expect(diff(["A", "X", "B", "X", "C"], ["A", "X", "C"])).toEqual([+ { sStart: 3, sLen: 2, cLen: 0 },+ ]);+ // Adjacent duplicates: removing one of [X, X] deletes the second.+ expect(diff(["A", "X", "X", "B"], ["A", "X", "B"])).toEqual([+ { sStart: 3, sLen: 1, cLen: 0 },+ ]);+ // Adding a duplicate inserts it after the existing one.+ expect(diff(["A", "X", "B"], ["A", "X", "X", "B"])).toEqual([+ { sStart: 3, sLen: 0, cLen: 1 },+ ]);+ });++ it("pins the alignment of a block reorder", () => {+ // Moving C above A/B is reported as deleting C below and inserting it+ // above, so A and B stay mapped and C does not.+ expect(diff(["A", "B", "C"], ["C", "A", "B"])).toEqual([+ { sStart: 1, sLen: 0, cLen: 1 },+ { sStart: 3, sLen: 1, cLen: 0 },+ ]);+ // Swapping two lines keeps the second one: A is deleted above B and+ // re-inserted below it.+ expect(diff(["A", "B"], ["B", "A"])).toEqual([+ { sStart: 1, sLen: 1, cLen: 0 },+ { sStart: 3, sLen: 0, cLen: 1 },+ ]);+ });++ it("compares tokens byte for byte, including terminators", () => {+ expect(diff(["A\r\n", "B"], ["A\n", "B"])).toEqual([+ { sStart: 1, sLen: 1, cLen: 1 },+ ]);+ expect(diff(["A\n", ""], ["A"])).toEqual([{ sStart: 1, sLen: 2, cLen: 1 }]);+ });++ it("counts work and stops without hunks once the budget is exceeded", () => {+ const a = Array.from({ length: 40 }, (_, i) => `a${i}`);+ const b = Array.from({ length: 40 }, (_, i) => `b${i}`);+ const full = diffLines(a, b, 1_000_000);+ expect(full.complete).toBe(true);+ expect(full.work).toBeGreaterThan(40);+ const bounded = diffLines(a, b, 100);+ expect(bounded).toEqual({ complete: false, work: 101 });+ // A budget exactly equal to the work needed still completes.+ expect(diffLines(a, b, full.work).complete).toBe(true);+ expect(diffLines(a, b, full.work - 1).complete).toBe(false);+ });++ it("produces a valid edit script for random inputs", () => {+ let seed = 7;+ const rand = () => {+ seed = (seed * 1103515245 + 12345) & 0x7fffffff;+ return seed;+ };+ for (let round = 0; round < 200; round++) {+ const alphabet = ["A", "B", "C", "D"];+ const a = Array.from({ length: rand() % 12 }, () => alphabet[rand() % 4]);+ const b = Array.from({ length: rand() % 12 }, () => alphabet[rand() % 4]);+ const result = diffLines(a, b, 1_000_000);+ expect(result.complete).toBe(true);+ if (result.complete) expect(applyHunks(a, b, result.hunks)).toEqual(b);+ }+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/myersDiff.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/myersDiff.tsnew file mode 100644index 0000000000..3983e2c64f--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/myersDiff.ts@@ -0,0 +1,126 @@+// A bounded Myers line diff whose hunk output is pinned by tests. Placement+// depends on exactly which lines a diff keeps, so this stays our own+// implementation rather than a library whose alignment may change on upgrade.++// `sLen` saved lines starting at saved line `sStart` (one-based) are replaced+// by `cLen` current lines. Hunks hold edits only, no context. For a pure+// insertion `sLen` is 0 and `sStart` is the saved line the new lines go in+// front of, in `1..N+1`.+export interface Hunk {+ readonly sStart: number;+ readonly sLen: number;+ readonly cLen: number;+}++export type LineDiffResult =+ | { readonly complete: true; readonly hunks: Hunk[]; readonly work: number }+ | { readonly complete: false; readonly work: number };++type Op = 0 | 1 | 2; // equal, delete, insert+const EQUAL: Op = 0;+const DELETE: Op = 1;+const INSERT: Op = 2;++// Classic forward Myers (An O(ND) Difference Algorithm, 1986) with a trace of+// each round's frontier for backtracking. Tie-breaking is the paper's: when+// both neighbors reach as far, extend from the k+1 diagonal, so an insertion+// is preferred over a deletion at equal cost, and a deletion is chosen only+// when it reaches strictly further. `work` counts frontier steps and token+// comparisons; when it would exceed `budget` the diff stops and reports+// `complete: false` with no hunks.+export function diffLines(+ saved: readonly string[],+ current: readonly string[],+ budget: number+): LineDiffResult {+ const n = saved.length;+ const m = current.length;+ const max = n + m;+ // Diagonal k maps to index k + offset; the extra slot on each side lets the+ // k == -d / k == d reads stay in range without branching.+ const offset = max + 1;+ const v = new Int32Array(2 * max + 3);+ const trace: Int32Array[] = [];+ let work = 0;++ let found = false;+ for (let d = 0; d <= max && !found; d++) {+ // Snapshot the diagonals round d reads from: [-d-1, d+1].+ trace.push(v.slice(offset - d - 1, offset + d + 2));+ for (let k = -d; k <= d; k += 2) {+ if (++work > budget) return { complete: false, work };+ let x: number;+ if (k === -d || (k !== d && v[k - 1 + offset] < v[k + 1 + offset])) {+ x = v[k + 1 + offset];+ } else {+ x = v[k - 1 + offset] + 1;+ }+ let y = x - k;+ while (x < n && y < m) {+ if (++work > budget) return { complete: false, work };+ if (saved[x] !== current[y]) break;+ x++;+ y++;+ }+ v[k + offset] = x;+ if (x >= n && y >= m) {+ found = true;+ break;+ }+ }+ }++ return { complete: true, hunks: backtrack(trace, n, m), work };+}++function backtrack(trace: Int32Array[], n: number, m: number): Hunk[] {+ const script: Op[] = [];+ let x = n;+ let y = m;+ for (let d = trace.length - 1; d > 0; d--) {+ const prev = trace[d];+ const at = (k: number) => prev[k + d + 1];+ const k = x - y;+ const prevK =+ k === -d || (k !== d && at(k - 1) < at(k + 1)) ? k + 1 : k - 1;+ const prevX = at(prevK);+ const prevY = prevX - prevK;+ while (x > prevX && y > prevY) {+ script.push(EQUAL);+ x--;+ y--;+ }+ script.push(x === prevX ? INSERT : DELETE);+ x = prevX;+ y = prevY;+ }+ // What remains is the leading snake on diagonal 0.+ while (x > 0) {+ script.push(EQUAL);+ x--;+ }+ script.reverse();++ const hunks: Hunk[] = [];+ let open: { sStart: number; sLen: number; cLen: number } | undefined;+ let sPos = 0; // saved lines consumed so far+ for (const op of script) {+ if (op === EQUAL) {+ if (open) {+ hunks.push(open);+ open = undefined;+ }+ sPos++;+ continue;+ }+ open ??= { sStart: sPos + 1, sLen: 0, cLen: 0 };+ if (op === DELETE) {+ open.sLen++;+ sPos++;+ } else {+ open.cLen++;+ }+ }+ if (open) hunks.push(open);+ return hunks;+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/place.test.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/place.test.tsnew file mode 100644index 0000000000..f5a99ebe3c--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/place.test.ts@@ -0,0 +1,208 @@+import { describe, expect, it } from "vitest";+import {+ current,+ diffPair,+ OUTDATED,+ placeOnPair,+ placeWithHunks,+ tokenizeSheet,+ UNAVAILABLE,+} from "./place";++const limits = { maxLinesPerSheet: 10_000, maxWork: 1_000_000 };+const at = (saved: string, currentText: string, first: number, last = first) =>+ placeOnPair(+ diffPair(tokenizeSheet(saved), tokenizeSheet(currentText), limits),+ { startLine: first, endLine: last }+ );++// A longer script with a comment on the middle statement.+const script = [+ "CREATE TABLE a (id INT);",+ "",+ "ALTER TABLE a",+ " ADD COLUMN name TEXT;",+ "",+ "DROP TABLE b;",+].join("\n");++describe("place: the design's example table", () => {+ it("shifts by the net line count for edits above", () => {+ const inserted = `-- header\n-- more\n${script}`;+ expect(at(script, inserted, 3, 4)).toEqual(current(5, 6));+ const deleted = script.split("\n").slice(1).join("\n");+ expect(at(script, deleted, 3, 4)).toEqual(current(2, 3));+ });++ it("keeps the same lines for edits below", () => {+ expect(at(script, `${script}\nDROP TABLE c;`, 3, 4)).toEqual(current(3, 4));+ const deletedBelow = script.split("\n").slice(0, 5).join("\n");+ expect(at(script, deletedBelow, 3, 4)).toEqual(current(3, 4));+ });++ it("outdates when any character inside changes", () => {+ const changed = script.replace("name TEXT", "name TEXT");+ expect(at(script, changed, 3, 4)).toEqual(OUTDATED);+ expect(at(script, changed, 4)).toEqual(OUTDATED);+ // The untouched line of the selection alone is still current.+ expect(at(script, changed, 3)).toEqual(current(3, 3));+ });++ it("comes back after an intermediate edit is reverted", () => {+ const inserted = `-- header\n${script}`;+ expect(at(script, inserted, 3, 4)).toEqual(current(4, 5));+ expect(at(script, script, 3, 4)).toEqual(current(3, 4));+ });++ it("outdates when its lines are deleted", () => {+ const removed = script.split("\n").filter((_, i) => i !== 2 && i !== 3);+ expect(at(script, removed.join("\n"), 3, 4)).toEqual(OUTDATED);+ });++ it("follows the pinned alignment for duplicate lines", () => {+ // [A, X, B, X, C] -> [A, X, C] keeps the first X.+ expect(at("A\nX\nB\nX\nC", "A\nX\nC", 2)).toEqual(current(2, 2));+ expect(at("A\nX\nB\nX\nC", "A\nX\nC", 4)).toEqual(OUTDATED);+ });+});++describe("place: hunk boundaries", () => {+ it("shifts for an insertion immediately above and ignores one below", () => {+ expect(at("A\nB\nC", "A\nX\nB\nC", 2)).toEqual(current(3, 3));+ expect(at("A\nB\nC", "A\nB\nX\nC", 2)).toEqual(current(2, 2));+ // Appending after the last line gives that line a terminator it did not+ // have, which is a change to it.+ expect(at("A\nB\nC", "A\nB\nC\nX", 2, 3)).toEqual(OUTDATED);+ expect(at("A\nB\nC\n", "A\nB\nC\nX\n", 2, 3)).toEqual(current(2, 3));+ });++ it("outdates a hunk that starts above and ends inside the selection", () => {+ expect(at("A\nB\nC\nD", "A\nX\nY\nD", 3, 4)).toEqual(OUTDATED);+ });++ it("outdates an insertion between selected lines", () => {+ expect(at("A\nB\nC", "A\nX\nB\nC", 1, 2)).toEqual(OUTDATED);+ expect(at("A\nB\nC", "A\nB\nX\nC", 2, 3)).toEqual(OUTDATED);+ });++ it("handles the first and last lines", () => {+ expect(at("A\nB", "X\nA\nB", 1)).toEqual(current(2, 2));+ expect(at("A\nB\n", "A\nB\nX\n", 2)).toEqual(current(2, 2));+ expect(at("A\nB", "A\nB\nX", 2)).toEqual(OUTDATED);+ expect(at("A\nB", "B", 1)).toEqual(OUTDATED);+ expect(at("A\nB", "A", 2)).toEqual(OUTDATED);+ });++ it("handles a multi-line anchor spanning the whole document", () => {+ expect(at("A\nB", "A\nB", 1, 2)).toEqual(current(1, 2));+ expect(at("A\nB\n", "X\nA\nB\nY\n", 1, 2)).toEqual(current(2, 3));+ expect(at("A\nB", "X\nA\nB\nY", 1, 2)).toEqual(OUTDATED);+ expect(at("A\nB", "A\nX\nB", 1, 2)).toEqual(OUTDATED);+ });+});++describe("place: line endings and terminal lines", () => {+ it("never keeps a comment on a line that no longer exists", () => {+ // "A\n" has an empty line 2; removing the newline removes that line.+ expect(at("A\n", "A", 2)).toEqual(OUTDATED);+ // Line 1 lost its terminator, so it changed too.+ expect(at("A\n", "A", 1)).toEqual(OUTDATED);+ expect(at("A\nB\n", "A\nB", 1)).toEqual(current(1, 1));+ });++ it("treats a final-newline change as a change to the last line", () => {+ expect(at("A\nB", "A\nB\n", 2)).toEqual(OUTDATED);+ expect(at("A\nB", "A\nB\n", 1)).toEqual(current(1, 1));+ });++ it("treats a line-ending change as a text change", () => {+ expect(at("A\r\nB\r\n", "A\nB\n", 1)).toEqual(OUTDATED);+ expect(at("A\r\nB\r\n", "A\nB\n", 2)).toEqual(OUTDATED);+ // The final empty line has no terminator on either side.+ expect(at("A\r\nB\r\n", "A\nB\n", 3)).toEqual(current(3, 3));+ expect(at("A\rB", "A\nB", 2)).toEqual(current(2, 2));+ });++ it("handles empty documents", () => {+ expect(at("", "", 1)).toEqual(current(1, 1));+ expect(at("", "A", 1)).toEqual(OUTDATED);+ expect(at("A", "", 1)).toEqual(OUTDATED);+ });+});++describe("place: invalid input and limits", () => {+ it("returns UNAVAILABLE for source bounds outside the saved sheet", () => {+ expect(at("A\nB", "A\nB", 0)).toEqual(UNAVAILABLE);+ expect(at("A\nB", "A\nB", 3)).toEqual(UNAVAILABLE);+ expect(at("A\nB", "A\nB", 2, 1)).toEqual(UNAVAILABLE);+ expect(at("A\nB", "A\nB", 1, 3)).toEqual(UNAVAILABLE);+ });++ it("returns UNAVAILABLE rather than trusting an inconsistent hunk list", () => {+ // A hunk list that claims one deleted line above but a shorter target.+ expect(+ placeWithHunks(["A", "B"], ["B"], [], { startLine: 2, endLine: 2 })+ ).toEqual(UNAVAILABLE);+ // Mapped range below line 1.+ expect(+ placeWithHunks(["A", "B"], ["B"], [{ sStart: 1, sLen: 2, cLen: 0 }], {+ startLine: 2,+ endLine: 2,+ })+ ).toEqual(OUTDATED);+ expect(+ placeWithHunks(["A", "B"], ["A"], [{ sStart: 1, sLen: 1, cLen: 0 }], {+ startLine: 2,+ endLine: 2,+ })+ ).toEqual(UNAVAILABLE);+ // Mapped lines exist but their text differs.+ expect(+ placeWithHunks(["A", "B"], ["A", "X"], [], { startLine: 2, endLine: 2 })+ ).toEqual(UNAVAILABLE);+ });++ it("skips the diff for identical content", () => {+ const pair = diffPair(tokenizeSheet("A\nB"), tokenizeSheet("A\nB"), limits);+ expect(pair.hunks).toEqual([]);+ expect(pair.work).toBe(0);+ });++ it("returns UNAVAILABLE for every anchor when the work budget is exceeded", () => {+ const saved = Array.from({ length: 200 }, (_, i) => `a${i}`).join("\n");+ const currentText = Array.from({ length: 200 }, (_, i) => `b${i}`).join(+ "\n"+ );+ const pair = diffPair(tokenizeSheet(saved), tokenizeSheet(currentText), {+ maxLinesPerSheet: 10_000,+ maxWork: 50,+ });+ expect(pair.hunks).toBeUndefined();+ expect(pair.work).toBe(51);+ expect(placeOnPair(pair, { startLine: 1, endLine: 1 })).toEqual(+ UNAVAILABLE+ );+ expect(placeOnPair(pair, { startLine: 200, endLine: 200 })).toEqual(+ UNAVAILABLE+ );+ });++ it("returns UNAVAILABLE when a sheet exceeds the line cap, even if identical", () => {+ const text = "A\nB\nC";+ const pair = diffPair(tokenizeSheet(text), tokenizeSheet(text), {+ maxLinesPerSheet: 2,+ maxWork: 1000,+ });+ expect(pair.hunks).toBeUndefined();+ expect(placeOnPair(pair, { startLine: 1, endLine: 1 })).toEqual(+ UNAVAILABLE+ );+ // The cap is inclusive.+ expect(+ diffPair(tokenizeSheet(text), tokenizeSheet(text), {+ maxLinesPerSheet: 3,+ maxWork: 1,+ }).hunks+ ).toEqual([]);+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/place.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/place.tsnew file mode 100644index 0000000000..9953fb38e8--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/place.ts@@ -0,0 +1,166 @@+import type { StatementAnchor } from "@/types/proto-es/v1/issue_service_pb";+import { tokenizeLines } from "./lineTokens";+import { diffLines, type Hunk } from "./myersDiff";++// One-based, inclusive. The one range shape shared by anchors, placements,+// and the editor.+export interface LineRange {+ readonly startLine: number;+ readonly endLine: number;+}++// Where an anchored comment shows for the spec's current statement. CURRENT+// carries the range in the current sheet; the text there is byte for byte+// what the reviewer selected. OUTDATED means the selected lines changed.+// UNAVAILABLE means the inputs were missing or invalid, or a limit was hit.+export type Placement =+ | { readonly state: "CURRENT"; readonly range: LineRange }+ | { readonly state: "OUTDATED" }+ | { readonly state: "UNAVAILABLE" };++export const OUTDATED: Placement = Object.freeze({ state: "OUTDATED" });+export const UNAVAILABLE: Placement = Object.freeze({ state: "UNAVAILABLE" });++export const current = (startLine: number, endLine: number): Placement => ({+ state: "CURRENT",+ range: { startLine, endLine },+});++// An anchor on a saved/current pair. `id` names the line range, so identical+// ranges from different comments share one computation.+export interface PairAnchor extends LineRange {+ readonly id: string;+}++export const anchorId = (range: LineRange): string =>+ `${range.startLine}-${range.endLine}`;++// This version supports whole-line anchors only: both columns zero, one-based+// lines, and an inclusive end at or after the start.+export function wholeLineRange(+ anchor: Pick<StatementAnchor, "startPosition" | "endPosition">+): LineRange | undefined {+ const start = anchor.startPosition;+ const end = anchor.endPosition;+ if (!start || !end) return undefined;+ if (start.column !== 0 || end.column !== 0) return undefined;+ if (start.line < 1 || end.line < start.line) return undefined;+ return { startLine: start.line, endLine: end.line };+}++// The part of the placement rule that needs no diff, shared by the planner+// and by every consumer that shows a comment before a run has settled it:+// an unsupported anchor is UNAVAILABLE, no target (spec gone or without a+// statement) is UNAVAILABLE, and an anchor on the target sheet itself is+// CURRENT at its own lines. Undefined means the diff has to decide.+export function trivialPlacement(+ anchor: Pick<+ StatementAnchor,+ "startPosition" | "endPosition" | "sheetSha256"+ >,+ targetSha256: string | undefined+): Placement | undefined {+ const range = wholeLineRange(anchor);+ if (!range || !targetSha256) return UNAVAILABLE;+ if (targetSha256 === anchor.sheetSha256) {+ return current(range.startLine, range.endLine);+ }+ return undefined;+}++// Maps the selected saved lines through `hunks` (a complete saved-to-current+// diff). Hunks entirely above shift the selection by their net line count,+// hunks entirely below have no effect, and a hunk that touches a selected+// line or inserts between selected lines outdates the comment.+export function placeWithHunks(+ saved: readonly string[],+ currentLines: readonly string[],+ hunks: readonly Hunk[],+ range: LineRange+): Placement {+ const { startLine: first, endLine: last } = range;+ if (!(first >= 1 && first <= last && last <= saved.length)) {+ return UNAVAILABLE;+ }+ let delta = 0;+ for (const hunk of hunks) {+ const sEnd = hunk.sStart + hunk.sLen - 1;+ if (hunk.sLen === 0 && hunk.sStart <= first) {+ delta += hunk.cLen;+ } else if (hunk.sLen > 0 && sEnd < first) {+ delta += hunk.cLen - hunk.sLen;+ } else if (hunk.sStart > last) {+ continue;+ } else {+ return OUTDATED;+ }+ }+ const mappedFirst = first + delta;+ const mappedLast = last + delta;+ if (!(mappedFirst >= 1 && mappedLast <= currentLines.length)) {+ return UNAVAILABLE;+ }+ for (let i = 0; i <= last - first; i++) {+ if (saved[first - 1 + i] !== currentLines[mappedFirst - 1 + i]) {+ return UNAVAILABLE;+ }+ }+ return current(mappedFirst, mappedLast);+}++// A sheet's complete text with its editor lines, tokenized once however many+// pairs it takes part in.+export interface SheetText {+ readonly text: string;+ readonly lines: readonly string[];+}++export const tokenizeSheet = (text: string): SheetText => ({+ text,+ lines: tokenizeLines(text),+});++// A diffed saved/current pair, reusable for every anchor on that pair.+export interface DiffedPair {+ readonly saved: readonly string[];+ readonly current: readonly string[];+ // Undefined when the diff did not run to completion; `reason` says why.+ // A "budget" miss is retriable with more budget, a "lines" miss is not.+ readonly hunks?: readonly Hunk[];+ readonly reason?: "budget" | "lines";+ readonly work: number;+}++export interface DiffPairLimits {+ readonly maxLinesPerSheet: number;+ readonly maxWork: number;+}++// Diffs one pair once. Identical contents skip the diff. A sheet over the+// line cap or a diff over the work budget yields no hunks, and every anchor+// on the pair then resolves UNAVAILABLE.+export function diffPair(+ saved: SheetText,+ current: SheetText,+ limits: DiffPairLimits+): DiffedPair {+ const base = { saved: saved.lines, current: current.lines };+ if (+ saved.lines.length > limits.maxLinesPerSheet ||+ current.lines.length > limits.maxLinesPerSheet+ ) {+ return { ...base, reason: "lines", work: 0 };+ }+ if (saved.text === current.text) {+ return { ...base, hunks: [], work: 0 };+ }+ const result = diffLines(saved.lines, current.lines, limits.maxWork);+ return result.complete+ ? { ...base, hunks: result.hunks, work: result.work }+ : { ...base, reason: "budget", work: result.work };+}++export function placeOnPair(pair: DiffedPair, range: LineRange): Placement {+ if (!pair.hunks) return UNAVAILABLE;+ return placeWithHunks(pair.saved, pair.current, pair.hunks, range);+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/placement.worker.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/placement.worker.tsnew file mode 100644index 0000000000..802a41a02a--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/placement.worker.ts@@ -0,0 +1,14 @@+import { type PlacementRequest, runPlacementBatch } from "./placementWorker";++// Dedicated worker entry: one request in, one response out.+const scope = globalThis as unknown as {+ addEventListener(+ type: "message",+ listener: (event: MessageEvent<PlacementRequest>) => void+ ): void;+ postMessage(message: unknown): void;+};++scope.addEventListener("message", (event) => {+ scope.postMessage(runPlacementBatch(event.data));+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/placementClient.test.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/placementClient.test.tsnew file mode 100644index 0000000000..d6d6d08e87--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/placementClient.test.ts@@ -0,0 +1,153 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import {+ createPlacementClient,+ PlacementError,+ type PlacementWorkerPort,+} from "./placementClient";+import {+ type PlacementRequest,+ type PlacementResponse,+ runPlacementBatch,+} from "./placementWorker";++const request = (generation: number): PlacementRequest => ({+ generation,+ limits: { maxLinesPerSheet: 100, maxWorkPerPair: 1000, maxWorkPerRun: 1000 },+ sheets: { s: "A\nB", c: "X\nA\nB" },+ pairs: [+ {+ key: "p",+ saved: "s",+ current: "c",+ anchors: [{ id: "1-1", startLine: 1, endLine: 1 }],+ },+ ],+});++class FakePort implements PlacementWorkerPort {+ onmessage: PlacementWorkerPort["onmessage"] = null;+ onerror: PlacementWorkerPort["onerror"] = null;+ terminated = false;+ received: PlacementRequest[] = [];+ constructor(+ private readonly behavior: (+ port: FakePort,+ request: PlacementRequest+ ) => void = () => {}+ ) {}+ postMessage(message: PlacementRequest) {+ this.received.push(message);+ this.behavior(this, message);+ }+ terminate() {+ this.terminated = true;+ }+ respond(response: PlacementResponse) {+ this.onmessage?.({ data: response } as MessageEvent<PlacementResponse>);+ }+}++const trackingClient = (+ behavior?: ConstructorParameters<typeof FakePort>[0]+) => {+ const ports: FakePort[] = [];+ const client = createPlacementClient(() => {+ const port = new FakePort(behavior);+ ports.push(port);+ return port;+ });+ return { client, ports };+};++const failure = (promise: Promise<unknown>) =>+ promise.then(+ () => undefined,+ (error: unknown) => error+ );++describe("createPlacementClient", () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ test("resolves with the worker's response and terminates the worker", async () => {+ const { client, ports } = trackingClient((self, req) =>+ queueMicrotask(() => self.respond(runPlacementBatch(req)))+ );+ const response = await client.compute(request(1), 1000);+ expect(response.results.p["1-1"]).toEqual({+ state: "CURRENT",+ range: { startLine: 2, endLine: 2 },+ });+ expect(ports).toHaveLength(1);+ expect(ports[0].received).toEqual([request(1)]);+ expect(ports[0].terminated).toBe(true);+ });++ test("rejects with deadline and terminates a worker that never answers", async () => {+ const { client, ports } = trackingClient();+ const outcome = failure(client.compute(request(1), 500));+ vi.advanceTimersByTime(499);+ expect(ports[0].terminated).toBe(false);+ vi.advanceTimersByTime(1);+ const error = await outcome;+ expect(error).toBeInstanceOf(PlacementError);+ expect((error as PlacementError).reason).toBe("deadline");+ expect(ports[0].terminated).toBe(true);+ // A late answer after the deadline is ignored.+ expect(() => ports[0].respond(runPlacementBatch(request(1)))).not.toThrow();+ });++ test("rejects with worker-error when the worker fails", async () => {+ const { client } = trackingClient((self) =>+ queueMicrotask(() => self.onerror?.({} as ErrorEvent))+ );+ await expect(client.compute(request(1), 1000)).rejects.toMatchObject({+ reason: "worker-error",+ });+ });++ test("rejects with worker-error when the worker cannot be posted to", async () => {+ const client = createPlacementClient(() => {+ const port = new FakePort();+ port.postMessage = () => {+ throw new Error("structured clone failed");+ };+ return port;+ });+ await expect(client.compute(request(1), 1000)).rejects.toMatchObject({+ reason: "worker-error",+ });+ });++ test("a newer request cancels the one in flight", async () => {+ const { client, ports } = trackingClient();+ const first = failure(client.compute(request(1), 1000));+ const second = client.compute(request(2), 1000);+ expect(await first).toMatchObject({ reason: "cancelled" });+ expect(ports[0].terminated).toBe(true);+ expect(ports[1].terminated).toBe(false);+ ports[1].respond(runPlacementBatch(request(2)));+ expect((await second).generation).toBe(2);+ expect(ports[1].terminated).toBe(true);+ });++ test("cancel rejects the in-flight request and is a no-op when idle", async () => {+ const { client, ports } = trackingClient();+ client.cancel();+ const pending = failure(client.compute(request(1), 1000));+ client.cancel();+ expect(await pending).toMatchObject({ reason: "cancelled" });+ expect(ports[0].terminated).toBe(true);+ client.cancel();+ expect(ports).toHaveLength(1);+ });++ test("ignores a response from a different generation", async () => {+ const { client, ports } = trackingClient();+ const pending = failure(client.compute(request(3), 1000));+ ports[0].respond({ generation: 2, results: {}, incomplete: [], work: 0 });+ expect(ports[0].terminated).toBe(false);+ vi.advanceTimersByTime(1000);+ expect(await pending).toMatchObject({ reason: "deadline" });+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/placementClient.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/placementClient.tsnew file mode 100644index 0000000000..98fb5acb75--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/placementClient.ts@@ -0,0 +1,101 @@+import type { PlacementRequest, PlacementResponse } from "./placementWorker";++// The subset of `Worker` the client drives, so tests can supply a fake.+export interface PlacementWorkerPort {+ postMessage(message: PlacementRequest): void;+ onmessage: ((event: MessageEvent<PlacementResponse>) => void) | null;+ onerror: ((event: ErrorEvent) => void) | null;+ terminate(): void;+}++export type PlacementWorkerFactory = () => PlacementWorkerPort;++export const createPlacementWorker: PlacementWorkerFactory = () =>+ new Worker(new URL("./placement.worker.ts", import.meta.url), {+ type: "module",+ });++export type PlacementFailure = "deadline" | "cancelled" | "worker-error";++export class PlacementError extends Error {+ constructor(readonly reason: PlacementFailure) {+ super(`placement ${reason}`);+ this.name = "PlacementError";+ }+}++export interface PlacementClient {+ // Runs one request in a fresh worker. Rejects with `PlacementError` when+ // the deadline expires, the worker fails, or a newer request or `cancel`+ // supersedes it. Only one request is in flight; a new one cancels the last.+ compute(+ request: PlacementRequest,+ deadlineMs: number+ ): Promise<PlacementResponse>;+ cancel(): void;+}++interface Timers {+ setTimeout(callback: () => void, ms: number): unknown;+ clearTimeout(handle: unknown): void;+}++const defaultTimers: Timers = {+ setTimeout: (callback, ms) => globalThis.setTimeout(callback, ms),+ clearTimeout: (handle) =>+ globalThis.clearTimeout(handle as ReturnType<typeof setTimeout>),+};++// A worker per request keeps termination simple: expiring the deadline or+// cancelling kills the worker outright, so no partial work can leak into a+// later run.+export function createPlacementClient(+ factory: PlacementWorkerFactory = createPlacementWorker,+ timers: Timers = defaultTimers+): PlacementClient {+ let active:+ | { port: PlacementWorkerPort; fail: (reason: PlacementFailure) => void }+ | undefined;++ const cancel = () => {+ active?.fail("cancelled");+ };++ const compute = (request: PlacementRequest, deadlineMs: number) =>+ new Promise<PlacementResponse>((resolve, reject) => {+ cancel();+ const port = factory();+ let settled = false;+ const finish = () => {+ settled = true;+ timers.clearTimeout(timer);+ port.onmessage = null;+ port.onerror = null;+ port.terminate();+ if (active?.port === port) active = undefined;+ };+ const fail = (reason: PlacementFailure) => {+ if (settled) return;+ finish();+ reject(new PlacementError(reason));+ };+ const timer = timers.setTimeout(() => fail("deadline"), deadlineMs);+ port.onmessage = (event) => {+ if (settled) return;+ // A response for another generation cannot come from this worker, but+ // guard the contract anyway.+ if (event.data.generation !== request.generation) return;+ finish();+ resolve(event.data);+ };+ port.onerror = () => fail("worker-error");+ active = { port, fail };+ try {+ port.postMessage(request);+ } catch {+ fail("worker-error");+ }+ });++ return { compute, cancel };+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.test.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.test.tsnew file mode 100644index 0000000000..8ee10990ac--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.test.ts@@ -0,0 +1,334 @@+import { create } from "@bufbuild/protobuf";+import { TimestampSchema } from "@bufbuild/protobuf/wkt";+import { describe, expect, test } from "vitest";+import { PositionSchema } from "@/types/proto-es/v1/common_pb";+import {+ IssueCommentSchema,+ StatementAnchorSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import {+ Plan_ChangeDatabaseConfigSchema,+ Plan_SpecSchema,+} from "@/types/proto-es/v1/plan_service_pb";+import { current, OUTDATED, UNAVAILABLE, wholeLineRange } from "./place";+import {+ type PlacementPlanInput,+ pairKey,+ planPlacements,+} from "./placementPlan";++const PROJECT = "projects/p";+const SHA_A = "a".repeat(64);+const SHA_B = "b".repeat(64);+const SHA_C = "c".repeat(64);+const SHA_D = "d".repeat(64);+const sheet = (sha: string) => `${PROJECT}/sheets/${sha}`;++const anchor = (+ sha: string,+ first: number,+ last = first,+ opts: { spec?: string; columns?: [number, number] } = {}+) =>+ create(StatementAnchorSchema, {+ spec: opts.spec ?? "spec-1",+ sheetSha256: sha,+ startPosition: create(PositionSchema, {+ line: first,+ column: opts.columns?.[0] ?? 0,+ }),+ endPosition: create(PositionSchema, {+ line: last,+ column: opts.columns?.[1] ?? 0,+ }),+ });++const nameOf = (id: string) => `${PROJECT}/issues/1/issueComments/${id}`;+const comment = (+ id: string,+ statementAnchor?: ReturnType<typeof anchor>,+ createdAt = 1+) =>+ create(IssueCommentSchema, {+ name: nameOf(id),+ createTime: create(TimestampSchema, { seconds: BigInt(createdAt) }),+ statementAnchor,+ });++const spec = (id: string, sha: string) =>+ create(Plan_SpecSchema, {+ id,+ config: {+ case: "changeDatabaseConfig",+ value: create(Plan_ChangeDatabaseConfigSchema, { sheet: sheet(sha) }),+ },+ });++const budgets = { maxSheets: 4, maxBytesPerSheet: 1000, maxTotalBytes: 2500 };++const plan = (+ overrides: Partial<PlacementPlanInput> & {+ sizes?: Record<string, number>;+ complete?: string[];+ }+) => {+ const sizes = overrides.sizes ?? {};+ const complete = new Set(overrides.complete ?? []);+ return planPlacements({+ comments: [],+ specs: [spec("spec-1", SHA_B)],+ projectName: PROJECT,+ sizeOf: (name) => (name in sizes ? BigInt(sizes[name]) : undefined),+ isComplete: (name) => complete.has(name),+ budgets,+ ...overrides,+ });+};++describe("wholeLineRange", () => {+ test("accepts zero-column ranges and rejects anything else", () => {+ expect(wholeLineRange(anchor(SHA_A, 2, 4))).toEqual({+ startLine: 2,+ endLine: 4,+ });+ expect(wholeLineRange(anchor(SHA_A, 2))).toEqual({+ startLine: 2,+ endLine: 2,+ });+ expect(+ wholeLineRange(anchor(SHA_A, 2, 4, { columns: [1, 1] }))+ ).toBeUndefined();+ expect(+ wholeLineRange(anchor(SHA_A, 2, 4, { columns: [0, 3] }))+ ).toBeUndefined();+ expect(wholeLineRange(anchor(SHA_A, 0, 1))).toBeUndefined();+ expect(wholeLineRange(anchor(SHA_A, 3, 2))).toBeUndefined();+ });+});++describe("planPlacements", () => {+ test("ignores unanchored comments and settles trivial cases without fetching", () => {+ const result = plan({+ comments: [+ comment("plain"),+ comment("same", anchor(SHA_B, 3, 5)),+ comment("columns", anchor(SHA_A, 1, 1, { columns: [1, 4] })),+ comment("no-spec", anchor(SHA_A, 1, 1, { spec: "gone" })),+ ],+ specs: [spec("spec-1", SHA_B), spec("other", SHA_C)],+ });+ expect(result.settled.has(nameOf("plain"))).toBe(false);+ expect(result.settled.get(nameOf("same"))).toEqual(current(3, 5));+ expect(result.settled.get(nameOf("columns"))).toEqual(UNAVAILABLE);+ expect(result.settled.get(nameOf("no-spec"))).toEqual(UNAVAILABLE);+ expect(result.pairs).toEqual([]);+ expect(result.fetches).toEqual([]);+ });++ test("settles UNAVAILABLE when the spec has no statement", () => {+ const result = plan({+ comments: [comment("c", anchor(SHA_A, 1))],+ specs: [create(Plan_SpecSchema, { id: "spec-1" })],+ });+ expect(result.settled.get(nameOf("c"))).toEqual(UNAVAILABLE);+ });++ test("groups anchors of one pair and dedupes identical ranges", () => {+ const result = plan({+ comments: [+ comment("later", anchor(SHA_A, 2, 3), 5),+ comment("early", anchor(SHA_A, 1), 1),+ comment("twin", anchor(SHA_A, 2, 3), 3),+ ],+ sizes: { [sheet(SHA_A)]: 100, [sheet(SHA_B)]: 200 },+ });+ expect(result.settled.size).toBe(0);+ expect(result.pairs).toHaveLength(1);+ const pair = result.pairs[0];+ expect(pair.key).toBe(pairKey("spec-1", SHA_A, SHA_B));+ expect(pair.sourceName).toBe(sheet(SHA_A));+ expect(pair.targetName).toBe(sheet(SHA_B));+ expect(pair.anchors).toEqual([+ { id: "1-1", startLine: 1, endLine: 1 },+ { id: "2-3", startLine: 2, endLine: 3 },+ ]);+ expect(pair.comments.get("2-3")).toEqual([nameOf("twin"), nameOf("later")]);+ expect(result.fetches).toEqual([sheet(SHA_A), sheet(SHA_B)]);+ });++ test("does not fetch sheets that are already complete", () => {+ const result = plan({+ comments: [comment("c", anchor(SHA_A, 1))],+ sizes: { [sheet(SHA_A)]: 100, [sheet(SHA_B)]: 200 },+ complete: [sheet(SHA_B)],+ });+ expect(result.fetches).toEqual([sheet(SHA_A)]);+ expect(result.pairs).toHaveLength(1);+ });++ test("marks pairs with an unknown size UNAVAILABLE and reports the sheet", () => {+ const result = plan({+ comments: [comment("c", anchor(SHA_A, 1))],+ sizes: { [sheet(SHA_B)]: 200 },+ });+ expect(result.settled.get(nameOf("c"))).toEqual(UNAVAILABLE);+ expect(result.unknownSizes).toEqual([sheet(SHA_A)]);+ expect(result.pairs).toEqual([]);+ expect(result.fetches).toEqual([]);+ });++ test("does not report unknown sheets of a pair an oversize sibling already rules out", () => {+ const result = plan({+ comments: [+ comment("doomed", anchor(SHA_A, 1), 1),+ comment("viable", anchor(SHA_C, 1, 1, { spec: "spec-2" }), 2),+ ],+ specs: [spec("spec-1", SHA_B), spec("spec-2", SHA_D)],+ sizes: { [sheet(SHA_B)]: 5000 },+ });+ expect(result.settled.get(nameOf("doomed"))).toEqual(UNAVAILABLE);+ // Only the viable pair's sheets are worth a probe.+ expect(result.unknownSizes).toEqual([sheet(SHA_C), sheet(SHA_D)]);+ });++ test("leaves an unknown-size pair unsettled when asked, unless it is UNAVAILABLE anyway", () => {+ const pending = plan({+ comments: [comment("c", anchor(SHA_A, 1))],+ sizes: { [sheet(SHA_B)]: 200 },+ settleUnknownSizes: false,+ });+ expect(pending.settled.has(nameOf("c"))).toBe(false);+ expect(pending.unknownSizes).toEqual([sheet(SHA_A)]);+ const oversize = plan({+ comments: [comment("c", anchor(SHA_A, 1))],+ sizes: { [sheet(SHA_B)]: 5000 },+ settleUnknownSizes: false,+ });+ expect(oversize.settled.get(nameOf("c"))).toEqual(UNAVAILABLE);+ });++ test("enforces the per-sheet byte cap inclusively", () => {+ const over = plan({+ comments: [comment("c", anchor(SHA_A, 1))],+ sizes: { [sheet(SHA_A)]: 1001, [sheet(SHA_B)]: 10 },+ });+ expect(over.settled.get(nameOf("c"))).toEqual(UNAVAILABLE);+ const at = plan({+ comments: [comment("c", anchor(SHA_A, 1))],+ sizes: { [sheet(SHA_A)]: 1000, [sheet(SHA_B)]: 10 },+ });+ expect(at.pairs).toHaveLength(1);+ });++ test("applies the per-sheet cap even to a sheet that is already cached", () => {+ const result = plan({+ comments: [comment("c", anchor(SHA_A, 1))],+ sizes: { [sheet(SHA_A)]: 10, [sheet(SHA_B)]: 5000 },+ complete: [sheet(SHA_B)],+ });+ expect(result.settled.get(nameOf("c"))).toEqual(UNAVAILABLE);+ });++ test("keeps earlier pairs and drops later ones past the sheet-count cap", () => {+ const result = plan({+ comments: [+ comment("first", anchor(SHA_A, 1), 1),+ comment("second", anchor(SHA_C, 1), 2),+ comment("third", anchor(SHA_D, 1), 3),+ ],+ sizes: {+ [sheet(SHA_A)]: 10,+ [sheet(SHA_B)]: 10,+ [sheet(SHA_C)]: 10,+ [sheet(SHA_D)]: 10,+ },+ budgets: { ...budgets, maxSheets: 3 },+ });+ // A+B, then C reusing B, then D would be the fourth sheet.+ expect(result.pairs.map((pair) => pair.sourceSha256)).toEqual([+ SHA_A,+ SHA_C,+ ]);+ expect(result.settled.get(nameOf("third"))).toEqual(UNAVAILABLE);+ expect(result.fetches).toEqual([sheet(SHA_A), sheet(SHA_B), sheet(SHA_C)]);+ });++ test("counts total bytes only for sheets it will download", () => {+ const input = {+ comments: [+ comment("first", anchor(SHA_A, 1), 1),+ comment("second", anchor(SHA_C, 1), 2),+ ],+ sizes: { [sheet(SHA_A)]: 900, [sheet(SHA_B)]: 900, [sheet(SHA_C)]: 800 },+ };+ // 900 + 900 fits; adding 800 exceeds 2500.+ const result = plan(input);+ expect(result.pairs.map((pair) => pair.sourceSha256)).toEqual([SHA_A]);+ expect(result.settled.get(nameOf("second"))).toEqual(UNAVAILABLE);++ const cached = plan({ ...input, complete: [sheet(SHA_B)] });+ expect(cached.pairs).toHaveLength(2);+ expect(cached.fetches).toEqual([sheet(SHA_A), sheet(SHA_C)]);+ });++ test("bytes already spent by the caller count against the total", () => {+ const input = {+ comments: [comment("c", anchor(SHA_A, 1))],+ sizes: { [sheet(SHA_A)]: 900, [sheet(SHA_B)]: 900 },+ };+ expect(plan(input).pairs).toHaveLength(1);+ expect(plan({ ...input, spentBytes: 800n }).pairs).toHaveLength(0);+ });++ test("a pair blocked by budget does not reserve any sheets", () => {+ const result = plan({+ comments: [+ comment("big", anchor(SHA_A, 1), 1),+ comment("small", anchor(SHA_C, 1), 2),+ ],+ sizes: { [sheet(SHA_A)]: 2000, [sheet(SHA_B)]: 10, [sheet(SHA_C)]: 10 },+ });+ expect(result.settled.get(nameOf("big"))).toEqual(UNAVAILABLE);+ expect(result.pairs.map((pair) => pair.sourceSha256)).toEqual([SHA_C]);+ expect(result.fetches).toEqual([sheet(SHA_C), sheet(SHA_B)]);+ });++ test("keeps anchors on different specs in different pairs", () => {+ const result = plan({+ comments: [+ comment("one", anchor(SHA_A, 1, 1, { spec: "spec-1" }), 1),+ comment("two", anchor(SHA_A, 1, 1, { spec: "spec-2" }), 2),+ ],+ specs: [spec("spec-1", SHA_B), spec("spec-2", SHA_B)],+ sizes: { [sheet(SHA_A)]: 10, [sheet(SHA_B)]: 10 },+ });+ expect(result.pairs.map((pair) => pair.specId)).toEqual([+ "spec-1",+ "spec-2",+ ]);+ expect(result.fetches).toEqual([sheet(SHA_A), sheet(SHA_B)]);+ });++ test("orders pairs by their oldest comment, not by discovery", () => {+ const result = plan({+ comments: [+ comment("c-new", anchor(SHA_C, 1), 10),+ comment("a-old", anchor(SHA_A, 1), 1),+ comment("c-oldest", anchor(SHA_C, 2), 0),+ ],+ sizes: { [sheet(SHA_A)]: 10, [sheet(SHA_B)]: 10, [sheet(SHA_C)]: 10 },+ });+ expect(result.pairs.map((pair) => pair.sourceSha256)).toEqual([+ SHA_C,+ SHA_A,+ ]);+ });++ test("never produces OUTDATED without a diff", () => {+ const result = plan({+ comments: [comment("c", anchor(SHA_A, 1))],+ sizes: { [sheet(SHA_A)]: 10, [sheet(SHA_B)]: 10 },+ });+ expect([...result.settled.values()]).not.toContainEqual(OUTDATED);+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.tsnew file mode 100644index 0000000000..1a5a4495ce--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.ts@@ -0,0 +1,200 @@+import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";+import {+ compareByCreateTime,+ sheetNameOfSha256,+ targetSha256OfSpec,+} from "../threadModel";+import type { PlacementBudgets } from "./budgets";+import {+ anchorId,+ type PairAnchor,+ type Placement,+ trivialPlacement,+ UNAVAILABLE,+ wholeLineRange,+} from "./place";++// One saved/current sheet pair to diff, with the anchors that map through it.+export interface PlacementPair {+ readonly key: string;+ readonly specId: string;+ readonly sourceSha256: string;+ readonly targetSha256: string;+ readonly sourceName: string;+ readonly targetName: string;+ readonly anchors: readonly PairAnchor[];+ // Comment names by anchor id.+ readonly comments: ReadonlyMap<string, readonly string[]>;+}++export interface PlacementPlan {+ // Comments settled without loading anything.+ readonly settled: ReadonlyMap<string, Placement>;+ // Pairs to compute, earliest comment first, within the fetch budget.+ readonly pairs: readonly PlacementPair[];+ // Sheet names the pairs need that are not complete in the cache, deduped.+ readonly fetches: readonly string[];+ // Sheets a candidate pair needs whose size is unknown. With+ // `settleUnknownSizes` those pairs' comments are UNAVAILABLE; without it+ // they are left out of `settled`, pending a caller that learns the sizes+ // and plans again.+ readonly unknownSizes: readonly string[];+}++export interface PlacementPlanInput {+ readonly comments: readonly IssueComment[];+ readonly specs: readonly Plan_Spec[];+ // "projects/{project}", the issue's project.+ readonly projectName: string;+ // Content size in bytes when known, from a cached sheet or size metadata.+ readonly sizeOf: (sheetName: string) => bigint | undefined;+ // Whether the cache holds the sheet's complete content.+ readonly isComplete: (sheetName: string) => boolean;+ readonly budgets: Pick<+ PlacementBudgets,+ "maxSheets" | "maxBytesPerSheet" | "maxTotalBytes"+ >;+ // Whether a pair blocked only by an unknown size settles UNAVAILABLE+ // (default) or stays out of the plan for a later pass.+ readonly settleUnknownSizes?: boolean;+ // Bytes this run has already downloaded, counted against the total budget.+ readonly spentBytes?: bigint;+}++export const pairKey = (+ specId: string,+ sourceSha256: string,+ targetSha256: string+): string => `${specId} ${sourceSha256} ${targetSha256}`;++interface CandidatePair {+ key: string;+ specId: string;+ sourceSha256: string;+ targetSha256: string;+ sourceName: string;+ targetName: string;+ anchors: Map<string, PairAnchor>;+ comments: Map<string, string[]>;+ // Position of the pair's oldest comment, for deterministic budgeting.+ order: number;+}++// Decides, without any fetch, which comments are already placed, which+// saved/current pairs must be diffed, and which sheets must be downloaded to+// do so. Fetching is bounded here: a pair whose sheets have unknown sizes, a+// sheet over the per-sheet cap, or pairs past the sheet-count or total-byte+// caps settle UNAVAILABLE instead of being fetched.+export function planPlacements(input: PlacementPlanInput): PlacementPlan {+ const settled = new Map<string, Placement>();+ const candidates = new Map<string, CandidatePair>();+ const specs = new Map(input.specs.map((spec) => [spec.id, spec]));+ const ordered = [...input.comments].sort(compareByCreateTime);++ ordered.forEach((comment, order) => {+ const anchor = comment.statementAnchor;+ if (!anchor) return;+ const targetSha256 = targetSha256OfSpec(specs.get(anchor.spec));+ const trivial = trivialPlacement(anchor, targetSha256);+ if (trivial) {+ settled.set(comment.name, trivial);+ return;+ }+ // `trivialPlacement` returned undefined, so both are present.+ const range = wholeLineRange(anchor);+ if (!range || !targetSha256) return;+ const key = pairKey(anchor.spec, anchor.sheetSha256, targetSha256);+ let candidate = candidates.get(key);+ if (!candidate) {+ candidate = {+ key,+ specId: anchor.spec,+ sourceSha256: anchor.sheetSha256,+ targetSha256,+ sourceName: sheetNameOfSha256(input.projectName, anchor.sheetSha256),+ targetName: sheetNameOfSha256(input.projectName, targetSha256),+ anchors: new Map(),+ comments: new Map(),+ order,+ };+ candidates.set(key, candidate);+ }+ const id = anchorId(range);+ candidate.anchors.set(id, { id, ...range });+ candidate.comments.set(id, [+ ...(candidate.comments.get(id) ?? []),+ comment.name,+ ]);+ });++ const pairs: PlacementPair[] = [];+ const fetches: string[] = [];+ const unknownSizes = new Set<string>();+ const fetchSet = new Set<string>();+ let totalBytes = input.spentBytes ?? 0n;+ const settleUnavailable = (candidate: CandidatePair) => {+ for (const names of candidate.comments.values()) {+ for (const name of names) settled.set(name, UNAVAILABLE);+ }+ };++ const byOrder = [...candidates.values()].sort((a, b) => a.order - b.order);+ for (const candidate of byOrder) {+ const needed =+ candidate.sourceName === candidate.targetName+ ? [candidate.sourceName]+ : [candidate.sourceName, candidate.targetName];+ let unavailable = false;+ let pairBytes = 0n;+ const pairFetches: string[] = [];+ const unknown: string[] = [];+ for (const name of needed) {+ const size = input.sizeOf(name);+ if (size === undefined) {+ unknown.push(name);+ continue;+ }+ if (size > BigInt(input.budgets.maxBytesPerSheet)) {+ unavailable = true;+ continue;+ }+ if (input.isComplete(name) || fetchSet.has(name)) continue;+ pairFetches.push(name);+ pairBytes += size;+ }+ // A sheet worth probing belongs to a pair that can still place; an+ // oversize sibling already decides the pair, so its unknown sheets are+ // not reported and no budget goes to them.+ if (unknown.length > 0 && !unavailable) {+ for (const name of unknown) unknownSizes.add(name);+ if (input.settleUnknownSizes === false) continue;+ }+ if (+ unknown.length > 0 ||+ unavailable ||+ fetchSet.size + pairFetches.length > input.budgets.maxSheets ||+ totalBytes + pairBytes > BigInt(input.budgets.maxTotalBytes)+ ) {+ settleUnavailable(candidate);+ continue;+ }+ for (const name of pairFetches) {+ fetchSet.add(name);+ fetches.push(name);+ }+ totalBytes += pairBytes;+ pairs.push({+ key: candidate.key,+ specId: candidate.specId,+ sourceSha256: candidate.sourceSha256,+ targetSha256: candidate.targetSha256,+ sourceName: candidate.sourceName,+ targetName: candidate.targetName,+ anchors: [...candidate.anchors.values()],+ comments: candidate.comments,+ });+ }++ return { settled, pairs, fetches, unknownSizes: [...unknownSizes] };+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/placementWorker.test.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/placementWorker.test.tsnew file mode 100644index 0000000000..d9392a8e81--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/placementWorker.test.ts@@ -0,0 +1,124 @@+import { describe, expect, test } from "vitest";+import { current, UNAVAILABLE } from "./place";+import { runPlacementBatch } from "./placementWorker";++const limits = {+ maxLinesPerSheet: 1000,+ maxWorkPerPair: 10_000,+ maxWorkPerRun: 100_000,+};++const changedScript = (prefix: string) =>+ Array.from({ length: 50 }, (_, i) => `${prefix}${i}`).join("\n");++describe("runPlacementBatch", () => {+ test("places every anchor of every pair and echoes the generation", () => {+ const response = runPlacementBatch({+ generation: 7,+ limits,+ sheets: { s1: "A\nB\nC\n", c1: "X\nA\nB\nC\n", s2: "A\nB", c2: "A\nZ" },+ pairs: [+ {+ key: "p1",+ saved: "s1",+ current: "c1",+ anchors: [+ { id: "1-1", startLine: 1, endLine: 1 },+ { id: "2-3", startLine: 2, endLine: 3 },+ ],+ },+ {+ key: "p2",+ saved: "s2",+ current: "c2",+ anchors: [{ id: "2-2", startLine: 2, endLine: 2 }],+ },+ ],+ });+ expect(response.generation).toBe(7);+ expect(response.results).toEqual({+ p1: { "1-1": current(2, 2), "2-3": current(3, 4) },+ p2: { "2-2": { state: "OUTDATED" } },+ });+ expect(response.work).toBeGreaterThan(0);+ });++ test("shares the per-run budget in order and leaves the rest UNAVAILABLE", () => {+ const sheets = { a: changedScript("a"), b: changedScript("b") };+ const pair = (key: string) => ({+ key,+ saved: "a",+ current: "b",+ anchors: [{ id: "1-1", startLine: 1, endLine: 1 }],+ });+ const single = runPlacementBatch({+ generation: 1,+ limits: { ...limits, maxWorkPerRun: 1_000_000 },+ sheets,+ pairs: [pair("only")],+ });+ expect(single.results.only["1-1"]).toEqual({ state: "OUTDATED" });+ const perPair = single.work;++ // Room for one full pair plus a little: the second pair runs out.+ const response = runPlacementBatch({+ generation: 2,+ limits: { ...limits, maxWorkPerRun: perPair + 10 },+ sheets,+ pairs: [pair("first"), pair("second"), pair("third")],+ });+ expect(response.results.first["1-1"]).toEqual({ state: "OUTDATED" });+ expect(response.results.second["1-1"]).toEqual(UNAVAILABLE);+ expect(response.results.third["1-1"]).toEqual(UNAVAILABLE);+ // The second pair stops one step past its remaining budget; the third+ // has none left and does not run at all.+ expect(response.work).toBe(perPair + 10 + 1);+ });++ test("applies the per-pair budget independently of the run budget", () => {+ const response = runPlacementBatch({+ generation: 3,+ limits: { ...limits, maxWorkPerPair: 20 },+ sheets: { a: changedScript("a"), b: changedScript("b") },+ pairs: [+ {+ key: "p",+ saved: "a",+ current: "b",+ anchors: [{ id: "1-1", startLine: 1, endLine: 1 }],+ },+ ],+ });+ expect(response.results.p["1-1"]).toEqual(UNAVAILABLE);+ expect(response.work).toBe(21);+ });++ test("settles a pair whose sheet is missing from the request", () => {+ const response = runPlacementBatch({+ generation: 5,+ limits,+ sheets: { a: "A" },+ pairs: [+ {+ key: "p",+ saved: "a",+ current: "missing",+ anchors: [{ id: "1-1", startLine: 1, endLine: 1 }],+ },+ ],+ });+ expect(response.results.p["1-1"]).toEqual(UNAVAILABLE);+ expect(response.incomplete).toEqual([]);+ });++ test("returns an empty result set for no pairs", () => {+ expect(+ runPlacementBatch({ generation: 4, limits, sheets: {}, pairs: [] })+ ).toEqual({+ generation: 4,+ results: {},+ incomplete: [],+ work: 0,+ });+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/placementWorker.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/placementWorker.tsnew file mode 100644index 0000000000..197946f558--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/placementWorker.ts@@ -0,0 +1,95 @@+import type { PlacementBudgets } from "./budgets";+import {+ diffPair,+ type PairAnchor,+ type Placement,+ placeOnPair,+ type SheetText,+ tokenizeSheet,+ UNAVAILABLE,+} from "./place";++// The message contract between the page and the placement worker. Sheets+// travel once, by name; pairs refer to them, so a target shared by several+// saved revisions is cloned and tokenized a single time.+export interface PlacementRequestPair {+ readonly key: string;+ readonly saved: string;+ readonly current: string;+ readonly anchors: readonly PairAnchor[];+}++export interface PlacementRequest {+ // Identifies the run; the page drops responses from earlier runs.+ readonly generation: number;+ // Complete sheet text by sheet name.+ readonly sheets: Readonly<Record<string, string>>;+ readonly pairs: readonly PlacementRequestPair[];+ readonly limits: Pick<+ PlacementBudgets,+ "maxLinesPerSheet" | "maxWorkPerPair" | "maxWorkPerRun"+ >;+}++export interface PlacementResponse {+ readonly generation: number;+ // Placement by pair key, then anchor id.+ readonly results: Record<string, Record<string, Placement>>;+ // Pairs whose diff ran out of budget. Their UNAVAILABLE results are not+ // definitive: a later run with budget to spare may place them.+ readonly incomplete: string[];+ // Total diff work spent.+ readonly work: number;+}++// Diffs each pair once and places every anchor on it. The per-run work budget+// is shared in request order: once it is spent, remaining pairs are+// UNAVAILABLE rather than partially computed.+export function runPlacementBatch(+ request: PlacementRequest+): PlacementResponse {+ const results: Record<string, Record<string, Placement>> = {};+ const incomplete: string[] = [];+ const sheets = new Map<string, SheetText>();+ const sheetOf = (name: string): SheetText | undefined => {+ const text = request.sheets[name];+ if (text === undefined) return undefined;+ let sheet = sheets.get(name);+ if (!sheet) {+ sheet = tokenizeSheet(text);+ sheets.set(name, sheet);+ }+ return sheet;+ };+ let remaining = request.limits.maxWorkPerRun;+ let work = 0;+ for (const pair of request.pairs) {+ const placed: Record<string, Placement> = {};+ results[pair.key] = placed;+ const settleUnavailable = () => {+ for (const anchor of pair.anchors) placed[anchor.id] = UNAVAILABLE;+ };+ if (remaining <= 0) {+ settleUnavailable();+ incomplete.push(pair.key);+ continue;+ }+ const saved = sheetOf(pair.saved);+ const current = sheetOf(pair.current);+ if (!saved || !current) {+ settleUnavailable();+ continue;+ }+ const diffed = diffPair(saved, current, {+ maxLinesPerSheet: request.limits.maxLinesPerSheet,+ maxWork: Math.min(request.limits.maxWorkPerPair, remaining),+ });+ remaining -= diffed.work;+ work += diffed.work;+ if (diffed.reason === "budget") incomplete.push(pair.key);+ for (const anchor of pair.anchors) {+ placed[anchor.id] = placeOnPair(diffed, anchor);+ }+ }+ return { generation: request.generation, results, incomplete, work };+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/statementThreads.css b/frontend/src/routes/project/plan-detail/components/threads/statementThreads.cssnew file mode 100644index 0000000000..0588672d47--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/statementThreads.css@@ -0,0 +1,140 @@+/* Monaco decoration classes for comment threads in the statement editor.+ Monaco applies these to its own DOM, so they live outside Tailwind. Colors+ come from the semantic tokens in tailwind.css. */++.monaco-editor .bb-thread-line--passive {+ background: rgb(var(--color-control-bg) / 0.65);+}++.monaco-editor .bb-thread-line {+ background: rgb(var(--color-accent) / 0.12);+}++.monaco-editor .bb-thread-line--selecting {+ background: rgb(var(--color-info) / 0.16);+}++/* Monaco owns the 24px hit area. Every marker uses the same centered 16px+ visual surface with 4px of breathing room on all sides: the element paints+ its surface inside a transparent 4px border, the icon fills the inner box,+ and the pseudo-element left over carries the thread-count badge. */+.monaco-editor .bb-thread-glyph,+.monaco-editor .bb-thread-add-glyph {+ --bb-thread-background: transparent;+ box-sizing: border-box;+ border: 4px solid transparent;+ border-radius: var(--radius-sm);+ background: var(--bb-thread-background);+ background-clip: padding-box;+ color: rgb(var(--color-control-light));+ cursor: pointer;+}++.monaco-editor .bb-thread-glyph::before,+.monaco-editor .bb-thread-add-glyph::before {+ content: "";+ position: absolute;+ inset: 0;+ pointer-events: none;+ background-color: currentColor;+ mask: var(--bb-thread-icon) center / 12px 12px no-repeat;+}++.monaco-editor .bb-thread-glyph {+ --bb-thread-icon: url("lucide-static/icons/message-square.svg");+}++/* Two or more threads on a line: the bubble stays and a filled badge sits on+ its top-right corner, so the number is attached to a shape and never reads+ as a line number in the lane beside it. */+.monaco-editor .bb-thread-glyph[class*="bb-thread-glyph--count-"]::after {+ content: var(--bb-thread-count);+ position: absolute;+ top: -5px;+ right: -5px;+ min-width: 12px;+ height: 12px;+ padding: 0 3px;+ box-sizing: border-box;+ border-radius: var(--radius-full);+ background: rgb(var(--color-accent));+ color: rgb(var(--color-accent-text));+ font:+ 500 9px / 12px ui-sans-serif,+ system-ui,+ sans-serif;+ font-variant-numeric: tabular-nums;+ text-align: center;+ pointer-events: none;+}++.monaco-editor .bb-thread-glyph--count-2 {+ --bb-thread-count: "2";+}++.monaco-editor .bb-thread-glyph--count-3 {+ --bb-thread-count: "3";+}++.monaco-editor .bb-thread-glyph--count-4 {+ --bb-thread-count: "4";+}++.monaco-editor .bb-thread-glyph--count-5 {+ --bb-thread-count: "5";+}++.monaco-editor .bb-thread-glyph--count-6 {+ --bb-thread-count: "6";+}++.monaco-editor .bb-thread-glyph--count-7 {+ --bb-thread-count: "7";+}++.monaco-editor .bb-thread-glyph--count-8 {+ --bb-thread-count: "8";+}++.monaco-editor .bb-thread-glyph--count-9 {+ --bb-thread-count: "9";+}++.monaco-editor .bb-thread-glyph--count-many {+ --bb-thread-count: "9+";+}++.monaco-editor .bb-thread-glyph--resolved {+ --bb-thread-icon: url("lucide-static/icons/message-square-check.svg");+}++/* The creation action rests as a plain accent plus, the same visual weight+ as the markers beside it; the tinted surface appears on hover only. */+.monaco-editor .bb-thread-add-glyph {+ --bb-thread-icon: url("lucide-static/icons/plus.svg");+ color: rgb(var(--color-accent));+}++.monaco-editor .bb-thread-add-glyph:hover {+ --bb-thread-background: rgb(var(--color-accent) / 0.12);+ color: rgb(var(--color-accent-hover));+}++.monaco-editor .bb-thread-add-glyph:active {+ --bb-thread-background: rgb(var(--color-accent) / 0.18);+}++.monaco-editor .bb-thread-glyph:hover,+.monaco-editor .bb-thread-glyph--active {+ --bb-thread-background: rgb(var(--color-control-bg));+ color: rgb(var(--color-control-hover));+}++.monaco-editor .bb-thread-glyph:active {+ --bb-thread-background: rgb(var(--color-control-bg-hover));+}++/* The gutter is the creation affordance; make that discoverable. */+.monaco-editor.bb-thread-creatable .margin-view-overlays .line-numbers {+ cursor: pointer;+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.ts b/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.tsnew file mode 100644index 0000000000..60a00c5031--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.ts@@ -0,0 +1,273 @@+import { create } from "@bufbuild/protobuf";+import { TimestampSchema } from "@bufbuild/protobuf/wkt";+import { describe, expect, test } from "vitest";+import { PositionSchema } from "@/types/proto-es/v1/common_pb";+import {+ IssueComment_ThreadState,+ IssueCommentSchema,+ StatementAnchorSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import {+ Plan_ChangeDatabaseConfigSchema,+ Plan_SpecSchema,+ PlanSchema,+} from "@/types/proto-es/v1/plan_service_pb";+import { current, OUTDATED, UNAVAILABLE } from "./placement/place";+import {+ anchorLineRange,+ buildWholeLineAnchor,+ defaultExpandedThread,+ excerptLines,+ formatLineRange,+ groupMarkersByLine,+ groupThreads,+ resolveAnchorState,+ selectEditorThreads,+ sheetSha256OfName,+} from "./threadModel";++const SHA = "a".repeat(64);+const OTHER_SHA = "b".repeat(64);+const ISSUE = "projects/p/issues/1";++const at = (seconds: number) =>+ create(TimestampSchema, { seconds: BigInt(seconds) });++const anchor = (startLine: number, endLine: number, sheetSha256 = SHA) =>+ create(StatementAnchorSchema, {+ spec: "spec-1",+ sheetSha256,+ startPosition: create(PositionSchema, { line: startLine, column: 0 }),+ endPosition: create(PositionSchema, { line: endLine, column: 0 }),+ });++const root = (+ id: string,+ opts: {+ anchor?: ReturnType<typeof anchor>;+ createdAt?: number;+ resolved?: boolean;+ } = {}+) =>+ create(IssueCommentSchema, {+ name: `${ISSUE}/issueComments/${id}`,+ comment: `root ${id}`,+ createTime: at(opts.createdAt ?? 1),+ threadState: opts.resolved+ ? IssueComment_ThreadState.RESOLVED+ : IssueComment_ThreadState.OPEN,+ statementAnchor: opts.anchor,+ });++const reply = (id: string, rootId: string, createdAt: number) =>+ create(IssueCommentSchema, {+ name: `${ISSUE}/issueComments/${id}`,+ comment: `reply ${id}`,+ createTime: at(createdAt),+ root: `${ISSUE}/issueComments/${rootId}`,+ });++const plan = (sheetSha256 = SHA) =>+ create(PlanSchema, {+ specs: [+ create(Plan_SpecSchema, {+ id: "spec-1",+ config: {+ case: "changeDatabaseConfig",+ value: create(Plan_ChangeDatabaseConfigSchema, {+ sheet: `projects/p/sheets/${sheetSha256}`,+ }),+ },+ }),+ ],+ });++describe("sheetSha256OfName", () => {+ test("reads the hash segment and rejects local drafts", () => {+ expect(sheetSha256OfName(`projects/p/sheets/${SHA.toUpperCase()}`)).toBe(+ SHA+ );+ expect(sheetSha256OfName("projects/p/sheets/-1")).toBeUndefined();+ expect(sheetSha256OfName("")).toBeUndefined();+ });+});++describe("groupThreads", () => {+ test("groups replies under their root, oldest first, and skips general comments", () => {+ const general = create(IssueCommentSchema, {+ name: `${ISSUE}/issueComments/general`,+ comment: "plain",+ });+ const threads = groupThreads([+ general,+ root("r1", { resolved: true }),+ reply("b", "r1", 5),+ reply("a", "r1", 3),+ root("r2"),+ reply("orphan", "missing", 1),+ ]);+ expect(threads.map((t) => t.root.name)).toEqual([+ `${ISSUE}/issueComments/r1`,+ `${ISSUE}/issueComments/r2`,+ ]);+ expect(threads[0].replies.map((r) => r.comment)).toEqual([+ "reply a",+ "reply b",+ ]);+ expect(threads[0].resolved).toBe(true);+ expect(threads[1].replies).toEqual([]);+ expect(threads[1].resolved).toBe(false);+ });+});++describe("resolveAnchorState", () => {+ test("a computed placement is authoritative", () => {+ expect(resolveAnchorState(anchor(1, 1), plan(), current(4, 4))).toBe(+ "CURRENT"+ );+ expect(resolveAnchorState(anchor(1, 1), plan(), OUTDATED)).toBe("OUTDATED");+ expect(resolveAnchorState(anchor(1, 1), plan(), UNAVAILABLE)).toBe(+ "UNAVAILABLE"+ );+ });++ test("without a placement, a hash match is CURRENT and a mismatch is PENDING", () => {+ expect(resolveAnchorState(anchor(1, 1), plan(), undefined)).toBe("CURRENT");+ expect(resolveAnchorState(anchor(1, 1), plan(OTHER_SHA), undefined)).toBe(+ "PENDING"+ );+ expect(+ resolveAnchorState(+ anchor(1, 1),+ create(PlanSchema, { specs: [] }),+ undefined+ )+ ).toBe("UNAVAILABLE");+ });+});++describe("anchorLineRange", () => {+ test("whole-line anchors include the end line", () => {+ expect(anchorLineRange(anchor(8, 10))).toEqual({+ startLine: 8,+ endLine: 10,+ });+ });++ test("code-point ranges ending at column 1 stop on the previous line", () => {+ const precise = create(StatementAnchorSchema, {+ startPosition: create(PositionSchema, { line: 3, column: 2 }),+ endPosition: create(PositionSchema, { line: 5, column: 1 }),+ });+ expect(anchorLineRange(precise)).toEqual({ startLine: 3, endLine: 4 });+ });++ test("rejects malformed anchors", () => {+ expect(anchorLineRange(create(StatementAnchorSchema))).toBeUndefined();+ expect(anchorLineRange(anchor(5, 2))).toBeUndefined();+ });+});++describe("buildWholeLineAnchor", () => {+ test("orders the lines and uses zero columns", () => {+ const built = buildWholeLineAnchor({+ spec: "spec-1",+ sheetSha256: SHA,+ startLine: 9,+ endLine: 4,+ });+ expect(built.spec).toBe("spec-1");+ expect(built.sheetSha256).toBe(SHA);+ expect(built.startPosition).toMatchObject({ line: 4, column: 0 });+ expect(built.endPosition).toMatchObject({ line: 9, column: 0 });+ });+});++describe("editor placement", () => {+ const threads = groupThreads([+ root("later", { anchor: anchor(12, 14), createdAt: 1 }),+ root("changed", { anchor: anchor(1, 1, OTHER_SHA), createdAt: 1 }),+ root("resolved-early", {+ anchor: anchor(3, 4),+ createdAt: 1,+ resolved: true,+ }),+ root("open-early-new", { anchor: anchor(6, 9), createdAt: 9 }),+ root("open-early-old", { anchor: anchor(6, 9), createdAt: 2 }),+ root("unanchored"),+ ]);+ const placed = selectEditorThreads(threads, {+ specId: "spec-1",+ sheetSha256: SHA,+ });++ test("keeps only current anchors of the displayed statement, by line then age", () => {+ expect(placed.map((entry) => entry.thread.root.comment)).toEqual([+ "root resolved-early",+ "root open-early-old",+ "root open-early-new",+ "root later",+ ]);+ expect(+ selectEditorThreads(threads, { specId: "spec-2", sheetSha256: SHA })+ ).toEqual([]);+ });++ test("a placement decides: CURRENT threads move to their mapped range, others leave", () => {+ const placements = new Map([+ // The old-revision thread survived edits above it.+ [`${ISSUE}/issueComments/changed`, current(3, 3)],+ // A same-revision thread the diff could not place.+ [`${ISSUE}/issueComments/later`, UNAVAILABLE],+ [`${ISSUE}/issueComments/resolved-early`, OUTDATED],+ ]);+ const withPlacements = selectEditorThreads(+ threads,+ { specId: "spec-1", sheetSha256: SHA },+ placements+ );+ expect(+ withPlacements.map((entry) => [+ entry.thread.root.comment,+ entry.range.startLine,+ entry.range.endLine,+ ])+ ).toEqual([+ ["root changed", 3, 3],+ ["root open-early-old", 6, 9],+ ["root open-early-new", 6, 9],+ ]);+ });++ test("expands the unresolved thread on the earliest line, oldest first", () => {+ expect(defaultExpandedThread(placed)?.thread.root.comment).toBe(+ "root open-early-old"+ );+ expect(+ defaultExpandedThread(placed.filter((entry) => entry.thread.resolved))+ ).toBeUndefined();+ });++ test("markers sit on the last line and combine per line, oldest first", () => {+ const markers = groupMarkersByLine(placed);+ expect(Array.from(markers.keys())).toEqual([4, 9, 14]);+ expect(markers.get(9)?.map((entry) => entry.thread.root.comment)).toEqual([+ "root open-early-old",+ "root open-early-new",+ ]);+ });+});++describe("excerpt and labels", () => {+ test("slices the anchored lines regardless of line endings", () => {+ expect(excerptLines("a\r\nb\nc\rd", { startLine: 2, endLine: 3 })).toEqual([+ "b",+ "c",+ ]);+ });++ test("formats single and multi-line ranges", () => {+ expect(formatLineRange({ startLine: 4, endLine: 4 })).toBe("4");+ expect(formatLineRange({ startLine: 8, endLine: 10 })).toBe("8–10");+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts b/frontend/src/routes/project/plan-detail/components/threads/threadModel.tsnew file mode 100644index 0000000000..31fed1c54f--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts@@ -0,0 +1,221 @@+// Pure helpers for comment threads and statement anchors (design doc: Plan+// Review Comment and Thread UI/UX). The store keeps a flat comment list; these+// group it into threads, derive anchor state from the plan, and decide what+// the statement editor shows.+import { create } from "@bufbuild/protobuf";+import type { TFunction } from "i18next";+import { isThreadReply, isThreadRoot } from "@/stores/app/issueComment";+import { getTimeForPbTimestampProtoEs } from "@/types";+import { PositionSchema } from "@/types/proto-es/v1/common_pb";+import {+ type IssueComment,+ IssueComment_ThreadState,+ type StatementAnchor,+ StatementAnchorSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import type { Plan, Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";+import { sheetNameOfSpec } from "@/utils/v1/issue/plan";+import { extractSheetUID } from "@/utils/v1/sheet";+import { tokenizeLines } from "./placement/lineTokens";+import {+ type LineRange,+ type Placement,+ trivialPlacement,+} from "./placement/place";++export type { LineRange };++export interface CommentThread {+ root: IssueComment;+ // Oldest first.+ replies: IssueComment[];+ resolved: boolean;+}++export type AnchorState = Placement["state"] | "PENDING";++// A thread placed in the statement editor: its root anchor is CURRENT for the+// displayed spec and sheet.+export interface EditorThread {+ thread: CommentThread;+ range: LineRange;+}++const createTimeOf = (comment: IssueComment): number =>+ getTimeForPbTimestampProtoEs(comment.createTime, 0);++export const compareByCreateTime = (a: IssueComment, b: IssueComment): number =>+ createTimeOf(a) - createTimeOf(b) || a.name.localeCompare(b.name);++// Sheet names embed the content hash: projects/{project}/sheets/{sha256}.+// Local drafts use negative ids and never anchor.+export const sheetSha256OfName = (sheetName: string): string | undefined => {+ const uid = extractSheetUID(sheetName).toLowerCase();+ return /^[0-9a-f]{64}$/.test(uid) ? uid : undefined;+};++export const sheetNameOfSha256 = (+ projectName: string,+ sheetSha256: string+): string => `${projectName}/sheets/${sheetSha256}`;++// The hash of the sheet a spec currently points at, the target every anchor+// on that spec is placed against.+export const targetSha256OfSpec = (+ spec: Plan_Spec | undefined+): string | undefined =>+ spec ? sheetSha256OfName(sheetNameOfSpec(spec)) : undefined;++export function groupThreads(comments: IssueComment[]): CommentThread[] {+ const repliesByRoot = new Map<string, IssueComment[]>();+ for (const comment of comments) {+ if (!isThreadReply(comment)) continue;+ const list = repliesByRoot.get(comment.root) ?? [];+ list.push(comment);+ repliesByRoot.set(comment.root, list);+ }+ return comments.filter(isThreadRoot).map((root) => ({+ root,+ replies: (repliesByRoot.get(root.name) ?? []).sort(compareByCreateTime),+ resolved: root.threadState === IssueComment_ThreadState.RESOLVED,+ }));+}++// The state shown for an anchor in the timeline. A computed placement is+// authoritative. Before one exists, a hash match is CURRENT, a missing spec+// is UNAVAILABLE, and anything else is PENDING until the diff settles it.+export function resolveAnchorState(+ anchor: StatementAnchor,+ plan: Pick<Plan, "specs">,+ placement: Placement | undefined+): AnchorState {+ if (placement) return placement.state;+ const spec = plan.specs.find((candidate) => candidate.id === anchor.spec);+ return trivialPlacement(anchor, targetSha256OfSpec(spec))?.state ?? "PENDING";+}++// Whole-line anchors use zero columns and an inclusive end line. A+// code-point range is end-exclusive, so an end at column 1 of a later line+// covers nothing on that line.+export function anchorLineRange(+ anchor: StatementAnchor+): LineRange | undefined {+ const start = anchor.startPosition;+ const end = anchor.endPosition;+ if (!start || !end || start.line < 1 || end.line < start.line) {+ return undefined;+ }+ const wholeLine = start.column === 0 && end.column === 0;+ const endLine =+ !wholeLine && end.column === 1 && end.line > start.line+ ? end.line - 1+ : end.line;+ return { startLine: start.line, endLine: Math.max(endLine, start.line) };+}++export function buildWholeLineAnchor(input: {+ spec: string;+ sheetSha256: string;+ startLine: number;+ endLine: number;+}): StatementAnchor {+ const startLine = Math.min(input.startLine, input.endLine);+ const endLine = Math.max(input.startLine, input.endLine);+ return create(StatementAnchorSchema, {+ spec: input.spec,+ sheetSha256: input.sheetSha256,+ startPosition: create(PositionSchema, { line: startLine, column: 0 }),+ endPosition: create(PositionSchema, { line: endLine, column: 0 }),+ });+}++export const formatLineRange = (range: LineRange): string =>+ range.startLine === range.endLine+ ? `${range.startLine}`+ : `${range.startLine}–${range.endLine}`;++// "Line 2" or "Lines 2–4".+export const lineRangeLabel = (t: TFunction, range: LineRange): string =>+ t("plan.review.thread.anchor.line", {+ count: range.endLine - range.startLine + 1,+ range: formatLineRange(range),+ });++// The whole lines a Monaco selection covers. An end at column 1 of a later+// line covers nothing on that line.+export const selectionLineRange = (selection: {+ startLineNumber: number;+ endLineNumber: number;+ endColumn: number;+}): LineRange => ({+ startLine: selection.startLineNumber,+ endLine:+ selection.endColumn === 1 &&+ selection.endLineNumber > selection.startLineNumber+ ? selection.endLineNumber - 1+ : selection.endLineNumber,+});++const compareEditorThreads = (a: EditorThread, b: EditorThread): number =>+ a.range.startLine - b.range.startLine ||+ a.range.endLine - b.range.endLine ||+ compareByCreateTime(a.thread.root, b.thread.root);++// Threads shown in the displayed statement, ordered by start line, then+// oldest first. A computed placement decides: CURRENT threads sit at their+// mapped range, which may differ from the anchor's when edits above shifted+// it; OUTDATED and UNAVAILABLE threads stay out of the editor. `placements`+// must have been computed against the displayed sheet; a thread without one+// falls back to the same no-diff rule the planner applies, so the two never+// disagree.+export function selectEditorThreads(+ threads: CommentThread[],+ target: { specId: string; sheetSha256: string },+ placements: ReadonlyMap<string, Placement> = new Map()+): EditorThread[] {+ const placed: EditorThread[] = [];+ for (const thread of threads) {+ const anchor = thread.root.statementAnchor;+ if (!anchor) continue;+ if (anchor.spec !== target.specId) continue;+ const placement =+ placements.get(thread.root.name) ??+ trivialPlacement(anchor, target.sheetSha256);+ if (placement?.state !== "CURRENT") continue;+ placed.push({ thread, range: placement.range });+ }+ return placed.sort(compareEditorThreads);+}++// Only the unresolved thread anchored on the earliest line expands by+// default; every other thread is a gutter marker.+export function defaultExpandedThread(+ editorThreads: EditorThread[]+): EditorThread | undefined {+ return editorThreads.find((entry) => !entry.thread.resolved);+}++// Markers sit on the last anchored line. Threads sharing that line combine+// into one marker with a count, listed oldest first.+export function groupMarkersByLine(+ editorThreads: EditorThread[]+): Map<number, EditorThread[]> {+ const byLine = new Map<number, EditorThread[]>();+ for (const entry of editorThreads) {+ const list = byLine.get(entry.range.endLine) ?? [];+ list.push(entry);+ byLine.set(entry.range.endLine, list);+ }+ for (const list of byLine.values()) {+ list.sort((a, b) => compareByCreateTime(a.thread.root, b.thread.root));+ }+ return byLine;+}++// The editor lines of a range, without terminators, on the same line model+// the placement diff uses.+export function excerptLines(statement: string, range: LineRange): string[] {+ return tokenizeLines(statement)+ .slice(range.startLine - 1, range.endLine)+ .map((line) => line.replace(/\r\n$|[\r\n]$/, ""));+}diff --git a/frontend/src/routes/project/plan-detail/components/threads/useThreadActions.ts b/frontend/src/routes/project/plan-detail/components/threads/useThreadActions.tsnew file mode 100644index 0000000000..492d62bb10--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/useThreadActions.ts@@ -0,0 +1,110 @@+import { useCallback, useState } from "react";+import { useTranslation } from "react-i18next";+import { pushNotification } from "@/stores";+import { useAppStore } from "@/stores/app";+import {+ IssueComment_ThreadState,+ type StatementAnchor,+} from "@/types/proto-es/v1/issue_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";+import { hasProjectPermissionV2 } from "@/utils/iam/permission";++// Resolve and Reopen go through UpdateIssueComment, which the server gates+// on the update permission alone; authoring the root grants nothing there,+// so the UI offers the actions only to users the server will accept.+export function canSettleThread(project: Project | undefined): boolean {+ return Boolean(+ project && hasProjectPermissionV2(project, "bb.issueComments.update")+ );+}++export function canReplyToThread(project: Project | undefined): boolean {+ return Boolean(+ project && hasProjectPermissionV2(project, "bb.issueComments.create")+ );+}++// Store calls shared by the timeline card, the editor card, and the inline+// composer. Failures surface as notifications; callers keep their drafts.+export function useThreadActions(issueName: string) {+ const { t } = useTranslation();+ const [pending, setPending] = useState(false);++ const run = useCallback(+ async <T>(+ action: () => Promise<T>,+ failureTitle?: string+ ): Promise<T | undefined> => {+ try {+ setPending(true);+ return await action();+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: failureTitle ?? t("common.failed"),+ description: String(error),+ });+ return undefined;+ } finally {+ setPending(false);+ }+ },+ [t]+ );++ const publish = useCallback(+ (comment: string, statementAnchor: StatementAnchor) =>+ run(() =>+ useAppStore+ .getState()+ .createIssueComment({ issueName, comment, statementAnchor })+ ),+ [issueName, run]+ );++ const reply = useCallback(+ (root: string, comment: string) =>+ run(() =>+ useAppStore.getState().createIssueComment({ issueName, comment, root })+ ),+ [issueName, run]+ );++ const edit = useCallback(+ (issueCommentName: string, comment: string) =>+ run(() =>+ useAppStore.getState().updateIssueComment({ issueCommentName, comment })+ ),+ [run]+ );++ const setThreadState = useCallback(+ (+ issueCommentName: string,+ threadState: IssueComment_ThreadState,+ failureTitle?: string+ ) =>+ run(+ () =>+ useAppStore+ .getState()+ .updateIssueComment({ issueCommentName, threadState }),+ failureTitle+ ),+ [run]+ );++ const resolve = useCallback(+ (root: string, failureTitle?: string) =>+ setThreadState(root, IssueComment_ThreadState.RESOLVED, failureTitle),+ [setThreadState]+ );+ const reopen = useCallback(+ (root: string, failureTitle?: string) =>+ setThreadState(root, IssueComment_ThreadState.OPEN, failureTitle),+ [setThreadState]+ );++ return { edit, pending, publish, reopen, reply, resolve };+}diff --git a/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.test.ts b/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.test.tsnew file mode 100644index 0000000000..7d3a08eade--- /dev/null+++ b/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.test.ts@@ -0,0 +1,80 @@+import { create } from "@bufbuild/protobuf";+import { renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { IssueSchema } from "@/types/proto-es/v1/issue_service_pb";++const mocks = vi.hoisted(() => ({+ fetchIssueCommentThreads: vi.fn(async () => undefined),+}));++vi.mock("@/stores/app", () => ({+ useAppStore: {+ getState: () => ({+ fetchIssueCommentThreads: mocks.fetchIssueCommentThreads,+ }),+ },+}));++import { useIssueCommentThreadsSync } from "./useIssueCommentThreadsSync";++const issue = (seconds: number) =>+ create(IssueSchema, {+ name: "projects/p/issues/1",+ updateTime: { seconds: BigInt(seconds), nanos: 0 },+ });++beforeEach(() => {+ vi.useFakeTimers();+ mocks.fetchIssueCommentThreads.mockClear();+});+afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+});++describe("useIssueCommentThreadsSync", () => {+ test("loads on mount, when the issue's update time moves, and on a visible cadence", () => {+ const { rerender } = renderHook(+ (props) => useIssueCommentThreadsSync(props),+ {+ initialProps: issue(1),+ }+ );+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(1);+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledWith({+ parent: "projects/p/issues/1",+ });++ // A poll that leaves updateTime alone (comment writes never move it)+ // does not refetch by itself.+ rerender(issue(1));+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(1);+ rerender(issue(2));+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(2);++ vi.advanceTimersByTime(15_000);+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(3);++ const hidden = vi.spyOn(document, "hidden", "get").mockReturnValue(true);+ vi.advanceTimersByTime(15_000);+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(3);+ hidden.mockReturnValue(false);+ document.dispatchEvent(new Event("visibilitychange"));+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(4);+ });++ test("does nothing without an issue and stops after unmount", () => {+ const { rerender, unmount } = renderHook(+ (props) => useIssueCommentThreadsSync(props),+ {+ initialProps: undefined as ReturnType<typeof issue> | undefined,+ }+ );+ expect(mocks.fetchIssueCommentThreads).not.toHaveBeenCalled();+ rerender(issue(1));+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(1);+ unmount();+ vi.advanceTimersByTime(60_000);+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.ts b/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.tsnew file mode 100644index 0000000000..88217428d3--- /dev/null+++ b/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.ts@@ -0,0 +1,41 @@+import { useEffect } from "react";+import { useAppStore } from "@/stores/app";+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";++// Comment writes never touch the issue's update time, so polling the issue+// cannot reveal another reviewer's reply, edit, resolve, or reopen. The+// threads are re-listed on their own cadence while the page is visible.+const THREADS_REFRESH_INTERVAL_MS = 15_000;++// Loads the issue's comments with thread replies when the issue changes+// server-side (polling bumps updateTime) or after local actions refresh it,+// and periodically in between for remote thread activity. Mounted once per+// plan page: both the Review Activity timeline and the statement editor read+// the same cache, so neither may depend on the other being expanded to have+// it filled.+export function useIssueCommentThreadsSync(issue: Issue | undefined) {+ const issueName = issue?.name;+ const updateKey = `${issue?.updateTime?.seconds ?? ""}:${issue?.updateTime?.nanos ?? ""}`;+ useEffect(() => {+ if (!issueName) return;+ const refresh = () => {+ void useAppStore+ .getState()+ .fetchIssueCommentThreads({ parent: issueName })+ .catch(() => undefined);+ };+ refresh();+ const timer = window.setInterval(() => {+ if (!document.hidden) refresh();+ }, THREADS_REFRESH_INTERVAL_MS);+ // Ticks are skipped while hidden; catch up as soon as the page is back.+ const onVisibilityChange = () => {+ if (!document.hidden) refresh();+ };+ document.addEventListener("visibilitychange", onVisibilityChange);+ return () => {+ window.clearInterval(timer);+ document.removeEventListener("visibilitychange", onVisibilityChange);+ };+ }, [issueName, updateKey]);+}diff --git a/frontend/src/routes/project/plan-detail/hooks/usePlacementSync.test.tsx b/frontend/src/routes/project/plan-detail/hooks/usePlacementSync.test.tsxnew file mode 100644index 0000000000..0bc463c43f--- /dev/null+++ b/frontend/src/routes/project/plan-detail/hooks/usePlacementSync.test.tsx@@ -0,0 +1,109 @@+import { create } from "@bufbuild/protobuf";+import { renderHook } from "@testing-library/react";+import type { ReactNode } from "react";+import { describe, expect, test, vi } from "vitest";+import { IssueCommentSchema } from "@/types/proto-es/v1/issue_service_pb";+import {+ Plan_ChangeDatabaseConfigSchema,+ Plan_SpecSchema,+} from "@/types/proto-es/v1/plan_service_pb";+import { PlanDetailStoreContext } from "../shared/stores/usePlanDetailStore";++const mocks = vi.hoisted(() => ({+ comments: [] as unknown[],+}));++vi.mock("@/stores/app", () => ({+ useAppStore: (selector: (state: unknown) => unknown) =>+ selector({ getIssueComments: () => mocks.comments }),+}));++import { usePlacementSync } from "./usePlacementSync";++const spec = (id: string, sha: string) =>+ create(Plan_SpecSchema, {+ id,+ config: {+ case: "changeDatabaseConfig",+ value: create(Plan_ChangeDatabaseConfigSchema, {+ sheet: `projects/p/sheets/${sha}`,+ }),+ },+ });++const setup = () => {+ const computePlacements = vi.fn(async () => {});+ const store = {+ getState: () => ({ computePlacements }),+ getInitialState: () => ({ computePlacements }),+ subscribe: () => () => {},+ setState: () => {},+ };+ const wrapper = ({ children }: { children: ReactNode }) => (+ <PlanDetailStoreContext.Provider+ value={store as unknown as React.ContextType<typeof PlanDetailStoreContext>}+ >+ {children}+ </PlanDetailStoreContext.Provider>+ );+ return { computePlacements, wrapper };+};++describe("usePlacementSync", () => {+ test("runs once the page is ready and has an issue, with the project name", () => {+ const { computePlacements, wrapper } = setup();+ const specs = [spec("s1", "a".repeat(64))];+ mocks.comments = [create(IssueCommentSchema, { name: "c1" })];+ const { rerender } = renderHook((props) => usePlacementSync(props), {+ wrapper,+ initialProps: {+ issueName: undefined as string | undefined,+ projectId: "p",+ ready: false,+ specs,+ },+ });+ expect(computePlacements).not.toHaveBeenCalled();+ rerender({ issueName: "projects/p/issues/1", projectId: "p", ready: false, specs });+ expect(computePlacements).not.toHaveBeenCalled();+ rerender({ issueName: "projects/p/issues/1", projectId: "p", ready: true, specs });+ expect(computePlacements).toHaveBeenCalledTimes(1);+ expect(computePlacements).toHaveBeenCalledWith({+ comments: mocks.comments,+ projectName: "projects/p",+ specs,+ });+ });++ test("reruns when comments or a spec's sheet change, not on a mere plan refresh", () => {+ const { computePlacements, wrapper } = setup();+ const base = {+ issueName: "projects/p/issues/1",+ projectId: "p",+ ready: true,+ };+ mocks.comments = [];+ const { rerender } = renderHook((props) => usePlacementSync(props), {+ wrapper,+ initialProps: { ...base, specs: [spec("s1", "a".repeat(64))] },+ });+ expect(computePlacements).toHaveBeenCalledTimes(1);++ // A fresh but identical spec list (polling) does not rerun.+ rerender({ ...base, specs: [spec("s1", "a".repeat(64))] });+ expect(computePlacements).toHaveBeenCalledTimes(1);++ // A new sheet on the spec does.+ const saved = [spec("s1", "b".repeat(64))];+ rerender({ ...base, specs: saved });+ expect(computePlacements).toHaveBeenCalledTimes(2);+ expect(computePlacements).toHaveBeenLastCalledWith(+ expect.objectContaining({ specs: saved })+ );++ // New comments do.+ mocks.comments = [create(IssueCommentSchema, { name: "c1" })];+ rerender({ ...base, specs: saved });+ expect(computePlacements).toHaveBeenCalledTimes(3);+ });+});diff --git a/frontend/src/routes/project/plan-detail/hooks/usePlacementSync.ts b/frontend/src/routes/project/plan-detail/hooks/usePlacementSync.tsnew file mode 100644index 0000000000..b3bbc48a98--- /dev/null+++ b/frontend/src/routes/project/plan-detail/hooks/usePlacementSync.ts@@ -0,0 +1,41 @@+import { useEffect, useMemo } from "react";+import { useAppStore } from "@/stores/app";+import { projectNamePrefix } from "@/stores/modules/v1/common";+import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";+import { sheetNameOfSpec } from "@/utils/v1/issue/plan";+import { usePlanDetailStore } from "../shared/stores/usePlanDetailStore";++const EMPTY_COMMENTS: IssueComment[] = [];++// Recomputes comment placements whenever the issue's comments or any spec's+// sheet changes. Mounted once per plan page so the statement editor and the+// Review Activity timeline read the same result.+export function usePlacementSync(page: {+ issueName: string | undefined;+ projectId: string;+ ready: boolean;+ specs: readonly Plan_Spec[];+}) {+ const { issueName, projectId, ready, specs } = page;+ const comments = useAppStore((state) =>+ issueName ? state.getIssueComments(issueName) : EMPTY_COMMENTS+ );+ const computePlacements = usePlanDetailStore((s) => s.computePlacements);++ // Polling replaces the plan object on every tick; only the spec ids and+ // their sheets matter here, so key the effect on those.+ const sheetKey = useMemo(+ () => specs.map((spec) => `${spec.id}=${sheetNameOfSpec(spec)}`).join("\n"),+ [specs]+ );++ useEffect(() => {+ if (!ready || !issueName) return;+ void computePlacements({+ comments,+ projectName: `${projectNamePrefix}${projectId}`,+ specs,+ });+ }, [comments, computePlacements, issueName, projectId, ready, sheetKey]);+}diff --git a/frontend/src/routes/project/plan-detail/shared/stores/placementSlice.test.ts b/frontend/src/routes/project/plan-detail/shared/stores/placementSlice.test.tsnew file mode 100644index 0000000000..c8cd27b88c--- /dev/null+++ b/frontend/src/routes/project/plan-detail/shared/stores/placementSlice.test.ts@@ -0,0 +1,651 @@+import { create } from "@bufbuild/protobuf";+import { TimestampSchema } from "@bufbuild/protobuf/wkt";+import { describe, expect, test, vi } from "vitest";+import { PositionSchema } from "@/types/proto-es/v1/common_pb";+import {+ IssueCommentSchema,+ StatementAnchorSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import {+ Plan_ChangeDatabaseConfigSchema,+ Plan_SpecSchema,+} from "@/types/proto-es/v1/plan_service_pb";+import { type Sheet, SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";+import { PLACEMENT_BUDGETS } from "../../components/threads/placement/budgets";+import {+ current,+ diffPair,+ tokenizeSheet,+ UNAVAILABLE,+} from "../../components/threads/placement/place";+import {+ type PlacementClient,+ PlacementError,+} from "../../components/threads/placement/placementClient";+import {+ type PlacementRequest,+ type PlacementResponse,+ runPlacementBatch,+} from "../../components/threads/placement/placementWorker";+import type { PlacementDeps } from "./placementSlice";+import { createPlanDetailStore } from "./usePlanDetailStore";++const PROJECT = "projects/p";+const SHA_OLD = "a".repeat(64);+const SHA_NEW = "b".repeat(64);+const SHA_NEWER = "c".repeat(64);+const sheetName = (sha: string) => `${PROJECT}/sheets/${sha}`;+const PREVIEW_BYTES = 4;++const OLD_TEXT = "CREATE TABLE a (id INT);\nALTER TABLE a ADD b INT;\n";+const NEW_TEXT = `-- header\n${OLD_TEXT}`;+const NEWER_TEXT = `-- one\n-- two\n${OLD_TEXT}`;++const anchor = (sha: string, first: number, last = first, spec = "spec-1") =>+ create(StatementAnchorSchema, {+ spec,+ sheetSha256: sha,+ startPosition: create(PositionSchema, { line: first, column: 0 }),+ endPosition: create(PositionSchema, { line: last, column: 0 }),+ });++const nameOf = (id: string) => `${PROJECT}/issues/1/issueComments/${id}`;+const comment = (+ id: string,+ statementAnchor?: ReturnType<typeof anchor>,+ createdAt = 1+) =>+ create(IssueCommentSchema, {+ name: nameOf(id),+ createTime: create(TimestampSchema, { seconds: BigInt(createdAt) }),+ statementAnchor,+ });++const specs = (sha: string, specId = "spec-1") => [+ create(Plan_SpecSchema, {+ id: specId,+ config: {+ case: "changeDatabaseConfig",+ value: create(Plan_ChangeDatabaseConfigSchema, {+ sheet: sheetName(sha),+ }),+ },+ }),+];++// A sheet cache that behaves like the app store's: previews are truncated to+// PREVIEW_BYTES with the full size attached, raw fetches are complete, and a+// complete sheet is never replaced by a preview.+const fakeSheets = (+ contents: Record<string, string>,+ previewBytes = PREVIEW_BYTES+) => {+ const cache = new Map<string, Sheet>();+ const calls: { name: string; raw: boolean }[] = [];+ const encoder = new TextEncoder();+ const build = (name: string, raw: boolean) => {+ const full = encoder.encode(contents[name]);+ return create(SheetSchema, {+ name,+ content: raw ? full : full.slice(0, previewBytes),+ contentSize: BigInt(full.byteLength),+ });+ };+ return {+ cache,+ calls,+ getSheet: (name: string) => cache.get(name),+ fetchSheet: async (name: string, raw: boolean) => {+ calls.push({ name, raw });+ if (!(name in contents)) return undefined;+ const sheet = build(name, raw);+ const existing = cache.get(name);+ if (!existing || raw) cache.set(name, sheet);+ return cache.get(name);+ },+ prime: (name: string, raw: boolean) => {+ cache.set(name, build(name, raw));+ },+ };+};++const immediateClient = (): PlacementClient & {+ requests: PlacementRequest[];+} => {+ const requests: PlacementRequest[] = [];+ return {+ requests,+ compute: async (request) => {+ requests.push(request);+ return runPlacementBatch(request);+ },+ cancel: vi.fn(),+ };+};++// A client whose answer the test releases by hand. Like the real client,+// `cancel` rejects the request in flight.+const heldClient = () => {+ let release: ((response: PlacementResponse) => void) | undefined;+ let fail: ((error: unknown) => void) | undefined;+ const requests: PlacementRequest[] = [];+ const client: PlacementClient = {+ compute: (request) => {+ requests.push(request);+ return new Promise<PlacementResponse>((resolve, reject) => {+ release = resolve;+ fail = reject;+ });+ },+ cancel: vi.fn(() => fail?.(new PlacementError("cancelled"))),+ };+ return {+ client,+ requests,+ release: () => release?.(runPlacementBatch(requests[requests.length - 1])),+ fail: (error: unknown) => fail?.(error),+ };+};++const setup = (+ overrides: Partial<PlacementDeps> & {+ sheets?: ReturnType<typeof fakeSheets>;+ } = {}+) => {+ const sheets =+ overrides.sheets ??+ fakeSheets({+ [sheetName(SHA_OLD)]: OLD_TEXT,+ [sheetName(SHA_NEW)]: NEW_TEXT,+ [sheetName(SHA_NEWER)]: NEWER_TEXT,+ });+ const client = overrides.client ?? immediateClient();+ let clock = 0;+ const store = createPlanDetailStore({+ getSheet: sheets.getSheet,+ fetchSheet: sheets.fetchSheet,+ client,+ budgets: PLACEMENT_BUDGETS,+ now: () => (clock += 5),+ ...overrides,+ });+ return { store, sheets, client };+};++const compute = (+ store: ReturnType<typeof createPlanDetailStore>,+ comments: ReturnType<typeof comment>[],+ targetSha = SHA_NEW+) =>+ store.getState().computePlacements({+ comments,+ projectName: PROJECT,+ specs: specs(targetSha),+ });++describe("placementSlice", () => {+ test("settles hash-equal anchors without fetching or diffing", async () => {+ const { store, sheets, client } = setup();+ await compute(store, [+ comment("same", anchor(SHA_NEW, 2, 3)),+ comment("plain"),+ ]);+ const state = store.getState();+ expect(state.placements.get(nameOf("same"))).toEqual(current(2, 3));+ expect(state.placements.has(nameOf("plain"))).toBe(false);+ expect(sheets.calls).toEqual([]);+ expect((client as ReturnType<typeof immediateClient>).requests).toEqual([]);+ expect(state.placementMetrics).toMatchObject({+ pairCount: 0,+ computedPairCount: 0,+ sheetCount: 0,+ bytes: 0,+ work: 0,+ });+ });++ test("probes unknown sizes, downloads complete sheets, and places through the worker", async () => {+ const { store, sheets, client } = setup();+ // The current sheet is cached as a preview, like the editor leaves it.+ sheets.prime(sheetName(SHA_NEW), false);+ await compute(store, [+ comment("moved", anchor(SHA_OLD, 1, 2), 1),+ comment("also", anchor(SHA_OLD, 2), 2),+ ]);+ const state = store.getState();+ expect(state.placements.get(nameOf("moved"))).toEqual(current(2, 3));+ expect(state.placements.get(nameOf("also"))).toEqual(current(3, 3));+ expect(sheets.calls).toEqual([+ // Size probe for the never-seen source, then raw downloads of both.+ { name: sheetName(SHA_OLD), raw: false },+ { name: sheetName(SHA_OLD), raw: true },+ { name: sheetName(SHA_NEW), raw: true },+ ]);+ const requests = (client as ReturnType<typeof immediateClient>).requests;+ expect(requests).toHaveLength(1);+ expect(requests[0].sheets).toEqual({+ [sheetName(SHA_OLD)]: OLD_TEXT,+ [sheetName(SHA_NEW)]: NEW_TEXT,+ });+ expect(requests[0].pairs).toEqual([+ expect.objectContaining({+ saved: sheetName(SHA_OLD),+ current: sheetName(SHA_NEW),+ anchors: [+ { id: "1-2", startLine: 1, endLine: 2 },+ { id: "2-2", startLine: 2, endLine: 2 },+ ],+ }),+ ]);+ expect(state.placementMetrics).toMatchObject({+ pairCount: 1,+ computedPairCount: 1,+ sheetCount: 2,+ bytes: OLD_TEXT.length + NEW_TEXT.length,+ });+ expect(state.placementMetrics?.work).toBeGreaterThan(0);+ expect(state.placementMetrics?.durationMs).toBeGreaterThan(0);+ });++ test("reuses a diffed pair on the next run without fetching or diffing again", async () => {+ const { store, sheets, client } = setup();+ await compute(store, [comment("moved", anchor(SHA_OLD, 1))]);+ const callsAfterFirst = sheets.calls.length;+ await compute(store, [+ comment("moved", anchor(SHA_OLD, 1)),+ comment("new-anchor", anchor(SHA_OLD, 2)),+ ]);+ const state = store.getState();+ expect(state.placements.get(nameOf("moved"))).toEqual(current(2, 2));+ // A new range on a cached pair is computed, but the sheets are complete.+ expect(state.placements.get(nameOf("new-anchor"))).toEqual(current(3, 3));+ expect(sheets.calls).toHaveLength(callsAfterFirst);+ expect(+ (client as ReturnType<typeof immediateClient>).requests+ ).toHaveLength(2);+ expect(state.placementMetrics).toMatchObject({+ pairCount: 1,+ computedPairCount: 1,+ sheetCount: 0,+ });+ });++ test("a range already computed on the cached pair costs no worker call", async () => {+ const { store, client } = setup();+ await compute(store, [comment("moved", anchor(SHA_OLD, 1))]);+ await compute(store, [comment("moved", anchor(SHA_OLD, 1))]);+ expect(+ (client as ReturnType<typeof immediateClient>).requests+ ).toHaveLength(1);+ expect(store.getState().placementMetrics).toMatchObject({+ pairCount: 1,+ computedPairCount: 0,+ });+ });++ test("settles UNAVAILABLE when the worker fails or times out", async () => {+ const held = heldClient();+ const { store } = setup({ client: held.client });+ const run = compute(store, [comment("moved", anchor(SHA_OLD, 1))]);+ await vi.waitFor(() => expect(held.requests).toHaveLength(1));+ held.fail(new PlacementError("deadline"));+ await run;+ expect(store.getState().placements.get(nameOf("moved"))).toEqual(+ UNAVAILABLE+ );+ expect(store.getState().placementMetrics).toMatchObject({+ computedPairCount: 1,+ work: 0,+ });+ });++ test("settles UNAVAILABLE when a sheet cannot be downloaded", async () => {+ const sheets = fakeSheets({ [sheetName(SHA_NEW)]: NEW_TEXT });+ const { store, client } = setup({ sheets });+ await compute(store, [comment("moved", anchor(SHA_OLD, 1))]);+ expect(store.getState().placements.get(nameOf("moved"))).toEqual(+ UNAVAILABLE+ );+ expect((client as ReturnType<typeof immediateClient>).requests).toEqual([]);+ // Only complete downloads count: neither the missing sheet nor the+ // truncated preview of the other.+ expect(store.getState().placementMetrics?.sheetCount).toBe(0);+ });++ test("counts a probe that returns a complete sheet as a download", async () => {+ const sheets = fakeSheets(+ { [sheetName(SHA_OLD)]: OLD_TEXT, [sheetName(SHA_NEW)]: NEW_TEXT },+ 1000+ );+ const { store } = setup({ sheets });+ await compute(store, [comment("moved", anchor(SHA_OLD, 1))]);+ expect(store.getState().placements.get(nameOf("moved"))).toEqual(+ current(2, 2)+ );+ expect(sheets.calls.filter((call) => call.raw)).toEqual([]);+ expect(store.getState().placementMetrics?.sheetCount).toBe(2);+ });++ test("settles UNAVAILABLE when a raw download comes back incomplete", async () => {+ const sheets = fakeSheets({+ [sheetName(SHA_OLD)]: OLD_TEXT,+ [sheetName(SHA_NEW)]: NEW_TEXT,+ });+ const truncating = {+ ...sheets,+ fetchSheet: async (name: string, raw: boolean) => {+ const sheet = await sheets.fetchSheet(name, raw);+ if (sheet && raw) {+ sheets.cache.set(+ name,+ create(SheetSchema, {+ ...sheet,+ content: sheet.content.slice(0, 2),+ })+ );+ }+ return sheets.cache.get(name);+ },+ };+ const { store, client } = setup({ sheets: truncating });+ await compute(store, [comment("moved", anchor(SHA_OLD, 1))]);+ expect(store.getState().placements.get(nameOf("moved"))).toEqual(+ UNAVAILABLE+ );+ expect((client as ReturnType<typeof immediateClient>).requests).toEqual([]);+ // Only complete downloads count: neither the missing sheet nor the+ // truncated preview of the other.+ expect(store.getState().placementMetrics?.sheetCount).toBe(0);+ });++ test("a save during the diff supersedes the run and diffs against the new target", async () => {+ const held = heldClient();+ const { store } = setup({ client: held.client });+ const first = compute(store, [comment("moved", anchor(SHA_OLD, 1))]);+ await vi.waitFor(() => expect(held.requests).toHaveLength(1));+ // The author saves a new version while the diff is in flight.+ const next = compute(+ store,+ [comment("moved", anchor(SHA_OLD, 1))],+ SHA_NEWER+ );+ await vi.waitFor(() => expect(held.requests).toHaveLength(2));+ expect(held.requests[1].sheets[sheetName(SHA_NEWER)]).toBe(NEWER_TEXT);+ // The late answer for the old target is dropped.+ held.release();+ await Promise.all([first, next]);+ expect(store.getState().placements.get(nameOf("moved"))).toEqual(+ current(3, 3)+ );+ });++ test("a newer run supersedes an older one and its late result is dropped", async () => {+ const held = heldClient();+ const { store } = setup({ client: held.client });+ const first = compute(store, [comment("moved", anchor(SHA_OLD, 1))]);+ await vi.waitFor(() => expect(held.requests).toHaveLength(1));+ const second = compute(store, [comment("same", anchor(SHA_NEW, 1))]);+ expect(held.client.cancel).toHaveBeenCalled();+ held.release();+ await Promise.all([first, second]);+ const state = store.getState();+ expect(state.placements.has(nameOf("moved"))).toBe(false);+ expect(state.placements.get(nameOf("same"))).toEqual(current(1, 1));+ });++ test("publishes hash-settled placements before the diff finishes", async () => {+ const held = heldClient();+ const { store } = setup({ client: held.client });+ const run = compute(store, [+ comment("same", anchor(SHA_NEW, 1)),+ comment("moved", anchor(SHA_OLD, 1)),+ ]);+ await vi.waitFor(() => expect(held.requests).toHaveLength(1));+ expect(store.getState().placements.get(nameOf("same"))).toEqual(+ current(1, 1)+ );+ expect(store.getState().placements.has(nameOf("moved"))).toBe(false);+ held.release();+ await run;+ expect(store.getState().placements.get(nameOf("moved"))).toEqual(+ current(2, 2)+ );+ });++ test("passes the fixed budgets to the worker", async () => {+ const { store, client } = setup();+ await compute(store, [comment("moved", anchor(SHA_OLD, 1))]);+ const request = (client as ReturnType<typeof immediateClient>).requests[0];+ expect(request.limits).toBe(PLACEMENT_BUDGETS);+ expect(request.generation).toBe(1);+ });++ test("bounds the size probe by the sheet cap", async () => {+ const contents: Record<string, string> = {+ [sheetName(SHA_NEW)]: NEW_TEXT,+ };+ const shas = Array.from({ length: 6 }, (_, i) => String(i + 1).repeat(64));+ for (const sha of shas) contents[sheetName(sha)] = OLD_TEXT;+ const sheets = fakeSheets(contents);+ const { store } = setup({+ sheets,+ budgets: { ...PLACEMENT_BUDGETS, maxSheets: 3 },+ });+ await compute(+ store,+ shas.map((sha, i) => comment(`c${i}`, anchor(sha, 1), i))+ );+ const probes = sheets.calls.filter((call) => !call.raw);+ // Only three sizes are learned: the first source, the shared target, and+ // the second source. Pairs whose source size stays unknown are never+ // downloaded.+ expect(probes.map((call) => call.name)).toEqual([+ sheetName(shas[0]),+ sheetName(SHA_NEW),+ sheetName(shas[1]),+ ]);+ const placed = shas.map((_, i) =>+ store.getState().placements.get(nameOf(`c${i}`))+ );+ expect(placed.slice(0, 2)).toEqual([current(2, 2), current(2, 2)]);+ expect(placed.slice(2)).toEqual(shas.slice(2).map(() => UNAVAILABLE));+ expect(sheets.calls.filter((call) => call.raw)).toHaveLength(3);+ });+});++test("invalidates changed targets before awaiting previews, preserving unchanged specs", async () => {+ const sheets = fakeSheets({+ [sheetName(SHA_OLD)]: OLD_TEXT,+ [sheetName(SHA_NEW)]: NEW_TEXT,+ [sheetName(SHA_NEWER)]: NEWER_TEXT,+ });+ let release!: () => void;+ const heldSheets = {+ ...sheets,+ fetchSheet: async (name: string, raw: boolean) => {+ if (name === sheetName(SHA_NEWER) && !raw)+ await new Promise<void>((resolve) => {+ release = resolve;+ });+ return sheets.fetchSheet(name, raw);+ },+ };+ const { store } = setup({ sheets: heldSheets });+ const comments = [+ comment("moved", anchor(SHA_OLD, 1)),+ comment("unchanged", anchor(SHA_NEW, 1, 1, "spec-2")),+ ];+ const stableSpec = specs(SHA_NEW, "spec-2");+ await store.getState().computePlacements({+ comments,+ projectName: PROJECT,+ specs: [...specs(SHA_NEW), ...stableSpec],+ });+ expect(store.getState().placements.get(nameOf("moved"))).toEqual(+ current(2, 2)+ );+ const pending = store.getState().computePlacements({+ comments,+ projectName: PROJECT,+ specs: [...specs(SHA_NEWER), ...stableSpec],+ });+ const duringProbe = new Map(store.getState().placements);+ release();+ await pending;+ expect(duringProbe.has(nameOf("moved"))).toBe(false);+ expect(duringProbe.get(nameOf("unchanged"))).toEqual(current(1, 1));+ expect(store.getState().placements.get(nameOf("moved"))).toEqual(+ current(3, 3)+ );+});++test("caches a definitive UNAVAILABLE so the pair is not diffed again", async () => {+ const { store, client } = setup({+ budgets: { ...PLACEMENT_BUDGETS, maxLinesPerSheet: 1 },+ });+ const input = {+ comments: [comment("moved", anchor(SHA_OLD, 1))],+ projectName: PROJECT,+ specs: specs(SHA_NEW),+ };+ await store.getState().computePlacements(input);+ expect(store.getState().placements.get(nameOf("moved"))).toEqual(UNAVAILABLE);+ await store.getState().computePlacements(input);+ const requests = (client as ReturnType<typeof immediateClient>).requests;+ expect(requests).toHaveLength(1);+});++test("reserves the per-sheet cap before each probe so concurrent probes stay within the total", async () => {+ const contents: Record<string, string> = { [sheetName(SHA_NEW)]: NEW_TEXT };+ const shas = Array.from({ length: 4 }, (_, i) => String(i + 1).repeat(64));+ for (const sha of shas) contents[sheetName(sha)] = OLD_TEXT;+ // Like the server at production budgets, a preview of a small sheet is+ // already complete.+ const sheets = fakeSheets(contents, Number.POSITIVE_INFINITY);+ const { store } = setup({+ sheets,+ budgets: {+ ...PLACEMENT_BUDGETS,+ // Two reservations fit; the third would exceed the total, so it never+ // starts even though four probes could run at once.+ maxBytesPerSheet: 100,+ maxTotalBytes: 200,+ },+ });+ await store.getState().computePlacements({+ comments: shas.map((sha, i) => comment(`c${i}`, anchor(sha, 1), i)),+ projectName: PROJECT,+ specs: specs(SHA_NEW),+ });+ expect(+ sheets.calls.filter((call) => !call.raw).map((call) => call.name)+ ).toEqual([sheetName(shas[0]), sheetName(SHA_NEW)]);+ expect(store.getState().placements.get(nameOf("c0"))).toEqual(current(2, 2));+ expect(store.getState().placements.get(nameOf("c1"))).toEqual(UNAVAILABLE);+});++test.each([+ { cap: "maxSheets", budgets: { maxSheets: 3 } },+ // Two OLD_TEXT sources and the NEW_TEXT target fit; a third source does not.+ { cap: "maxTotalBytes", budgets: { maxTotalBytes: 2 * 50 + 60 } },+])(+ "holds the worker payload to $cap even for sheets already cached",+ async ({ budgets }) => {+ const contents: Record<string, string> = { [sheetName(SHA_NEW)]: NEW_TEXT };+ const shas = Array.from({ length: 4 }, (_, i) => String(i + 1).repeat(64));+ for (const sha of shas) contents[sheetName(sha)] = OLD_TEXT;+ const sheets = fakeSheets(contents);+ for (const name of Object.keys(contents)) sheets.prime(name, true);+ const client = immediateClient();+ const { store } = setup({+ sheets,+ client,+ budgets: { ...PLACEMENT_BUDGETS, ...budgets },+ });+ await compute(+ store,+ shas.map((sha, i) => comment(`c${i}`, anchor(sha, 1), i))+ );+ // Nothing to download, so the planner's caps saw nothing to count.+ expect(sheets.calls).toEqual([]);+ expect(Object.keys(client.requests[0].sheets)).toHaveLength(3);+ const placed = shas.map((_, i) =>+ store.getState().placements.get(nameOf(`c${i}`))+ );+ expect(placed).toEqual([+ current(2, 2),+ current(2, 2),+ UNAVAILABLE,+ UNAVAILABLE,+ ]);+ }+);++test("counts probe bytes against the raw download budget", async () => {+ // Previews come back truncated here, so the sheets still need a raw fetch+ // that must fit in whatever the probes left of the budget.+ const { store, sheets } = setup({+ budgets: {+ ...PLACEMENT_BUDGETS,+ maxBytesPerSheet: 100,+ maxTotalBytes: 100,+ },+ });+ await compute(store, [comment("moved", anchor(SHA_OLD, 1))]);+ // One probe spends its bytes; the raw downloads no longer fit.+ expect(sheets.calls.filter((call) => call.raw)).toEqual([]);+ expect(store.getState().placements.get(nameOf("moved"))).toEqual(UNAVAILABLE);+});++test("retries shared-budget failures after other pairs have been cached", async () => {+ const work = diffPair(tokenizeSheet(OLD_TEXT), tokenizeSheet(NEW_TEXT), {+ maxLinesPerSheet: 100,+ maxWork: 10000,+ }).work;+ const { store, client } = setup({+ budgets: { ...PLACEMENT_BUDGETS, maxWorkPerRun: work },+ });+ const first = comment("first", anchor(SHA_OLD, 1, 1, "spec-1"), 1);+ const second = comment("second", anchor(SHA_OLD, 1, 1, "spec-2"), 2);+ const input = {+ comments: [first, second],+ projectName: PROJECT,+ specs: [...specs(SHA_NEW), ...specs(SHA_NEW, "spec-2")],+ };+ await store.getState().computePlacements(input);+ expect(store.getState().placements.get(first.name)).toEqual(current(2, 2));+ expect(store.getState().placements.get(second.name)).toEqual(UNAVAILABLE);+ await store.getState().computePlacements(input);+ expect(store.getState().placements.get(second.name)).toEqual(current(2, 2));+ const requests = (client as ReturnType<typeof immediateClient>).requests;+ expect(requests).toHaveLength(2);+ expect(requests[1].pairs).toHaveLength(1);+});++test.each([false, true])(+ "keeps cached ranges while computing a new range (failure=%s)",+ async (fail) => {+ const held = heldClient();+ const { store } = setup({ client: held.client });+ const old = comment("old", anchor(SHA_OLD, 1));+ const first = compute(store, [old]);+ await vi.waitFor(() => expect(held.requests).toHaveLength(1));+ held.release();+ await first;+ const existing = store.getState().placements.get(old.name);+ const added = comment("new", anchor(SHA_OLD, 2));+ const next = compute(store, [old, added]);+ await vi.waitFor(() => expect(held.requests).toHaveLength(2));+ expect(store.getState().placements.get(old.name)).toBe(existing);+ expect(held.requests[1].pairs[0].anchors).toEqual([+ { id: "2-2", startLine: 2, endLine: 2 },+ ]);+ if (fail) held.fail(new PlacementError("deadline"));+ else held.release();+ await next;+ expect(store.getState().placements.get(old.name)).toBe(existing);+ expect(store.getState().placements.get(added.name)).toEqual(+ fail ? UNAVAILABLE : current(3, 3)+ );+ }+);diff --git a/frontend/src/routes/project/plan-detail/shared/stores/placementSlice.ts b/frontend/src/routes/project/plan-detail/shared/stores/placementSlice.tsnew file mode 100644index 0000000000..098cc6ecef--- /dev/null+++ b/frontend/src/routes/project/plan-detail/shared/stores/placementSlice.ts@@ -0,0 +1,326 @@+import { useAppStore } from "@/stores/app";+import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";+import { getSheetStatement, isSheetContentComplete } from "@/utils/v1/sheet";+import {+ PLACEMENT_BUDGETS,+ type PlacementBudgets,+} from "../../components/threads/placement/budgets";+import { runWithConcurrency } from "../../components/threads/placement/concurrency";+import {+ type Placement,+ UNAVAILABLE,+} from "../../components/threads/placement/place";+import {+ createPlacementClient,+ type PlacementClient,+} from "../../components/threads/placement/placementClient";+import {+ type PlacementPair,+ planPlacements,+} from "../../components/threads/placement/placementPlan";+import type { PlacementRequestPair } from "../../components/threads/placement/placementWorker";+import { targetSha256OfSpec } from "../../components/threads/threadModel";+import type { PlacementSlice, PlanDetailSliceCreator } from "./types";++// What the slice needs from outside: the sheet cache, a way to fill it, and+// the worker. Tests substitute fakes.+export interface PlacementDeps {+ getSheet: (name: string) => Sheet | undefined;+ fetchSheet: (name: string, raw: boolean) => Promise<Sheet | undefined>;+ client: PlacementClient;+ budgets: PlacementBudgets;+ now: () => number;+}++const FETCH_CONCURRENCY = 4;++export const defaultPlacementDeps = (): PlacementDeps => ({+ getSheet: (name) => useAppStore.getState().getSheetByName(name),+ fetchSheet: (name, raw) => useAppStore.getState().fetchSheet(name, raw),+ client: createPlacementClient(),+ budgets: PLACEMENT_BUDGETS,+ now: () => performance.now(),+});++const samePlacement = (a: Placement, b: Placement): boolean =>+ a.state === b.state &&+ (a.state !== "CURRENT" ||+ b.state !== "CURRENT" ||+ (a.range.startLine === b.range.startLine &&+ a.range.endLine === b.range.endLine));++// The placements of the latest run apply to a spec only while it still+// points at the sheet that run was computed against; a consumer showing+// another revision falls back to the no-diff rule instead.+export const placementsForSheet = (+ state: Pick<PlacementSlice, "placements" | "placementTargets">,+ specId: string,+ sheetSha256: string | undefined+): ReadonlyMap<string, Placement> | undefined =>+ sheetSha256 !== undefined &&+ state.placementTargets.get(specId) === sheetSha256+ ? state.placements+ : undefined;++export const placementOf = (+ state: Pick<PlacementSlice, "placements" | "placementTargets">,+ commentName: string,+ specId: string,+ sheetSha256: string | undefined+): Placement | undefined =>+ placementsForSheet(state, specId, sheetSha256)?.get(commentName);++// Computes where every anchored comment shows for the plan's current+// statements. Placement is derived, never stored server-side: each run plans+// the sheets it needs within the fetch budget, loads them complete, diffs+// each saved/current pair once in a worker, and applies the result only while+// the run is still the latest. Pair results are cached by content identity,+// so a repeated run for unchanged sheets costs nothing.+export const createPlacementSlice =+ (deps: PlacementDeps): PlanDetailSliceCreator<PlacementSlice> =>+ (set, get) => {+ const pairCache = new Map<string, Record<string, Placement>>();++ // Settles the comments behind each of the pair's anchors; an anchor the+ // results do not cover is UNAVAILABLE.+ const applyPair = (+ into: Map<string, Placement>,+ pair: PlacementPair,+ results: Record<string, Placement>+ ) => {+ for (const anchor of pair.anchors) {+ const placement = results[anchor.id] ?? UNAVAILABLE;+ for (const name of pair.comments.get(anchor.id) ?? []) {+ into.set(name, placement);+ }+ }+ };++ const settleUnavailable = (+ into: Map<string, Placement>,+ pair: PlacementPair+ ) => applyPair(into, pair, {});++ const completeSheet = (name: string): Sheet | undefined => {+ const sheet = deps.getSheet(name);+ return sheet && isSheetContentComplete(sheet) ? sheet : undefined;+ };++ // Writes the run's targets and placements together, reusing previous+ // entry objects where equal, so consumers selecting the map or one entry+ // rerender only on a real change and never see new targets paired with+ // an older run's placements.+ const publish = (+ next: Map<string, Placement>,+ targets?: ReadonlyMap<string, string>+ ) => {+ const previous = get().placements;+ let changed = previous.size !== next.size;+ const merged = new Map<string, Placement>();+ for (const [name, placement] of next) {+ const before = previous.get(name);+ if (before && samePlacement(before, placement)) {+ merged.set(name, before);+ } else {+ merged.set(name, placement);+ changed = true;+ }+ }+ if (targets) {+ set({ placementTargets: targets, placements: merged });+ } else if (changed) {+ set({ placements: merged });+ }+ };++ // Bumped per run; a run that finds itself superseded stops writing.+ let generation = 0;++ return {+ placements: new Map(),+ placementTargets: new Map(),+ placementMetrics: undefined,++ computePlacements: async ({ comments, projectName, specs }) => {+ const run = ++generation;+ deps.client.cancel();+ const started = deps.now();+ const stale = () => generation !== run;+ const { budgets } = deps;++ const planInput = {+ comments,+ specs,+ projectName,+ sizeOf: (name: string) => deps.getSheet(name)?.contentSize,+ isComplete: (name: string) => completeSheet(name) !== undefined,+ budgets,+ };+ const targets = new Map<string, string>();+ for (const spec of specs) {+ const sha256 = targetSha256OfSpec(spec);+ if (sha256) targets.set(spec.id, sha256);+ }++ // Everything that needs no download or diff settles right away.+ // Cached pairs serve the ranges they have seen, and only the missing+ // ranges go to the worker, so known threads stay visible meanwhile.+ let plan = planPlacements(planInput);+ const placements = new Map<string, Placement>();+ let pending: PlacementPair[] = [];+ // Bytes downloaded by this run so far, so every phase shares one+ // total budget.+ let spentBytes = 0n;+ // Sheets this run downloaded complete, by probe or raw fetch.+ const downloaded = new Set<string>();+ const recordDownload = (name: string, sheet: Sheet | undefined) => {+ if (sheet && isSheetContentComplete(sheet)) downloaded.add(name);+ return sheet;+ };+ const settle = (settleUnknownSizes: boolean) => {+ plan = planPlacements({+ ...planInput,+ settleUnknownSizes,+ spentBytes,+ });+ placements.clear();+ for (const [name, placement] of plan.settled) {+ placements.set(name, placement);+ }+ pending = [];+ for (const pair of plan.pairs) {+ const cached = pairCache.get(pair.key) ?? {};+ const known = pair.anchors.filter((anchor) => anchor.id in cached);+ const missing = pair.anchors.filter(+ (anchor) => !(anchor.id in cached)+ );+ applyPair(placements, { ...pair, anchors: known }, cached);+ if (missing.length > 0) pending.push({ ...pair, anchors: missing });+ }+ };+ settle(false);+ publish(placements, targets);++ // A sheet the cache has never seen has no known size. A preview fetch+ // is capped by the server at the per-sheet budget, so it doubles as+ // the bounded download. Each probe reserves that cap before it starts+ // and settles to the real size when it lands, so concurrent probes+ // cannot overshoot the total budget between them.+ if (plan.unknownSizes.length > 0) {+ const byteCap = BigInt(budgets.maxTotalBytes);+ const perSheet = BigInt(budgets.maxBytesPerSheet);+ await runWithConcurrency(+ plan.unknownSizes.slice(0, budgets.maxSheets),+ FETCH_CONCURRENCY,+ async (name) => {+ if (spentBytes + perSheet > byteCap) return undefined;+ spentBytes += perSheet;+ const sheet = await deps.fetchSheet(name, false);+ spentBytes -= perSheet - BigInt(sheet?.content.byteLength ?? 0);+ return recordDownload(name, sheet);+ }+ );+ if (stale()) return;+ settle(true);+ publish(placements);+ }++ // Sheets the probe left incomplete are re-fetched raw and verified.+ const needed = new Set(+ pending.flatMap((pair) => [pair.sourceName, pair.targetName])+ );+ const fetches = plan.fetches.filter((name) => needed.has(name));+ await runWithConcurrency(fetches, FETCH_CONCURRENCY, async (name) =>+ recordDownload(name, await deps.fetchSheet(name, true))+ );+ if (stale()) return;++ // Each sheet travels to the worker once, however many pairs use it.+ // The planner's caps count downloads only, so sheets already complete+ // in the cache reach here uncounted; the payload is held to the same+ // caps so a session that has cached many revisions never clones an+ // unbounded amount onto the worker.+ let bytes = 0;+ let sheetCount = 0;+ const sheets: Record<string, string> = {};+ const requestPairs: PlacementRequestPair[] = [];+ const requested: PlacementPair[] = [];+ for (const pair of pending) {+ const source = completeSheet(pair.sourceName);+ const target = completeSheet(pair.targetName);+ if (!source || !target) {+ settleUnavailable(placements, pair);+ continue;+ }+ const added = new Set(+ [source, target].filter((sheet) => !(sheet.name in sheets))+ );+ let addedBytes = 0;+ for (const sheet of added) addedBytes += sheet.content.byteLength;+ if (+ sheetCount + added.size > budgets.maxSheets ||+ bytes + addedBytes > budgets.maxTotalBytes+ ) {+ settleUnavailable(placements, pair);+ continue;+ }+ for (const sheet of added) {+ sheets[sheet.name] = getSheetStatement(sheet);+ }+ sheetCount += added.size;+ bytes += addedBytes;+ requestPairs.push({+ key: pair.key,+ saved: source.name,+ current: target.name,+ anchors: pair.anchors,+ });+ requested.push(pair);+ }++ let work = 0;+ if (requestPairs.length > 0) {+ try {+ const response = await deps.client.compute(+ { generation: run, sheets, pairs: requestPairs, limits: budgets },+ budgets.workerDeadlineMs+ );+ if (stale()) return;+ work = response.work;+ const incomplete = new Set(response.incomplete);+ for (const pair of requested) {+ const results = response.results[pair.key];+ if (!results) {+ settleUnavailable(placements, pair);+ continue;+ }+ // A pair that ran out of budget may place next time; every+ // other result is a function of the two sheets and is final.+ if (!incomplete.has(pair.key)) {+ pairCache.set(pair.key, {+ ...pairCache.get(pair.key),+ ...results,+ });+ }+ applyPair(placements, pair, results);+ }+ } catch {+ if (stale()) return;+ for (const pair of requested) settleUnavailable(placements, pair);+ }+ }++ publish(placements);+ set({+ placementMetrics: {+ durationMs: deps.now() - started,+ pairCount: plan.pairs.length,+ computedPairCount: requestPairs.length,+ sheetCount: downloaded.size,+ bytes,+ work,+ },+ });+ },+ };+ };diff --git a/frontend/src/routes/project/plan-detail/shared/stores/threadFocusSlice.ts b/frontend/src/routes/project/plan-detail/shared/stores/threadFocusSlice.tsnew file mode 100644index 0000000000..309cb7e2fb--- /dev/null+++ b/frontend/src/routes/project/plan-detail/shared/stores/threadFocusSlice.ts@@ -0,0 +1,23 @@+import type { PlanDetailSliceCreator, ThreadFocusSlice } from "./types";++// "View in Statement" hands the target thread to the statement editor through+// the store: the timeline and the editor live in different phase sections and+// the editor may still be mounting when the request is made.+export const createThreadFocusSlice: PlanDetailSliceCreator<+ ThreadFocusSlice+> = (set) => ({+ threadFocus: undefined,+ requestThreadFocus: (request) =>+ set((state) => ({+ threadFocus: {+ ...request,+ nonce: (state.threadFocus?.nonce ?? 0) + 1,+ },+ })),+ clearThreadFocus: (nonce) =>+ set((state) =>+ state.threadFocus && state.threadFocus.nonce === nonce+ ? { threadFocus: undefined }+ : state+ ),+});diff --git a/frontend/src/routes/project/plan-detail/shared/stores/types.ts b/frontend/src/routes/project/plan-detail/shared/stores/types.tsindex d6dd984308..d57051e7aa 100644--- a/frontend/src/routes/project/plan-detail/shared/stores/types.ts+++ b/frontend/src/routes/project/plan-detail/shared/stores/types.ts@@ -1,7 +1,12 @@import type { StateCreator } from "zustand";-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";-import type { Plan, PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";+import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import type {+ Plan,+ Plan_Spec,+ PlanCheckRun,+} from "@/types/proto-es/v1/plan_service_pb";import type { Rollout, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";+import type { Placement } from "../../components/threads/placement/place";export type PlanDetailPhase = "changes" | "review" | "deploy";@@ -62,11 +67,61 @@ export type PollingSlice = {setPollTimerId: (id: number | undefined) => void;};+export interface ThreadFocusRequest {+ // Root comment name of the thread to expand.+ commentName: string;+ // Spec the thread anchors to; the editor of this spec consumes the request.+ specId: string;+ nonce: number;+}++export type ThreadFocusSlice = {+ threadFocus: ThreadFocusRequest | undefined;+ requestThreadFocus: (request: Omit<ThreadFocusRequest, "nonce">) => void;+ clearThreadFocus: (nonce: number) => void;+};++// Measurements of one placement run, kept so the decision to move the rule+// server-side can be made on data.+export interface PlacementMetrics {+ durationMs: number;+ // Saved/current pairs the run needed, including ones served from cache.+ pairCount: number;+ // Pairs actually sent to the worker.+ computedPairCount: number;+ // Distinct sheets the run downloaded complete, by probe or raw fetch.+ sheetCount: number;+ // Bytes of every sheet sent to the worker, downloaded or cached.+ bytes: number;+ // Diff work spent by the worker.+ work: number;+}++export type PlacementSlice = {+ // Placement by comment name, for every anchored comment the last run+ // settled. A comment absent here is unplaced until the next run.+ placements: ReadonlyMap<string, Placement>;+ // The sheet hash each spec pointed at when the latest run started, so a+ // consumer showing a different sheet ignores `placements` instead of+ // drawing another revision's ranges on it.+ placementTargets: ReadonlyMap<string, string>;+ placementMetrics: PlacementMetrics | undefined;+ computePlacements: (input: {+ comments: readonly IssueComment[];+ // "projects/{project}", the issue's project.+ projectName: string;+ // The plan's current specs; their sheets are the diff targets.+ specs: readonly Plan_Spec[];+ }) => Promise<void>;+};+export type PlanDetailStore = SnapshotSlice &PhaseSlice &EditingSlice &SelectionSlice &- PollingSlice;+ PollingSlice &+ ThreadFocusSlice &+ PlacementSlice;export type PlanDetailSliceCreator<Slice> = StateCreator<PlanDetailStore,diff --git a/frontend/src/routes/project/plan-detail/shared/stores/usePlanDetailStore.ts b/frontend/src/routes/project/plan-detail/shared/stores/usePlanDetailStore.tsindex 29e325b442..fcabadab29 100644--- a/frontend/src/routes/project/plan-detail/shared/stores/usePlanDetailStore.ts+++ b/frontend/src/routes/project/plan-detail/shared/stores/usePlanDetailStore.ts@@ -2,18 +2,28 @@ import { createContext, useContext } from "react";import { create, useStore } from "zustand";import { createEditingSlice } from "./editingSlice";import { createPhaseSlice } from "./phaseSlice";+import {+ createPlacementSlice,+ defaultPlacementDeps,+ type PlacementDeps,+} from "./placementSlice";import { createPollingSlice } from "./pollingSlice";import { createSelectionSlice } from "./selectionSlice";import { createSnapshotSlice } from "./snapshotSlice";+import { createThreadFocusSlice } from "./threadFocusSlice";import type { PlanDetailStore } from "./types";-export const createPlanDetailStore = () =>+export const createPlanDetailStore = (+ placement: PlacementDeps = defaultPlacementDeps()+) =>create<PlanDetailStore>()((...args) => ({...createSnapshotSlice(...args),...createPhaseSlice(...args),...createEditingSlice(...args),...createSelectionSlice(...args),...createPollingSlice(...args),+ ...createThreadFocusSlice(...args),+ ...createPlacementSlice(placement)(...args),}));export type PlanDetailStoreApi = ReturnType<typeof createPlanDetailStore>;diff --git a/frontend/src/stores/app/issueComment.test.ts b/frontend/src/stores/app/issueComment.test.tsindex 3075ce7999..811e2db3d7 100644--- a/frontend/src/stores/app/issueComment.test.ts+++ b/frontend/src/stores/app/issueComment.test.ts@@ -1,14 +1,19 @@import { create } from "@bufbuild/protobuf";import { beforeEach, expect, test, vi } from "vitest";+import { PositionSchema } from "@/types/proto-es/v1/common_pb";import {+ type IssueComment,+ IssueComment_ThreadState,IssueCommentSchema,ListIssueCommentsRequestSchema,+ StatementAnchorSchema,} from "@/types/proto-es/v1/issue_service_pb";import { createIssueCommentSlice } from "./issueComment";const mocks = vi.hoisted(() => ({createIssueComment: vi.fn(),listIssueComments: vi.fn(),+ updateIssueComment: vi.fn(),}));vi.mock("@/api", () => ({issueServiceClientConnect: mocks,@@ -158,3 +163,543 @@ test("failed timeline refresh preserves the cached content and propagates the erawait expect(store.fetchIssueCommentTimeline({ parent })).rejects.toBe(error);expect(store.getIssueComments(parent)).toEqual(cached);});++test("a thread load pages the timeline and fetches replies per root chunk", async () => {+ const store = createStore();+ const parent = "projects/p/issues/101";+ const rootA = create(IssueCommentSchema, {+ name: parent + "/issueComments/a",+ threadState: IssueComment_ThreadState.OPEN,+ });+ const rootB = create(IssueCommentSchema, {+ name: parent + "/issueComments/b",+ threadState: IssueComment_ThreadState.RESOLVED,+ });+ const general = create(IssueCommentSchema, {+ name: parent + "/issueComments/general",+ });+ const replyA = create(IssueCommentSchema, {+ name: parent + "/issueComments/reply-a",+ root: rootA.name,+ });+ mocks.listIssueComments+ .mockResolvedValueOnce({ issueComments: [rootA], nextPageToken: "p2" })+ .mockResolvedValueOnce({+ issueComments: [general, rootB],+ nextPageToken: "",+ })+ .mockResolvedValueOnce({ issueComments: [replyA], nextPageToken: "" });++ const loaded = await store.fetchIssueCommentThreads({ parent });++ expect(mocks.listIssueComments).toHaveBeenCalledTimes(3);+ expect(mocks.listIssueComments.mock.calls[0][0]).toMatchObject({+ parent,+ filter: "",+ pageSize: 1000,+ pageToken: "",+ });+ expect(mocks.listIssueComments.mock.calls[1][0]).toMatchObject({+ filter: "",+ pageToken: "p2",+ });+ expect(mocks.listIssueComments.mock.calls[2][0]).toMatchObject({+ parent,+ filter: `root in ["${rootA.name}", "${rootB.name}"]`,+ pageSize: 1000,+ });+ expect(loaded).toEqual([rootA, general, rootB, replyA]);+ expect(store.getIssueComments(parent)).toEqual(loaded);+});++test("a thread load without roots skips the reply query", async () => {+ const store = createStore();+ const parent = "projects/p/issues/101";+ mocks.listIssueComments.mockResolvedValueOnce({+ issueComments: [create(IssueCommentSchema, { comment: "plain" })],+ nextPageToken: "",+ });+ await store.fetchIssueCommentThreads({ parent });+ expect(mocks.listIssueComments).toHaveBeenCalledTimes(1);+});++test("an anchored comment starts a thread and a root creates a reply", async () => {+ const store = createStore();+ const parent = "projects/p/issues/101";+ const anchor = create(StatementAnchorSchema, {+ spec: "spec-1",+ sheetSha256: "f".repeat(64),+ startPosition: create(PositionSchema, { line: 2, column: 0 }),+ endPosition: create(PositionSchema, { line: 3, column: 0 }),+ });+ const root = create(IssueCommentSchema, {+ name: parent + "/issueComments/root",+ threadState: IssueComment_ThreadState.OPEN,+ statementAnchor: anchor,+ });+ mocks.createIssueComment.mockResolvedValueOnce(root);+ const created = await store.createIssueComment({+ issueName: parent,+ comment: "No LIMIT here",+ statementAnchor: anchor,+ });+ expect(created).toBe(root);+ const rootRequest = mocks.createIssueComment.mock.calls[0][0];+ expect(rootRequest.issueComment.statementAnchor).toMatchObject({+ spec: "spec-1",+ startPosition: { line: 2, column: 0 },+ endPosition: { line: 3, column: 0 },+ });+ expect(rootRequest.issueComment.root).toBeUndefined();++ const reply = create(IssueCommentSchema, {+ name: parent + "/issueComments/reply",+ root: root.name,+ });+ mocks.createIssueComment.mockResolvedValueOnce(reply);+ await store.createIssueComment({+ issueName: parent,+ comment: "Agreed",+ root: root.name,+ });+ const replyRequest = mocks.createIssueComment.mock.calls[1][0];+ expect(replyRequest.issueComment.root).toBe(root.name);+ expect(replyRequest.issueComment.statementAnchor).toBeUndefined();+ expect(store.getIssueComments(parent)).toEqual([root, reply]);+});++test("updates mask only the provided fields", async () => {+ const store = createStore();+ const parent = "projects/p/issues/101";+ const name = parent + "/issueComments/root";+ const resolved = create(IssueCommentSchema, {+ name,+ threadState: IssueComment_ThreadState.RESOLVED,+ });+ mocks.updateIssueComment.mockResolvedValueOnce(resolved);+ await store.updateIssueComment({+ issueCommentName: name,+ threadState: IssueComment_ThreadState.RESOLVED,+ });+ const resolveRequest = mocks.updateIssueComment.mock.calls[0][0];+ expect(resolveRequest.updateMask.paths).toEqual(["thread_state"]);+ expect(resolveRequest.issueComment.threadState).toBe(+ IssueComment_ThreadState.RESOLVED+ );+ expect(resolveRequest.parent).toBe(parent);++ mocks.updateIssueComment.mockResolvedValueOnce(+ create(IssueCommentSchema, { name, comment: "edited" })+ );+ await store.updateIssueComment({ issueCommentName: name, comment: "edited" });+ const editRequest = mocks.updateIssueComment.mock.calls[1][0];+ expect(editRequest.updateMask.paths).toEqual(["comment"]);+ expect(editRequest.issueComment.threadState).toBeUndefined();+});++test.each(["resolve", "create"])(+ "thread refresh preserves a successful local %s",+ async (action) => {+ const store = createStore();+ const parent = "projects/p/issues/101";+ const root = create(IssueCommentSchema, {+ name: parent + "/issueComments/root",+ threadState: IssueComment_ThreadState.OPEN,+ });+ store.issueCommentsByIssue[parent] = [root];+ let release!: (value: {+ issueComments: never[];+ nextPageToken: string;+ }) => void;+ mocks.listIssueComments.mockReset();+ mocks.listIssueComments+ .mockResolvedValueOnce({ issueComments: [root], nextPageToken: "" })+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ release = resolve;+ })+ );+ const pending = store.fetchIssueCommentThreads({ parent });+ await vi.waitFor(() =>+ expect(mocks.listIssueComments).toHaveBeenCalledTimes(2)+ );+ if (action === "resolve") {+ mocks.updateIssueComment.mockResolvedValueOnce(+ create(IssueCommentSchema, {+ ...root,+ threadState: IssueComment_ThreadState.RESOLVED,+ })+ );+ await store.updateIssueComment({+ issueCommentName: root.name,+ threadState: IssueComment_ThreadState.RESOLVED,+ });+ } else {+ mocks.createIssueComment.mockResolvedValueOnce(+ create(IssueCommentSchema, {+ name: parent + "/issueComments/new",+ comment: "New comment",+ })+ );+ await store.createIssueComment({+ issueName: parent,+ comment: "New comment",+ });+ }+ const expected = store.getIssueComments(parent);+ release({ issueComments: [], nextPageToken: "" });+ await pending;+ expect(store.getIssueComments(parent)).toEqual(expected);+ }+);++test("a newer timeline fetch supersedes an older thread fetch", async () => {+ const store = createStore();+ const parent = "projects/p/issues/101";+ const oldRoot = create(IssueCommentSchema, {+ name: parent + "/issueComments/root",+ threadState: IssueComment_ThreadState.OPEN,+ });+ const newRoot = create(IssueCommentSchema, {+ ...oldRoot,+ threadState: IssueComment_ThreadState.RESOLVED,+ });+ let release!: (value: {+ issueComments: never[];+ nextPageToken: string;+ }) => void;+ mocks.listIssueComments.mockReset();+ mocks.listIssueComments+ .mockResolvedValueOnce({ issueComments: [oldRoot], nextPageToken: "" })+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ release = resolve;+ })+ )+ .mockResolvedValueOnce({ issueComments: [newRoot], nextPageToken: "" });+ const older = store.fetchIssueCommentThreads({ parent });+ await vi.waitFor(() =>+ expect(mocks.listIssueComments).toHaveBeenCalledTimes(2)+ );+ await store.fetchIssueCommentTimeline({ parent });+ release({ issueComments: [], nextPageToken: "" });+ await older;+ expect(store.getIssueComments(parent)).toEqual([newRoot]);+});++test("a failed newer fetch hands the cache back to an older fetch still in flight", async () => {+ const store = createStore();+ const parent = "projects/p/issues/100";+ const root = create(IssueCommentSchema, {+ name: parent + "/issueComments/root",+ threadState: IssueComment_ThreadState.OPEN,+ });+ let release!: (value: {+ issueComments: never[];+ nextPageToken: string;+ }) => void;+ mocks.listIssueComments.mockReset();+ mocks.listIssueComments+ // Older load: timeline page, then its reply query is held.+ .mockResolvedValueOnce({ issueComments: [root], nextPageToken: "" })+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ release = resolve;+ })+ )+ // Newer load fails on its first page.+ .mockRejectedValueOnce(new Error("network"));+ const older = store.fetchIssueCommentThreads({ parent });+ await vi.waitFor(() =>+ expect(mocks.listIssueComments).toHaveBeenCalledTimes(2)+ );+ await expect(store.fetchIssueCommentThreads({ parent })).rejects.toThrow(+ "network"+ );+ release({ issueComments: [], nextPageToken: "" });+ await older;+ expect(store.getIssueComments(parent)).toEqual([root]);+});++test.each([+ ["timeline", "resolve"],+ ["timeline", "create"],+ ["threads", "resolve"],+ ["threads", "create"],+])(+ "a fallback %s fetch preserves a successful local %s",+ async (kind, action) => {+ const store = createStore();+ const parent = "projects/p/issues/101";+ const root = create(IssueCommentSchema, {+ name: parent + "/issueComments/root",+ threadState: IssueComment_ThreadState.OPEN,+ });+ store.issueCommentsByIssue[parent] = [root];+ let finishOlder!: (value: {+ issueComments: (typeof root)[];+ nextPageToken: string;+ }) => void;+ let failNewer!: (error: Error) => void;+ mocks.listIssueComments.mockReset();+ if (kind === "threads") {+ mocks.listIssueComments.mockResolvedValueOnce({+ issueComments: [root],+ nextPageToken: "",+ });+ }+ mocks.listIssueComments+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishOlder = resolve;+ })+ )+ .mockImplementationOnce(+ () =>+ new Promise((_resolve, reject) => {+ failNewer = reject;+ })+ );+ const fetch = () =>+ kind === "threads"+ ? store.fetchIssueCommentThreads({ parent })+ : store.fetchIssueCommentTimeline({ parent });+ const older = fetch();+ await vi.waitFor(() => expect(finishOlder).toBeDefined());+ const newer = fetch();+ if (action === "resolve") {+ mocks.updateIssueComment.mockResolvedValueOnce(+ create(IssueCommentSchema, {+ ...root,+ threadState: IssueComment_ThreadState.RESOLVED,+ })+ );+ await store.updateIssueComment({+ issueCommentName: root.name,+ threadState: IssueComment_ThreadState.RESOLVED,+ });+ } else {+ mocks.createIssueComment.mockResolvedValueOnce(+ create(IssueCommentSchema, {+ name: parent + "/issueComments/new",+ comment: "New comment",+ })+ );+ await store.createIssueComment({+ issueName: parent,+ comment: "New comment",+ });+ }+ const expected = store.getIssueComments(parent);+ const failure = expect(newer).rejects.toThrow("network");+ failNewer(new Error("network"));+ await failure;+ finishOlder({+ issueComments: kind === "threads" ? [] : [root],+ nextPageToken: "",+ });+ await older;+ expect(store.getIssueComments(parent)).toEqual(expected);+ }+);++test("an older success is kept as a fallback and promoted when the newer fetch fails", async () => {+ const store = createStore();+ const parent = "projects/p/issues/100";+ const root = create(IssueCommentSchema, {+ name: parent + "/issueComments/root",+ });+ let releaseOlder!: (value: {+ issueComments: IssueComment[];+ nextPageToken: string;+ }) => void;+ let failNewer!: (error: Error) => void;+ mocks.listIssueComments.mockReset();+ mocks.listIssueComments+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ releaseOlder = resolve;+ })+ )+ .mockImplementationOnce(+ () =>+ new Promise((_, reject) => {+ failNewer = reject;+ })+ );+ const older = store.fetchIssueCommentTimeline({ parent });+ const newer = store.fetchIssueCommentTimeline({ parent });+ await vi.waitFor(() =>+ expect(mocks.listIssueComments).toHaveBeenCalledTimes(2)+ );+ // The older result lands first: held back, not written, not discarded.+ releaseOlder({ issueComments: [root], nextPageToken: "" });+ await older;+ expect(store.getIssueComments(parent)).toEqual([]);+ failNewer(new Error("network"));+ await expect(newer).rejects.toThrow("network");+ expect(store.getIssueComments(parent)).toEqual([root]);+});++test("mutations invalidate only their issue, including colliding IDs across projects", async () => {+ const store = createStore();+ const parent = "projects/p/issues/101";+ const other = "projects/q/issues/101";+ const oldRoot = create(IssueCommentSchema, {+ name: parent + "/issueComments/root",+ threadState: IssueComment_ThreadState.OPEN,+ });+ const otherRoot = create(IssueCommentSchema, {+ name: other + "/issueComments/root",+ comment: "Other project",+ });+ expect(parent.split("/").pop()).toBe(other.split("/").pop());+ store.issueCommentsByIssue[parent] = [oldRoot];+ let finishTarget!: (value: {+ issueComments: (typeof oldRoot)[];+ nextPageToken: string;+ }) => void;+ let finishOther!: typeof finishTarget;+ mocks.listIssueComments.mockReset();+ mocks.listIssueComments+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishTarget = resolve;+ })+ )+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishOther = resolve;+ })+ );+ const targetFetch = store.fetchIssueCommentTimeline({ parent });+ const otherFetch = store.fetchIssueCommentTimeline({ parent: other });+ const updated = create(IssueCommentSchema, {+ ...oldRoot,+ threadState: IssueComment_ThreadState.RESOLVED,+ });+ mocks.updateIssueComment.mockResolvedValueOnce(updated);+ await store.updateIssueComment({+ issueCommentName: oldRoot.name,+ threadState: IssueComment_ThreadState.RESOLVED,+ });+ finishTarget({ issueComments: [oldRoot], nextPageToken: "" });+ finishOther({ issueComments: [otherRoot], nextPageToken: "" });+ await Promise.all([targetFetch, otherFetch]);+ expect(store.getIssueComments(parent)).toEqual([updated]);+ expect(store.getIssueComments(other)).toEqual([otherRoot]);+});++test("a failed mutation does not discard an in-flight refresh", async () => {+ const store = createStore();+ const parent = "projects/p/issues/101";+ const root = create(IssueCommentSchema, {+ name: parent + "/issueComments/root",+ threadState: IssueComment_ThreadState.OPEN,+ });+ let release!: (value: {+ issueComments: (typeof root)[];+ nextPageToken: string;+ }) => void;+ mocks.listIssueComments.mockReset();+ mocks.listIssueComments.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ release = resolve;+ })+ );+ const pending = store.fetchIssueCommentTimeline({ parent });+ mocks.updateIssueComment.mockRejectedValueOnce(new Error("Write failed"));+ await expect(+ store.updateIssueComment({+ issueCommentName: root.name,+ threadState: IssueComment_ThreadState.RESOLVED,+ })+ ).rejects.toThrow("Write failed");+ release({ issueComments: [root], nextPageToken: "" });+ await pending;+ expect(store.getIssueComments(parent)).toEqual([root]);+});++test.each(["timeline", "threads"])(+ "first %s load preserves fetched history and concurrent creation",+ async (kind) => {+ const store = createStore();+ const parent = "projects/p/issues/101";+ const old = create(IssueCommentSchema, {+ name: parent + "/issueComments/old",+ threadState: IssueComment_ThreadState.OPEN,+ });+ const added = create(IssueCommentSchema, {+ name: parent + "/issueComments/new",+ comment: "new",+ });+ const reply = create(IssueCommentSchema, {+ name: parent + "/issueComments/reply",+ root: old.name,+ });+ let finish!: (value: {+ issueComments: (typeof old)[];+ nextPageToken: string;+ }) => void;+ mocks.listIssueComments.mockReset();+ if (kind === "threads")+ mocks.listIssueComments.mockResolvedValueOnce({+ issueComments: [old],+ nextPageToken: "",+ });+ mocks.listIssueComments.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ })+ );+ const pending =+ kind === "threads"+ ? store.fetchIssueCommentThreads({ parent })+ : store.fetchIssueCommentTimeline({ parent });+ await vi.waitFor(() =>+ expect(mocks.listIssueComments).toHaveBeenCalledTimes(+ kind === "threads" ? 2 : 1+ )+ );+ mocks.createIssueComment.mockResolvedValueOnce(added);+ await store.createIssueComment({ issueName: parent, comment: "new" });+ if (kind === "threads") {+ // The reply read can already include a just-created reply: do not duplicate it.+ mocks.createIssueComment.mockResolvedValueOnce(reply);+ await store.createIssueComment({+ issueName: parent,+ root: old.name,+ comment: "reply",+ });+ }+ finish({+ issueComments: kind === "threads" ? [reply] : [old, added],+ nextPageToken: "",+ });+ await pending;+ expect(store.getIssueComments(parent)).toEqual(+ kind === "threads" ? [old, reply, added] : [old, added]+ );++ // Local write protection ends with the load; later server changes must win.+ const remote = create(IssueCommentSchema, {+ ...added,+ comment: "edited elsewhere",+ });+ mocks.listIssueComments.mockResolvedValueOnce({+ issueComments: [old, remote],+ nextPageToken: "",+ });+ await store.fetchIssueCommentTimeline({ parent });+ expect(store.getIssueComments(parent)).toEqual([old, remote]);+ }+);diff --git a/frontend/src/stores/app/issueComment.ts b/frontend/src/stores/app/issueComment.tsindex ecc57d2eb2..3600559bf8 100644--- a/frontend/src/stores/app/issueComment.ts+++ b/frontend/src/stores/app/issueComment.ts@@ -12,6 +12,7 @@ import {ListIssueCommentsRequestSchema,UpdateIssueCommentRequestSchema,} from "@/types/proto-es/v1/issue_service_pb";+import { celStringList } from "@/utils/v1/celLiteral";import type { AppSliceCreator, IssueCommentSlice } from "./types";export enum IssueCommentType {@@ -37,6 +38,21 @@ export const getIssueCommentType = (return IssueCommentType.USER_COMMENT;};+// A thread root carries a thread state; a reply names its root. General+// comments and events carry neither.+export const isThreadRoot = (comment: IssueComment): boolean =>+ comment.threadState !== undefined && !comment.root;++export const isThreadReply = (+ comment: IssueComment+): comment is IssueComment & { root: string } => Boolean(comment.root);++// The server caps a page at 1000 entries; a full load pages until the token+// runs out, per the design's "client fetches all comments" contract.+const MAX_PAGE_SIZE = 1000;+// Roots per reply query. Keeps the CEL filter short; volumes are small.+const REPLY_QUERY_ROOTS = 50;+// Stable empty reference so `getIssueComments` can be read inside a reactive// selector without producing a fresh array (which would loop forever).const EMPTY_COMMENTS: IssueComment[] = [];@@ -44,87 +60,201 @@ const EMPTY_COMMENTS: IssueComment[] = [];export const createIssueCommentSlice: AppSliceCreator<IssueCommentSlice> = (set,get-) => ({- issueCommentsByIssue: {},-- listIssueComments: async (request) => {- const resp = await issueServiceClientConnect.listIssueComments(- createProto(ListIssueCommentsRequestSchema, {- parent: request.parent,- pageSize: request.pageSize,- pageToken: request.pageToken,- filter: request.filter,- })- );- return {- nextPageToken: resp.nextPageToken,- issueComments: resp.issueComments,- };- },-- fetchIssueCommentTimeline: async ({ parent, pageSize, pageToken }) => {- const resp = await get().listIssueComments(- createProto(ListIssueCommentsRequestSchema, {- parent,- pageSize,- pageToken,- })- );+) => {+ // Loads per issue, oldest first. Only the newest load may replace the+ // cache: a load that succeeds while it is newest retires every older one,+ // so an older response never overwrites a newer one. An older load that+ // finishes first keeps its result as a fallback; if the newer load then+ // fails, the fallback is promoted rather than leaving the cache stale.+ // Successful writes are recorded on every active load, so whichever+ // result lands preserves them.+ interface Load {+ writes: Map<string, IssueComment>;+ result?: IssueComment[];+ }+ const activeLoads = new Map<string, Load[]>();+ const loadsOf = (parent: string) => activeLoads.get(parent) ?? [];+ const recordWrite = (parent: string, comment: IssueComment) => {+ for (const load of loadsOf(parent)) load.writes.set(comment.name, comment);+ };+ const beginLoad = (parent: string) => {+ const load: Load = { writes: new Map() };+ activeLoads.set(parent, [...loadsOf(parent), load]);+ return load.writes;+ };+ const applyLoad = (parent: string, load: Load, comments: IssueComment[]) => {+ activeLoads.delete(parent);+ const merged = new Map(comments.map((comment) => [comment.name, comment]));+ for (const [name, comment] of load.writes) merged.set(name, comment);set((state) => ({issueCommentsByIssue: {...state.issueCommentsByIssue,- [parent]: resp.issueComments,+ [parent]: [...merged.values()],},}));- return resp;- },+ };+ // Runs after a load leaves: the newest remaining load wins if it already+ // finished; otherwise the cache waits for it.+ const settleLoads = (parent: string) => {+ const newest = loadsOf(parent).at(-1);+ if (newest?.result) applyLoad(parent, newest, newest.result);+ };+ const withdrawLoad = (parent: string, writes: Map<string, IssueComment>) => {+ const loads = loadsOf(parent).filter((load) => load.writes !== writes);+ if (loads.length === 0) activeLoads.delete(parent);+ else activeLoads.set(parent, loads);+ settleLoads(parent);+ };+ const cacheLoadedComments = (+ parent: string,+ writes: Map<string, IssueComment>,+ comments: IssueComment[]+ ) => {+ const load = loadsOf(parent).find((l) => l.writes === writes);+ // Already retired by a newer success.+ if (!load) return;+ load.result = comments;+ settleLoads(parent);+ };- createIssueComment: async ({ issueName, comment }) => {- const newIssueComment = await issueServiceClientConnect.createIssueComment(- createProto(CreateIssueCommentRequestSchema, {- parent: issueName,- issueComment: createProto(IssueCommentSchema, { comment }),- })- );- set((state) => ({- issueCommentsByIssue: {- ...state.issueCommentsByIssue,- [issueName]: [- ...(state.issueCommentsByIssue[issueName] ?? []),- newIssueComment,- ],- },- }));- },+ return {+ issueCommentsByIssue: {},- updateIssueComment: async ({ issueCommentName, comment }) => {- const { projectId, issueId } =- getProjectIdIssueIdIssueCommentId(issueCommentName);- const parent = `${projectNamePrefix}${projectId}/${issueNamePrefix}${issueId}`;- const updatedIssueComment =- await issueServiceClientConnect.updateIssueComment(- createProto(UpdateIssueCommentRequestSchema, {- parent,- issueComment: createProto(IssueCommentSchema, {- name: issueCommentName,- comment,- }),- updateMask: { paths: ["comment"] },+ listIssueComments: async (request) => {+ const resp = await issueServiceClientConnect.listIssueComments(+ createProto(ListIssueCommentsRequestSchema, {+ parent: request.parent,+ pageSize: request.pageSize,+ pageToken: request.pageToken,+ filter: request.filter,}));- set((state) => ({- issueCommentsByIssue: {- ...state.issueCommentsByIssue,- [parent]: (state.issueCommentsByIssue[parent] ?? []).map(- (issueComment) =>- issueComment.name === issueCommentName- ? updatedIssueComment- : issueComment- ),- },- }));- },+ return {+ nextPageToken: resp.nextPageToken,+ issueComments: resp.issueComments,+ };+ },++ fetchIssueCommentTimeline: async ({ parent, pageSize, pageToken }) => {+ const writes = beginLoad(parent);+ try {+ const resp = await get().listIssueComments(+ createProto(ListIssueCommentsRequestSchema, {+ parent,+ pageSize,+ pageToken,+ })+ );+ cacheLoadedComments(parent, writes, resp.issueComments);+ return resp;+ } catch (error) {+ withdrawLoad(parent, writes);+ throw error;+ }+ },- getIssueComments: (issueName) =>- get().issueCommentsByIssue[issueName] ?? EMPTY_COMMENTS,-});+ fetchIssueCommentThreads: async ({ parent }) => {+ const writes = beginLoad(parent);+ try {+ const listAll = async (filter: string): Promise<IssueComment[]> => {+ const all: IssueComment[] = [];+ let pageToken = "";+ do {+ const resp = await get().listIssueComments(+ createProto(ListIssueCommentsRequestSchema, {+ parent,+ pageSize: MAX_PAGE_SIZE,+ pageToken,+ filter,+ })+ );+ all.push(...resp.issueComments);+ pageToken = resp.nextPageToken;+ } while (pageToken);+ return all;+ };++ const timeline = await listAll("");+ const rootNames = timeline.filter(isThreadRoot).map((c) => c.name);+ const replies: IssueComment[] = [];+ for (let i = 0; i < rootNames.length; i += REPLY_QUERY_ROOTS) {+ const chunk = rootNames.slice(i, i + REPLY_QUERY_ROOTS);+ replies.push(...(await listAll(`root in ${celStringList(chunk)}`)));+ }+ const issueComments = [...timeline, ...replies];+ cacheLoadedComments(parent, writes, issueComments);+ return issueComments;+ } catch (error) {+ withdrawLoad(parent, writes);+ throw error;+ }+ },++ createIssueComment: async ({+ issueName,+ comment,+ root,+ statementAnchor,+ }) => {+ const newIssueComment =+ await issueServiceClientConnect.createIssueComment(+ createProto(CreateIssueCommentRequestSchema, {+ parent: issueName,+ issueComment: createProto(IssueCommentSchema, {+ comment,+ root,+ statementAnchor,+ }),+ })+ );+ recordWrite(issueName, newIssueComment);+ set((state) => ({+ issueCommentsByIssue: {+ ...state.issueCommentsByIssue,+ [issueName]: [+ ...(state.issueCommentsByIssue[issueName] ?? []),+ newIssueComment,+ ],+ },+ }));+ return newIssueComment;+ },++ updateIssueComment: async ({ issueCommentName, comment, threadState }) => {+ const { projectId, issueId } =+ getProjectIdIssueIdIssueCommentId(issueCommentName);+ const parent = `${projectNamePrefix}${projectId}/${issueNamePrefix}${issueId}`;+ const paths: string[] = [];+ if (comment !== undefined) paths.push("comment");+ if (threadState !== undefined) paths.push("thread_state");+ const updatedIssueComment =+ await issueServiceClientConnect.updateIssueComment(+ createProto(UpdateIssueCommentRequestSchema, {+ parent,+ issueComment: createProto(IssueCommentSchema, {+ name: issueCommentName,+ comment,+ threadState,+ }),+ updateMask: { paths },+ })+ );+ recordWrite(parent, updatedIssueComment);+ set((state) => ({+ issueCommentsByIssue: {+ ...state.issueCommentsByIssue,+ [parent]: (state.issueCommentsByIssue[parent] ?? []).map(+ (issueComment) =>+ issueComment.name === issueCommentName+ ? updatedIssueComment+ : issueComment+ ),+ },+ }));+ return updatedIssueComment;+ },++ getIssueComments: (issueName) =>+ get().issueCommentsByIssue[issueName] ?? EMPTY_COMMENTS,+ };+};diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.tsindex ddd2ac1026..c73d76812c 100644--- a/frontend/src/stores/app/types.ts+++ b/frontend/src/stores/app/types.ts@@ -53,7 +53,9 @@ import type {import type {Issue,IssueComment,+ IssueComment_ThreadState,ListIssueCommentsRequest,+ StatementAnchor,} from "@/types/proto-es/v1/issue_service_pb";import type {Policy,@@ -1103,7 +1105,8 @@ export type DatabaseCatalogSlice = {};export type IssueCommentSlice = {- // Cache keyed by issue resource name → its timeline page (no replies).+ // Cache keyed by issue resource name → its comments. A timeline fetch stores+ // events and root comments; a thread fetch also appends the replies.issueCommentsByIssue: Record<string, IssueComment[]>;// Arbitrary CEL queries return results without changing the timeline cache.listIssueComments: (@@ -1115,14 +1118,25 @@ export type IssueCommentSlice = {pageSize?: number;pageToken?: string;}) => Promise<{ nextPageToken: string; issueComments: IssueComment[] }>;+ // Fetch every comment of the issue: the whole timeline plus the replies of+ // each thread root. Replaces the cache for this issue.+ fetchIssueCommentThreads: (request: {+ parent: string;+ }) => Promise<IssueComment[]>;+ // Omit `root` and `statementAnchor` for a general comment. An anchor starts+ // a thread; `root` creates a reply in that thread.createIssueComment: (params: {issueName: string;comment: string;- }) => Promise<void>;+ root?: string;+ statementAnchor?: StatementAnchor;+ }) => Promise<IssueComment>;+ // Only the provided fields join the update mask.updateIssueComment: (params: {issueCommentName: string;- comment: string;- }) => Promise<void>;+ comment?: string;+ threadState?: IssueComment_ThreadState;+ }) => Promise<IssueComment>;// Synchronous cache read; returns a stable empty array on miss.getIssueComments: (issueName: string) => IssueComment[];};diff --git a/frontend/src/utils/v1/sheet.ts b/frontend/src/utils/v1/sheet.tsindex fc6cb3dbd2..86ed1ab428 100644--- a/frontend/src/utils/v1/sheet.ts+++ b/frontend/src/utils/v1/sheet.ts@@ -15,8 +15,16 @@ export const setSheetStatement = (sheet.contentSize = BigInt(new TextEncoder().encode(statement).length);};+// Decoded once per content buffer: sheets are immutable and several+// consumers read the same one, and a 2 MB decode is not free.+const decodedStatements = new WeakMap<Uint8Array, string>();export const getSheetStatement = (sheet: Sheet | SavedQuery) => {- return new TextDecoder().decode(sheet.content);+ let statement = decodedStatements.get(sheet.content);+ if (statement === undefined) {+ statement = new TextDecoder().decode(sheet.content);+ decodedStatements.set(sheet.content, statement);+ }+ return statement;};// Whether the sheet carries its full content rather than a truncated previewdiff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.tsindex b76804e690..d71dcbee05 100644--- a/frontend/tests/e2e/framework/api-client.ts+++ b/frontend/tests/e2e/framework/api-client.ts@@ -592,7 +592,10 @@ export class BytebaseApiClient {hasRollout: boolean;issue: string;state: string;- specs?: { id: string; changeDatabaseConfig?: { targets?: string[] } }[];+ specs?: {+ id: string;+ changeDatabaseConfig?: { targets?: string[]; sheet?: string };+ }[];}> {return this.request("GET", `/v1/${planName}`);}@@ -666,9 +669,34 @@ export class BytebaseApiClient {);}- async createIssueComment(issueName: string, comment: string): Promise<{ name: string }> {+ // `root` creates a reply in that thread; `statementAnchor` starts a thread+ // anchored to whole lines of the spec's saved sheet (zero columns, inclusive+ // end line). Both omitted: a general comment.+ async createIssueComment(+ issueName: string,+ comment: string,+ thread: {+ root?: string;+ statementAnchor?: {+ spec: string;+ sheetSha256: string;+ startLine: number;+ endLine: number;+ };+ } = {},+ ): Promise<{ name: string }> {+ const anchor = thread.statementAnchor;return this.request<{ name: string }>("POST", `/v1/${issueName}:comment`, {comment,+ ...(thread.root !== undefined && { root: thread.root }),+ ...(anchor !== undefined && {+ statementAnchor: {+ spec: anchor.spec,+ sheetSha256: anchor.sheetSha256,+ startPosition: { line: anchor.startLine, column: 0 },+ endPosition: { line: anchor.endLine, column: 0 },+ },+ }),});}diff --git a/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-review.spec.tsindex 576edf84f1..9c722ac8d2 100644--- a/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts@@ -17,6 +17,8 @@// - Long-history timeline fold (torn separator + Show all) (CUJ J)// - Non-candidate sees no Review action but can still comment (permission boundary)// - BYT-9746 guard: "(edited)" marker shows in place after an inline edit+// - Inline comment threads: seeded thread in editor + timeline, gutter+// creation, reply / resolve / reopen, View in Statement (CUJ K)//// Rollout-readiness footer + bypass (readinessFooterState.ts)// - Approved/skipped + failed checks → "Bypass and deploy" → confirm sheet →@@ -423,6 +425,134 @@ test.describe("Permission boundary: non-candidate cannot review but can comment"});});+// Inline comment threads (design doc: Plan Review Comment and Thread UI/UX).+// A thread anchors to whole lines of the spec's saved sheet; it renders as a+// gutter marker + expanded card in the statement editor and as a card with+// its recorded context in the Review Activity timeline.+test.describe("Inline comment threads (CUJ K)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;+ let issueName: string;+ let specId: string;+ let sheetSha256: string;+ const seededRoot = `K seeded root ${Date.now()}`;+ const seededReply = `K seeded reply ${Date.now()}`;+ const createdRoot = `K gutter root ${Date.now()}`;+ const typedReply = `K typed reply ${Date.now()}`;++ test.beforeAll(async () => {+ await setupApproval(ONE_STEP_RULE);+ const suffix = Date.now();+ const seeded = await seedReviewPlan(env, page, {+ prefix: "E2E Review K",+ sql: [+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_k1_${suffix} TEXT;`,+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_k2_${suffix} TEXT;`,+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_k3_${suffix} TEXT;`,+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_k4_${suffix} TEXT;`,+ ].join("\n"),+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;+ issueName = seeded.issueName;+ // The anchor names the spec and the content hash embedded in the sheet name.+ const plan = await env.api.getPlan(seeded.planName);+ const spec = plan.specs?.[0];+ specId = spec?.id ?? "";+ sheetSha256 = spec?.changeDatabaseConfig?.sheet?.split("/").pop() ?? "";+ expect(specId).not.toBe("");+ expect(sheetSha256).toMatch(/^[0-9a-f]{64}$/);+ const root = await env.api.createIssueComment(issueName, seededRoot, {+ statementAnchor: { spec: specId, sheetSha256, startLine: 2, endLine: 3 },+ });+ await env.api.createIssueComment(issueName, seededReply, { root: root.name });+ await goReview(planId);+ await planPage.expandSection("Changes");+ });++ test("a seeded thread shows as a marker + expanded card in the editor and as an anchored card in the timeline", async () => {+ // Editor: one marker on the last anchored line, the unresolved thread expanded.+ await expect(planPage.threadMarkers).toHaveCount(1, { timeout: 15_000 });+ const editorCard = planPage.threadCardIn("changes", seededRoot);+ await expect(editorCard).toBeVisible();+ await expect(editorCard).toContainText(seededReply);++ // Timeline: the same thread with its recorded context.+ const timelineCard = planPage.threadCardIn("review", seededRoot);+ await expect(timelineCard).toBeVisible();+ await expect(timelineCard).toContainText(seededReply);+ const anchor = timelineCard.getByTestId("statement-anchor");+ await expect(anchor).toHaveAttribute("data-anchor-state", "CURRENT");+ await expect(anchor).toContainText("Lines 2–3");+ await expect(anchor).toContainText("e2e_rev_k2_");+ await expect(anchor.getByRole("button", { name: "View in Statement" })).toBeVisible();+ // The reply never renders as its own timeline row.+ await expect(+ page.locator("#plan-phase-review [data-testid='comment-thread']"),+ ).toHaveCount(1);+ });++ // One journey: create a thread from the gutter, then reply, resolve,+ // reopen, and jump back into the editor. The final assertion, that the+ // gutter-created thread collapses when View in Statement expands the+ // seeded one, depends on the created thread being open, so the steps stay+ // in one test.+ test("a gutter-created thread, then reply, resolve, reopen, and View in Statement round-trip between the surfaces", async () => {+ await planPage.hoverStatementLine(1);+ await expect(planPage.addThreadGlyph).toBeVisible({ timeout: 5_000 });+ await planPage.addThreadGlyph.click();+ await expect(planPage.inlineComposer).toBeVisible();+ await expect(planPage.inlineComposer).toContainText("Add a comment on line 1");+ await planPage.inlineComposerEditor.fill(createdRoot);+ await planPage.inlineComposerPublishButton.click();++ // The composer closes; the new thread expands in place of the seeded one+ // and both markers now sit in the gutter.+ await expect(planPage.inlineComposer).not.toBeVisible({ timeout: 15_000 });+ await expect(planPage.threadCardIn("changes", createdRoot)).toBeVisible();+ await expect(planPage.threadMarkers).toHaveCount(2);+ const createdAnchor = planPage+ .threadCardIn("review", createdRoot)+ .getByTestId("statement-anchor");+ await expect(createdAnchor).toBeVisible({ timeout: 15_000 });+ await expect(createdAnchor).toContainText("Line 1");+ await expect(createdAnchor).toContainText("e2e_rev_k1_");++ const timelineCard = planPage.threadCardIn("review", seededRoot);+ await timelineCard.scrollIntoViewIfNeeded();+ await timelineCard.getByRole("button", { name: "Reply..." }).click();+ await timelineCard.locator("textarea[placeholder='Reply...']").fill(typedReply);+ await timelineCard.getByRole("button", { name: "Reply", exact: true }).click();+ await expect(timelineCard).toContainText(typedReply, { timeout: 15_000 });++ // Resolving collapses the timeline card to its summary row.+ await timelineCard.getByRole("button", { name: "Resolve", exact: true }).click();+ const resolvedCard = planPage.threadCardIn("review", seededRoot);+ await expect(resolvedCard).toHaveAttribute("data-thread-state", "resolved", { timeout: 15_000 });+ await expect(resolvedCard).toContainText("Resolved");+ await expect(resolvedCard).toContainText("2 replies");+ await expect(resolvedCard).toContainText(seededRoot);+ await expect(resolvedCard.getByTestId("thread-comment")).toHaveCount(0);++ // Expanding keeps it resolved and offers Reopen.+ await resolvedCard.getByRole("button", { name: /Resolved/ }).click();+ await expect(resolvedCard).toContainText(seededRoot);+ await resolvedCard.getByRole("button", { name: "Reopen", exact: true }).click();+ const reopened = planPage.threadCardIn("review", seededRoot);+ await expect(reopened.getByRole("button", { name: "Resolve", exact: true })).toBeVisible({+ timeout: 15_000,+ });++ // View in Statement lands on the anchored lines with the seeded thread+ // expanded, collapsing the thread created above.+ await reopened.getByRole("button", { name: "View in Statement" }).click();+ const editorCard = planPage.threadCardIn("changes", seededRoot);+ await expect(editorCard).toBeVisible({ timeout: 15_000 });+ await expect(editorCard).toContainText(typedReply);+ await expect(planPage.threadCardIn("changes", createdRoot)).not.toBeVisible();+ });+});+// Regression guard for BYT-9746 (was finding O7): editing your own comment// inline must show the "(edited)" marker immediately, not only after a reload.// The original bug: stores/app/issueComment.ts updateIssueComment() patcheddiff --git a/frontend/tests/e2e/plan-detail/plan-detail.page.ts b/frontend/tests/e2e/plan-detail/plan-detail.page.tsindex 4196943e32..eaa2cf3183 100644--- a/frontend/tests/e2e/plan-detail/plan-detail.page.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail.page.ts@@ -29,6 +29,18 @@ export class PlanDetailPage {// The readiness footer's single action, in either weight (link or button).readonly bypassAndDeployAction: Locator;+ // --- Inline comment threads (StatementThreadsLayer / CommentThreadCard) ---+ // The read-only statement editor of the selected change.+ readonly statementEditor: Locator;+ // Thread markers in the statement editor's glyph margin.+ readonly threadMarkers: Locator;+ // The hover affordance that starts a thread on the hovered line.+ readonly addThreadGlyph: Locator;+ // The inline composer that opens below the selected lines.+ readonly inlineComposer: Locator;+ readonly inlineComposerEditor: Locator;+ readonly inlineComposerPublishButton: Locator;+// --- Header lifecycle slot (PlanDetailHeader, BYT-9722) ---// The sticky title/action row. Scope every header-slot assertion to this so a// pill/stamp/label in a phase section can't be mistaken for the header slot.@@ -71,6 +83,18 @@ export class PlanDetailPage {this.composerSubmitButton = page.getByRole("button", { name: "Comment", exact: true });this.bypassAndDeployAction = page.getByRole("button", { name: "Bypass and deploy" });+ this.statementEditor = page.locator("#plan-phase-changes .monaco-editor").first();+ this.threadMarkers = this.statementEditor.locator(".bb-thread-glyph");+ this.addThreadGlyph = this.statementEditor.locator(".bb-thread-add-glyph");+ this.inlineComposer = page.getByTestId("inline-thread-composer");+ this.inlineComposerEditor = this.inlineComposer.locator(+ "textarea[placeholder='Write a comment...']",+ );+ this.inlineComposerPublishButton = this.inlineComposer.getByRole("button", {+ name: "Publish",+ exact: true,+ });+// The sticky header row, located structurally (no product-code testid): the// title <input> sits in the row's left group (beside the terminal stamp), so// its grandparent is the row that also holds the lifecycle slot + ⋯ overflow.@@ -268,4 +292,28 @@ export class PlanDetailPage {checksSummary(): Locator {return this.page.getByRole("button", { name: "Checks", exact: true });}++ // A thread card by its root comment text, in either surface. Scope with+ // `threadCardIn` when the same thread shows in the editor and the timeline.+ threadCard(rootText: string): Locator {+ return this.page.getByTestId("comment-thread").filter({ hasText: rootText });+ }++ threadCardIn(phase: "changes" | "review", rootText: string): Locator {+ return this.page+ .locator(`#plan-phase-${phase}`)+ .getByTestId("comment-thread")+ .filter({ hasText: rootText });+ }++ // Hover a line's number in the statement editor so the add-thread glyph+ // appears on that line.+ async hoverStatementLine(lineNumber: number): Promise<void> {+ await this.statementEditor+ .locator(".margin-view-overlays .line-numbers", {+ hasText: new RegExp(`^${lineNumber}$`),+ })+ .first()+ .hover();+ }}