Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
test(plan): cover inline comment thread journeys end to end (#21424)
boojack9e2a93c44d45
diff --git a/frontend/src/components/monaco/MonacoOverlayWidget.test.tsx b/frontend/src/components/monaco/MonacoOverlayWidget.test.tsxnew file mode 100644index 0000000000..dbbf34768f--- /dev/null+++ b/frontend/src/components/monaco/MonacoOverlayWidget.test.tsx@@ -0,0 +1,64 @@+import { act } from "react";+import { createRoot } from "react-dom/client";+import { expect, test, vi } from "vitest";+import { MonacoOverlayWidget } from "./MonacoOverlayWidget";+import type { IStandaloneCodeEditor } from "./types";++type Widget = { getDomNode: () => HTMLElement };++function createEditor() {+ const widgets = new Set<Widget>();+ let relayout = () => {};+ const layout = { verticalScrollbarWidth: 14 };+ const editor = {+ addOverlayWidget: (widget: Widget) => widgets.add(widget),+ removeOverlayWidget: (widget: Widget) => widgets.delete(widget),+ getLayoutInfo: () => layout,+ onDidLayoutChange: (listener: () => void) => {+ relayout = listener;+ return { dispose: vi.fn() };+ },+ getModel: () => ({}),+ } as unknown as IStandaloneCodeEditor;+ return { editor, layout, widgets, relayout: () => relayout() };+}++test("sits in the top-right corner past the scrollbar and follows layout changes", () => {+ const fake = createEditor();+ const container = document.createElement("div");+ const root = createRoot(container);+ act(() =>+ root.render(+ <MonacoOverlayWidget editor={fake.editor}>+ <span data-testid="content" />+ </MonacoOverlayWidget>+ )+ );+ expect(fake.widgets.size).toBe(1);+ const [widget] = fake.widgets;+ const node = widget.getDomNode();+ expect(node.querySelector("[data-testid='content']")).not.toBeNull();+ expect(node.style.zIndex).toBe("10");+ expect([node.style.top, node.style.right]).toEqual(["8px", "22px"]);++ fake.layout.verticalScrollbarWidth = 20;+ fake.relayout();+ expect(node.style.right).toBe("28px");++ act(() => root.unmount());+ expect(fake.widgets.size).toBe(0);+});++test("skips removal once the editor is disposed", () => {+ const fake = createEditor();+ (fake.editor as unknown as { getModel: () => null }).getModel = () => null;+ const removeOverlayWidget = vi.spyOn(fake.editor, "removeOverlayWidget");+ const container = document.createElement("div");+ const root = createRoot(container);+ act(() =>+ root.render(<MonacoOverlayWidget editor={fake.editor}>x</MonacoOverlayWidget>)+ );+ expect(fake.widgets.size).toBe(1);+ act(() => root.unmount());+ expect(removeOverlayWidget).not.toHaveBeenCalled();+});diff --git a/frontend/src/components/monaco/MonacoOverlayWidget.tsx b/frontend/src/components/monaco/MonacoOverlayWidget.tsxnew file mode 100644index 0000000000..967fb1c153--- /dev/null+++ b/frontend/src/components/monaco/MonacoOverlayWidget.tsx@@ -0,0 +1,51 @@+import { type ReactNode, useId, useLayoutEffect, useMemo } from "react";+import { createPortal } from "react-dom";+import type { IStandaloneCodeEditor } from "./types";++// Inset from the editor's top edge and from the scrollbar lane, in px.+const CORNER_INSET = 8;++// Hosts React content in the editor's top-right corner through Monaco's+// overlay-widget slot, so it stays put while the editor scrolls. Positioned+// here rather than by Monaco's corner preference so it sits right beside+// the scrollbar and above the view-zone widgets added after it.+export function MonacoOverlayWidget({+ children,+ editor,+}: {+ children: ReactNode;+ editor: IStandaloneCodeEditor;+}) {+ const id = useId();+ const domNode = useMemo(() => {+ const node = document.createElement("div");+ node.style.pointerEvents = "auto";+ // Above the view-zone widgets, which Monaco stacks by insertion order.+ node.style.zIndex = "10";+ return node;+ }, []);++ useLayoutEffect(() => {+ const widget = {+ getId: () => `bytebase.overlay-widget.${id}`,+ getDomNode: () => domNode,+ getPosition: () => ({ preference: null }),+ };+ const layout = () => {+ const info = editor.getLayoutInfo();+ domNode.style.top = `${CORNER_INSET}px`;+ domNode.style.right = `${info.verticalScrollbarWidth + CORNER_INSET}px`;+ };+ layout();+ editor.addOverlayWidget(widget);+ const subscription = editor.onDidLayoutChange(layout);+ return () => {+ subscription.dispose();+ // The editor may already be disposed when the host unmounts.+ if (!editor.getModel()) return;+ editor.removeOverlayWidget(widget);+ };+ }, [domNode, editor, id]);++ return createPortal(children, domNode);+}diff --git a/frontend/src/components/monaco/useMonacoFindWidgetVisible.ts b/frontend/src/components/monaco/useMonacoFindWidgetVisible.tsnew file mode 100644index 0000000000..a9dec748e3--- /dev/null+++ b/frontend/src/components/monaco/useMonacoFindWidgetVisible.ts@@ -0,0 +1,33 @@+import type * as monaco from "monaco-editor";+import { useEffect, useState } from "react";+import type { IStandaloneCodeEditor } from "./types";++// The find controller is not part of Monaco's public editor API; this is the+// shape of the state it exposes.+type FindController = monaco.editor.IEditorContribution & {+ getState: () => {+ isRevealed: boolean;+ onFindReplaceStateChange: (listener: () => void) => {+ dispose: () => void;+ };+ };+};++// Whether the editor's find widget is open. It owns the top-right corner, so+// other corner overlays yield to it.+export function useMonacoFindWidgetVisible(+ editor: IStandaloneCodeEditor+): boolean {+ const [visible, setVisible] = useState(false);+ useEffect(() => {+ const state = editor+ .getContribution<FindController>("editor.contrib.findController")+ ?.getState();+ if (!state) return;+ const sync = () => setVisible(state.isRevealed);+ sync();+ const subscription = state.onFindReplaceStateChange(sync);+ return () => subscription.dispose();+ }, [editor]);+ return visible;+}diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 6c0dac5638..655f4e51cf 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1827,21 +1827,29 @@"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",+ "reopen-thread": "Reopen thread","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",+ "resolve-thread": "Resolve thread","resolved": "Resolved","threads-on-line_one": "{{count}} thread on this line","threads-on-line_other": "{{count}} threads on this line",+ "walker": {+ "count_one": "{{count}} unresolved thread on this version",+ "count_other": "{{count}} unresolved threads on this version",+ "next": "Next unresolved thread",+ "position": "Thread {{index}} of {{count}}",+ "previous": "Previous unresolved thread",+ "remainder_one": "{{count}} more not shown on this version",+ "remainder_other": "{{count}} more not shown on this version"+ },"write-comment": "Write a comment..."}},@@ -1885,6 +1893,8 @@"n-of-m-approved": "{{n}} of {{m}} approved","n-of-m-tasks": "{{n}}/{{m}} tasks","n-passed": "{{n}} passed",+ "n-unresolved-threads_one": "{{count}} unresolved thread",+ "n-unresolved-threads_other": "{{count}} unresolved threads","n-warning": "{{n}} warning"},"targets": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 21b769d854..5bed709f15 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1827,21 +1827,29 @@"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",+ "reopen-thread": "Reabrir hilo","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",+ "resolve-thread": "Resolver hilo","resolved": "Resuelto","threads-on-line_one": "{{count}} hilo en esta línea","threads-on-line_other": "{{count}} hilos en esta línea",+ "walker": {+ "count_one": "{{count}} hilo sin resolver en esta versión",+ "count_other": "{{count}} hilos sin resolver en esta versión",+ "next": "Siguiente hilo sin resolver",+ "position": "Hilo {{index}} de {{count}}",+ "previous": "Hilo sin resolver anterior",+ "remainder_one": "{{count}} más no se muestra en esta versión",+ "remainder_other": "{{count}} más no se muestran en esta versión"+ },"write-comment": "Escribe un comentario..."}},@@ -1885,6 +1893,8 @@"n-of-m-approved": "{{n}} de {{m}} aprobadas","n-of-m-tasks": "{{n}}/{{m}} tareas","n-passed": "{{n}} aprobadas",+ "n-unresolved-threads_one": "{{count}} hilo sin resolver",+ "n-unresolved-threads_other": "{{count}} hilos sin resolver","n-warning": "{{n}} advertencia"},"targets": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 635d4fcf87..d24888ef9a 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1827,21 +1827,29 @@"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": "コメントして再開",+ "reopen-thread": "スレッドを再開","reply": "返信","reply-placeholder": "返信...","reply-posted-status-failed": "返信は投稿されましたが、スレッドの状態を更新できませんでした。状態の変更を再試行してください。","resolve": "解決",- "resolve-with-comment": "コメントして解決",+ "resolve-thread": "スレッドを解決","resolved": "解決済み","threads-on-line_one": "この行に {{count}} 件のスレッド","threads-on-line_other": "この行に {{count}} 件のスレッド",+ "walker": {+ "count_one": "このバージョンに未解決のスレッドが {{count}} 件",+ "count_other": "このバージョンに未解決のスレッドが {{count}} 件",+ "next": "次の未解決スレッド",+ "position": "{{count}} 件中 {{index}} 件目",+ "previous": "前の未解決スレッド",+ "remainder_one": "他に {{count}} 件がこのバージョンでは表示されません",+ "remainder_other": "他に {{count}} 件がこのバージョンでは表示されません"+ },"write-comment": "コメントを書く..."}},@@ -1885,6 +1893,8 @@"n-of-m-approved": "{{m}} 件中 {{n}} 件承認済み","n-of-m-tasks": "{{n}}/{{m}} タスク","n-passed": "{{n}} 件合格",+ "n-unresolved-threads_one": "未解決のスレッド {{count}} 件",+ "n-unresolved-threads_other": "未解決のスレッド {{count}} 件","n-warning": "{{n}} 件の警告"},"targets": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 30550a1ed7..d8358c227c 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1827,21 +1827,29 @@"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",+ "reopen-thread": "Mở lại luồng","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",+ "resolve-thread": "Giải quyết luồng","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",+ "walker": {+ "count_one": "{{count}} luồng chưa giải quyết ở phiên bản này",+ "count_other": "{{count}} luồng chưa giải quyết ở phiên bản này",+ "next": "Luồng chưa giải quyết tiếp theo",+ "position": "Luồng {{index}} trên {{count}}",+ "previous": "Luồng chưa giải quyết trước đó",+ "remainder_one": "Còn {{count}} luồng không hiển thị ở phiên bản này",+ "remainder_other": "Còn {{count}} luồng không hiển thị ở phiên bản này"+ },"write-comment": "Viết bình luận..."}},@@ -1885,6 +1893,8 @@"n-of-m-approved": "{{n}} trên {{m}} đã được phê duyệt","n-of-m-tasks": "{{n}}/{{m}} tác vụ","n-passed": "{{n}} đã vượt qua",+ "n-unresolved-threads_one": "{{count}} luồng chưa giải quyết",+ "n-unresolved-threads_other": "{{count}} luồng chưa giải quyết","n-warning": "{{n}} cảnh báo"},"targets": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 4ea9820cb2..3c4f62fa1f 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1827,21 +1827,29 @@"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": "回复并重新打开",+ "reopen-thread": "重新打开线程","reply": "回复","reply-placeholder": "回复...","reply-posted-status-failed": "回复已发布,但讨论状态更新失败。请重试状态操作。","resolve": "解决",- "resolve-with-comment": "回复并解决",+ "resolve-thread": "解决线程","resolved": "已解决","threads-on-line_one": "此行有 {{count}} 个讨论","threads-on-line_other": "此行有 {{count}} 个讨论",+ "walker": {+ "count_one": "此版本有 {{count}} 个未解决的讨论",+ "count_other": "此版本有 {{count}} 个未解决的讨论",+ "next": "下一个未解决的讨论",+ "position": "第 {{index}} 个,共 {{count}} 个",+ "previous": "上一个未解决的讨论",+ "remainder_one": "另有 {{count}} 个未在此版本显示",+ "remainder_other": "另有 {{count}} 个未在此版本显示"+ },"write-comment": "撰写评论..."}},@@ -1885,6 +1893,8 @@"n-of-m-approved": "{{n}}/{{m}} 已审批","n-of-m-tasks": "{{n}}/{{m}} 任务","n-passed": "{{n}} 通过",+ "n-unresolved-threads_one": "{{count}} 个未解决的讨论",+ "n-unresolved-threads_other": "{{count}} 个未解决的讨论","n-warning": "{{n}} 警告"},"targets": {diff --git a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsxindex 44b78a8470..efe709bc03 100644--- a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx+++ b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx@@ -23,6 +23,7 @@ import { PlanDetailDeployFuture } from "./components/PlanDetailDeployFuture";import { PlanDetailHeader } from "./components/PlanDetailHeader";import { PlanDetailHeaderDetails } from "./components/PlanDetailHeaderDetails";import { PlanReviewSection } from "./components/review/PlanReviewSection";+import { useUnresolvedThreadTotal } from "./components/threads/useUnresolvedThreadCounts";import { useIssueCommentThreadsSync } from "./hooks/useIssueCommentThreadsSync";import { usePlacementSync } from "./hooks/usePlacementSync";import { PlanDetailStoreProvider } from "./shared/stores/PlanDetailStoreProvider";@@ -109,6 +110,7 @@ function ProjectPlanDetailPageInner({taskId,});useIssueCommentThreadsSync(page.issue);+ const unresolvedThreads = useUnresolvedThreadTotal(page.issue?.name);usePlacementSync({issueName: page.issue?.name,projectId,@@ -318,7 +320,7 @@ function ProjectPlanDetailPageInner({onSelect={() => selectPhase("review")}status={phaseConfigs.review.status}onToggle={() => page.togglePhase("review")}- summary={buildReviewSummary(page.issue, t)}+ summary={buildReviewSummary(page.issue, t, unresolvedThreads)}future={<p className="mt-0.5 text-sm text-control-placeholder">{t("plan.phase.review-description")}diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsxindex 7bc16b41ef..49fd211310 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsx@@ -3,6 +3,7 @@ import { act, useState } from "react";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Engine, State } from "@/types/proto-es/v1/common_pb";+import { IssueComment_ThreadState } from "@/types/proto-es/v1/issue_service_pb";import type { PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";import type { CheckReleaseResponse_CheckResult } from "@/types/proto-es/v1/release_service_pb";import type { PlanDetailPageState } from "../shell/hooks/types";@@ -17,6 +18,7 @@ import {).IS_REACT_ACT_ENVIRONMENT = true;const mocks = vi.hoisted(() => ({+ issueComments: [] as unknown[],fetchDatabases: vi.fn(),fetchDBGroupListByProjectName: vi.fn(),getDatabaseByName: vi.fn(),@@ -65,6 +67,7 @@ const mocks = vi.hoisted(() => ({}));vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },useTranslation: () => ({t: (key: string,@@ -250,6 +253,7 @@ vi.mock("@/app/router", async (importOriginal) => ({}));vi.mock("@/types", () => ({+ getTimeForPbTimestampProtoEs: () => 0,isValidDatabaseGroupName: (name: string) =>name?.includes("/databaseGroups/"),isValidDatabaseName: (name: string) => name?.includes("/databases/"),@@ -270,6 +274,11 @@ vi.mock("@/stores", () => ({pushNotification: vi.fn(),}));+vi.mock("../shared/stores/usePlanDetailStore", () => ({+ usePlanDetailStore: (selector: (state: unknown) => unknown) =>+ selector({ placements: new Map(), placementTargets: new Map() }),+}));+// The migrated component reads resource state via imperative// `useAppStore.getState().<method>()` and reactive selectors over app-store// maps. Delegate map lookups to the existing store mocks so per-test setup@@ -308,6 +317,7 @@ vi.mock("@/stores/app", async () => {dbGroupViewByName: Record<string, unknown>;projectsByName: Record<string, unknown>;environmentList: unknown[];+ getIssueComments: (issueName: string) => unknown[];}) => unknown) =>selector({@@ -316,6 +326,7 @@ vi.mock("@/stores/app", async () => {dbGroupViewByName,projectsByName,environmentList: [],+ getIssueComments: () => mocks.issueComments,}),{getState: () => ({@@ -323,6 +334,8 @@ vi.mock("@/stores/app", async () => {...mocks.dbGroupStore,getProjectByName: mocks.projectStore.getProjectByName,getEnvironmentByName: mocks.environmentStore.getEnvironmentByName,+ getSheetByName: () => undefined,+ getOrFetchSheetByName: async () => undefined,}),});@@ -527,6 +540,7 @@ beforeEach(() => {vi.useFakeTimers();vi.clearAllMocks();mocks.localSheets.clear();+ mocks.issueComments = [];mocks.getPlanOptionVisibility.mockReturnValue({shouldShow: false,showGhost: false,@@ -703,6 +717,51 @@ async function flush() {}describe("PlanDetailChangesBranch", () => {+ it("shows a count of unresolved threads on the tabs of the changes they anchor to", async () => {+ const page = buildPageState();+ page.issue = { name: "projects/foo/issues/1" } as PlanDetailPageState["issue"];+ const sha = "a".repeat(64);+ page.plan.specs = [+ { id: "spec-orders", config: { case: "changeDatabaseConfig", value: { targets: [DB_WIDGETS], sheet: `projects/foo/sheets/${sha}` } } },+ { id: "spec-cogs", config: { case: "changeDatabaseConfig", value: { targets: [DB_COGS], sheet: `projects/foo/sheets/${sha}` } } },+ ] as unknown as PlanDetailPageState["plan"]["specs"];+ const thread = (id: string, spec: string, opts: { resolved?: boolean; sheetSha256?: string } = {}) => ({+ name: `projects/foo/issues/1/issueComments/${id}`,+ comment: id,+ threadState: opts.resolved+ ? IssueComment_ThreadState.RESOLVED+ : IssueComment_ThreadState.OPEN,+ statementAnchor: {+ spec,+ sheetSha256: opts.sheetSha256 ?? sha,+ startPosition: { line: 1, column: 0 },+ endPosition: { line: 1, column: 0 },+ },+ });+ mocks.issueComments = [+ thread("a", "spec-orders"),+ thread("b", "spec-orders"),+ thread("c", "spec-orders", { resolved: true }),+ // Anchored to an older statement: unresolved, but not shown in the editor.+ thread("stale", "spec-orders", { sheetSha256: "b".repeat(64) }),+ thread("d", "spec-cogs", { resolved: true }),+ { name: "projects/foo/issues/1/issueComments/reply", comment: "reply", root: thread("a", "spec-orders").name },+ ];++ act(() => {+ root.render(+ <PlanDetailProvider value={page}>+ <PlanDetailChangesBranch selectedSpecId="spec-orders" onSelectedSpecIdChange={vi.fn()} />+ </PlanDetailProvider>+ );+ });+ await flush();++ const pills = [...container.querySelectorAll("[data-testid='spec-unresolved-threads']")];+ expect(pills.map((pill) => pill.textContent)).toEqual(["2"]);+ expect(pills[0].closest("[aria-label]")?.getAttribute("aria-label")).toContain("widgets");+ });+it("renders target-derived change references instead of generic types", async () => {const page = buildPageState();page.plan.specs = [diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsxindex 2071242d52..1748c15501 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx@@ -155,6 +155,7 @@ import { PlanDetailDraftChecks } from "./PlanDetailDraftChecks";import { PlanDetailStatementSection } from "./PlanDetailStatementSection";import { PlanDetailTabItem, PlanDetailTabStrip } from "./PlanDetailTabStrip";import { PlanTargetDisplay } from "./PlanTargetDisplay";+import { usePlacedUnresolvedThreadCounts } from "./threads/useUnresolvedThreadCounts";const DEFAULT_VISIBLE_TARGETS = 20;const DATABASE_GROUP_VISIBLE_DATABASES = 3;@@ -210,6 +211,10 @@ export function PlanDetailChangesBranch({const page = usePlanDetailContext();const { patchState } = page;const currentUser = useCurrentUser();+ const unresolvedThreadsBySpec = usePlacedUnresolvedThreadCounts(+ page.issue?.name,+ page.plan.specs+ );// subscribe to re-render on project cache changeconst projectsByName = useAppStore((s) => s.projectsByName);void projectsByName;@@ -600,6 +605,7 @@ export function PlanDetailChangesBranch({{visibleSpecs.map((spec, index) => {const isSelected = selectedSpec.id === spec.id;const isPending = pendingNewSpec?.id === spec.id;+ const unresolvedCount = unresolvedThreadsBySpec.get(spec.id) ?? 0;const reference = derivePlanChangeReference({index,resources: changeReferenceResources,@@ -616,10 +622,7 @@ export function PlanDetailChangesBranch({canModifySpecs && visibleSpecs.length > 1 ? (<DropdownMenu><DropdownMenuTrigger- className={cn(- ICON_ACTION_CLASS,- "mr-2 size-6 shrink-0 rounded-xs"- )}+ className={cn(ICON_ACTION_CLASS, "size-6 rounded-xs")}><EllipsisVertical className="size-3.5" /></DropdownMenuTrigger>@@ -666,6 +669,18 @@ export function PlanDetailChangesBranch({density="tab"reference={reference}/>+ {unresolvedCount > 0 && (+ <Badge+ className="h-5 min-w-5 shrink-0 justify-center px-1.5 py-0 text-xs tabular-nums"+ data-testid="spec-unresolved-threads"+ title={t("plan.summary.n-unresolved-threads", {+ count: unresolvedCount,+ })}+ variant="secondary"+ >+ {unresolvedCount}+ </Badge>+ )}</PlanDetailTabItem>);})}diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailTabStrip.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailTabStrip.tsxindex 2606d098ef..acb03f77cd 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailTabStrip.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailTabStrip.tsx@@ -75,7 +75,10 @@ export function PlanDetailTabItem({>{children}</button>- {action}+ {action && (+ // Pulled into the label's right padding so it sits close to the text.+ <div className="-ml-3 mr-2 flex shrink-0 items-center">{action}</div>+ )}</div>);}diff --git a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsx b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsxindex 0308e04144..875f6496c7 100644--- a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsx@@ -165,16 +165,22 @@ const buttonByText = (text: string) =>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}`));+const stateCheckbox = () => container.querySelector('[role="checkbox"]');++// Submits the open composer, optionally flipping the thread-state checkbox+// first so the reply also resolves or reopens the thread.+const submitReply = ({ toggleState = false } = {}) => {+ if (toggleState) click(stateCheckbox());+ click(buttonByText("plan.review.thread.reply"));};+// Grants reply but not the update permission the settle actions need.+const denySettle = () =>+ mocks.hasPermission.mockImplementation(+ (_project: unknown, permission: unknown) =>+ permission === "bb.issueComments.create"+ );+describe("CommentThreadCard", () => {test("places statement context above the root author as a separate full-width region", () => {const [thread] = groupThreads([comment("root", "Root question")]);@@ -305,7 +311,7 @@ describe("CommentThreadCard", () => {setter?.call(textarea, "Sounds good");textarea?.dispatchEvent(new Event("input", { bubbles: true }));});- chooseReplyAction();+ submitReply();await act(async () => {});expect(mocks.createIssueComment).toHaveBeenCalledWith({issueName: ISSUE,@@ -368,7 +374,9 @@ describe("CommentThreadCard", () => {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");+ // Open threads resolve when the box is ticked; resolved ones reopen by+ // default, so the box is left alone there.+ submitReply({ toggleState: !resolved });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}));});@@ -380,12 +388,68 @@ describe("CommentThreadCard", () => {expect(onThreadStateChanged).toHaveBeenCalledExactlyOnceWith(!resolved);});+ test.each([false, true])("the composer checkbox mirrors the thread state: resolved=%s", (resolved) => {+ const [thread] = groupThreads([comment("root", "Root", { resolved })]);+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} collapsible={false} replyDraft="Draft" onReplyDraftChange={vi.fn()} />);+ expect(stateCheckbox()?.getAttribute("aria-checked")).toBe(String(resolved));+ expect(container.querySelector("label")?.textContent).toBe(+ resolved ? "plan.review.thread.reopen-thread" : "plan.review.thread.resolve-thread"+ );+ expect(buttonByText("plan.review.thread.reply")).toBeDefined();+ expect(container.querySelector('button[aria-label="common.actions"]')).toBeNull();+ });++ test("an untouched checkbox on an open thread posts a plain reply", async () => {+ const [thread] = groupThreads([comment("root", "Root")]);+ const onThreadStateChanged = vi.fn();+ mocks.createIssueComment.mockResolvedValueOnce(comment("reply", "Just a note", { root: rootName }));+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} collapsible={false} replyDraft="Just a note" onReplyDraftChange={vi.fn()} onThreadStateChanged={onThreadStateChanged} />);+ submitReply();+ await act(async () => {});+ expect(mocks.createIssueComment).toHaveBeenCalledTimes(1);+ expect(mocks.updateIssueComment).not.toHaveBeenCalled();+ expect(onThreadStateChanged).not.toHaveBeenCalled();+ });++ test("an untouched checkbox on a resolved thread reopens it with the reply; unticking keeps it resolved", async () => {+ const [thread] = groupThreads([comment("root", "Root", { resolved: true })]);+ const onThreadStateChanged = vi.fn();+ mocks.createIssueComment.mockResolvedValue(comment("reply", "Not done yet", { root: rootName }));+ mocks.updateIssueComment.mockResolvedValueOnce(comment("root", "Root", { resolved: false }));+ const props = { issueName: ISSUE, project, thread, collapsible: false, onReplyDraftChange: vi.fn(), onThreadStateChanged };+ render(<CommentThreadCard {...props} replyDraft="Not done yet" />);+ expect(stateCheckbox()?.getAttribute("aria-checked")).toBe("true");+ submitReply();+ await act(async () => {});+ expect(mocks.updateIssueComment).toHaveBeenCalledExactlyOnceWith({ issueCommentName: rootName, threadState: IssueComment_ThreadState.OPEN });+ expect(onThreadStateChanged).toHaveBeenCalledExactlyOnceWith(false);++ vi.clearAllMocks();+ mocks.hasPermission.mockReturnValue(true);+ mocks.createIssueComment.mockResolvedValue(comment("reply", "Still resolved", { root: rootName }));+ render(<CommentThreadCard {...props} replyDraft="Still resolved" />);+ // The composer closed after the first reply; open it again.+ click(buttonByText("plan.review.thread.reply-placeholder"));+ submitReply({ toggleState: true });+ await act(async () => {});+ expect(mocks.createIssueComment).toHaveBeenCalledTimes(1);+ expect(mocks.updateIssueComment).not.toHaveBeenCalled();+ });++ test("hides the state checkbox without the update permission", () => {+ denySettle();+ const [thread] = groupThreads([comment("root", "Root")]);+ render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} collapsible={false} replyDraft="Draft" onReplyDraftChange={vi.fn()} />);+ expect(stateCheckbox()).toBeNull();+ expect(buttonByText("plan.review.thread.reply")).toBeDefined();+ });+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");+ submitReply({ toggleState: true });await act(async () => {});expect(mocks.updateIssueComment).not.toHaveBeenCalled();expect(onReplyDraftChange).not.toHaveBeenCalled();@@ -399,7 +463,7 @@ describe("CommentThreadCard", () => {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");+ submitReply({ toggleState: true });await act(async () => {});expect(onReplyDraftChange).toHaveBeenCalledWith(expect.any(Function));expect(onThreadStateChanged).not.toHaveBeenCalled();@@ -413,19 +477,8 @@ describe("CommentThreadCard", () => {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"- );+ denySettle();const [thread] = groupThreads([comment("root", "Root", { creator: "users/[email protected]" }),]);@@ -436,10 +489,7 @@ describe("CommentThreadCard", () => {});test("hides Resolve from users who may neither update nor own the root", () => {- mocks.hasPermission.mockImplementation(- (_project: unknown, permission: unknown) =>- permission === "bb.issueComments.create"- );+ denySettle();const [thread] = groupThreads([comment("root", "Root")]);render(<CommentThreadCard issueName={ISSUE} project={project} thread={thread} />@@ -456,7 +506,7 @@ test.each(["ctrlKey", "metaKey"])("ignores %s+Enter while a reply is pending", amocks.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();+ submitReply();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}));});@@ -466,21 +516,17 @@ test.each(["ctrlKey", "metaKey"])("ignores %s+Enter while a reply is pending", a});-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"})]);+test("disables Reply on an empty draft, checkbox or not", () => {+ const [thread] = groupThreads([comment("root", "Root")]);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();+ click(stateCheckbox());+ expect(buttonByText("plan.review.thread.reply")?.disabled).toBe(true);+ act(() => {container.querySelector("textarea")!.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", metaKey: true, bubbles: true}));});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();+ expect(buttonByText("plan.review.thread.reply")?.disabled).toBe(false);});diff --git a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsx b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsxindex dd494a513c..99103b6d94 100644--- a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsx+++ b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsx@@ -11,6 +11,7 @@ import {type SetStateAction,useContext,useEffect,+ useId,useLayoutEffect,useMemo,useRef,@@ -23,13 +24,7 @@ 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 { Checkbox } from "@/components/ui/checkbox";import { useCurrentUser, useUserByIdentifier } from "@/hooks/useAppState";import { cn } from "@/lib/utils";import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";@@ -45,11 +40,12 @@ import {// 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.+// in the footer. The reply composer carries a checkbox that mirrors the thread+// state and, when toggled, settles the thread after the reply is posted.+// Resolved threads collapse to a summary row.export function CommentThreadCard({className,collapsible = true,@@ -99,12 +95,8 @@ export function CommentThreadCard({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 [settleWithReply, setSettleWithReply] = useState(thread.resolved);+ const resolveCheckboxId = useId();const submissionPending = useRef(false);const busy = actions.pending || submitting;const draftRef = useRef(replyDraft);@@ -138,19 +130,18 @@ export function CommentThreadCard({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");+ // The reply composer's checkbox names the action for the thread's current+ // state and, when checked, performs it after the reply is posted:+ // open thread -> "Resolve thread", unchecked; a reply keeps it open.+ // resolved thread -> "Reopen thread", checked; a reply reopens it.+ // The resolved default is deliberate: replying to a resolved thread is+ // rare and nearly always means the matter is not settled, so reopening is+ // the expected outcome and keeping it resolved is the opt-out. A state+ // change from elsewhere or a fresh composer resets the box to its default.useEffect(() => {- setReplyAction("reply");- }, [thread.resolved, allowSettle]);+ setSettleWithReply(thread.resolved);+ }, [thread.resolved, replyOpen]);+ const settleAfterReply = allowSettle && settleWithReply;const { hiddenCount, visibleReplies } = useMemo(() => {const replies = thread.replies;@@ -163,30 +154,25 @@ export function CommentThreadCard({};}, [showAllReplies, thread.replies]);- const submitReply = async (action: ReplyAction = "reply") => {+ const submitReply = async () => {if (busy || submissionPending.current) return;- if (!allowReply || (action !== "reply" && !allowSettle)) return;- if (!replyDraft.trim()) {- setReplyAttempted(true);- return;- }+ if (!allowReply) return;+ if (!replyDraft.trim()) 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;+ if (!settleAfterReply) return;const failureTitle = t("plan.review.thread.reply-posted-status-failed");- const resolved = action === "resolve";+ const resolved = !thread.resolved;const updated = await (resolved? actions.resolve(thread.root.name, failureTitle): actions.reopen(thread.root.name, failureTitle));@@ -318,83 +304,44 @@ export function CommentThreadCard({compactcontent={replyDraft}onChange={setReplyDraft}- onSubmit={() => void submitReply(selectedAction)}+ onSubmit={() => void submitReply()}placeholder={t("plan.review.thread.reply-placeholder")}/>- <div className="flex flex-wrap items-center justify-end gap-2">+ <div className="flex flex-wrap items-center gap-2">+ {allowSettle && (+ <div className="flex items-center gap-x-2">+ <Checkbox+ id={resolveCheckboxId}+ checked={settleWithReply}+ disabled={busy}+ onCheckedChange={setSettleWithReply}+ />+ <label+ htmlFor={resolveCheckboxId}+ className="cursor-pointer text-sm"+ >+ {thread.resolved+ ? t("plan.review.thread.reopen-thread")+ : t("plan.review.thread.resolve-thread")}+ </label>+ </div>+ )}<Button+ className="ml-auto"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>+ <Button+ size="sm"+ disabled={busy || !replyDraft.trim()}+ onClick={() => void submitReply()}+ >+ {busy && <Loader2 className="size-4 animate-spin" />}+ {t("plan.review.thread.reply")}+ </Button></div></div>) : (diff --git a/frontend/src/routes/project/plan-detail/components/threads/InlineThreadComposer.tsx b/frontend/src/routes/project/plan-detail/components/threads/InlineThreadComposer.tsxindex f265121062..1e2a27e588 100644--- a/frontend/src/routes/project/plan-detail/components/threads/InlineThreadComposer.tsx+++ b/frontend/src/routes/project/plan-detail/components/threads/InlineThreadComposer.tsx@@ -1,5 +1,4 @@-import { Loader2, Send } from "lucide-react";-import { useState } from "react";+import { Loader2 } from "lucide-react";import { useTranslation } from "react-i18next";import { MarkdownEditor } from "@/components/MarkdownEditor";import { UserAvatar } from "@/components/UserAvatar";@@ -8,27 +7,28 @@ 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.+// root comment anchored to those lines. The owner holds the draft, so it+// survives a failed publish and the form's own re-renders.export function InlineThreadComposer({+ draft,onCancel,+ onDraftChange,onPublish,pending,range,}: {+ draft: string;onCancel: () => void;- onPublish: (comment: string) => Promise<boolean>;+ onDraftChange: (draft: string) => void;+ onPublish: (comment: string) => void;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("");+ const publish = () => {+ if (canPublish) onPublish(draft);};return (@@ -55,26 +55,19 @@ export function InlineThreadComposer({</div><div className="flex flex-col gap-y-2 px-3 py-2"><MarkdownEditor+ autoFocuscompactcontent={draft}- onChange={setDraft}- onSubmit={() => void publish()}+ onChange={onDraftChange}+ onSubmit={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" />- )}+ <Button disabled={!canPublish} onClick={publish} size="sm">+ {pending && <Loader2 className="size-4 animate-spin" />}{t("plan.review.thread.publish")}</Button></div>diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadWalker.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadWalker.tsxnew file mode 100644index 0000000000..1b82919422--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadWalker.tsx@@ -0,0 +1,69 @@+import { ChevronDown, ChevronUp, MessagesSquare } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";++// Touch has no hover and keeps focus on the tapped arrow, so coarse pointers+// get no ring: the flash on the target card is the feedback there.+// Size comes from the shared "sm" button, whose 28px height is the strip's.+const ARROW_CLASS =+ "rounded-none border-l border-control-border text-control-light hover:text-control focus-visible:ring-inset focus-visible:ring-offset-0 pointer-coarse:focus-visible:ring-0";++// Steps through the unresolved threads placed on the displayed statement.+// `count` is what the arrows can visit; `remainder` is how many unresolved+// threads of this change are not placed on this version.+export function StatementThreadWalker({+ announcement,+ count,+ onNext,+ onPrevious,+ remainder,+}: {+ announcement: string;+ count: number;+ onNext: () => void;+ onPrevious: () => void;+ remainder: number;+}) {+ const { t } = useTranslation();+ const title = [+ t("plan.review.thread.walker.count", { count }),+ remainder > 0+ ? t("plan.review.thread.walker.remainder", { count: remainder })+ : undefined,+ ]+ .filter(Boolean)+ .join(" · ");+ return (+ <div+ className="flex h-7 items-stretch overflow-hidden rounded-sm border border-control-border bg-background text-xs shadow-sm pointer-coarse:shadow-none"+ data-testid="thread-walker"+ title={title}+ >+ <span className="inline-flex items-center gap-1 px-2 font-medium text-accent tabular-nums">+ <MessagesSquare className="size-3.5" />+ {count}+ </span>+ <Button+ appearance="secondary"+ aria-label={t("plan.review.thread.walker.previous")}+ className={ARROW_CLASS}+ onClick={onPrevious}+ size="sm"+ >+ <ChevronUp className="size-4" />+ </Button>+ <Button+ appearance="secondary"+ aria-label={t("plan.review.thread.walker.next")}+ className={ARROW_CLASS}+ onClick={onNext}+ size="sm"+ >+ <ChevronDown className="size-4" />+ </Button>+ <span aria-live="polite" className="sr-only">+ {announcement}+ </span>+ </div>+ );+}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.tsxindex 1feba37889..537e198131 100644--- a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsx@@ -34,6 +34,12 @@ const mocks = vi.hoisted(() => ({placements: new Map<string, unknown>(),placementTargets: new Map<string, string>(),hasPermission: vi.fn((_project: unknown, _permission: unknown) => true),+ findController: null as null | {+ getState: () => {+ isRevealed: boolean;+ onFindReplaceStateChange: (listener: () => void) => { dispose: () => void };+ };+ },}));vi.mock("react-i18next", () => ({@@ -121,16 +127,25 @@ vi.mock("./CommentThreadCard", () => ({vi.mock("./InlineThreadComposer", () => ({InlineThreadComposer: ({+ draft,onCancel,+ onDraftChange,onPublish,range,}: {+ draft: string;onCancel: () => void;+ onDraftChange: (draft: string) => void;onPublish: (comment: string) => Promise<boolean>;range: { startLine: number; endLine: number };}) => (- <div data-testid="composer" data-range={`${range.startLine}-${range.endLine}`}>+ <div data-testid="composer" data-draft={draft} data-range={`${range.startLine}-${range.endLine}`}><button data-testid="cancel-composer" onClick={onCancel} type="button" />+ <button+ data-testid="type-draft"+ onClick={() => onDraftChange(`Draft ${range.startLine}-${range.endLine}`)}+ type="button"+ /><buttondata-testid="publish"onClick={() => void onPublish("No LIMIT")}@@ -260,6 +275,7 @@ function createFakeEditor(lineMaxColumn = 20) {removeOverlayWidget: (widget: { getDomNode: () => HTMLElement }) => {widgets.delete(widget);},+ getContribution: () => mocks.findController,getLayoutInfo: () => ({contentLeft: 52,width: 800,@@ -312,6 +328,7 @@ function createFakeEditor(lineMaxColumn = 20) {onMouseMove: subscribe("move"),onMouseUp: subscribe("up"),revealLineInCenter: vi.fn(),+ revealLineNearTop: vi.fn(),};const fire = (key: string, line: number | undefined, type: number, detail?: Record<string, unknown>) => {const event = {@@ -361,7 +378,7 @@ const threadRoot = (id: string,startLine: number,endLine: number,- extra: { createdAt?: number; resolved?: boolean } = {}+ extra: { createdAt?: number; resolved?: boolean; sheetSha256?: string } = {}) =>create(IssueCommentSchema, {name: `${ISSUE}/issueComments/${id}`,@@ -372,7 +389,7 @@ const threadRoot = (: IssueComment_ThreadState.OPEN,statementAnchor: create(StatementAnchorSchema, {spec: "spec-1",- sheetSha256: SHA,+ sheetSha256: extra.sheetSha256 ?? SHA,startPosition: create(PositionSchema, { line: startLine, column: 0 }),endPosition: create(PositionSchema, { line: endLine, column: 0 }),}),@@ -385,6 +402,7 @@ let container: HTMLDivElement;let root: Root;beforeEach(() => {+ mocks.findController = null;vi.clearAllMocks();mocks.threadFocus = undefined;mocks.hasPermission.mockReturnValue(true);@@ -434,6 +452,26 @@ const classesOf = ((d) => d.options.className ?? d.options.glyphMarginClassName ?? d.options.linesDecorationsClassName ?? "");+const lines = (+ decorations: monaco.editor.IModelDeltaDecoration[],+ className: string+) =>+ decorations+ .filter((d) => d.options.className === className)+ .map((d) => d.range.startLineNumber);++const walkerNode = (widgets: Set<{ getDomNode: () => HTMLElement }>) =>+ Array.from(widgets)+ .map((widget) => widget.getDomNode())+ .find((node) => node.querySelector("[data-testid='thread-walker']"));++const pressWalker = (widgets: Set<{ getDomNode: () => HTMLElement }>, label: string) =>+ act(() => {+ hosted(widgets, `button[aria-label='plan.review.thread.walker.${label}']`)?.dispatchEvent(+ new MouseEvent("click", { bubbles: true })+ );+ });+describe("StatementThreadsLayer", () => {test("decorates current anchors and expands the earliest unresolved thread", () => {mocks.comments = [@@ -477,29 +515,102 @@ describe("StatementThreadsLayer", () => {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", () => {+ test("a pending selection replaces the reading highlight; an open composer keeps both", () => {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]);+ expect(lines(fake.decorations.current, "bb-thread-line")).toEqual([]);+ expect(lines(fake.decorations.current, "bb-thread-line--selecting")).toEqual([1, 2]);fake.pressEscape();- expect(lines("bb-thread-line")).toEqual([2]);- expect(lines("bb-thread-line--selecting")).toEqual([]);+ expect(lines(fake.decorations.current, "bb-thread-line")).toEqual([2]);+ expect(lines(fake.decorations.current, "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();+ expect(lines(fake.decorations.current, "bb-thread-line")).toEqual([2]);+ expect(lines(fake.decorations.current, "bb-thread-line--selecting")).toEqual([3]);+ expect(lines(fake.decorations.current, "bb-thread-line--passive")).toEqual([]);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([]);+ expect(lines(fake.decorations.current, "bb-thread-line")).toEqual([2]);+ expect(lines(fake.decorations.current, "bb-thread-line--selecting")).toEqual([]);+ });++ test("composers on different lines stay open together and close independently", async () => {+ mocks.comments = [];+ mocks.createIssueComment.mockResolvedValue(+ create(IssueCommentSchema, { name: `${ISSUE}/issueComments/new` })+ );+ const fake = createFakeEditor();+ mount(fake.editor);+ const composers = () =>+ Array.from(fake.widgets)+ .flatMap((widget) => Array.from(widget.getDomNode().querySelectorAll("[data-testid='composer']")))+ .map((node) => node.getAttribute("data-range"));+ const composerAt = (range: string) => hosted(fake.widgets, `[data-testid='composer'][data-range='${range}']`);++ fake.fire("move", 2, MouseTargetType.CONTENT_TEXT);+ fake.fire("down", 2, MouseTargetType.GUTTER_LINE_DECORATIONS);+ expect(composers()).toEqual(["2-2"]);+ act(() => composerAt("2-2")?.querySelector("[data-testid='type-draft']")?.dispatchEvent(new MouseEvent("click", { bubbles: true })));+ expect(composerAt("2-2")?.getAttribute("data-draft")).toBe("Draft 2-2");++ // The add action stays available on other lines while a form is open.+ fake.fire("move", 5, MouseTargetType.CONTENT_TEXT);+ expect(classesOf(fake.decorations.current, 5)).toContain("bb-thread-add-glyph");+ fake.fire("down", 5, MouseTargetType.GUTTER_LINE_NUMBERS);+ fake.dragTo(6);+ fake.release();+ fake.fire("down", 6, MouseTargetType.GUTTER_LINE_DECORATIONS);+ expect(composers()).toEqual(["2-2", "5-6"]);+ expect(zoneAfter(fake.zones)).toEqual([2, 6]);+ expect(lines(fake.decorations.current, "bb-thread-line--selecting")).toEqual([2, 5, 6]);+ expect(composerAt("2-2")?.getAttribute("data-draft")).toBe("Draft 2-2");++ // The action is hidden on a line that already carries a form.+ fake.fire("move", 2, MouseTargetType.CONTENT_TEXT);+ expect(classesOf(fake.decorations.current, 2)).not.toContain("bb-thread-add-glyph");++ act(() => composerAt("5-6")?.querySelector("[data-testid='cancel-composer']")?.dispatchEvent(new MouseEvent("click", { bubbles: true })));+ expect(composers()).toEqual(["2-2"]);+ expect(lines(fake.decorations.current, "bb-thread-line--selecting")).toEqual([2]);++ await act(async () => {+ composerAt("2-2")?.querySelector("[data-testid='publish']")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ expect(mocks.createIssueComment).toHaveBeenCalledTimes(1);+ expect(mocks.createIssueComment.mock.calls[0][0].statementAnchor).toMatchObject({+ startPosition: { line: 2, column: 0 },+ endPosition: { line: 2, column: 0 },+ });+ expect(composers()).toEqual([]);+ });++ test("the comment action on a form's own line reopens it with its draft and range intact", () => {+ mocks.comments = [];+ const fake = createFakeEditor();+ mount(fake.editor);+ fake.fire("down", 3, MouseTargetType.GUTTER_LINE_NUMBERS);+ fake.dragTo(4);+ fake.release();+ fake.fire("down", 4, MouseTargetType.GUTTER_LINE_DECORATIONS);+ const composer = () => hosted(fake.widgets, "[data-testid='composer']");+ expect(composer()?.getAttribute("data-range")).toBe("3-4");+ act(() => composer()?.querySelector("[data-testid='type-draft']")?.dispatchEvent(new MouseEvent("click", { bubbles: true })));++ // A fresh single-line selection ending on the same line targets the+ // existing form instead of replacing it.+ fake.fire("down", 4, MouseTargetType.GUTTER_LINE_NUMBERS);+ fake.release();+ expect(classesOf(fake.decorations.current, 4)).not.toContain("bb-thread-add-glyph");+ const addAction = (fake.editor as unknown as { addAction: ReturnType<typeof vi.fn> }).addAction;+ const commentOnLines = addAction.mock.calls.at(-1)?.[0] as { run: () => void };+ act(() => commentOnLines.run());+ expect(fake.zones.size).toBe(1);+ expect(composer()?.getAttribute("data-range")).toBe("3-4");+ expect(composer()?.getAttribute("data-draft")).toBe("Draft 3-4");});test("a marker opens its thread, a combined marker offers a picker, and closing returns to markers", () => {@@ -742,4 +853,89 @@ describe("StatementThreadsLayer", () => {).toHaveBeenCalledWith(10);expect(mocks.clearThreadFocus).toHaveBeenCalledWith(7);});+ test("the walker steps through unresolved threads in editor order and wraps", () => {+ mocks.comments = [+ threadRoot("a", 2, 2, { createdAt: 1 }),+ threadRoot("done", 5, 5, { createdAt: 2, resolved: true }),+ threadRoot("c", 7, 8, { createdAt: 3 }),+ ];+ const fake = createFakeEditor();+ mount(fake.editor);+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/a`);+ const control = walkerNode(fake.widgets);+ expect(control?.textContent).toContain("2");+ expect([control?.style.top, control?.style.right]).toEqual(["8px", "22px"]);+ expect(hosted(fake.widgets, "[data-testid='thread-walker']")?.getAttribute("title")).toBe(+ "plan.review.thread.walker.count:2"+ );++ pressWalker(fake.widgets, "next");+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/c`);+ expect(zoneAfter(fake.zones)).toEqual([8]);+ expect(fake.editor.revealLineNearTop).toHaveBeenLastCalledWith(7);+ expect(fake.editor.getDomNode()?.scrollIntoView).toHaveBeenCalledWith({ block: "nearest" });+ pressWalker(fake.widgets, "next");+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/a`);+ pressWalker(fake.widgets, "previous");+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/c`);++ // Closing the open line leaves no current thread: down starts over, up ends.+ fake.fire("down", 8, MouseTargetType.GUTTER_GLYPH_MARGIN);+ expect(fake.zones.size).toBe(0);+ pressWalker(fake.widgets, "previous");+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/c`);+ });++ test("the walker is absent without unresolved placed threads and reports unplaced ones", () => {+ mocks.comments = [threadRoot("done", 2, 2, { resolved: true })];+ const fake = createFakeEditor();+ mount(fake.editor);+ expect(hosted(fake.widgets, "[data-testid='thread-walker']")).toBeNull();++ mocks.comments = [+ threadRoot("placed", 2, 2),+ threadRoot("elsewhere", 4, 4, { sheetSha256: "d".repeat(64) }),+ ];+ mount(fake.editor);+ expect(hosted(fake.widgets, "[data-testid='thread-walker']")?.getAttribute("title")).toBe(+ "plan.review.thread.walker.count:1 · plan.review.thread.walker.remainder:1"+ );+ pressWalker(fake.widgets, "next");+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/placed`);+ });++ test("resolving the current thread moves the walker on, and the last resolution removes it", () => {+ mocks.comments = [threadRoot("a", 2, 2, { createdAt: 1 }), threadRoot("b", 5, 5, { createdAt: 2 })];+ const fake = createFakeEditor();+ mount(fake.editor);+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/a`);+ mocks.comments = [threadRoot("a", 2, 2, { createdAt: 1, resolved: true }), threadRoot("b", 5, 5, { createdAt: 2 })];+ mount(fake.editor);+ expect(hosted(fake.widgets, "[data-testid='thread-walker']")?.textContent).toContain("1");+ pressWalker(fake.widgets, "next");+ expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/b`);+ mocks.comments = [threadRoot("a", 2, 2, { createdAt: 1, resolved: true }), threadRoot("b", 5, 5, { createdAt: 2, resolved: true })];+ mount(fake.editor);+ expect(hosted(fake.widgets, "[data-testid='thread-walker']")).toBeNull();+ });++ test("the walker yields the corner to the find widget", () => {+ let notify = () => {};+ const state = {+ isRevealed: true,+ onFindReplaceStateChange: (listener: () => void) => {+ notify = listener;+ return { dispose: vi.fn() };+ },+ };+ mocks.findController = { getState: () => state };+ mocks.comments = [threadRoot("a", 2, 2)];+ const fake = createFakeEditor();+ mount(fake.editor);+ expect(hosted(fake.widgets, "[data-testid='thread-walker']")).toBeNull();+ state.isRevealed = false;+ act(() => notify());+ expect(hosted(fake.widgets, "[data-testid='thread-walker']")).not.toBeNull();+ });});+diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsxindex 7cfd7518fb..f709e0fde3 100644--- a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx@@ -8,11 +8,13 @@ import {useState,} from "react";import { useTranslation } from "react-i18next";+import { MonacoOverlayWidget } from "@/components/monaco/MonacoOverlayWidget";import { MonacoViewZone } from "@/components/monaco/MonacoViewZone";import type {IStandaloneCodeEditor,MonacoModule,} from "@/components/monaco/types";+import { useMonacoFindWidgetVisible } from "@/components/monaco/useMonacoFindWidgetVisible";import { useProjectByName } from "@/hooks/useProjectByName";import { useAppStore } from "@/stores/app";import { projectNamePrefix } from "@/stores/modules/v1/common";@@ -23,6 +25,7 @@ import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";import { usePlanDetailContext } from "../../shell/PlanDetailContext";import { InlineThreadComposer } from "./InlineThreadComposer";import "./statementThreads.css";+import { StatementThreadWalker } from "./StatementThreadWalker";import { ThreadStack } from "./ThreadStack";import {buildWholeLineAnchor,@@ -34,6 +37,7 @@ import {lineRangeLabel,selectEditorThreads,selectionLineRange,+ selectUnresolvedEditorThreads,} from "./threadModel";import { canReplyToThread, useThreadActions } from "./useThreadActions";@@ -44,10 +48,21 @@ const firstToExpand = (threads: EditorThread[] | undefined): string[] => {return entry ? [entry.thread.root.name] : [];};+// An unpublished comment form, keyed by the last line of its range so one+// line carries at most one form. Drafts live in their own record so typing+// leaves the decorations and listeners keyed on this map alone.+type Composer = {+ range: LineRange;+ // Bumped when the form is opened again, to reveal it.+ revealNonce: number;+};+// 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.+// for highlights, and view zones for the composers and the expanded threads.+// Several composers may be open at once, one per line, like unsent review+// forms in a diff.//// 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@@ -79,14 +94,34 @@ export function StatementThreadsLayer({const actions = useThreadActions(issue.name);const canCreate = canReplyToThread(project);+ const threads = useMemo(() => groupThreads(comments), [comments]);const editorThreads = useMemo(() =>selectEditorThreads(- groupThreads(comments),+ threads,+ { specId: spec.id, sheetSha256 },+ placements+ ),+ [placements, sheetSha256, spec.id, threads]+ );+ // What the walker can visit, in editor order, and how many unresolved+ // threads of this change it cannot because they are not placed here.+ const visitableThreads = useMemo(+ () =>+ selectUnresolvedEditorThreads(+ threads,{ specId: spec.id, sheetSha256 },placements),- [comments, placements, sheetSha256, spec.id]+ [placements, sheetSha256, spec.id, threads]+ );+ const unplacedUnresolved = useMemo(+ () =>+ threads.filter(+ (thread) =>+ !thread.resolved && thread.root.statementAnchor?.spec === spec.id+ ).length - visitableThreads.length,+ [spec.id, threads, visitableThreads.length]);const markersByLine = useMemo(() => groupMarkersByLine(editorThreads),@@ -151,7 +186,44 @@ export function StatementThreadsLayer({const [hoveredLine, setHoveredLine] = useState<number | undefined>();const [selection, setSelection] = useState<LineRange | undefined>();const dragRef = useRef<LineRange | undefined>(undefined);- const [composerRange, setComposerRange] = useState<LineRange | undefined>();+ const [composers, setComposers] = useState<ReadonlyMap<number, Composer>>(+ () => new Map()+ );+ const [composerDrafts, setComposerDrafts] = useState<+ Readonly<Record<number, string>>+ >({});++ // Walker: the current thread is the expanded one when it is unresolved.+ // Stepping wraps; with nothing open, down starts at the first and up at+ // the last.+ const [walkerAnnouncement, setWalkerAnnouncement] = useState("");+ const [flashRoot, setFlashRoot] = useState<string | undefined>();+ const findWidgetVisible = useMonacoFindWidgetVisible(editor);+ const currentVisitableIndex = useMemo(+ () =>+ visitableThreads.findIndex(+ (entry) =>+ entry.range.endLine === openLine &&+ expandedRoots.has(entry.thread.root.name)+ ),+ [expandedRoots, openLine, visitableThreads]+ );+ const walk = (step: 1 | -1) => {+ const count = visitableThreads.length;+ if (!count) return;+ const from =+ currentVisitableIndex === -1 && step < 0 ? count : currentVisitableIndex;+ const index = (from + step + count) % count;+ const target = visitableThreads[index];+ openThreads(target.range.endLine, [target.thread.root.name]);+ setSelection(undefined);+ setFlashRoot(target.thread.root.name);+ editor.revealLineNearTop(target.range.startLine);+ editor.getDomNode()?.scrollIntoView({ block: "nearest" });+ setWalkerAnnouncement(+ t("plan.review.thread.walker.position", { index: index + 1, count })+ );+ };// The line that carries the comment action: the end of the selection, or// the hovered line when nothing is selected.@@ -220,16 +292,21 @@ export function StatementThreadsLayer({entry.range.endLine === openLine &&expandedRoots.has(entry.thread.root.name));- const creationRange = composerRange ?? (canCreate ? selection : undefined);- const range = creationRange ?? activeThread?.range;- if (range) {+ // A pending selection replaces the reading highlight; open composers+ // keep theirs beside it, and win where they overlap.+ const pendingSelection = canCreate ? selection : undefined;+ const paint = (range: LineRange, className: string) => {for (let line = range.startLine; line <= range.endLine; line++) {- lineClasses.set(- line,- creationRange ? "bb-thread-line--selecting" : "bb-thread-line"- );+ lineClasses.set(line, className);}+ };+ if (activeThread && !pendingSelection) {+ paint(activeThread.range, "bb-thread-line");}+ for (const composer of composers.values()) {+ paint(composer.range, "bb-thread-line--selecting");+ }+ if (pendingSelection) paint(pendingSelection, "bb-thread-line--selecting");for (const [line, className] of [...lineClasses].sort(([a], [b]) => a - b)) {@@ -268,7 +345,7 @@ export function StatementThreadsLayer({},});}- if (actionLine !== undefined && !composerRange) {+ if (actionLine !== undefined && !composers.has(actionLine)) {const actionRange = selection ?? {startLine: actionLine,endLine: actionLine,@@ -290,7 +367,7 @@ export function StatementThreadsLayer({actionLine,canCreate,commentedLines,- composerRange,+ composers,editor,editorThreads,expandedRoots,@@ -303,7 +380,17 @@ export function StatementThreadsLayer({const openComposer = useCallback((range: LineRange) => {- setComposerRange(range);+ setComposers((previous) => {+ const next = new Map(previous);+ const existing = previous.get(range.endLine);+ // The line already has a form: bring it back into view and leave+ // its range alone.+ next.set(range.endLine, {+ range: existing?.range ?? range,+ revealNonce: (existing?.revealNonce ?? 0) + 1,+ });+ return next;+ });// 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,@@ -412,7 +499,7 @@ export function StatementThreadsLayer({const isCreationAction =e.target.type ===monacoModule.editor.MouseTargetType.GUTTER_LINE_DECORATIONS;- if (isCreationAction && actionLine === line && !composerRange) {+ if (isCreationAction && actionLine === line && !composers.has(line)) {e.event.preventDefault();openComposer(selection ?? { startLine: line, endLine: line });return;@@ -448,7 +535,7 @@ export function StatementThreadsLayer({}, [actionLine,canCreate,- composerRange,+ composers,editor,markersByLine,monacoModule,@@ -482,31 +569,54 @@ export function StatementThreadsLayer({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 closeComposer = (line: number) => {+ setComposers((previous) => {+ if (!previous.has(line)) return previous;+ const next = new Map(previous);+ next.delete(line);+ return next;+ });+ setComposerDrafts(({ [line]: _dropped, ...rest }) => rest);+ };++ const updateComposerDraft = (line: number, draft: string) =>+ setComposerDrafts((previous) =>+ previous[line] === draft ? previous : { ...previous, [line]: draft }+ );++ const publish = async (line: number, comment: string) => {+ const range = composers.get(line)?.range;+ if (!range) return;+ const created = await actions.publish(+ comment,+ buildWholeLineAnchor({+ spec: spec.id,+ sheetSha256,+ startLine: range.startLine,+ endLine: range.endLine,+ })+ );+ if (!created) return;+ closeComposer(line);+ openThreads(line, [created.name]);+ };const openEntries: EditorThread[] =openLine !== undefined ? (markersByLine.get(openLine) ?? []) : [];return (<>+ {visitableThreads.length > 0 && !findWidgetVisible && (+ <MonacoOverlayWidget editor={editor}>+ <StatementThreadWalker+ announcement={walkerAnnouncement}+ count={visitableThreads.length}+ onNext={() => walk(1)}+ onPrevious={() => walk(-1)}+ remainder={unplacedUnresolved}+ />+ </MonacoOverlayWidget>+ )}{openLine !== undefined && openEntries.length > 0 && (<MonacoViewZoneafterLineNumber={openLine}@@ -514,11 +624,13 @@ export function StatementThreadsLayer({revealKey={expandedRoots.size > 0 ? expandedRoots : undefined}revealTarget={expandedThreadRef}>- <div className="py-2 pr-2 sm:pr-4">+ <div className="py-2 pr-2"><ThreadStackkey={openLine}expandedRoots={expandedRoots}expandedThreadRef={expandedThreadRef}+ flashRoot={flashRoot}+ onFlashEnd={() => setFlashRoot(undefined)}issueName={issue.name}onCollapse={(rootName) =>openThreads(@@ -535,22 +647,25 @@ export function StatementThreadsLayer({</div></MonacoViewZone>)}- {composerRange && (+ {Array.from(composers, ([line, composer]) => (<MonacoViewZone- afterLineNumber={composerRange.endLine}+ afterLineNumber={line}editor={editor}- revealKey={`${composerRange.startLine}-${composerRange.endLine}`}+ key={line}+ revealKey={composer.revealNonce}>- <div className="py-2 pr-2 sm:pr-4">+ <div className="py-2 pr-2"><InlineThreadComposer- onCancel={() => setComposerRange(undefined)}- onPublish={publish}+ draft={composerDrafts[line] ?? ""}+ onCancel={() => closeComposer(line)}+ onDraftChange={(draft) => updateComposerDraft(line, draft)}+ onPublish={(comment) => publish(line, comment)}pending={actions.pending}- range={composerRange}+ range={composer.range}/></div></MonacoViewZone>- )}+ ))}</>);}diff --git a/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsx b/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsxindex 7eec1d23ea..e850fded22 100644--- a/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsx+++ b/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsx@@ -6,6 +6,7 @@ import { UserAvatar } from "@/components/UserAvatar";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { useUserByIdentifier } from "@/hooks/useAppState";+import { cn } from "@/lib/utils";import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";@@ -51,6 +52,8 @@ function includeNewThreads(export function ThreadStack({expandedRoots,expandedThreadRef,+ flashRoot,+ onFlashEnd,issueName,onCollapse,onExpand,@@ -61,6 +64,9 @@ export function ThreadStack({}: {expandedRoots: ReadonlySet<string>;expandedThreadRef?: Ref<HTMLDivElement>;+ // The thread the walker just landed on; its card flashes once.+ flashRoot?: string;+ onFlashEnd?: () => void;issueName: string;onCollapse: (rootName: string) => void;onExpand: (rootName: string) => void;@@ -116,7 +122,13 @@ export function ThreadStack({>{ordered.map((entry) => (<div+ className={cn(+ flashRoot === entry.thread.root.name && "bb-thread-card--flash"+ )}key={entry.thread.root.name}+ onAnimationEnd={+ flashRoot === entry.thread.root.name ? onFlashEnd : undefined+ }ref={expandedRoots.has(entry.thread.root.name)? expandedThreadRefdiff --git a/frontend/src/routes/project/plan-detail/components/threads/statementThreads.css b/frontend/src/routes/project/plan-detail/components/threads/statementThreads.cssindex 0588672d47..cd5fcce607 100644--- a/frontend/src/routes/project/plan-detail/components/threads/statementThreads.css+++ b/frontend/src/routes/project/plan-detail/components/threads/statementThreads.css@@ -14,19 +14,20 @@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 owns the 24px hit area. Every marker is an 18px tile centered in+ it: the element paints its surface inside a transparent 3px border, the+ icon fills the inner box, and the pseudo-element left over carries the+ thread-count badge. Three weights tell the tiles apart: the creation+ action is a solid accent tile, an open thread an accent tint, a resolved+ thread grey. */.monaco-editor .bb-thread-glyph,.monaco-editor .bb-thread-add-glyph {--bb-thread-background: transparent;box-sizing: border-box;- border: 4px solid transparent;+ border: 3px solid transparent;border-radius: var(--radius-sm);background: var(--bb-thread-background);background-clip: padding-box;- color: rgb(var(--color-control-light));cursor: pointer;}@@ -37,11 +38,13 @@inset: 0;pointer-events: none;background-color: currentColor;- mask: var(--bb-thread-icon) center / 12px 12px no-repeat;+ mask: var(--bb-thread-icon) center / 14px 14px no-repeat;}.monaco-editor .bb-thread-glyph {--bb-thread-icon: url("lucide-static/icons/message-square.svg");+ --bb-thread-background: rgb(var(--color-accent) / 0.14);+ color: rgb(var(--color-accent));}/* Two or more threads on a line: the bubble stays and a filled badge sits on@@ -106,32 +109,65 @@.monaco-editor .bb-thread-glyph--resolved {--bb-thread-icon: url("lucide-static/icons/message-square-check.svg");+ --bb-thread-background: rgb(var(--color-control-bg));+ color: rgb(var(--color-control-light));+}++.monaco-editor .bb-thread-glyph:hover,+.monaco-editor .bb-thread-glyph--active {+ --bb-thread-background: rgb(var(--color-accent) / 0.24);+ color: rgb(var(--color-accent-hover));+}++.monaco-editor .bb-thread-glyph--resolved:hover,+.monaco-editor .bb-thread-glyph--resolved.bb-thread-glyph--active {+ --bb-thread-background: rgb(var(--color-control-bg-hover));+ color: rgb(var(--color-control-hover));+}++/* The creation action is a solid accent tile with a bold plus, the same+ pattern as GitHub's line-hover button: it pops in when its line is hovered+ and darkens under the pointer. Hover changes color only: Monaco re-creates+ the node as the pointer moves, so a size transition never settles. The+ plus is inlined so its stroke can be heavier than the outline icon set. */+@keyframes bb-thread-add-glyph-in {+ from {+ transform: scale(0.6);+ opacity: 0;+ }}-/* 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));+ --bb-thread-icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='3' stroke-linecap='round'%3E%3Cpath d='M5 12h14M12 5v14'/%3E%3C/svg%3E");+ --bb-thread-background: rgb(var(--color-accent));+ color: rgb(var(--color-accent-text));+ animation: bb-thread-add-glyph-in 120ms ease-out;}.monaco-editor .bb-thread-add-glyph:hover {- --bb-thread-background: rgb(var(--color-accent) / 0.12);- color: rgb(var(--color-accent-hover));+ --bb-thread-background: rgb(var(--color-accent-hover));}-.monaco-editor .bb-thread-add-glyph:active {- --bb-thread-background: rgb(var(--color-accent) / 0.18);+/* The walker landed on this card (a React node inside a view zone). */+@keyframes bb-thread-card-flash {+ from {+ box-shadow: 0 0 0 3px rgb(var(--color-accent) / 0.45);+ }+ to {+ box-shadow: 0 0 0 3px rgb(var(--color-accent) / 0);+ }}-.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));+.bb-thread-card--flash {+ border-radius: var(--radius-sm);+ animation: bb-thread-card-flash 1.2s ease-out;}-.monaco-editor .bb-thread-glyph:active {- --bb-thread-background: rgb(var(--color-control-bg-hover));+@media (prefers-reduced-motion: reduce) {+ .monaco-editor .bb-thread-add-glyph,+ .bb-thread-card--flash {+ animation: none;+ }}/* The gutter is the creation affordance; make that discoverable. */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.tsindex 60a00c5031..b0ad3dcc9e 100644--- a/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.ts+++ b/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.ts@@ -16,6 +16,8 @@ import { current, OUTDATED, UNAVAILABLE } from "./placement/place";import {anchorLineRange,buildWholeLineAnchor,+ countPlacedUnresolvedBySpec,+ countUnresolvedThreads,defaultExpandedThread,excerptLines,formatLineRange,@@ -92,6 +94,41 @@ describe("sheetSha256OfName", () => {});});+describe("countUnresolvedThreads", () => {+ test("counts open roots, anchored or not, and never replies", () => {+ const threads = groupThreads([+ root("a", { anchor: anchor(1, 1) }),+ root("b", { anchor: anchor(2, 2, OTHER_SHA) }),+ root("c", { anchor: anchor(3, 3), resolved: true }),+ root("d"),+ reply("r", "a", 2),+ ]);+ expect(countUnresolvedThreads(threads)).toBe(3);+ expect(countUnresolvedThreads([])).toBe(0);+ });++ test("placed counts follow each spec's current sheet and its placements", () => {+ const threads = groupThreads([+ root("current", { anchor: anchor(1, 1) }),+ root("outdated", { anchor: anchor(2, 2, OTHER_SHA) }),+ root("resolved", { anchor: anchor(3, 3), resolved: true }),+ ]);+ const specs = plan().specs;+ expect([+ ...countPlacedUnresolvedBySpec(threads, specs, () => undefined),+ ]).toEqual([["spec-1", 1]]);+ const placed = new Map([+ [`${ISSUE}/issueComments/outdated`, current(4, 4)],+ ]);+ expect([+ ...countPlacedUnresolvedBySpec(threads, specs, () => placed),+ ]).toEqual([["spec-1", 2]]);+ expect(countPlacedUnresolvedBySpec(threads, [], () => undefined).size).toBe(+ 0+ );+ });+});+describe("groupThreads", () => {test("groups replies under their root, oldest first, and skips general comments", () => {const general = create(IssueCommentSchema, {diff --git a/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts b/frontend/src/routes/project/plan-detail/components/threads/threadModel.tsindex 31fed1c54f..f2d9b1e338 100644--- a/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts+++ b/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts@@ -81,6 +81,34 @@ export function groupThreads(comments: IssueComment[]): CommentThread[] {}));}+export const countUnresolvedThreads = (threads: CommentThread[]): number =>+ threads.filter((thread) => !thread.resolved).length;++// Unresolved threads placed on each spec's current sheet: the number the+// statement editor shows for that change. Specs without a placed thread+// have no entry.+export function countPlacedUnresolvedBySpec(+ threads: CommentThread[],+ specs: Plan_Spec[],+ placementsFor: (+ specId: string,+ sheetSha256: string+ ) => ReadonlyMap<string, Placement> | undefined+): ReadonlyMap<string, number> {+ const counts = new Map<string, number>();+ for (const spec of specs) {+ const sheetSha256 = targetSha256OfSpec(spec);+ if (!sheetSha256) continue;+ const placed = selectUnresolvedEditorThreads(+ threads,+ { specId: spec.id, sheetSha256 },+ placementsFor(spec.id, sheetSha256)+ ).length;+ if (placed > 0) counts.set(spec.id, placed);+ }+ return counts;+}+// 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.@@ -187,6 +215,13 @@ export function selectEditorThreads(return placed.sort(compareEditorThreads);}+// The placed threads still open: what the editor walker visits and what the+// change tab counts.+export const selectUnresolvedEditorThreads = (+ ...args: Parameters<typeof selectEditorThreads>+): EditorThread[] =>+ selectEditorThreads(...args).filter((entry) => !entry.thread.resolved);+// Only the unresolved thread anchored on the earliest line expands by// default; every other thread is a gutter marker.export function defaultExpandedThread(diff --git a/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.ts b/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.tsnew file mode 100644index 0000000000..f90eed6655--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.ts@@ -0,0 +1,44 @@+import { useMemo } from "react";+import { useAppStore } from "@/stores/app";+import type { IssueComment } 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 {+ countPlacedUnresolvedBySpec,+ countUnresolvedThreads,+ groupThreads,+} from "./threadModel";++const NO_COMMENTS: IssueComment[] = [];++const useIssueThreads = (issueName: string | undefined) => {+ const comments = useAppStore((state) =>+ issueName ? state.getIssueComments(issueName) : NO_COMMENTS+ );+ return useMemo(() => groupThreads(comments), [comments]);+};++// Every unresolved thread on the issue; zero before an issue exists.+export function useUnresolvedThreadTotal(issueName: string | undefined) {+ const threads = useIssueThreads(issueName);+ return useMemo(() => countUnresolvedThreads(threads), [threads]);+}++// Unresolved threads the statement editor shows for each of `specs`, so a+// change tab and its editor walker agree.+export function usePlacedUnresolvedThreadCounts(+ issueName: string | undefined,+ specs: Plan_Spec[]+): ReadonlyMap<string, number> {+ const threads = useIssueThreads(issueName);+ const placements = usePlanDetailStore((s) => s.placements);+ const placementTargets = usePlanDetailStore((s) => s.placementTargets);+ return useMemo(+ () =>+ countPlacedUnresolvedBySpec(threads, specs, (specId, sha) =>+ placementsForSheet({ placements, placementTargets }, specId, sha)+ ),+ [placementTargets, placements, specs, threads]+ );+}diff --git a/frontend/src/routes/project/plan-detail/utils/phaseSummary.test.ts b/frontend/src/routes/project/plan-detail/utils/phaseSummary.test.tsindex 37f6addf24..b00fc69dd0 100644--- a/frontend/src/routes/project/plan-detail/utils/phaseSummary.test.ts+++ b/frontend/src/routes/project/plan-detail/utils/phaseSummary.test.ts@@ -26,6 +26,7 @@ const templates: Record<string, string> = {"plan.summary.n-of-m-approved": "{{n}} of {{m}} approved","plan.summary.n-of-m-tasks": "{{n}}/{{m}} tasks","plan.summary.n-passed": "{{n}} passed",+ "plan.summary.n-unresolved-threads": "{{count}} unresolved threads","plan.summary.n-warning": "{{n}} warning",};@@ -89,6 +90,18 @@ describe("plan detail phase summaries", () => {);});+ test("appends the unresolved thread count only when there are any", () => {+ const issue = {+ approvalTemplate: { flow: { roles: ["roles/PROJECT_OWNER"] } },+ approvers: [],+ } as unknown as Issue;++ expect(buildReviewSummary(issue, t, 0)).toBe("0 of 1 approved");+ expect(buildReviewSummary(issue, t, 3)).toBe(+ "0 of 1 approved · 3 unresolved threads"+ );+ });+test("summarizes deploy task progress", () => {const rollout = {stages: [diff --git a/frontend/src/routes/project/plan-detail/utils/phaseSummary.ts b/frontend/src/routes/project/plan-detail/utils/phaseSummary.tsindex 94011fd9d0..1c1571c39f 100644--- a/frontend/src/routes/project/plan-detail/utils/phaseSummary.ts+++ b/frontend/src/routes/project/plan-detail/utils/phaseSummary.ts@@ -134,7 +134,11 @@ export const buildChangesSummary = (plan: Plan, t: T): string => {return parts.join(" · ");};-export const buildReviewSummary = (issue: Issue | undefined, t: T): string => {+export const buildReviewSummary = (+ issue: Issue | undefined,+ t: T,+ unresolvedThreads = 0+): string => {if (!issue) return "";const roles = issue.approvalTemplate?.flow?.roles ?? [];@@ -156,6 +160,12 @@ export const buildReviewSummary = (issue: Issue | undefined, t: T): string => {parts.push(t("plan.summary.last-approved-by", { name }));}+ if (unresolvedThreads > 0) {+ parts.push(+ t("plan.summary.n-unresolved-threads", { count: unresolvedThreads })+ );+ }+return parts.join(" · ");};diff --git a/frontend/tests/e2e/README.md b/frontend/tests/e2e/README.mdindex bfcbc05a2d..283c70104b 100644--- a/frontend/tests/e2e/README.md+++ b/frontend/tests/e2e/README.md@@ -132,4 +132,6 @@ frontend/tests/e2e/| Server won't start / port in use | `lsof -ti:18234 \| xargs kill` and check for orphan processes matching `bytebase-e2e` || Stale PID file | `rm /tmp/bytebase-e2e-pid` || Stale auth state | `rm -rf frontend/.auth/ frontend/tests/.auth/` |+| `postmaster became multithreaded during startup` (macOS) | The shell has no valid UTF-8 `LANG`; the harness defaults one, so export `LANG=en_US.UTF-8` only when running the binary by hand |+| `token signature is invalid` on license install | The license is signed with the production key: build with `-tags embed_frontend,release` || "This Bytebase build does not bundle frontend" error | Binary was built without `embed_frontend` tag — rebuild with the prerequisite commands above |diff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.tsindex d71dcbee05..8eccb7cc7e 100644--- a/frontend/tests/e2e/framework/api-client.ts+++ b/frontend/tests/e2e/framework/api-client.ts@@ -669,6 +669,20 @@ export class BytebaseApiClient {);}+ // Resolve or reopen a thread root through the thread_state field mask.+ // UpdateIssueComment is bound to the issue's :comment path with the comment+ // as the body, like CreateIssueComment.+ async setIssueCommentThreadState(+ commentName: string,+ threadState: "OPEN" | "RESOLVED",+ ): Promise<void> {+ const issueName = commentName.replace(/\/issueComments\/[^/]+$/, "");+ await this.request(+ "PATCH", `/v1/${issueName}:comment?updateMask=thread_state`,+ { name: commentName, threadState },+ );+ }+// `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.diff --git a/frontend/tests/e2e/framework/mode-start-new-bytebase.ts b/frontend/tests/e2e/framework/mode-start-new-bytebase.tsindex b5c7b6bfb1..ad72ecb9cc 100644--- a/frontend/tests/e2e/framework/mode-start-new-bytebase.ts+++ b/frontend/tests/e2e/framework/mode-start-new-bytebase.ts@@ -199,7 +199,10 @@ export async function startServer(): Promise<{{detached: true,stdio: "ignore",- env: { ...process.env, PG_URL: "" },+ // The embedded Postgres needs a valid UTF-8 locale: without LANG,+ // initdb rejects the locale and Postgres 17 on macOS then fails with+ // "postmaster became multithreaded during startup".+ env: { LANG: "en_US.UTF-8", ...process.env, PG_URL: "" },});diff --git a/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-review.spec.tsindex 9c722ac8d2..f990d0feee 100644--- a/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts@@ -481,8 +481,10 @@ test.describe("Inline comment threads (CUJ K)", () => {const timelineCard = planPage.threadCardIn("review", seededRoot);await expect(timelineCard).toBeVisible();await expect(timelineCard).toContainText(seededReply);+ // The recorded statement downloads once the card nears the viewport.+ await timelineCard.scrollIntoViewIfNeeded();const anchor = timelineCard.getByTestId("statement-anchor");- await expect(anchor).toHaveAttribute("data-anchor-state", "CURRENT");+ await expect(anchor).toHaveAttribute("data-anchor-state", "CURRENT", { timeout: 15_000 });await expect(anchor).toContainText("Lines 2–3");await expect(anchor).toContainText("e2e_rev_k2_");await expect(anchor.getByRole("button", { name: "View in Statement" })).toBeVisible();@@ -499,8 +501,7 @@ test.describe("Inline comment threads (CUJ K)", () => {// 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 planPage.clickAddThreadGlyph();await expect(planPage.inlineComposer).toBeVisible();await expect(planPage.inlineComposer).toContainText("Add a comment on line 1");await planPage.inlineComposerEditor.fill(createdRoot);@@ -516,7 +517,9 @@ test.describe("Inline comment threads (CUJ K)", () => {.getByTestId("statement-anchor");await expect(createdAnchor).toBeVisible({ timeout: 15_000 });await expect(createdAnchor).toContainText("Line 1");- await expect(createdAnchor).toContainText("e2e_rev_k1_");+ // The recorded statement downloads once the card nears the viewport.+ await createdAnchor.scrollIntoViewIfNeeded();+ await expect(createdAnchor).toContainText("e2e_rev_k1_", { timeout: 15_000 });const timelineCard = planPage.threadCardIn("review", seededRoot);await timelineCard.scrollIntoViewIfNeeded();@@ -836,3 +839,400 @@ test.describe("Long approval flow adaptive rendering (CUJ I)", () => {await expect(page.getByText("2 pending")).toBeHidden();});});++// Inline comment threads, second pass: several composers at once, the+// reply composer's thread-state checkbox, the editor walker, and the+// unresolved counts on the change tab and the Review summary.+test.describe("Inline comment threads: composers, checkbox, walker, counts (CUJ L)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;+ let issueName: string;+ let specId: string;+ let sheetSha256: string;+ const stamp = Date.now();+ const rootA = `L root A line 2 ${stamp}`;+ const rootB = `L root B lines 4-5 ${stamp}`;+ const rootResolved = `L resolved root line 6 ${stamp}`;+ const rootStale = `L stale root ${stamp}`;+ const draftOne = `L draft one ${stamp}`;+ const draftThree = `L draft three ${stamp}`;+ const replyResolving = `L resolving reply ${stamp}`;+ const replyReopening = `L reopening reply ${stamp}`;++ // The phase summary line renders only while the section is collapsed.+ const expectReviewSummary = async (text: string | RegExp) => {+ await planPage.setPhaseExpanded("review", false);+ await expect(planPage.reviewPhase).toContainText(text, { timeout: 15_000 });+ await planPage.setPhaseExpanded("review", true);+ };++ test.beforeAll(async () => {+ await setupApproval(ONE_STEP_RULE);+ const seeded = await seedReviewPlan(env, page, {+ prefix: "E2E Review L",+ sql: [1, 2, 3, 4, 5, 6]+ .map((n) => `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_l${n}_${stamp} TEXT;`)+ .join("\n"),+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;+ issueName = seeded.issueName;+ 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 anchor = (startLine: number, endLine: number, sha = sheetSha256) => ({+ statementAnchor: { spec: specId, sheetSha256: sha, startLine, endLine },+ });+ await env.api.createIssueComment(issueName, rootA, anchor(2, 2));+ await env.api.createIssueComment(issueName, rootB, anchor(4, 5));+ const resolved = await env.api.createIssueComment(issueName, rootResolved, anchor(6, 6));+ await env.api.setIssueCommentThreadState(resolved.name, "RESOLVED");+ // Anchored to an earlier statement of this change whose line has no+ // counterpart in the displayed one: unresolved, but not placed here.+ const staleSheet = await env.api.createSheet(env.project, "SELECT 1;\n");+ const staleSha256 = staleSheet.split("/").pop() ?? "";+ expect(staleSha256).toMatch(/^[0-9a-f]{64}$/);+ await env.api.createIssueComment(issueName, rootStale, anchor(1, 1, staleSha256));+ await goReview(planId);+ await planPage.expandSection("Changes");+ });++ test("the change tab counts placed unresolved threads; the Review summary counts all of them", async () => {+ // Placed and unresolved: A and B. The resolved thread and the stale one+ // stay out of the tab and the walker; the stale one still counts for+ // the plan-wide summary.+ await expect(planPage.specUnresolvedCounts).toHaveCount(1, { timeout: 15_000 });+ await expect(planPage.specUnresolvedCounts).toHaveText("2");+ await expectReviewSummary("3 unresolved threads");+ await expect(planPage.threadWalker).toContainText("2");+ await expect(planPage.threadWalker).toHaveAttribute(+ "title",+ "2 unresolved threads on this version · 1 more not shown on this version",+ );+ // Markers: A, B, and the resolved one; the stale thread has none.+ await expect(planPage.threadMarkers).toHaveCount(3);+ });++ test("the walker steps through unresolved threads in editor order and wraps", async () => {+ // The first unresolved thread opens by default.+ await expect(planPage.threadCardIn("changes", rootA)).toBeVisible();+ await planPage.threadWalkerNext.click();+ await expect(planPage.threadCardIn("changes", rootB)).toBeVisible({ timeout: 10_000 });+ await expect(planPage.threadCardIn("changes", rootA)).not.toBeVisible();+ await planPage.threadWalkerNext.click();+ await expect(planPage.threadCardIn("changes", rootA)).toBeVisible({ timeout: 10_000 });+ await planPage.threadWalkerPrevious.click();+ await expect(planPage.threadCardIn("changes", rootB)).toBeVisible({ timeout: 10_000 });+ // The resolved thread is never a stop.+ await expect(planPage.threadCardIn("changes", rootResolved)).not.toBeVisible();+ });++ test("several composers stay open with their own drafts, and each closes on its own", async () => {+ const first = await planPage.openInlineComposerOn(1);+ const firstEditor = first.locator("textarea");+ const firstPublish = first.getByRole("button", { name: "Publish", exact: true });+ await expect(firstPublish).toBeDisabled();+ await firstEditor.fill(draftOne);+ await expect(firstPublish).toBeEnabled();++ // The add tile is gone on a line that already carries a form.+ await planPage.hoverStatementLine(1);+ await expect(planPage.addThreadGlyph).toHaveCount(0);++ const third = await planPage.openInlineComposerOn(3);+ await expect(planPage.inlineComposer).toHaveCount(2);+ await third.locator("textarea").fill(draftThree);+ await expect(firstEditor).toHaveValue(draftOne);++ // Cancel closes only the form it belongs to.+ await third.getByRole("button", { name: "Cancel" }).click();+ await expect(planPage.inlineComposer).toHaveCount(1);+ await expect(firstEditor).toHaveValue(draftOne);++ // Publishing the remaining form creates its thread and opens it.+ await firstPublish.click();+ await expect(planPage.inlineComposer).toHaveCount(0, { timeout: 15_000 });+ await expect(planPage.threadCardIn("changes", draftOne)).toBeVisible();+ await expect(planPage.threadMarkers).toHaveCount(4);+ await expect(planPage.specUnresolvedCounts).toHaveText("3");+ await expect(planPage.threadWalker).toContainText("3");+ await expect(planPage.threadCardIn("review", draftOne)).toBeVisible({ timeout: 15_000 });+ });++ test("the reply composer's checkbox resolves with the reply and reopens again", async () => {+ const card = planPage.threadCardIn("review", rootA);+ await card.scrollIntoViewIfNeeded();+ await card.getByRole("button", { name: "Reply..." }).click();+ const reply = card.getByRole("button", { name: "Reply", exact: true });+ const editor = card.locator("textarea[placeholder='Reply...']");+ await expect(reply).toBeDisabled();++ // An open thread offers Resolve thread, unchecked.+ const resolveBox = planPage.threadStateCheckbox(card, "Resolve thread");+ await expect(resolveBox).toHaveAttribute("aria-checked", "false");+ await editor.fill(replyResolving);+ await resolveBox.click();+ await expect(resolveBox).toHaveAttribute("aria-checked", "true");+ await reply.click();++ const resolvedCard = planPage.threadCardIn("review", rootA);+ await expect(resolvedCard).toHaveAttribute("data-thread-state", "resolved", { timeout: 15_000 });+ await expect(resolvedCard).toContainText("1 reply");+ // The counts follow: A left the placed-unresolved set.+ await expect(planPage.specUnresolvedCounts).toHaveText("2");+ await expect(planPage.threadWalker).toContainText("2");+ await expectReviewSummary("3 unresolved threads");++ // Expand and reply again: a resolved thread offers Reopen thread,+ // checked by default, so an untouched reply reopens it.+ await resolvedCard.getByRole("button", { name: /Resolved/ }).click();+ await expect(resolvedCard).toContainText(replyResolving);+ await resolvedCard.getByRole("button", { name: "Reply..." }).click();+ const reopenBox = planPage.threadStateCheckbox(resolvedCard, "Reopen thread");+ await expect(reopenBox).toHaveAttribute("aria-checked", "true");+ await resolvedCard.locator("textarea[placeholder='Reply...']").fill(replyReopening);+ await resolvedCard.getByRole("button", { name: "Reply", exact: true }).click();+ const reopenedCard = planPage.threadCardIn("review", rootA);+ await expect(reopenedCard).toHaveAttribute("data-thread-state", "open", { timeout: 15_000 });+ await expect(reopenedCard).toContainText(replyReopening);+ await expect(planPage.specUnresolvedCounts).toHaveText("3");++ // Unticking it keeps the thread resolved.+ await reopenedCard.getByRole("button", { name: "Resolve", exact: true }).click();+ await expect(reopenedCard).toHaveAttribute("data-thread-state", "resolved", { timeout: 15_000 });+ await reopenedCard.getByRole("button", { name: /Resolved/ }).click();+ await reopenedCard.getByRole("button", { name: "Reply..." }).click();+ await planPage.threadStateCheckbox(reopenedCard, "Reopen thread").click();+ await reopenedCard.locator("textarea[placeholder='Reply...']").fill(`${replyReopening} still`);+ await reopenedCard.getByRole("button", { name: "Reply", exact: true }).click();+ await expect(reopenedCard).toContainText(`${replyReopening} still`, { timeout: 15_000 });+ await expect(reopenedCard).toHaveAttribute("data-thread-state", "resolved");+ await expect(planPage.specUnresolvedCounts).toHaveText("2");++ // Leave A open for the next journey.+ await reopenedCard.getByRole("button", { name: "Reopen", exact: true }).click();+ await expect(planPage.threadCardIn("review", rootA)).toHaveAttribute("data-thread-state", "open", {+ timeout: 15_000,+ });+ await expect(planPage.specUnresolvedCounts).toHaveText("3");+ });++ test("resolving every placed thread removes the walker and the tab count, and reopening restores them", async () => {+ for (const rootText of [rootA, rootB, draftOne]) {+ const card = planPage.threadCardIn("review", rootText);+ await card.scrollIntoViewIfNeeded();+ await card.getByRole("button", { name: "Resolve", exact: true }).click();+ await expect(card).toHaveAttribute("data-thread-state", "resolved", { timeout: 15_000 });+ }+ await expect(planPage.threadWalker).toHaveCount(0);+ await expect(planPage.specUnresolvedCounts).toHaveCount(0);+ // Only the stale thread remains open.+ await expectReviewSummary(/1 unresolved thread(?!s)/);++ const card = planPage.threadCardIn("review", rootB);+ await card.getByRole("button", { name: /Resolved/ }).click();+ await card.getByRole("button", { name: "Reopen", exact: true }).click();+ await expect(planPage.threadWalker).toContainText("1", { timeout: 15_000 });+ await expect(planPage.specUnresolvedCounts).toHaveText("1");+ await expectReviewSummary("2 unresolved threads");+ });+});++// A reader who may reply but not resolve sees neither the standalone+// Resolve action nor the reply composer's state checkbox. No predefined role+// separates the two comment permissions, so the test provisions its own.+test.describe("Inline comment threads as a reply-only reader (CUJ L, restricted)", () => {+ const stamp = Date.now();+ const readerEmail = `e2e-reply-only-${stamp}@example.com`;+ const readerPassword = "12345678";+ const readerAuthFile = ".auth/plan-reply-only.json";+ const roleId = `e2e-reply-only-${stamp}`;+ let roleName = "";+ let readerContext: BrowserContext | undefined;+ let readerPlanPage: PlanDetailPage;+ let planId: string;+ const rootText = `L restricted root ${stamp}`;++ test.beforeAll(async ({ browser }) => {+ await setupApproval(ONE_STEP_RULE);+ const seeded = await seedReviewPlan(env, page, {+ prefix: "E2E Review L restricted",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_lr_${stamp} TEXT;`,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;+ const plan = await env.api.getPlan(seeded.planName);+ const spec = plan.specs?.[0];+ const sheetSha256 = spec?.changeDatabaseConfig?.sheet?.split("/").pop() ?? "";+ await env.api.createIssueComment(seeded.issueName, rootText, {+ statementAnchor: { spec: spec?.id ?? "", sheetSha256, startLine: 1, endLine: 1 },+ });++ // The viewer role plus what the plan page needs, minus comment update.+ const role = await env.api.createRole(roleId, "E2E reply-only reader", [+ "bb.projects.get",+ "bb.projects.getIamPolicy",+ "bb.databases.get",+ "bb.databases.list",+ "bb.databases.getSchema",+ "bb.instances.get",+ "bb.plans.get",+ "bb.plans.list",+ "bb.planCheckRuns.get",+ "bb.taskRuns.list",+ "bb.rollouts.get",+ "bb.rollouts.list",+ "bb.sheets.get",+ "bb.issues.get",+ "bb.issues.list",+ "bb.issueComments.list",+ "bb.issueComments.create",+ ]);+ roleName = role.name;+ await env.api.createUser(readerEmail, readerPassword, "E2E reply-only reader");+ await env.api.appendProjectBinding(env.project, roleName, [`user:${readerEmail}`]);+ await signInBrowserAs(browser, env.baseURL, readerEmail, readerPassword, readerAuthFile);+ readerContext = await browser.newContext({ storageState: readerAuthFile });+ readerPlanPage = new PlanDetailPage(await readerContext.newPage(), env.baseURL);+ });++ // DeleteRole refuses a role a binding still references, so drop the+ // binding and the reader first; the throwaway workspace must not carry+ // this role or user into later suites.+ test.afterAll(async () => {+ await readerContext?.close();+ if (roleName) {+ const policy = await env.api.getProjectIamPolicy(env.project);+ policy.bindings = policy.bindings.filter((binding) => binding.role !== roleName);+ await env.api.setProjectIamPolicy(env.project, policy);+ }+ await env.api.deleteUser(readerEmail).catch(() => {});+ if (roleName) await env.api.deleteRole(roleName);+ });++ test("the reader can reply but sees no Resolve action and no state checkbox", async () => {+ await readerPlanPage.goto(projectId, planId);+ await readerPlanPage.dismissModals();+ await readerPlanPage.expandSection("Review");+ const card = readerPlanPage.threadCardIn("review", rootText);+ await expect(card).toBeVisible({ timeout: 15_000 });+ await expect(card.getByRole("button", { name: "Resolve", exact: true })).toHaveCount(0);+ await card.getByRole("button", { name: "Reply..." }).click();+ await expect(card.getByRole("checkbox")).toHaveCount(0);+ await expect(card.getByRole("button", { name: "Reply", exact: true })).toBeDisabled();+ });+});++// Inline comment threads, third pass: a range selected from the gutter, two+// threads sharing one marker, the walker's announcement and its retreat+// behind the find widget, and a narrow viewport.+test.describe("Inline comment threads: ranges, shared markers, walker details, narrow view (CUJ M)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;+ let issueName: string;+ let specId: string;+ let sheetSha256: string;+ let laterRootName = "";+ const stamp = Date.now();+ const earlierRoot = `M earlier root lines 4-5 ${stamp}`;+ const laterRoot = `M later root line 5 ${stamp}`;+ const rangeRoot = `M range root lines 2-3 ${stamp}`;++ test.beforeAll(async () => {+ await setupApproval(ONE_STEP_RULE);+ const seeded = await seedReviewPlan(env, page, {+ prefix: "E2E Review M",+ sql: [1, 2, 3, 4, 5, 6]+ .map((n) => `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_m${n}_${stamp} TEXT;`)+ .join("\n"),+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;+ issueName = seeded.issueName;+ 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 anchor = (startLine: number, endLine: number) => ({+ statementAnchor: { spec: specId, sheetSha256, startLine, endLine },+ });+ // Both end on line 5, so they share its marker.+ await env.api.createIssueComment(issueName, earlierRoot, anchor(4, 5));+ const later = await env.api.createIssueComment(issueName, laterRoot, anchor(5, 5));+ laterRootName = later.name;+ await goReview(planId);+ await planPage.expandSection("Changes");+ });++ test.afterAll(async () => {+ await page?.setViewportSize({ width: 1280, height: 720 }).catch(() => {});+ });++ test("dragging across line numbers starts a thread on that range", async () => {+ await planPage.selectStatementLines(2, 3);+ await planPage.clickAddThreadGlyph();+ const composer = planPage.inlineComposer;+ await expect(composer).toBeVisible();+ await expect(composer).toContainText("Add a comment on lines 2 to 3");+ await planPage.inlineComposerEditor.fill(rangeRoot);+ await planPage.inlineComposerPublishButton.click();+ await expect(composer).not.toBeVisible({ timeout: 15_000 });+ await expect(planPage.threadCardIn("changes", rangeRoot)).toBeVisible();+ // One marker on line 3 for the new thread, one shared marker on line 5.+ await expect(planPage.threadMarkers).toHaveCount(2);+ const anchorContext = planPage.threadCardIn("review", rangeRoot).getByTestId("statement-anchor");+ await anchorContext.scrollIntoViewIfNeeded();+ await expect(anchorContext).toContainText("Lines 2–3", { timeout: 15_000 });+ await expect(anchorContext).toContainText(`e2e_rev_m2_${stamp}`);+ });++ test("two threads ending on one line share a counted marker, and the stack expands either one", async () => {+ const shared = planPage.statementEditor.locator(".bb-thread-glyph--count-2");+ await expect(shared).toHaveCount(1);+ await shared.click();+ // The earliest unresolved thread expands; the other waits as a row.+ await expect(planPage.threadCardIn("changes", earlierRoot)).toBeVisible();+ const laterRow = planPage.collapsedThreadRow(laterRootName);+ await expect(laterRow).toBeVisible();+ await expect(laterRow).toContainText(laterRoot);+ await laterRow.click();+ await expect(planPage.threadCardIn("changes", laterRoot)).toBeVisible();+ await expect(planPage.threadCardIn("changes", earlierRoot)).not.toBeVisible();+ });++ test("the walker announces its position and yields the corner to the find widget", async () => {+ await expect(planPage.threadWalker).toContainText("3");+ await planPage.threadWalkerNext.click();+ await expect(planPage.threadWalkerAnnouncement).toHaveText(/^Thread [1-3] of 3$/);+ // Monaco's find widget takes the corner while it is open. Focus the+ // editor through its input, since open thread cards cover the lines.+ await planPage.statementEditor.locator("textarea.inputarea").focus();+ await page.keyboard.press("Control+f");+ await expect(planPage.statementEditor.locator(".find-widget.visible")).toBeVisible();+ await expect(planPage.threadWalker).toHaveCount(0);+ await page.keyboard.press("Escape");+ await expect(planPage.threadWalker).toBeVisible({ timeout: 5_000 });+ });++ test("a narrow viewport keeps the walker inside the editor's top-right corner and composers usable", async () => {+ await page.setViewportSize({ width: 480, height: 1200 });+ await expect(planPage.threadWalker).toBeVisible({ timeout: 10_000 });+ const editorBox = await planPage.statementEditor.boundingBox();+ const walkerBox = await planPage.threadWalker.boundingBox();+ expect(editorBox && walkerBox).toBeTruthy();+ if (editorBox && walkerBox) {+ expect(walkerBox.x + walkerBox.width).toBeLessThanOrEqual(editorBox.x + editorBox.width);+ expect(walkerBox.y).toBeGreaterThanOrEqual(editorBox.y);+ expect(walkerBox.y - editorBox.y).toBeLessThan(40);+ }+ const composer = await planPage.openInlineComposerOn(1);+ await expect(composer.getByRole("button", { name: "Publish", exact: true })).toBeDisabled();+ await composer.getByRole("button", { name: "Cancel" }).click();+ await expect(planPage.inlineComposer).toHaveCount(0);+ });+});diff --git a/frontend/tests/e2e/plan-detail/plan-detail.page.ts b/frontend/tests/e2e/plan-detail/plan-detail.page.tsindex eaa2cf3183..55969abe24 100644--- a/frontend/tests/e2e/plan-detail/plan-detail.page.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail.page.ts@@ -40,6 +40,16 @@ export class PlanDetailPage {readonly inlineComposer: Locator;readonly inlineComposerEditor: Locator;readonly inlineComposerPublishButton: Locator;+ // The unresolved-thread walker pinned to the editor's top-right corner.+ readonly threadWalker: Locator;+ readonly threadWalkerNext: Locator;+ readonly threadWalkerPrevious: Locator;+ // The walker's polite live region ("Thread 2 of 3").+ readonly threadWalkerAnnouncement: Locator;+ // Per-change unresolved counts on the Changes tab strip.+ readonly specUnresolvedCounts: Locator;+ // The Review phase block, whose summary line carries the plan-wide count.+ readonly reviewPhase: Locator;// --- Header lifecycle slot (PlanDetailHeader, BYT-9722) ---// The sticky title/action row. Scope every header-slot assertion to this so a@@ -94,6 +104,18 @@ export class PlanDetailPage {name: "Publish",exact: true,});+ this.threadWalker = this.statementEditor.getByTestId("thread-walker");+ this.threadWalkerNext = this.threadWalker.getByRole("button", {+ name: "Next unresolved thread",+ });+ this.threadWalkerPrevious = this.threadWalker.getByRole("button", {+ name: "Previous unresolved thread",+ });+ this.threadWalkerAnnouncement = this.threadWalker.locator("[aria-live]");+ this.specUnresolvedCounts = page+ .locator("#plan-phase-changes")+ .getByTestId("spec-unresolved-threads");+ this.reviewPhase = page.locator("#plan-phase-review");// 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@@ -306,14 +328,103 @@ export class PlanDetailPage {.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+ // The inline composer anchored to one line, by its heading.+ inlineComposerOn(lineNumber: number): Locator {+ return this.inlineComposer.filter({+ hasText: `Add a comment on line ${lineNumber}`,+ });+ }++ // Start a thread from the gutter of one line: hover it, click the add tile.+ async openInlineComposerOn(lineNumber: number): Promise<Locator> {+ await this.hoverStatementLine(lineNumber);+ await this.clickAddThreadGlyph();+ const composer = this.inlineComposerOn(lineNumber);+ await expect(composer).toBeVisible();+ return composer;+ }++ // The reply composer's thread-state checkbox inside a thread card. It names+ // the action for the current state: "Resolve thread" on an open thread,+ // "Reopen thread" (checked by default) on a resolved one.+ threadStateCheckbox(card: Locator, label: "Resolve thread" | "Reopen thread"): Locator {+ return card.getByRole("checkbox", { name: label });+ }++ // Collapse or expand a phase block by its anchor id, which is unambiguous+ // where the section's label text is not (the header has a "Review" action).+ async setPhaseExpanded(phase: "changes" | "review" | "deploy", expanded: boolean): Promise<void> {+ const block = this.page.locator(`#plan-phase-${phase}`);+ const toggle = block.getByText(expanded ? "Show details" : "Hide details", { exact: true });+ if (!(await toggle.isVisible({ timeout: 1000 }).catch(() => false))) return;+ await toggle.click();+ await expect(+ block.getByText(expanded ? "Hide details" : "Show details", { exact: true }),+ ).toBeVisible({ timeout: 5_000 });+ }++ // Click the add-thread tile by its coordinates. Monaco re-creates the tile+ // as the pointer moves and it animates in, so Playwright's actionability+ // retries never settle on it; a plain pointer click does.+ async clickAddThreadGlyph(): Promise<void> {+ await expect(this.addThreadGlyph).toBeVisible({ timeout: 5_000 });+ const box = await this.addThreadGlyph.boundingBox();+ if (!box) throw new Error("add-thread tile has no box");+ await this.page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);+ }++ // A line's number cell in the statement editor's gutter.+ statementLineNumber(lineNumber: number): Locator {+ return this.statementEditor.locator(".margin-view-overlays .line-numbers", {hasText: new RegExp(`^${lineNumber}$`),})- .first()- .hover();+ .first();+ }++ // A collapsed thread row in the editor's open line stack, by root name.+ collapsedThreadRow(rootName: string): Locator {+ return this.page.locator(+ `#plan-phase-changes [data-testid='thread-row'][data-thread-name='${rootName}']`,+ );+ }++ // Scroll the editor clear of the sticky page header, which otherwise+ // intercepts pointer actions on its top lines. The dashboard body, not the+ // window, owns the page scroll, so walk up to the nearest scrolling+ // ancestor.+ private async scrollEditorClearOfHeader(): Promise<void> {+ await this.statementEditor.evaluate((node) => {+ const top = node.getBoundingClientRect().top;+ if (top >= 96) return;+ let owner: HTMLElement | null = node.parentElement;+ while (owner) {+ const overflowY = getComputedStyle(owner).overflowY;+ if ((overflowY === "auto" || overflowY === "scroll") && owner.scrollHeight > owner.clientHeight) break;+ owner = owner.parentElement;+ }+ (owner ?? window).scrollBy({ top: top - 96 });+ });+ }++ // 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.scrollEditorClearOfHeader();+ await this.statementLineNumber(lineNumber).hover();+ }++ // Drag across line numbers to select a range; the add-thread glyph then+ // sits on the last selected line.+ async selectStatementLines(from: number, to: number): Promise<void> {+ await this.scrollEditorClearOfHeader();+ const start = await this.statementLineNumber(from).boundingBox();+ const end = await this.statementLineNumber(to).boundingBox();+ if (!start || !end) throw new Error(`line numbers ${from}-${to} not rendered`);+ const mouse = this.page.mouse;+ await mouse.move(start.x + start.width / 2, start.y + start.height / 2);+ await mouse.down();+ await mouse.move(end.x + end.width / 2, end.y + end.height / 2, { steps: 4 });+ await mouse.up();}}