Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor(plan-detail): redesign the deploy section as inline stage cards (#20785)
boojack7bb031417398
diff --git a/frontend/scripts/check-react-i18n.mjs b/frontend/scripts/check-react-i18n.mjsindex 7bbee20535..52d1a6d221 100644--- a/frontend/scripts/check-react-i18n.mjs+++ b/frontend/scripts/check-react-i18n.mjs@@ -80,9 +80,15 @@ const DYNAMIC_PREFIXES = [// - sheet.{mine,shared} — src/views/sql-editor/Sheet/context.ts"sheet.mine","sheet.shared",- // - task.status.available / .not-started — src/utils/v1/issue/rollout.ts+ // - task.status.* — stringifyTaskStatus / stringifyTaskRunStatus+ // (src/utils/v1/issue/rollout.ts); failed/skipped also have literal+ // React callers and stay unlisted"task.status.available",+ "task.status.canceled",+ "task.status.done","task.status.not-started",+ "task.status.pending",+ "task.status.running",// - auth.token-expired-description — src/connect/middlewares/authInterceptorMiddleware.ts"auth.token-expired-description",// - issue.title.export-data — src/utils/v1/issue/issue.tsdiff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex d63adcfaaa..7f41be0910 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -3131,7 +3131,6 @@"description": "Set a specific date and time for tasks to automatically start running. Useful for maintenance windows or off-peak hours.","self": "Schedule for later"},- "scheduled-time": "Scheduled time","select-scheduled-time": "Select scheduled time","select-task": "Select Task","skip-prior-backup": "Skip prior backup",@@ -3156,8 +3155,8 @@"blocking-sessions": "Blocking Sessions","blocking-sessions-description": "The sessions that are blocking the current session","history": "History",+ "history-with-count": "History ({{count}})","latest": "Latest",- "latest-logs": "Latest Logs","log-detail": {"backing-up": "Backing up...","backup-completed": "completed ({{count}} tables)",@@ -3185,6 +3184,7 @@"replica-n": "Replica #{{n}}","summary": "{{sections}} sections · {{entries}} entries"},+ "no-blocking-sessions": "No blocking sessions","no-session-found": "No session found","rollback": {"available": "{{count}} rollback available",@@ -3193,6 +3193,7 @@"description": "Review the generated rollback statements before creating the rollback plan."}},+ "run-number": "Run #{{number}}","status": {"enqueued": "Waiting for execution.","enqueued-with-rollout-time": "Waiting to execute after {{time}}.",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 94568de518..90b1b771ad 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -3131,7 +3131,6 @@"description": "Establezca una fecha y hora específicas para que las tareas comiencen a ejecutarse automáticamente. Útil para periodos de mantenimiento o horas de baja demanda.","self": "Programar para más tarde"},- "scheduled-time": "Hora programada","select-scheduled-time": "Seleccionar hora programada","select-task": "Seleccionar tarea","skip-prior-backup": "Omitir respaldo previo",@@ -3156,8 +3155,8 @@"blocking-sessions": "Sesiones bloqueantes","blocking-sessions-description": "Las sesiones que están bloqueando la sesión actual.","history": "Historial",+ "history-with-count": "Historial ({{count}})","latest": "Último",- "latest-logs": "Últimos registros","log-detail": {"backing-up": "haciendo copia de seguridad...","backup-completed": "completadas ({{count}} tablas)",@@ -3185,6 +3184,7 @@"replica-n": "Réplica #{{n}}","summary": "{{sections}} secciones · {{entries}} entradas"},+ "no-blocking-sessions": "Sin sesiones bloqueantes","no-session-found": "No se encontró sesión","rollback": {"available": "{{count}} rollback disponible",@@ -3193,6 +3193,7 @@"description": "Revisa las sentencias de rollback generadas antes de crear el plan de rollback."}},+ "run-number": "Ejecución n.º {{number}}","status": {"enqueued": "Esperando a ser ejecutada.","enqueued-with-rollout-time": "Esperando para ejecutar después de {{time}}.",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 5504d10355..5f06bd6737 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -3131,7 +3131,6 @@"description": "タスクを自動的に実行開始する日時を指定します。メンテナンス期間やオフピーク時に便利です。","self": "後でスケジュールする"},- "scheduled-time": "スケジュール時刻","select-scheduled-time": "予定時刻を選択してください","select-task": "タスクを選択","skip-prior-backup": "事前バックアップをスキップ",@@ -3156,8 +3155,8 @@"blocking-sessions": "ブロッキングセッション","blocking-sessions-description": "現在のセッションをブロックしているセッション","history": "履歴",+ "history-with-count": "履歴({{count}})","latest": "最新",- "latest-logs": "最新ログ","log-detail": {"backing-up": "バックアップ中...","backup-completed": "完了しました({{count}} テーブル)",@@ -3185,6 +3184,7 @@"replica-n": "レプリカ #{{n}}","summary": "{{sections}} セクション · {{entries}} エントリ"},+ "no-blocking-sessions": "ブロッキングセッションはありません","no-session-found": "セッションが見つかりません","rollback": {"available": "{{count}} 件のロールバックが利用可能",@@ -3193,6 +3193,7 @@"description": "ロールバックプランを作成する前に生成されたロールバック文を確認してください。"}},+ "run-number": "実行 #{{number}}","status": {"enqueued": "実行を待っています。","enqueued-with-rollout-time": "{{time}} の後に実行される予定です。",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 1adffa028f..721fca1567 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -3131,7 +3131,6 @@"description": "Đặt ngày và giờ cụ thể để các tác vụ tự động bắt đầu chạy. Hữu ích cho các khung giờ bảo trì hoặc ngoài giờ cao điểm.","self": "Lên lịch cho sau"},- "scheduled-time": "Thời gian đã lên lịch","select-scheduled-time": "Chọn thời gian đã lên lịch","select-task": "Chọn tác vụ","skip-prior-backup": "Bỏ qua sao lưu trước",@@ -3156,8 +3155,8 @@"blocking-sessions": "Phiên chặn","blocking-sessions-description": "Các phiên đang chặn phiên hiện tại","history": "Lịch sử",+ "history-with-count": "Lịch sử ({{count}})","latest": "Mới nhất",- "latest-logs": "Nhật ký mới nhất","log-detail": {"backing-up": "đang sao lưu...","backup-completed": "đã hoàn thành ({{count}} bảng)",@@ -3185,6 +3184,7 @@"replica-n": "Bản sao #{{n}}","summary": "{{sections}} phần · {{entries}} mục"},+ "no-blocking-sessions": "Không có phiên chặn nào","no-session-found": "Không tìm thấy phiên","rollback": {"available": "Có {{count}} mục có thể hoàn tác",@@ -3193,6 +3193,7 @@"description": "Xem lại các câu lệnh hoàn tác đã tạo trước khi tạo kế hoạch hoàn tác."}},+ "run-number": "Lần chạy #{{number}}","status": {"enqueued": "Đang chờ thực thi.","enqueued-with-rollout-time": "Đang chờ thực thi sau {{time}}.",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 879211bcd5..3fc1558cba 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -3131,7 +3131,6 @@"description": "设置任务自动开始运行的特定时间。","self": "定时运行"},- "scheduled-time": "计划执行时间","select-scheduled-time": "选择计划时间","select-task": "选择任务","skip-prior-backup": "跳过预备份",@@ -3156,8 +3155,8 @@"blocking-sessions": "阻塞会话","blocking-sessions-description": "当前会话被以下会话阻塞","history": "历史",+ "history-with-count": "历史记录({{count}})","latest": "最新",- "latest-logs": "最新日志","log-detail": {"backing-up": "备份中...","backup-completed": "已完成({{count}} 个表)",@@ -3185,6 +3184,7 @@"replica-n": "副本 #{{n}}","summary": "{{sections}} 个分组 · {{entries}} 条记录"},+ "no-blocking-sessions": "无阻塞会话","no-session-found": "未找到会话","rollback": {"available": "有 {{count}} 个可回滚任务",@@ -3193,6 +3193,7 @@"description": "在创建回滚计划前先检查生成的回滚语句。"}},+ "run-number": "第 {{number}} 次运行","status": {"enqueued": "等待执行。","enqueued-with-rollout-time": "等待执行,{{time}} 后执行。",diff --git a/frontend/src/react/components/monaco/MonacoEditor.tsx b/frontend/src/react/components/monaco/MonacoEditor.tsxindex 02e9b36e68..a668e698c6 100644--- a/frontend/src/react/components/monaco/MonacoEditor.tsx+++ b/frontend/src/react/components/monaco/MonacoEditor.tsx@@ -78,6 +78,13 @@ const normalizeContent = (value: unknown): string =>const normalizeLanguage = (value: unknown): Language =>supportedLanguages.has(value as Language) ? (value as Language) : "sql";+// Text overlays (the loading stand-in and the empty placeholder) that must+// align with the editor's own text layout. Mirrors defaultEditorOptions in+// core.ts — fontSize 14 (text-sm), lineHeight 24 (leading-6), padding.top 8+// (pt-2) — plus Monaco's computed ~52px line-number gutter, which is not an+// option, just measured.+const MONACO_TEXT_OVERLAY_CLASS = "pl-[52px] pt-2 font-mono text-sm leading-6";+export interface MonacoEditorProps {advices?: AdviceOption[];autoCompleteContext?: AutoCompleteContext;@@ -701,13 +708,36 @@ export function MonacoEditor({)}style={autoHeight ? { height } : undefined}/>- {!ready && (- <div className="absolute inset-0 flex items-center justify-center rounded-md border bg-background/70">- <Loader2 className="h-5 w-5 animate-spin text-control-light" />- </div>- )}+ {!ready &&+ (safeContent ? (+ // The text is already in hand — paint it as a static stand-in+ // instead of flashing a spinner, so editor initialization reads as+ // highlighting fading in rather than loading → content. Only the+ // first chunk is laid out: the stand-in just covers the init window+ // and anything past it is below the fold.+ <div className="pointer-events-none absolute inset-0 overflow-hidden bg-background">+ <pre+ className={cn(+ "m-0 h-full overflow-hidden whitespace-pre-wrap break-words text-main",+ MONACO_TEXT_OVERLAY_CLASS+ )}+ >+ {safeContent.slice(0, 10_000)}+ </pre>+ </div>+ ) : (+ <div className="absolute inset-0 flex items-center justify-center rounded-md border bg-background/70">+ <Loader2 className="h-5 w-5 animate-spin text-control-light" />+ </div>+ ))}{ready && !content && placeholder && (- <div className="pointer-events-none absolute left-[52px] top-2 font-mono text-sm text-control-placeholder">+ <div+ className={cn(+ "pointer-events-none absolute inset-0",+ MONACO_TEXT_OVERLAY_CLASS,+ "text-control-placeholder"+ )}+ >{placeholder}</div>)}diff --git a/frontend/src/react/components/task-run-log/SectionContent.tsx b/frontend/src/react/components/task-run-log/SectionContent.tsxindex c028497c91..39ce65a1de 100644--- a/frontend/src/react/components/task-run-log/SectionContent.tsx+++ b/frontend/src/react/components/task-run-log/SectionContent.tsx@@ -60,7 +60,7 @@ export function SectionContent({<span className={cn("shrink-0", item.levelClass)}>{item.levelIndicator}</span>- <span className={cn("break-all", item.detailClass)}>+ <span className={cn("min-w-0 break-words", item.detailClass)}>{item.detail}</span><span className="ml-auto flex shrink-0 items-center gap-x-2">diff --git a/frontend/src/react/components/task-run-log/SectionHeader.tsx b/frontend/src/react/components/task-run-log/SectionHeader.tsxindex b6808521d3..a28d475855 100644--- a/frontend/src/react/components/task-run-log/SectionHeader.tsx+++ b/frontend/src/react/components/task-run-log/SectionHeader.tsx@@ -3,6 +3,21 @@ import type { ButtonHTMLAttributes } from "react";import { cn } from "@/react/lib/utils";import type { Section } from "./types";+// The status glyph shared by the collapsible header and the sole-section+// (non-collapsible) label in TaskRunLogViewer, so the two can't drift.+export function SectionStatusIcon({ section }: { section: Section }) {+ const StatusIcon = section.statusIcon;+ return (+ <StatusIcon+ className={cn(+ "h-3.5 w-3.5 shrink-0",+ section.statusClass,+ section.status === "running" && "animate-spin"+ )}+ />+ );+}+export interface SectionHeaderPropsextends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "onClick"> {section: Section;@@ -19,8 +34,6 @@ export function SectionHeader({className,...props}: SectionHeaderProps) {- const StatusIcon = section.statusIcon;-return (<buttontype="button"@@ -38,13 +51,7 @@ export function SectionHeader({) : (<ChevronRight className="size-3.5 shrink-0 text-control-placeholder" />)}- <StatusIcon- className={cn(- "h-3.5 w-3.5 shrink-0",- section.statusClass,- section.status === "running" && "animate-spin"- )}- />+ <SectionStatusIcon section={section} /><span className="text-control">{section.label}</span>{section.entryCount > 1 ? (<span className="text-control-placeholder">({section.entryCount})</span>diff --git a/frontend/src/react/components/task-run-log/TaskRunLogViewer.test.tsx b/frontend/src/react/components/task-run-log/TaskRunLogViewer.test.tsxindex 41a512de37..bef191eda0 100644--- a/frontend/src/react/components/task-run-log/TaskRunLogViewer.test.tsx+++ b/frontend/src/react/components/task-run-log/TaskRunLogViewer.test.tsx@@ -116,7 +116,6 @@ const createDefaultSections = () => ({areAllExpanded: true,totalSections: 1,totalEntries: 1,- totalDuration: "2s",});const renderIntoContainer = (element: ReturnType<typeof createElement>) => {@@ -143,12 +142,14 @@ beforeEach(() => {});describe("TaskRunLogViewer", () => {- test("renders the summary and section content", () => {+ test("drops the summary scaffolding for a lone section", () => {const { container, unmount } = renderIntoContainer(createElement(TaskRunLogViewer, { taskRunName: "runs/1" }));- expect(container.textContent).toContain("1 sections · 1 entries");+ // A single section has no structure worth disclosing: no summary bar, but+ // its label and entries render directly.+ expect(container.textContent).not.toContain("1 sections · 1 entries");expect(container.textContent).toContain("Command Execute");expect(container.textContent).toContain("SELECT 1;");@@ -262,13 +263,14 @@ describe("TaskRunLogViewer", () => {areAllExpanded: true,totalSections: 2,totalEntries: 2,- totalDuration: "",});const { container, unmount } = renderIntoContainer(createElement(TaskRunLogViewer, { taskRunName: "runs/1" }));+ // More than one section keeps the summary bar and the disclosure chrome.+ expect(container.textContent).toContain("2 sections · 2 entries");expect(container.textContent).toContain("ORPHAN SELECT");expect(container.textContent).toContain("v1: 001.sql");expect(container.textContent?.indexOf("ORPHAN SELECT") ?? -1).toBeLessThan(diff --git a/frontend/src/react/components/task-run-log/TaskRunLogViewer.tsx b/frontend/src/react/components/task-run-log/TaskRunLogViewer.tsxindex ee6e87aec3..6091321539 100644--- a/frontend/src/react/components/task-run-log/TaskRunLogViewer.tsx+++ b/frontend/src/react/components/task-run-log/TaskRunLogViewer.tsx@@ -6,23 +6,45 @@ import {List,Server,} from "lucide-react";-import { useCallback, useMemo } from "react";+import { memo, useCallback, useMemo } from "react";import { useTranslation } from "react-i18next";import { Button } from "@/react/components/ui/button";-import { TaskRunLogEntry_Type } from "@/types/proto-es/v1/rollout_service_pb";+import {+ type TaskRun_Status,+ TaskRunLogEntry_Type,+} from "@/types/proto-es/v1/rollout_service_pb";import type { TaskRunLogDetailText } from "./model";import { SectionContent } from "./SectionContent";-import { SectionHeader } from "./SectionHeader";+import { SectionHeader, SectionStatusIcon } from "./SectionHeader";import { useTaskRunLogData } from "./useTaskRunLogData";import { useTaskRunLogSections } from "./useTaskRunLogSections";export interface TaskRunLogViewerProps {taskRunName: string;+ // Pass when known: a terminal status lets a cached log render without a+ // refetch, since a finished run's log is immutable. Callers without a+ // TaskRun in hand (changelog/revision pages) omit it and always revalidate,+ // even though those runs are terminal by construction.+ taskRunStatus?: TaskRun_Status;+ // When false, pause the live log poll — the card is mounted but its stage is+ // hidden. Defaults to live.+ active?: boolean;}-export function TaskRunLogViewer({ taskRunName }: TaskRunLogViewerProps) {+// memo: both props are scalars and data flows in via zustand subscriptions+// (not React context), so re-renders of the surrounding card don't cascade+// into the log tree unless the run itself changed.+export const TaskRunLogViewer = memo(function TaskRunLogViewer({+ taskRunName,+ taskRunStatus,+ active = true,+}: TaskRunLogViewerProps) {const { t } = useTranslation();- const { entries, sheet, sheetsMap } = useTaskRunLogData(taskRunName);+ const { entries, logFetch, sheet, sheetsMap } = useTaskRunLogData(+ taskRunName,+ taskRunStatus,+ active+ );const getSectionLabel = useCallback((type: TaskRunLogEntry_Type) => {@@ -90,7 +112,6 @@ export function TaskRunLogViewer({ taskRunName }: TaskRunLogViewerProps) {areAllExpanded,totalSections,totalEntries,- totalDuration,} = useTaskRunLogSections({entries,sheet,@@ -110,9 +131,45 @@ export function TaskRunLogViewer({ taskRunName }: TaskRunLogViewerProps) {}if (!hasContent) {+ // Reserve the approximate height of a small loaded log (label row plus a+ // couple of entries) while the first fetch is in flight, so entries fill+ // the box in place instead of popping the card taller.+ if (logFetch.status === "loading") {+ return (+ <div className="flex min-h-20 items-center justify-center rounded-md border bg-gray-50 px-3 py-2 text-sm text-control-light">+ {t("common.loading")}+ </div>+ );+ }return null;}+ // A single section with no replicas or release files carries no structure+ // worth disclosing — skip the summary bar and the collapsible section header+ // and show the entries directly under a lightweight, non-collapsible label.+ const soleSection =+ !hasMultipleReplicas && !hasRenderableReleaseFiles && sections.length === 1+ ? sections[0]+ : undefined;+ if (soleSection) {+ return (+ <div className="w-full font-mono text-xs">+ <div className="w-full overflow-hidden rounded border border-gray-200 bg-gray-50">+ <div className="flex items-center gap-x-2 px-3 py-1.5 text-control">+ <SectionStatusIcon section={soleSection} />+ <span>{soleSection.label}</span>+ {soleSection.duration ? (+ <span className="ml-auto tabular-nums text-control-light">+ {soleSection.duration}+ </span>+ ) : null}+ </div>+ <SectionContent section={soleSection} datasetKey={taskRunName} />+ </div>+ </div>+ );+ }+const toggleExpandAll = () => {if (areAllExpanded) {collapseAll();@@ -242,47 +299,40 @@ export function TaskRunLogViewer({ taskRunName }: TaskRunLogViewerProps) {return (<div className="w-full font-mono text-xs">- {hasContent ? (- <div className="w-full overflow-hidden rounded border border-gray-200 bg-gray-50">- <div className="flex items-center justify-between border-b border-gray-200 bg-gray-100 px-2 py-1">- <div className="flex items-center gap-x-2 text-gray-500">- <List className="h-3.5 w-3.5" />- <span>- {t("task-run.log-viewer.summary", {- sections: totalSections,- entries: totalEntries,- })}- </span>- {totalDuration ? (- <span className="tabular-nums text-blue-500">- {totalDuration}- </span>- ) : null}- </div>- <Button- type="button"- appearance="secondary"- size="sm"- className="gap-x-1 text-control-light hover:text-control"- onClick={toggleExpandAll}- >- {areAllExpanded ? (- <ChevronsDownUp className="h-3.5 w-3.5" />- ) : (- <ChevronsUpDown className="h-3.5 w-3.5" />- )}- <span>- {areAllExpanded- ? t("task-run.log-viewer.collapse-all")- : t("task-run.log-viewer.expand-all")}- </span>- </Button>+ <div className="w-full overflow-hidden rounded border border-gray-200 bg-gray-50">+ <div className="flex items-center justify-between border-b border-gray-200 bg-gray-100 px-2 py-1">+ <div className="flex items-center gap-x-2 text-gray-500">+ <List className="h-3.5 w-3.5" />+ <span>+ {t("task-run.log-viewer.summary", {+ sections: totalSections,+ entries: totalEntries,+ })}+ </span></div>- {content}+ <Button+ type="button"+ appearance="secondary"+ size="sm"+ className="gap-x-1 text-control-light hover:text-control"+ onClick={toggleExpandAll}+ >+ {areAllExpanded ? (+ <ChevronsDownUp className="h-3.5 w-3.5" />+ ) : (+ <ChevronsUpDown className="h-3.5 w-3.5" />+ )}+ <span>+ {areAllExpanded+ ? t("task-run.log-viewer.collapse-all")+ : t("task-run.log-viewer.expand-all")}+ </span>+ </Button></div>- ) : null}+ {content}+ </div></div>);-}+});export default TaskRunLogViewer;diff --git a/frontend/src/react/components/task-run-log/model.ts b/frontend/src/react/components/task-run-log/model.tsindex 4574625c79..8f9c14245b 100644--- a/frontend/src/react/components/task-run-log/model.ts+++ b/frontend/src/react/components/task-run-log/model.ts@@ -74,7 +74,7 @@ export const formatTime = (timestamp?: Timestamp): string => {);};-export const formatDuration = (ms: number): string => {+const formatDuration = (ms: number): string => {if (ms < 1) return "<1ms";if (ms < 1000) return `${ms.toFixed(0)}ms`;if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;@@ -243,7 +243,7 @@ export const groupEntriesByReplica = (return grouped;};-export const getEntryTimeRange = (+const getEntryTimeRange = (entry: TaskRunLogEntry): { start: number; end: number } => {switch (entry.type) {diff --git a/frontend/src/react/components/task-run-log/useTaskRunLogData.test.tsx b/frontend/src/react/components/task-run-log/useTaskRunLogData.test.tsxnew file mode 100644index 0000000000..8ba5569380--- /dev/null+++ b/frontend/src/react/components/task-run-log/useTaskRunLogData.test.tsx@@ -0,0 +1,418 @@+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import {+ type Task,+ TaskRun_Status,+} from "@/types/proto-es/v1/rollout_service_pb";+import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";+import type { UseTaskRunLogDataResult } from "./useTaskRunLogData";+import { useTaskRunLogData } from "./useTaskRunLogData";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ fetchRelease: vi.fn(),+ fetchRolloutByName: vi.fn(),+ fetchSheet: vi.fn(),+ getSheetByName: vi.fn(),+ getTaskRunLog: vi.fn(),+ rolloutsByName: {} as Record<string, unknown>,+}));++vi.mock("@/connect", () => ({+ rolloutServiceClientConnect: { getTaskRunLog: mocks.getTaskRunLog },+}));++vi.mock("@/react/stores/app", () => {+ const state = () => ({+ fetchRelease: mocks.fetchRelease,+ fetchRolloutByName: mocks.fetchRolloutByName,+ fetchSheet: mocks.fetchSheet,+ getSheetByName: mocks.getSheetByName,+ rolloutsByName: mocks.rolloutsByName,+ });+ const useAppStore = (selector?: (s: unknown) => unknown) =>+ selector ? selector(state()) : state();+ useAppStore.getState = state;+ return { useAppStore };+});++vi.mock("@/utils", () => ({+ extractRolloutNameFromTaskRunName: (name: string) =>+ name.split("/stages/")[0],+ extractTaskNameFromTaskRunName: (name: string) => name.split("/taskRuns/")[0],+ isReleaseBasedTask: () => false,+ releaseNameOfTaskV1: () => "",+ sheetNameOfTaskV1: (task: Task) =>+ (task as unknown as { sheet: string }).sheet,+}));++const ROLLOUT_NAME = "projects/p/rollouts/r";+const TASK_NAME = `${ROLLOUT_NAME}/stages/s/tasks/t1`;+const SHEET_NAME = "projects/p/sheets/101";++// The real isSheetContentComplete compares content byte length to+// contentSize, so fixtures carry actual encoded content.+const makeSheet = (statement: string, contentSize: number): Sheet =>+ ({+ name: SHEET_NAME,+ content: new TextEncoder().encode(statement),+ contentSize: BigInt(contentSize),+ }) as unknown as Sheet;++const makeRolloutWithTask = () => ({+ stages: [{ tasks: [{ name: TASK_NAME, sheet: SHEET_NAME }] }],+});++const renderHook = (+ taskRunName: string,+ taskRunStatus?: TaskRun_Status,+ live = true+) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ let latest: UseTaskRunLogDataResult | undefined;+ let props = { taskRunName, taskRunStatus, live };+ const Probe = () => {+ latest = useTaskRunLogData(+ props.taskRunName,+ props.taskRunStatus,+ props.live+ );+ return null;+ };+ act(() => {+ root.render(<Probe />);+ });+ return {+ result: () => latest as UseTaskRunLogDataResult,+ rerender: (+ nextTaskRunName: string,+ nextTaskRunStatus?: TaskRun_Status,+ nextLive = true+ ) =>+ act(() => {+ props = {+ taskRunName: nextTaskRunName,+ taskRunStatus: nextTaskRunStatus,+ live: nextLive,+ };+ root.render(<Probe />);+ }),+ flush: async () => {+ await act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });+ },+ unmount: () => act(() => root.unmount()),+ };+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.rolloutsByName = {};+ mocks.getTaskRunLog.mockResolvedValue({ entries: [] });+ mocks.getSheetByName.mockReturnValue(undefined);+ mocks.fetchSheet.mockResolvedValue(undefined);+ mocks.fetchRolloutByName.mockResolvedValue(makeRolloutWithTask());+});++describe("useTaskRunLogData caching", () => {+ test("resolves the task from the cached rollout without refetching it", async () => {+ mocks.rolloutsByName = { [ROLLOUT_NAME]: makeRolloutWithTask() };+ mocks.getSheetByName.mockReturnValue(makeSheet("select 1", 8));++ const hook = renderHook(`${TASK_NAME}/taskRuns/cached-rollout`);+ await hook.flush();++ expect(mocks.fetchRolloutByName).not.toHaveBeenCalled();+ expect(hook.result().metadataFetch.status).toBe("success");+ hook.unmount();+ });++ test("falls back to fetching the rollout when the cache misses", async () => {+ const hook = renderHook(`${TASK_NAME}/taskRuns/rollout-miss`);+ await hook.flush();++ expect(mocks.fetchRolloutByName).toHaveBeenCalledWith(ROLLOUT_NAME, true);+ hook.unmount();+ });++ test("reuses a complete cached sheet instead of refetching raw", async () => {+ mocks.rolloutsByName = { [ROLLOUT_NAME]: makeRolloutWithTask() };+ mocks.getSheetByName.mockReturnValue(makeSheet("select 1", 8));++ const hook = renderHook(`${TASK_NAME}/taskRuns/sheet-cached`);+ await hook.flush();++ expect(mocks.fetchSheet).not.toHaveBeenCalled();+ expect(hook.result().sheetFetch.status).toBe("success");+ expect(hook.result().sheet).toBeDefined();+ hook.unmount();+ });++ test("refetches raw when the cached sheet is a truncated preview", async () => {+ mocks.rolloutsByName = { [ROLLOUT_NAME]: makeRolloutWithTask() };+ mocks.getSheetByName.mockReturnValue(makeSheet("select", 9999));+ mocks.fetchSheet.mockResolvedValue(makeSheet("select 1 -- full", 16));++ const hook = renderHook(`${TASK_NAME}/taskRuns/sheet-truncated`);+ await hook.flush();++ expect(mocks.fetchSheet).toHaveBeenCalledWith(SHEET_NAME, true);+ expect(hook.result().sheetFetch.status).toBe("success");+ hook.unmount();+ });++ test("serves cached log entries synchronously on remount", async () => {+ mocks.rolloutsByName = { [ROLLOUT_NAME]: makeRolloutWithTask() };+ mocks.getSheetByName.mockReturnValue(makeSheet("select 1", 8));+ const taskRunName = `${TASK_NAME}/taskRuns/log-cache`;+ const entries = [{ deployId: "a" }, { deployId: "b" }];+ mocks.getTaskRunLog.mockResolvedValue({ entries });++ const first = renderHook(taskRunName);+ await first.flush();+ expect(first.result().entries).toHaveLength(2);+ first.unmount();++ // Remount with the request hanging: cached entries must paint on the very+ // first render, before any effect or request resolves.+ mocks.getTaskRunLog.mockReturnValue(new Promise(() => {}));+ const second = renderHook(taskRunName);+ expect(second.result().entries).toHaveLength(2);+ expect(second.result().logFetch.status).toBe("success");+ second.unmount();+ });++ test("skips the log refetch entirely for a cached terminal run", async () => {+ mocks.rolloutsByName = { [ROLLOUT_NAME]: makeRolloutWithTask() };+ mocks.getSheetByName.mockReturnValue(makeSheet("select 1", 8));+ const taskRunName = `${TASK_NAME}/taskRuns/terminal`;+ mocks.getTaskRunLog.mockResolvedValue({ entries: [{ deployId: "a" }] });++ const first = renderHook(taskRunName, TaskRun_Status.DONE);+ await first.flush();+ expect(mocks.getTaskRunLog).toHaveBeenCalledTimes(1);+ first.unmount();++ const second = renderHook(taskRunName, TaskRun_Status.DONE);+ await second.flush();+ expect(mocks.getTaskRunLog).toHaveBeenCalledTimes(1);+ expect(second.result().entries).toHaveLength(1);+ expect(second.result().logFetch.status).toBe("success");+ second.unmount();+ });++ test("still revalidates a cached log for a running task", async () => {+ mocks.rolloutsByName = { [ROLLOUT_NAME]: makeRolloutWithTask() };+ mocks.getSheetByName.mockReturnValue(makeSheet("select 1", 8));+ const taskRunName = `${TASK_NAME}/taskRuns/running`;+ mocks.getTaskRunLog.mockResolvedValue({ entries: [{ deployId: "a" }] });++ const first = renderHook(taskRunName, TaskRun_Status.RUNNING);+ await first.flush();+ expect(mocks.getTaskRunLog).toHaveBeenCalledTimes(1);+ // The log poll runs every 5s while running, so its request must be silent —+ // a transient failure must not spam the global error toast.+ expect(mocks.getTaskRunLog).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ contextValues: expect.anything() })+ );+ first.unmount();++ mocks.getTaskRunLog.mockResolvedValue({+ entries: [{ deployId: "a" }, { deployId: "b" }],+ });+ const second = renderHook(taskRunName, TaskRun_Status.RUNNING);+ // Cached entry paints first…+ expect(second.result().entries).toHaveLength(1);+ await second.flush();+ // …then the revalidation replaces it.+ expect(mocks.getTaskRunLog).toHaveBeenCalledTimes(2);+ expect(second.result().entries).toHaveLength(2);+ second.unmount();+ });++ test("does not live-poll the log while the stage is hidden (inactive)", async () => {+ vi.useFakeTimers();+ try {+ mocks.rolloutsByName = { [ROLLOUT_NAME]: makeRolloutWithTask() };+ mocks.getSheetByName.mockReturnValue(makeSheet("select 1", 8));+ const taskRunName = `${TASK_NAME}/taskRuns/inactive-poll`;+ mocks.getTaskRunLog.mockResolvedValue({ entries: [{ deployId: "a" }] });++ // Inactive + running: the mount revalidation still fires once…+ const hook = renderHook(taskRunName, TaskRun_Status.RUNNING, false);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(mocks.getTaskRunLog).toHaveBeenCalledTimes(1);++ // …but the 5s live poll must not run while the card's stage is hidden.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(15000);+ });+ expect(mocks.getTaskRunLog).toHaveBeenCalledTimes(1);+ hook.unmount();+ } finally {+ vi.useRealTimers();+ }+ });++ test("does not overlap live log polls while a fetch is slow", async () => {+ vi.useFakeTimers();+ try {+ mocks.rolloutsByName = { [ROLLOUT_NAME]: makeRolloutWithTask() };+ mocks.getSheetByName.mockReturnValue(makeSheet("select 1", 8));+ const taskRunName = `${TASK_NAME}/taskRuns/slow-poll`;+ // Every log fetch stays pending — slower than the 5s poll interval.+ mocks.getTaskRunLog.mockReturnValue(new Promise(() => {}));++ const hook = renderHook(taskRunName, TaskRun_Status.RUNNING, true);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });++ // fetchLog returns its promise, so the live poller awaits it and can't+ // start another tick while the fetch is in flight. Past several intervals+ // there's at most the mount revalidation plus one still-pending poll — a+ // fixed setInterval (or a `void`ed promise) would have fired many more.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(30000);+ });+ expect(mocks.getTaskRunLog.mock.calls.length).toBeLessThanOrEqual(2);+ hook.unmount();+ } finally {+ vi.useRealTimers();+ }+ });++ test("revalidates once when a cached running log remounts as done", async () => {+ mocks.rolloutsByName = { [ROLLOUT_NAME]: makeRolloutWithTask() };+ mocks.getSheetByName.mockReturnValue(makeSheet("select 1", 8));+ const taskRunName = `${TASK_NAME}/taskRuns/run-to-done`;+ mocks.getTaskRunLog.mockResolvedValue({ entries: [{ deployId: "a" }] });++ const running = renderHook(taskRunName, TaskRun_Status.RUNNING);+ await running.flush();+ running.unmount();++ // First mount at DONE: cache was recorded at RUNNING → revalidate once.+ const done = renderHook(taskRunName, TaskRun_Status.DONE);+ await done.flush();+ expect(mocks.getTaskRunLog).toHaveBeenCalledTimes(2);+ done.unmount();++ // Subsequent DONE mounts hit the terminal cache.+ const again = renderHook(taskRunName, TaskRun_Status.DONE);+ await again.flush();+ expect(mocks.getTaskRunLog).toHaveBeenCalledTimes(2);+ again.unmount();+ });++ test("a late log response from an unmounted instance cannot rewind the cache", async () => {+ mocks.rolloutsByName = { [ROLLOUT_NAME]: makeRolloutWithTask() };+ mocks.getSheetByName.mockReturnValue(makeSheet("select 1", 8));+ const taskRunName = `${TASK_NAME}/taskRuns/late-clobber`;++ // The RUNNING instance's log request stays in flight.+ let resolveRunning: (value: { entries: { deployId: string }[] }) => void =+ () => {};+ mocks.getTaskRunLog.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveRunning = resolve;+ })+ );+ const running = renderHook(taskRunName, TaskRun_Status.RUNNING);+ await running.flush();++ // Status flips RUNNING→DONE: the viewer remounts under a new key. The DONE+ // instance fetches and caches the terminal log.+ running.unmount();+ mocks.getTaskRunLog.mockResolvedValueOnce({+ entries: [{ deployId: "done-1" }, { deployId: "done-2" }],+ });+ const done = renderHook(taskRunName, TaskRun_Status.DONE);+ await done.flush();+ expect(done.result().entries).toHaveLength(2);++ // The old RUNNING request resolves late, after the terminal cache write. Its+ // partial entries must not overwrite the cached DONE log.+ await act(async () => {+ resolveRunning({ entries: [{ deployId: "running-partial" }] });+ await Promise.resolve();+ await Promise.resolve();+ });+ done.unmount();++ // A fresh DONE mount seeds synchronously from the cache; it must still be the+ // 2-entry terminal log, not the stale 1-entry running snapshot.+ mocks.getTaskRunLog.mockReturnValue(new Promise(() => {}));+ const reopened = renderHook(taskRunName, TaskRun_Status.DONE);+ expect(reopened.result().entries).toHaveLength(2);+ reopened.unmount();+ });++ test("drops a late log response when the same viewer switches to another task run", async () => {+ mocks.rolloutsByName = { [ROLLOUT_NAME]: makeRolloutWithTask() };+ mocks.getSheetByName.mockReturnValue(makeSheet("select 1", 8));+ const oldRunName = `${TASK_NAME}/taskRuns/late-previous-run`;+ const newRunName = `${TASK_NAME}/taskRuns/cached-next-run`;++ // Seed a fresh terminal cache for the next run, so switching to it does not+ // start a new fetch that would otherwise bump the sequence guard.+ mocks.getTaskRunLog.mockResolvedValueOnce({+ entries: [{ deployId: "new-1" }, { deployId: "new-2" }],+ });+ const seed = renderHook(newRunName, TaskRun_Status.DONE);+ await seed.flush();+ expect(seed.result().entries).toHaveLength(2);+ seed.unmount();++ let resolveOld: (value: { entries: { deployId: string }[] }) => void =+ () => {};+ mocks.getTaskRunLog.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveOld = resolve;+ })+ );+ const hook = renderHook(oldRunName, TaskRun_Status.RUNNING);+ await hook.flush();++ hook.rerender(newRunName, TaskRun_Status.DONE);+ expect(hook.result().entries).toHaveLength(2);++ await act(async () => {+ resolveOld({ entries: [{ deployId: "old-stale" }] });+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(+ hook+ .result()+ .entries.map(+ (entry) => (entry as unknown as { deployId: string }).deployId+ )+ ).toEqual(["new-1", "new-2"]);+ hook.unmount();+ });++ test("seeds a complete cached sheet on the first render", () => {+ mocks.rolloutsByName = { [ROLLOUT_NAME]: makeRolloutWithTask() };+ mocks.getSheetByName.mockReturnValue(makeSheet("select 1", 8));+ mocks.getTaskRunLog.mockReturnValue(new Promise(() => {}));++ const hook = renderHook(`${TASK_NAME}/taskRuns/sheet-seed`);+ // No flush: the sheet must come from the synchronous render-time seed.+ expect(hook.result().sheet).toBeDefined();+ expect(hook.result().sheetFetch.status).toBe("success");+ expect(hook.result().metadataFetch.status).toBe("success");+ hook.unmount();+ });+});diff --git a/frontend/src/react/components/task-run-log/useTaskRunLogData.ts b/frontend/src/react/components/task-run-log/useTaskRunLogData.tsindex bde6087d61..fecf6fde04 100644--- a/frontend/src/react/components/task-run-log/useTaskRunLogData.ts+++ b/frontend/src/react/components/task-run-log/useTaskRunLogData.ts@@ -1,15 +1,20 @@import { create } from "@bufbuild/protobuf";-import { useEffect, useMemo, useRef, useState } from "react";-import {- rolloutServiceClientConnect,- sheetServiceClientConnect,-} from "@/connect";+import { createContextValues } from "@connectrpc/connect";+import { useCallback, useEffect, useMemo, useRef } from "react";+import { rolloutServiceClientConnect } from "@/connect";+import { silentContextKey } from "@/connect/context-key";+import { useLatestRef } from "@/react/hooks/useLatestRef";+import { usePolling } from "@/react/hooks/usePolling";+import { useSeededState } from "@/react/hooks/useSeededState";+import { sameMessageList } from "@/react/lib/protoIdentity";import { useAppStore } from "@/react/stores/app";import { unknownRollout } from "@/types";import {GetTaskRunLogRequestSchema,type Task,+ TaskRun_Status,type TaskRunLogEntry,+ TaskRunLogEntrySchema,} from "@/types/proto-es/v1/rollout_service_pb";import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";import {@@ -19,6 +24,7 @@ import {releaseNameOfTaskV1,sheetNameOfTaskV1,} from "@/utils";+import { isSheetContentComplete } from "@/utils/v1/sheet";export type FetchStatus = "idle" | "loading" | "success" | "partial" | "error";export type SheetSource = "none" | "sheet" | "release";@@ -49,6 +55,72 @@ interface ReleaseSheetFetchResult {const TASK_RESOLUTION_ERROR = "Task cannot be resolved from rollout metadata";+// The viewer remounts on every stage switch (and on the card's refresh key+// bump), so all three data slices below seed synchronously from caches during+// render — a remount paints fully formed instead of flashing empty states+// while effects and requests settle (same pattern as useSheetStatement /+// BYT-9763).++type LogCacheEntry = {+ entries: TaskRunLogEntry[];+ // The run's status when the entries were fetched. Once a run is terminal+ // its log is immutable, so a matching cached copy needs no revalidation.+ status?: TaskRun_Status;+};+const taskRunLogEntriesCache = new Map<string, LogCacheEntry>();+// Keep the session-lifetime cache bounded; Map iteration order gives FIFO.+const LOG_CACHE_MAX_ENTRIES = 100;+const cacheLogEntries = (taskRunName: string, entry: LogCacheEntry) => {+ taskRunLogEntriesCache.delete(taskRunName);+ taskRunLogEntriesCache.set(taskRunName, entry);+ if (taskRunLogEntriesCache.size > LOG_CACHE_MAX_ENTRIES) {+ const oldest = taskRunLogEntriesCache.keys().next().value;+ if (oldest !== undefined) {+ taskRunLogEntriesCache.delete(oldest);+ }+ }+};++const TERMINAL_TASK_RUN_STATUSES: ReadonlySet<TaskRun_Status> = new Set([+ TaskRun_Status.DONE,+ TaskRun_Status.FAILED,+ TaskRun_Status.CANCELED,+]);++const isLogCacheFresh = (+ cached: LogCacheEntry | undefined,+ taskRunStatus?: TaskRun_Status+): boolean =>+ !!cached &&+ taskRunStatus !== undefined &&+ TERMINAL_TASK_RUN_STATUSES.has(taskRunStatus) &&+ cached.status === taskRunStatus;++// A running task appends log entries as it executes; poll on this cadence so+// the log grows live instead of freezing until the run's status flips.+const LIVE_LOG_POLL_INTERVAL_MS = 5000;++type LogSlice = { entries: TaskRunLogEntry[]; state: FetchState };++const seedLogSlice = (taskRunName?: string): LogSlice => {+ if (!taskRunName) {+ return { entries: [], state: { status: "idle" } };+ }+ const cached = taskRunLogEntriesCache.get(taskRunName);+ if (cached) {+ return { entries: cached.entries, state: { status: "success" } };+ }+ return { entries: [], state: { status: "loading" } };+};++// A cached sheet satisfies a raw consumer only when it holds the full content;+// the store's `fetchSheet(name, raw=true)` applies the same rule, so the async+// path just delegates to it and this sync probe backs the render-time seed.+const getCachedCompleteSheet = (name: string): Sheet | undefined => {+ const cached = useAppStore.getState().getSheetByName(name);+ return cached && isSheetContentComplete(cached) ? cached : undefined;+};+const getTaskFromRollout = (taskRunName: string | undefined,rollout: { stages: Array<{ tasks: Task[] }> } | undefined@@ -152,26 +224,81 @@ export const buildReleaseSheetFetchResult = (};};-export const useTaskRunLogData = (+const seedMetadataState = (+ rolloutName: string,taskRunName?: string+): FetchState => {+ if (!rolloutName || !taskRunName) {+ return { status: "idle" };+ }+ // The cached rollout usually already carries the task (the surrounding page+ // loaded it); the effect only hits the network when it can't be resolved.+ const cachedRollout = useAppStore.getState().rolloutsByName[rolloutName];+ if (getTaskFromRollout(taskRunName, cachedRollout)) {+ return { status: "success" };+ }+ return { status: "loading" };+};++const EMPTY_SHEETS_MAP = new Map<string, Sheet>();++type SheetSlice = {+ sheet: Sheet | undefined;+ sheetsMap: Map<string, Sheet>;+ state: SheetFetchState;+};++const sheetlessSlice = (state: SheetFetchState): SheetSlice => ({+ sheet: undefined,+ sheetsMap: EMPTY_SHEETS_MAP,+ state,+});++const seedSheetSlice = (+ task: Task | undefined,+ taskRunName: string | undefined,+ metadataFetchState: FetchState+): SheetSlice => {+ if (!task) {+ return sheetlessSlice(+ buildSheetFetchStateForMissingTask(taskRunName, metadataFetchState)+ );+ }+ if (isReleaseBasedTask(task)) {+ return sheetlessSlice(+ releaseNameOfTaskV1(task)+ ? { status: "loading", source: "release" }+ : { status: "success", source: "release" }+ );+ }+ const sheetName = sheetNameOfTaskV1(task);+ if (!sheetName) {+ return sheetlessSlice({ status: "success", source: "sheet" });+ }+ const cached = getCachedCompleteSheet(sheetName);+ if (cached) {+ return {+ sheet: cached,+ sheetsMap: EMPTY_SHEETS_MAP,+ state: { status: "success", source: "sheet" },+ };+ }+ return sheetlessSlice({ status: "loading", source: "sheet" });+};++export const useTaskRunLogData = (+ taskRunName?: string,+ // When provided, a terminal status lets a cached log skip revalidation+ // entirely — a finished run's log never changes.+ taskRunStatus?: TaskRun_Status,+ // When false, the live log poll is paused (e.g. the card's stage is hidden but+ // kept mounted). The already-fetched log stays; only background refresh stops.+ live = true): UseTaskRunLogDataResult => {const fetchRelease = useAppStore((state) => state.fetchRelease);- const [entries, setEntries] = useState<TaskRunLogEntry[]>([]);- const [sheet, setSheet] = useState<Sheet | undefined>(undefined);- const [sheetsMap, setSheetsMap] = useState<Map<string, Sheet>>(new Map());- const [metadataFetchState, setMetadataFetchState] = useState<FetchState>({- status: "idle",- });- const [logFetchState, setLogFetchState] = useState<FetchState>({- status: "idle",- });- const [sheetFetchState, setSheetFetchState] = useState<SheetFetchState>({- status: "idle",- source: "none",- });const metadataFetchVersion = useRef(0);- const logFetchVersion = useRef(0);+ const logFetchSeq = useRef(0);const sheetFetchVersion = useRef(0);const rolloutName = useMemo(() => {@@ -179,14 +306,24 @@ export const useTaskRunLogData = (return extractRolloutNameFromTaskRunName(taskRunName);}, [taskRunName]);+ // ---- Task metadata (rollout) ----++ // rolloutName is derived from taskRunName, so the run name alone keys both.+ const [metadataFetchState, setMetadataFetchState] =+ useSeededState<FetchState>(taskRunName ?? "", () =>+ seedMetadataState(rolloutName, taskRunName)+ );+useEffect(() => {const version = ++metadataFetchVersion.current;if (!rolloutName || !taskRunName) {- setMetadataFetchState({ status: "idle" });+ return;+ }+ if (seedMetadataState(rolloutName, taskRunName).status === "success") {+ // The cached rollout resolves the task; seeded as success during render.return;}- setMetadataFetchState({ status: "loading" });void useAppStore.getState().fetchRolloutByName(rolloutName, true)@@ -238,56 +375,126 @@ export const useTaskRunLogData = ([metadataFetchState, task]);- useEffect(() => {- const version = ++logFetchVersion.current;- setEntries([]);+ // ---- Log entries ----+ const [logSlice, setLogSlice] = useSeededState<LogSlice>(+ taskRunName ?? "",+ () => seedLogSlice(taskRunName)+ );+ const taskRunNameRef = useLatestRef(taskRunName);++ // A monotonic per-fetch sequence: initial revalidation and every live-poll+ // tick take a number, and a response whose number is no longer the latest is+ // dropped entirely — no cache write, no state write. This keeps overlapping+ // fetches (a slow one for a RUNNING run resolving after a newer one) from+ // rewinding the log or clobbering the terminal-status cache.+ const fetchLog = useCallback(() => {if (!taskRunName) {- setLogFetchState({ status: "idle" });return;}-- setLogFetchState({ status: "loading" });- const request = create(GetTaskRunLogRequestSchema, {- parent: taskRunName,- });- void rolloutServiceClientConnect- .getTaskRunLog(request)+ const requestedTaskRunName = taskRunName;+ const seq = ++logFetchSeq.current;+ // Returned (not `void`ed) so the live poller awaits it and can't start an+ // overlapping tick while the RPC is in flight — otherwise a call slower than+ // the poll interval would be invalidated by the next tick's seq bump and the+ // log could stay loading/stale under sustained latency.+ return rolloutServiceClientConnect+ .getTaskRunLog(+ create(GetTaskRunLogRequestSchema, { parent: taskRunName }),+ { contextValues: createContextValues().set(silentContextKey, true) }+ ).then((response) => {- if (version !== logFetchVersion.current) return;- setEntries(response.entries);- setLogFetchState({ status: "success" });+ if (+ seq !== logFetchSeq.current ||+ requestedTaskRunName !== taskRunNameRef.current+ ) {+ return;+ }+ cacheLogEntries(requestedTaskRunName, {+ entries: response.entries,+ status: taskRunStatus,+ });+ // Identity-stable across live-poll ticks: unchanged entries keep the+ // previous slice so the viewer doesn't re-render for nothing.+ setLogSlice((prev) =>+ prev.state.status === "success" &&+ sameMessageList(TaskRunLogEntrySchema, prev.entries, response.entries)+ ? prev+ : { entries: response.entries, state: { status: "success" } }+ );}).catch((error: unknown) => {- if (version !== logFetchVersion.current) return;- setEntries([]);- setLogFetchState({- status: "error",- error: getErrorMessage(error),- });+ if (+ seq !== logFetchSeq.current ||+ requestedTaskRunName !== taskRunNameRef.current+ ) {+ return;+ }+ // Keep showing stale cached entries over an empty error state.+ setLogSlice((prev) => ({+ entries: prev.entries,+ state: { status: "error", error: getErrorMessage(error) },+ }));});- }, [taskRunName]);+ }, [taskRunName, taskRunNameRef, taskRunStatus, setLogSlice]);+ // Cached entries were painted during render; revalidate on mount / status+ // change only when the cached copy could still change (run not finished).useEffect(() => {- const version = ++sheetFetchVersion.current;+ if (+ taskRunName &&+ !isLogCacheFresh(taskRunLogEntriesCache.get(taskRunName), taskRunStatus)+ ) {+ fetchLog();+ }+ }, [taskRunName, taskRunStatus, fetchLog]);++ // A running task appends log lines as it executes; poll while it runs — but+ // only while this card is live (its stage visible), so a hidden kept-alive+ // stage doesn't keep issuing background log RPCs until the run finishes.+ usePolling(+ live && Boolean(taskRunName) && taskRunStatus === TaskRun_Status.RUNNING,+ LIVE_LOG_POLL_INTERVAL_MS,+ fetchLog+ );++ // Invalidate any in-flight log request on unmount. A status flip (RUNNING→DONE)+ // remounts the viewer under a new key, so a newer instance may already have+ // cached the terminal log; without this, a late RUNNING-era response from this+ // now-unmounted instance would still pass its own per-instance seq guard and+ // rewind that shared cache to an incomplete, stale snapshot. The seq guard is+ // per-instance, so only bumping it here closes the cross-instance window.+ useEffect(+ () => () => {+ logFetchSeq.current++;+ },+ []+ );- // Always clear both sources when task changes, so previous-task data- // cannot be displayed while the new task's requests are in flight.- setSheet(undefined);- setSheetsMap(new Map());+ // ---- Sheet(s) referenced by the log ----- if (!task) {- setSheetFetchState(- buildSheetFetchStateForMissingTask(taskRunName, metadataFetchState)- );+ const sheetSeedKey = `${sheetFetchTaskKey}:${unresolvedTaskMetadataStateKey}:${taskRunName ?? ""}`;+ const [sheetSlice, setSheetSlice] = useSeededState<SheetSlice>(+ sheetSeedKey,+ () => seedSheetSlice(task, taskRunName, metadataFetchState)+ );++ // The effect below is keyed on derived stable strings and reads the latest+ // task through this ref, so a task identity change alone doesn't re-run it+ // (and refetch).+ const taskRef = useLatestRef(task);++ useEffect(() => {+ const version = ++sheetFetchVersion.current;+ const currentTask = taskRef.current;+ if (!currentTask) {+ // The missing-task state was seeded during render.return;}- if (isReleaseBasedTask(task)) {- setSheetFetchState({ status: "loading", source: "release" });- const releaseName = releaseNameOfTaskV1(task);+ if (isReleaseBasedTask(currentTask)) {+ const releaseName = releaseNameOfTaskV1(currentTask);if (!releaseName) {- setSheetFetchState({ status: "success", source: "release" });return;}@@ -296,89 +503,91 @@ export const useTaskRunLogData = (const fileSheets = await Promise.all((release?.files ?? []).filter((file) => file.sheet && file.version)- .map(async (file) => {- try {- const fetchedSheet = await sheetServiceClientConnect.getSheet(- {- name: file.sheet,- raw: true,- }- );- return { version: file.version, sheet: fetchedSheet };- } catch (error: unknown) {- return {- version: file.version,- error: getErrorMessage(error),- };- }- })+ .map(async (file) => ({+ version: file.version,+ // Resolves undefined on failure; the result builder counts+ // sheetless versions as failed.+ sheet: await useAppStore+ .getState()+ .fetchSheet(file.sheet, true),+ })));if (version !== sheetFetchVersion.current) return;- const releaseResult = buildReleaseSheetFetchResult(- fileSheets- .filter((item) => item?.version)- .map((item) => ({- version: item.version,- sheet: item.sheet,- }))- );- setSheetsMap(releaseResult.sheetsMap);- setSheetFetchState(releaseResult.state);+ const releaseResult = buildReleaseSheetFetchResult(fileSheets);+ setSheetSlice({+ sheet: undefined,+ sheetsMap: releaseResult.sheetsMap,+ state: releaseResult.state,+ });}).catch((error: unknown) => {if (version !== sheetFetchVersion.current) return;- setSheetsMap(new Map());- setSheetFetchState({- status: "error",- source: "release",- error: getErrorMessage(error),- });+ setSheetSlice(+ sheetlessSlice({+ status: "error",+ source: "release",+ error: getErrorMessage(error),+ })+ );});return;}- setSheetFetchState({ status: "loading", source: "sheet" });- const sheetName = sheetNameOfTaskV1(task);- if (!sheetName) {- setSheetFetchState({ status: "success", source: "sheet" });+ const sheetName = sheetNameOfTaskV1(currentTask);+ if (!sheetName || getCachedCompleteSheet(sheetName)) {+ // Seeded as success (empty or from cache) during render.return;}- void sheetServiceClientConnect- .getSheet({- name: sheetName,- raw: true,- })+ void useAppStore+ .getState()+ .fetchSheet(sheetName, true).then((fetchedSheet) => {if (version !== sheetFetchVersion.current) return;- setSheet(fetchedSheet);- setSheetFetchState({ status: "success", source: "sheet" });+ if (!fetchedSheet) {+ setSheetSlice(+ sheetlessSlice({+ status: "error",+ source: "sheet",+ error: `Failed to fetch sheet ${sheetName}`,+ })+ );+ return;+ }+ setSheetSlice({+ sheet: fetchedSheet,+ sheetsMap: EMPTY_SHEETS_MAP,+ state: { status: "success", source: "sheet" },+ });}).catch((error: unknown) => {+ // Symmetric with the release branch: without this a rejecting fetch+ // would leave the slice stuck on "loading" and float an unhandled+ // rejection.if (version !== sheetFetchVersion.current) return;- setSheet(undefined);- setSheetFetchState({- status: "error",- source: "sheet",- error: getErrorMessage(error),- });+ setSheetSlice(+ sheetlessSlice({+ status: "error",+ source: "sheet",+ error: getErrorMessage(error),+ })+ );});}, [fetchRelease,- task,taskRunName,sheetFetchTaskKey,unresolvedTaskMetadataStateKey,]);return {- entries,- sheet,- sheetsMap,+ entries: logSlice.entries,+ sheet: sheetSlice.sheet,+ sheetsMap: sheetSlice.sheetsMap,metadataFetch: metadataFetchState,- logFetch: logFetchState,- sheetFetch: sheetFetchState,+ logFetch: logSlice.state,+ sheetFetch: sheetSlice.state,};};diff --git a/frontend/src/react/components/task-run-log/useTaskRunLogSections.ts b/frontend/src/react/components/task-run-log/useTaskRunLogSections.tsindex 13ed89c3ac..0d0fdada66 100644--- a/frontend/src/react/components/task-run-log/useTaskRunLogSections.ts+++ b/frontend/src/react/components/task-run-log/useTaskRunLogSections.ts@@ -8,8 +8,6 @@ import type { TaskRunLogDetailText } from "./model";import {buildReleaseFileGroups,buildSectionsFromEntries,- formatDuration,- getEntryTimeRange,getUniqueReplicaIds,groupEntriesByReleaseFile,groupEntriesByReplica,@@ -64,7 +62,6 @@ export interface UseTaskRunLogSectionsResult {areAllExpanded: boolean;totalSections: number;totalEntries: number;- totalDuration: string;}export const useTaskRunLogSections = ({@@ -472,22 +469,6 @@ export const useTaskRunLogSections = ({sections,]);- const totalDuration = useMemo(() => {- if (entries.length === 0) return "";- const timeRanges = entries.map(getEntryTimeRange);- const startTimes = timeRanges- .map((range) => range.start)- .filter((time) => time > 0);- const endTimes = timeRanges- .map((range) => range.end)- .filter((time) => time > 0);- if (startTimes.length === 0 || endTimes.length === 0) return "";-- const startTime = Math.min(...startTimes);- const endTime = Math.max(...endTimes);- return formatDuration(endTime - startTime);- }, [entries]);-return {sections,hasMultipleReplicas,@@ -508,6 +489,5 @@ export const useTaskRunLogSections = ({areAllExpanded,totalSections,totalEntries,- totalDuration,};};diff --git a/frontend/src/react/hooks/useLatestRef.ts b/frontend/src/react/hooks/useLatestRef.tsnew file mode 100644index 0000000000..62085764f1--- /dev/null+++ b/frontend/src/react/hooks/useLatestRef.ts@@ -0,0 +1,15 @@+import { type RefObject, useRef } from "react";++/**+ * A ref that always holds the latest `value`, updated during render.+ *+ * For effects/callbacks that should be keyed on stable derived strings while+ * still reading the freshest object: polling pages replace proto objects with+ * fresh identities every tick, so depending on the object directly would+ * re-run the effect (and refetch) per tick even when nothing changed.+ */+export function useLatestRef<T>(value: T): RefObject<T> {+ const ref = useRef(value);+ ref.current = value;+ return ref;+}diff --git a/frontend/src/react/hooks/useOnKeyChange.ts b/frontend/src/react/hooks/useOnKeyChange.tsnew file mode 100644index 0000000000..ffda0b4853--- /dev/null+++ b/frontend/src/react/hooks/useOnKeyChange.ts@@ -0,0 +1,19 @@+import { useState } from "react";++/**+ * Runs `onChange` during render whenever `key` changes — the render-time reset+ * idiom (see React docs "storing information from previous renders" and+ * BYT-9763). Resetting state here, instead of in a post-paint effect, means+ * the first paint after a key change already shows the reseeded state rather+ * than flashing the previous key's state and patching it up a frame later.+ *+ * `onChange` should only call state setters (of the same component) and update+ * refs; React re-renders immediately with the new state.+ */+export function useOnKeyChange(key: string, onChange: () => void): void {+ const [trackedKey, setTrackedKey] = useState(key);+ if (key !== trackedKey) {+ setTrackedKey(key);+ onChange();+ }+}diff --git a/frontend/src/react/hooks/usePolling.test.tsx b/frontend/src/react/hooks/usePolling.test.tsxnew file mode 100644index 0000000000..6535135781--- /dev/null+++ b/frontend/src/react/hooks/usePolling.test.tsx@@ -0,0 +1,78 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { usePolling } from "./usePolling";++describe("usePolling", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ test("does not start a new call while the previous is still in flight", async () => {+ let concurrent = 0;+ let maxConcurrent = 0;+ const resolvers: Array<() => void> = [];+ // Each call stays pending until we resolve it — simulating a fetch slower+ // than the poll interval.+ const fn = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ concurrent += 1;+ maxConcurrent = Math.max(maxConcurrent, concurrent);+ resolvers.push(() => {+ concurrent -= 1;+ resolve();+ });+ })+ );++ renderHook(() => usePolling(true, 5000, fn));++ // First tick fires after the interval; its call stays in flight.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(fn).toHaveBeenCalledTimes(1);++ // Long past several intervals, no second call starts while the first is+ // pending — a fixed setInterval would have fired several overlapping calls.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(20000);+ });+ expect(fn).toHaveBeenCalledTimes(1);+ expect(maxConcurrent).toBe(1);++ // Once it settles, the next tick is scheduled one interval later.+ await act(async () => {+ resolvers[0]();+ await Promise.resolve();+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(fn).toHaveBeenCalledTimes(2);+ });++ test("stops the loop when disabled and on unmount", async () => {+ const fn = vi.fn().mockResolvedValue(undefined);+ const { rerender, unmount } = renderHook(+ ({ enabled }: { enabled: boolean }) => usePolling(enabled, 1000, fn),+ { initialProps: { enabled: true } }+ );++ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(fn).toHaveBeenCalledTimes(1);++ // Disabling clears the loop.+ rerender({ enabled: false });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(fn).toHaveBeenCalledTimes(1);+ unmount();+ });+});diff --git a/frontend/src/react/hooks/usePolling.ts b/frontend/src/react/hooks/usePolling.tsnew file mode 100644index 0000000000..a2e33abab8--- /dev/null+++ b/frontend/src/react/hooks/usePolling.ts@@ -0,0 +1,50 @@+import { useEffect } from "react";+import { useLatestRef } from "./useLatestRef";++/**+ * Polls `fn` while `enabled`, waiting `intervalMs` between the end of one call+ * and the start of the next — so a call slower than the interval can't overlap+ * the next tick — and only while the tab is visible (a background tab does no+ * work). `fn` may be async; a rejected tick is swallowed so it never surfaces as+ * an unhandled rejection or stops the loop. The loop stops on unmount or when+ * `enabled` goes false, and reschedules when `intervalMs` changes.+ *+ * `fn` is read through a ref, so passing a fresh closure each render does not+ * restart the loop — only `enabled`/`intervalMs` changes do. To poll again right+ * away after a user action, do an immediate fetch in the action handler; the+ * next tick follows `intervalMs` from there.+ */+export function usePolling(+ enabled: boolean,+ intervalMs: number,+ fn: () => void | Promise<void>+): void {+ const fnRef = useLatestRef(fn);+ useEffect(() => {+ if (!enabled) {+ return;+ }+ let canceled = false;+ let timer: number | undefined;+ const tick = async () => {+ if (!document.hidden) {+ try {+ await fnRef.current();+ } catch {+ // A rejected tick is swallowed — it must not surface as an unhandled+ // rejection or break the loop.+ }+ }+ if (!canceled) {+ timer = window.setTimeout(tick, intervalMs);+ }+ };+ timer = window.setTimeout(tick, intervalMs);+ return () => {+ canceled = true;+ if (timer !== undefined) {+ window.clearTimeout(timer);+ }+ };+ }, [enabled, intervalMs, fnRef]);+}diff --git a/frontend/src/react/hooks/useSeededState.ts b/frontend/src/react/hooks/useSeededState.tsnew file mode 100644index 0000000000..93af307d2d--- /dev/null+++ b/frontend/src/react/hooks/useSeededState.ts@@ -0,0 +1,17 @@+import type { Dispatch, SetStateAction } from "react";+import { useState } from "react";+import { useOnKeyChange } from "./useOnKeyChange";++/**+ * `useState` that re-seeds itself during render whenever `seedKey` changes.+ * Single-state convenience over `useOnKeyChange` — reach for that hook+ * directly when one key change must reset several states at once.+ */+export function useSeededState<T>(+ seedKey: string,+ seed: () => T+): [T, Dispatch<SetStateAction<T>>] {+ const [state, setState] = useState<T>(seed);+ useOnKeyChange(seedKey, () => setState(seed()));+ return [state, setState];+}diff --git a/frontend/src/react/lib/protoIdentity.ts b/frontend/src/react/lib/protoIdentity.tsnew file mode 100644index 0000000000..ab9927b2e7--- /dev/null+++ b/frontend/src/react/lib/protoIdentity.ts@@ -0,0 +1,97 @@+import type { DescMessage, MessageShape } from "@bufbuild/protobuf";+import { equals, isMessage } from "@bufbuild/protobuf";+import type {+ Rollout,+ Stage,+ Task,+ TaskRun,+} from "@/types/proto-es/v1/rollout_service_pb";+import {+ RolloutSchema,+ StageSchema,+ TaskRunSchema,+ TaskSchema,+} from "@/types/proto-es/v1/rollout_service_pb";++// Identity-preserving comparison for polled proto data. Every poll tick+// rebuilds objects from the wire; keeping the previous reference when content+// is unchanged is what lets memoized components, effect deps, and prop+// comparisons skip work. Object identity is the contract downstream code keys+// off.++// Reference equality first; structural equality only for actual proto+// messages (test fixtures often cast plain objects, which `equals` rejects).+export const sameMessage = <Desc extends DescMessage>(+ schema: Desc,+ prev: MessageShape<Desc> | undefined,+ next: MessageShape<Desc> | undefined+): boolean =>+ prev === next ||+ (!!prev &&+ !!next &&+ isMessage(prev, schema) &&+ isMessage(next, schema) &&+ equals(schema, prev, next));++export const sameMessageList = <Desc extends DescMessage>(+ schema: Desc,+ prev: MessageShape<Desc>[],+ next: MessageShape<Desc>[]+): boolean =>+ prev === next ||+ (prev.length === next.length &&+ prev.every((item, index) => sameMessage(schema, item, next[index])));++// Rollout gets deep structural sharing: a poll tick that changes one running+// task's fields hands out new references for that task (plus its stage and the+// rollout shell) only — every other task and stage keeps its previous+// reference, so their memoized consumers skip re-rendering. Rebuilt levels are+// plain spreads, which keep $typeName and stay comparable by equals() on the+// next tick.+export const preserveRolloutIdentities = (+ prev: Rollout | undefined,+ next: Rollout | undefined+): Rollout | undefined => {+ if (sameMessage(RolloutSchema, prev, next)) {+ return prev;+ }+ if (!prev || !next) {+ return next;+ }+ const prevStages = new Map(prev.stages.map((stage) => [stage.name, stage]));+ const stages = next.stages.map((nextStage): Stage => {+ const prevStage = prevStages.get(nextStage.name);+ if (!prevStage) {+ return nextStage;+ }+ if (sameMessage(StageSchema, prevStage, nextStage)) {+ return prevStage;+ }+ const prevTasks = new Map(prevStage.tasks.map((task) => [task.name, task]));+ const tasks = nextStage.tasks.map((nextTask): Task => {+ const prevTask = prevTasks.get(nextTask.name);+ return prevTask && sameMessage(TaskSchema, prevTask, nextTask)+ ? prevTask+ : nextTask;+ });+ return { ...nextStage, tasks };+ });+ return { ...next, stages };+};++// Task runs get the same per-element sharing: when one run changes (e.g. its+// updateTime ticks while executing), every other run keeps its previous+// reference so per-task groups downstream stay identity-stable.+export const preserveTaskRunIdentities = (+ prev: TaskRun[],+ next: TaskRun[]+): TaskRun[] => {+ if (sameMessageList(TaskRunSchema, prev, next)) {+ return prev;+ }+ const prevByName = new Map(prev.map((run) => [run.name, run]));+ return next.map((run) => {+ const prevRun = prevByName.get(run.name);+ return prevRun && sameMessage(TaskRunSchema, prevRun, run) ? prevRun : run;+ });+};diff --git a/frontend/src/react/lib/taskRun.test.ts b/frontend/src/react/lib/taskRun.test.tsnew file mode 100644index 0000000000..8f0b99f57a--- /dev/null+++ b/frontend/src/react/lib/taskRun.test.ts@@ -0,0 +1,197 @@+import type { MessageInitShape } from "@bufbuild/protobuf";+import { create } from "@bufbuild/protobuf";+import { TimestampSchema } from "@bufbuild/protobuf/wkt";+import type { TFunction } from "i18next";+import { describe, expect, test } from "vitest";+import {+ TaskRun_Status,+ TaskRunSchema,+} from "@/types/proto-es/v1/rollout_service_pb";+import {+ executionDurationOfTaskRun,+ getTaskRunComment,+ getTaskRunWaitingMessage,+ sortTaskRunsNewestFirst,+} from "./taskRun";++const t = ((key: string, options?: Record<string, unknown>) =>+ options ? `${key}:${JSON.stringify(options)}` : key) as TFunction;++const ts = (seconds: number) =>+ create(TimestampSchema, { seconds: BigInt(seconds) });++const makeTaskRun = (overrides: MessageInitShape<typeof TaskRunSchema> = {}) =>+ create(TaskRunSchema, overrides);++describe("sortTaskRunsNewestFirst", () => {+ const taskName = "projects/p1/rollouts/r1/stages/s1/tasks/t1";++ test("sorts by createTime descending without mutating the input", () => {+ const oldest = makeTaskRun({+ name: `${taskName}/taskRuns/1`,+ createTime: ts(100),+ });+ const newest = makeTaskRun({+ name: `${taskName}/taskRuns/3`,+ createTime: ts(300),+ });+ const middle = makeTaskRun({+ name: `${taskName}/taskRuns/2`,+ createTime: ts(200),+ });+ const input = [oldest, newest, middle];++ const sorted = sortTaskRunsNewestFirst(input);++ expect(sorted.map((run) => run.name)).toEqual([+ newest.name,+ middle.name,+ oldest.name,+ ]);+ expect(input[0]).toBe(oldest);+ });++ test("orders runs created in the same second by sub-second precision", () => {+ const tsMs = (seconds: number, millis: number) =>+ create(TimestampSchema, {+ seconds: BigInt(seconds),+ nanos: millis * 1_000_000,+ });+ const earlier = makeTaskRun({ name: "r/a", createTime: tsMs(100, 100) });+ const later = makeTaskRun({ name: "r/b", createTime: tsMs(100, 800) });++ expect(+ sortTaskRunsNewestFirst([earlier, later]).map((run) => run.name)+ ).toEqual([later.name, earlier.name]);+ });+});++describe("executionDurationOfTaskRun", () => {+ test("returns undefined without start or update time", () => {+ expect(executionDurationOfTaskRun(makeTaskRun())).toBeUndefined();+ expect(+ executionDurationOfTaskRun(makeTaskRun({ startTime: ts(100) }))+ ).toBeUndefined();+ expect(+ executionDurationOfTaskRun(+ makeTaskRun({ startTime: ts(0), updateTime: ts(100) })+ )+ ).toBeUndefined();+ });++ test("computes duration from start to update time for finished runs", () => {+ const duration = executionDurationOfTaskRun(+ makeTaskRun({+ startTime: ts(100),+ status: TaskRun_Status.DONE,+ updateTime: ts(163),+ })+ );+ expect(duration?.seconds).toBe(63n);+ });++ test("computes elapsed-until-now duration for running runs", () => {+ const startSeconds = Math.floor(Date.now() / 1000) - 30;+ const duration = executionDurationOfTaskRun(+ makeTaskRun({+ startTime: ts(startSeconds),+ status: TaskRun_Status.RUNNING,+ updateTime: ts(startSeconds),+ })+ );+ expect(Number(duration?.seconds)).toBeGreaterThanOrEqual(29);+ expect(Number(duration?.seconds)).toBeLessThan(40);+ });++ test("a running run counts up even without an updateTime yet", () => {+ const startSeconds = Math.floor(Date.now() / 1000) - 30;+ const duration = executionDurationOfTaskRun(+ makeTaskRun({+ startTime: ts(startSeconds),+ status: TaskRun_Status.RUNNING,+ })+ );+ expect(Number(duration?.seconds)).toBeGreaterThanOrEqual(29);+ });++ test("clamps a future start time (clock skew) to zero, never negative", () => {+ const startSeconds = Math.floor(Date.now() / 1000) + 10_000;+ const duration = executionDurationOfTaskRun(+ makeTaskRun({+ startTime: ts(startSeconds),+ status: TaskRun_Status.RUNNING,+ })+ );+ expect(duration?.seconds).toBe(0n);+ expect(duration?.nanos).toBe(0);+ });+});++describe("getTaskRunComment", () => {+ test("pending without runTime reports enqueued", () => {+ const comment = getTaskRunComment(+ makeTaskRun({ status: TaskRun_Status.PENDING }),+ t+ );+ expect(comment).toBe("task-run.status.enqueued");+ });++ test("pending with runTime reports the scheduled time", () => {+ const comment = getTaskRunComment(+ makeTaskRun({ runTime: ts(1700000000), status: TaskRun_Status.PENDING }),+ t+ );+ expect(comment).toContain("task-run.status.enqueued-with-rollout-time");+ });++ test("running with parallel-tasks-limit waiting cause reports it", () => {+ const comment = getTaskRunComment(+ makeTaskRun({+ schedulerInfo: {+ reportTime: ts(1700000000),+ waitingCause: {+ cause: { case: "parallelTasksLimit", value: true },+ },+ },+ status: TaskRun_Status.RUNNING,+ }),+ t+ );+ expect(comment).toContain("task-run.status.waiting-max-tasks-per-rollout");+ });++ test("falls back to detail, then a dash", () => {+ expect(+ getTaskRunComment(+ makeTaskRun({ detail: "applied", status: TaskRun_Status.DONE }),+ t+ )+ ).toBe("applied");+ expect(+ getTaskRunComment(makeTaskRun({ status: TaskRun_Status.DONE }), t)+ ).toBe("-");+ });+});++describe("getTaskRunWaitingMessage", () => {+ test("reports waiting states and stays silent otherwise", () => {+ expect(+ getTaskRunWaitingMessage(+ makeTaskRun({ status: TaskRun_Status.PENDING }),+ t+ )+ ).toBe("task-run.status.enqueued");+ // Running without a recognized waiting cause is not "waiting" — even with+ // detail set, the waiting helper stays silent (the card shows no state+ // line rather than an italic dash).+ expect(+ getTaskRunWaitingMessage(+ makeTaskRun({ detail: "applying", status: TaskRun_Status.RUNNING }),+ t+ )+ ).toBeUndefined();+ expect(+ getTaskRunWaitingMessage(makeTaskRun({ status: TaskRun_Status.DONE }), t)+ ).toBeUndefined();+ });+});diff --git a/frontend/src/react/lib/taskRun.ts b/frontend/src/react/lib/taskRun.tsnew file mode 100644index 0000000000..452164debc--- /dev/null+++ b/frontend/src/react/lib/taskRun.ts@@ -0,0 +1,89 @@+import { create } from "@bufbuild/protobuf";+import type { Duration } from "@bufbuild/protobuf/wkt";+import { DurationSchema } from "@bufbuild/protobuf/wkt";+import type { TFunction } from "i18next";+import { extractUserEmail } from "@/store/modules/v1/common";+import { getTimeForPbTimestampProtoEs } from "@/types";+import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";+import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";+import { formatAbsoluteDateTime, humanizeDurationV1 } from "@/utils";++// Millisecond resolution so two runs created in the same wall-clock second+// (e.g. a quick double rerun) still sort by their real order.+const createTimeMs = (taskRun: TaskRun): number =>+ taskRun.createTime ? getTimeForPbTimestampProtoEs(taskRun.createTime) : 0;++export const sortTaskRunsNewestFirst = (taskRuns: TaskRun[]): TaskRun[] =>+ [...taskRuns].sort((left, right) => createTimeMs(right) - createTimeMs(left));++export const executorEmailOfTaskRun = (taskRun: TaskRun): string =>+ extractUserEmail(taskRun.creator);++export const executionDurationOfTaskRun = (+ taskRun: TaskRun+): Duration | undefined => {+ const { startTime, updateTime, status } = taskRun;+ if (!startTime || Number(startTime.seconds) === 0) {+ return undefined;+ }+ const startMS = getTimeForPbTimestampProtoEs(startTime);+ // A running run counts up to now (no updateTime needed); a finished run uses+ // its last update. Clamp negatives to 0 so client/server clock skew can't+ // render a nonsensical negative duration.+ let elapsedMS: number;+ if (status === TaskRun_Status.RUNNING) {+ elapsedMS = Date.now() - startMS;+ } else {+ if (!updateTime) {+ return undefined;+ }+ elapsedMS = getTimeForPbTimestampProtoEs(updateTime) - startMS;+ }+ elapsedMS = Math.max(0, elapsedMS);+ return create(DurationSchema, {+ nanos: (elapsedMS % 1000) * 1e6,+ seconds: BigInt(Math.floor(elapsedMS / 1000)),+ });+};++// The canonical rendered duration for a task run: empty string when the run+// has no duration yet. One place so the card, expanded body, and history sheet+// stay identical.+export const formatTaskRunDuration = (taskRun: TaskRun): string => {+ const duration = executionDurationOfTaskRun(taskRun);+ return duration ? humanizeDurationV1(duration) : "";+};++// The one state line that matters for a run that hasn't produced output yet:+// enqueued, scheduled after a time, or held back by the parallel-task limit.+// Returns undefined when the run isn't waiting.+export const getTaskRunWaitingMessage = (+ taskRun: TaskRun,+ t: TFunction+): string | undefined => {+ if (taskRun.status === TaskRun_Status.PENDING) {+ const earliestAllowedTime = taskRun.runTime+ ? getTimeForPbTimestampProtoEs(taskRun.runTime)+ : null;+ if (earliestAllowedTime) {+ return t("task-run.status.enqueued-with-rollout-time", {+ time: formatAbsoluteDateTime(earliestAllowedTime),+ });+ }+ return t("task-run.status.enqueued");+ }+ if (taskRun.status === TaskRun_Status.RUNNING && taskRun.schedulerInfo) {+ const cause = taskRun.schedulerInfo.waitingCause;+ if (cause?.cause?.case === "parallelTasksLimit") {+ return t("task-run.status.waiting-max-tasks-per-rollout", {+ time: formatAbsoluteDateTime(+ getTimeForPbTimestampProtoEs(taskRun.schedulerInfo.reportTime)+ ),+ });+ }+ }+ return undefined;+};++export const getTaskRunComment = (taskRun: TaskRun, t: TFunction): string =>+ getTaskRunWaitingMessage(taskRun, t) ?? (taskRun.detail || "-");diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailTaskRunTable.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailTaskRunTable.tsxindex ed3213fedf..c366b189f3 100644--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailTaskRunTable.tsx+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailTaskRunTable.tsx@@ -1,5 +1,3 @@-import { create } from "@bufbuild/protobuf";-import { DurationSchema } from "@bufbuild/protobuf/wkt";import { useEffect, useMemo } from "react";import { useTranslation } from "react-i18next";import { EngineIcon } from "@/react/components/EngineIcon";@@ -15,18 +13,16 @@ import {TableRow,} from "@/react/components/ui/table";import { useProjectByName } from "@/react/hooks/useProjectByName";+import {+ executionDurationOfTaskRun,+ getTaskRunComment,+ sortTaskRunsNewestFirst,+} from "@/react/lib/taskRun";import { useAppStore } from "@/react/stores/app";import { projectNamePrefix } from "@/store/modules/v1/common";-import {- getDateForPbTimestampProtoEs,- getTimeForPbTimestampProtoEs,-} from "@/types";+import { getDateForPbTimestampProtoEs } from "@/types";import type { Database } from "@/types/proto-es/v1/database_service_pb";-import {- type Task,- type TaskRun,- TaskRun_Status,-} from "@/types/proto-es/v1/rollout_service_pb";+import type { Task, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";import {databaseForTask,extractDatabaseResourceName,@@ -64,13 +60,10 @@ export function IssueDetailTaskRunTable({return map;}, [page.rollout?.stages]);- const sortedTaskRuns = useMemo(() => {- return [...taskRuns].sort((left, right) => {- const leftTime = left.createTime ? Number(left.createTime.seconds) : 0;- const rightTime = right.createTime ? Number(right.createTime.seconds) : 0;- return rightTime - leftTime;- });- }, [taskRuns]);+ const sortedTaskRuns = useMemo(+ () => sortTaskRunsNewestFirst(taskRuns),+ [taskRuns]+ );useEffect(() => {if (!showDatabaseColumn) {@@ -135,6 +128,7 @@ export function IssueDetailTaskRunTable({<TableBody>{sortedTaskRuns.map((taskRun) => {const database = getDatabaseForTaskRun(taskRun);+ const duration = executionDurationOfTaskRun(taskRun);return (<TableRow key={taskRun.name}><TableCell className="px-2">@@ -160,11 +154,7 @@ export function IssueDetailTaskRunTable({</TableCell><TableCell className="pr-6 whitespace-nowrap"><span className="whitespace-nowrap text-sm text-control">- {executionDurationOfTaskRun(taskRun)- ? humanizeDurationV1(- executionDurationOfTaskRun(taskRun)- )- : "-"}+ {duration ? humanizeDurationV1(duration) : "-"}</span></TableCell></TableRow>@@ -179,31 +169,7 @@ export function IssueDetailTaskRunTable({function IssueDetailTaskRunComment({ taskRun }: { taskRun: TaskRun }) {const { t } = useTranslation();- const earliestAllowedTime = taskRun.runTime- ? getTimeForPbTimestampProtoEs(taskRun.runTime)- : null;-- const comment = (() => {- if (taskRun.status === TaskRun_Status.PENDING) {- if (earliestAllowedTime) {- return t("task-run.status.enqueued-with-rollout-time", {- time: formatAbsoluteDateTime(earliestAllowedTime),- });- }- return t("task-run.status.enqueued");- }- if (taskRun.status === TaskRun_Status.RUNNING && taskRun.schedulerInfo) {- const cause = taskRun.schedulerInfo.waitingCause;- if (cause?.cause?.case === "parallelTasksLimit") {- return t("task-run.status.waiting-max-tasks-per-rollout", {- time: formatAbsoluteDateTime(- getTimeForPbTimestampProtoEs(taskRun.schedulerInfo.reportTime)- ),- });- }- }- return taskRun.detail || "-";- })();+ const comment = getTaskRunComment(taskRun, t);return (<div className="flex flex-col gap-y-0.5 xl:flex-row xl:items-center xl:gap-x-1">@@ -278,27 +244,3 @@ function IssueDetailTaskRunDatabaseCell({ database }: { database: Database }) {</div>);}--function executionDurationOfTaskRun(taskRun: TaskRun) {- const { startTime, updateTime } = taskRun;- if (!startTime || !updateTime) {- return undefined;- }- if (Number(startTime.seconds) === 0) {- return undefined;- }- if (taskRun.status === TaskRun_Status.RUNNING) {- const elapsedMS = Date.now() - getTimeForPbTimestampProtoEs(startTime);- return create(DurationSchema, {- nanos: (elapsedMS % 1000) * 1e6,- seconds: BigInt(Math.floor(elapsedMS / 1000)),- });- }- const elapsedMS =- getTimeForPbTimestampProtoEs(updateTime) -- getTimeForPbTimestampProtoEs(startTime);- return create(DurationSchema, {- nanos: (elapsedMS % 1000) * 1e6,- seconds: BigInt(Math.floor(elapsedMS / 1000)),- });-}diff --git a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsxindex 1d62521612..14989a7434 100644--- a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx@@ -53,17 +53,6 @@ vi.mock("@/react/components/ui/button", () => ({}) => <button onClick={onClick}>{children}</button>,}));-vi.mock("@/react/components/ui/sheet", () => ({- Sheet: ({ children, open }: { children: ReactNode; open: boolean }) =>- open ? <div>{children}</div> : null,- SheetBody: ({ children }: { children: ReactNode }) => <div>{children}</div>,- SheetContent: ({ children }: { children: ReactNode }) => (- <div>{children}</div>- ),- SheetHeader: ({ children }: { children: ReactNode }) => <div>{children}</div>,- SheetTitle: ({ children }: { children: ReactNode }) => <div>{children}</div>,-}));-vi.mock("@/react/lib/utils", () => ({cn: (...classes: Array<string | false | null | undefined>) =>classes.filter(Boolean).join(" "),@@ -73,10 +62,6 @@ vi.mock("./components/deploy/DeployBranch", () => ({DeployBranch: () => null,}));-vi.mock("./components/deploy/DeployTaskDetailPanel", () => ({- DeployTaskDetailPanel: () => null,-}));-vi.mock("./components/review/PlanReviewSection", () => ({PlanReviewSection: () => null,}));@@ -110,10 +95,6 @@ vi.mock("./components/PlanDetailHeaderDetails", () => ({PlanDetailHeaderDetails: () => null,}));-vi.mock("./shell/constants", () => ({- INLINE_TASK_PANEL_BREAKPOINT_PX: 1024,-}));-vi.mock("./shell/hooks/usePlanDetailPage", () => ({usePlanDetailPage: mocks.usePlanDetailPage,}));@@ -147,14 +128,11 @@ const buildPage = (): PlanDetailPageState =>({activePhases: new Set(["changes"]),bypassLeaveGuardOnce: vi.fn(),- closeTaskPanel: vi.fn(),- containerWidth: 1200,currentUser: { name: "users/[email protected]" },expandPhase: vi.fn(),isCreating: true,isEditing: false,isInitializing: false,- isRefreshing: false,pageKey: "foo/create/spec-1",patchState: vi.fn(),pendingLeaveConfirm: false,@@ -181,7 +159,6 @@ const buildPage = (): PlanDetailPageState =>routePhase: "changes",selectedTaskName: undefined,setEditing: vi.fn(),- layoutMode: "NONE",taskRuns: [],togglePhase: vi.fn(),}) as unknown as PlanDetailPageState;diff --git a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsxindex f2422dbcd9..7af0e09822 100644--- a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx+++ b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx@@ -1,5 +1,5 @@-import { Code2, Loader2, MessageSquareMore, Rocket, X } from "lucide-react";-import type { CSSProperties, ReactNode } from "react";+import { Code2, Loader2, MessageSquareMore, Rocket } from "lucide-react";+import type { ReactNode } from "react";import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import {@@ -10,27 +10,18 @@ import {} from "@/react/components/ui/alert-dialog";import { Badge } from "@/react/components/ui/badge";import { Button } from "@/react/components/ui/button";-import {- Sheet,- SheetBody,- SheetContent,- SheetHeader,- SheetTitle,-} from "@/react/components/ui/sheet";import { cn } from "@/react/lib/utils";import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";import { getRolloutStatus } from "@/utils";import { getReviewBadge } from "../utils/reviewBadge";import { DeployBranch } from "./components/deploy/DeployBranch";-import { DeployTaskDetailPanel } from "./components/deploy/DeployTaskDetailPanel";import { PlanDetailChangesBranch } from "./components/PlanDetailChangesBranch";import { PlanDetailDeployFuture } from "./components/PlanDetailDeployFuture";import { PlanDetailHeader } from "./components/PlanDetailHeader";import { PlanDetailHeaderDetails } from "./components/PlanDetailHeaderDetails";import { PlanReviewSection } from "./components/review/PlanReviewSection";import { PlanDetailStoreProvider } from "./shared/stores/PlanDetailStoreProvider";-import { INLINE_TASK_PANEL_BREAKPOINT_PX } from "./shell/constants";import { planPhaseAnchorId } from "./shell/focusPhase";import { usePlanDetailPage } from "./shell/hooks/usePlanDetailPage";import { PlanDetailProvider } from "./shell/PlanDetailContext";@@ -96,43 +87,7 @@ function ProjectPlanDetailPageInner({routeName,routeQuery,specId,- pageHost,});- const selectedTask = useMemo(() => {- if (!page.routeTaskId || !page.rollout) {- return undefined;- }- for (const stage of page.rollout.stages) {- const task = stage.tasks.find((item) =>- item.name.endsWith(`/${page.routeTaskId}`)- );- if (task) {- return task;- }- }- return undefined;- }, [page.rollout, page.routeTaskId]);- const supportsInlineDetailPanel =- page.layoutMode === "DESKTOP" &&- page.containerWidth >= INLINE_TASK_PANEL_BREAKPOINT_PX;- const showDesktopDetail = supportsInlineDetailPanel && !!selectedTask;- const showTaskDrawer =- !!selectedTask && !showDesktopDetail && page.layoutMode !== "NONE";-- const desktopLayoutStyle = useMemo<CSSProperties>(() => {- const baseStyle: CSSProperties = {- minHeight: "calc(100vh - 4rem)",- };-- if (showDesktopDetail) {- return {- ...baseStyle,- gridTemplateColumns: "minmax(0, 1fr) minmax(0, 50%)",- };- }-- return baseStyle;- }, [showDesktopDetail]);const isGitOpsPlan = useMemo(() => isReleaseBackedPlan(page.plan.specs),[page.plan.specs]@@ -292,95 +247,67 @@ function ProjectPlanDetailPageInner({</header><PlanDetailHeaderDetails />- <div- className="min-h-0 flex flex-1 flex-col lg:grid"- style={desktopLayoutStyle}- >- <main className="min-w-0 flex-1">- {/* No row gap here: each PhaseSection's pb-6 carries the spacing,+ <main className="min-h-[calc(100vh-4rem)] min-w-0 flex-1">+ {/* No row gap here: each PhaseSection's pb-6 carries the spacing,which the connector line fills so it stays continuous. */}- <div className="flex min-w-0 flex-col pb-6 pl-2 pr-4 pt-4 xl:pr-8 2xl:pr-12">- <PhaseSection- anchorId={planPhaseAnchorId("changes")}- badge={phaseConfigs.changes.badge}- expanded={page.activePhases.has("changes")}- icon={<Code2 className="size-3 md:size-4" />}- lineClass={phaseConfigs.changes.lineClass}- label={t("plan.navigator.changes")}- onSelect={() => page.expandPhase("changes")}- status={phaseConfigs.changes.status}- onToggle={() => page.togglePhase("changes")}- summary={buildChangesSummary(page.plan, t)}- >- <PlanDetailChangesBranch- onSelectedSpecIdChange={setSelectedSpecId}- selectedSpecId={selectedSpecId}- />- </PhaseSection>-- {reviewVisible && (- <PhaseSection- anchorId={planPhaseAnchorId("review")}- badge={phaseConfigs.review.badge}- expanded={page.activePhases.has("review")}- icon={<MessageSquareMore className="size-3 md:size-4" />}- lineClass={phaseConfigs.review.lineClass}- label={t("plan.navigator.review")}- onSelect={() => page.expandPhase("review")}- status={phaseConfigs.review.status}- onToggle={() => page.togglePhase("review")}- summary={buildReviewSummary(page.issue, t)}- future={- <p className="mt-0.5 text-sm text-control-placeholder">- {t("plan.phase.review-description")}- </p>- }- >- <PlanReviewSection />- </PhaseSection>- )}+ <div className="flex min-w-0 flex-col pb-6 pl-2 pr-4 pt-4 xl:pr-8 2xl:pr-12">+ <PhaseSection+ anchorId={planPhaseAnchorId("changes")}+ badge={phaseConfigs.changes.badge}+ expanded={page.activePhases.has("changes")}+ icon={<Code2 className="size-3 md:size-4" />}+ lineClass={phaseConfigs.changes.lineClass}+ label={t("plan.navigator.changes")}+ onSelect={() => page.expandPhase("changes")}+ status={phaseConfigs.changes.status}+ onToggle={() => page.togglePhase("changes")}+ summary={buildChangesSummary(page.plan, t)}+ >+ <PlanDetailChangesBranch+ onSelectedSpecIdChange={setSelectedSpecId}+ selectedSpecId={selectedSpecId}+ />+ </PhaseSection>+ {reviewVisible && (<PhaseSection- anchorId={planPhaseAnchorId("deploy")}- badge={phaseConfigs.deploy.badge}- expanded={page.activePhases.has("deploy")}- icon={<Rocket className="size-3 md:size-4" />}- isLast- label={t("plan.navigator.deploy")}- status={phaseConfigs.deploy.status}- onSelect={() => page.expandPhase("deploy")}- onToggle={() => page.togglePhase("deploy")}- summary={buildDeploySummary(page.rollout, t)}- future={<PlanDetailDeployFuture />}+ anchorId={planPhaseAnchorId("review")}+ badge={phaseConfigs.review.badge}+ expanded={page.activePhases.has("review")}+ icon={<MessageSquareMore className="size-3 md:size-4" />}+ lineClass={phaseConfigs.review.lineClass}+ label={t("plan.navigator.review")}+ onSelect={() => page.expandPhase("review")}+ status={phaseConfigs.review.status}+ onToggle={() => page.togglePhase("review")}+ summary={buildReviewSummary(page.issue, t)}+ future={+ <p className="mt-0.5 text-sm text-control-placeholder">+ {t("plan.phase.review-description")}+ </p>+ }>- <DeployBranch- selectedTask={selectedTask}- onCloseTaskPanel={page.closeTaskPanel}- />+ <PlanReviewSection /></PhaseSection>- </div>- </main>+ )}- {showDesktopDetail && selectedTask && (- <DesktopColumn- header={- <div className="flex items-center justify-between border-b bg-white px-4 py-2">- <span className="textinfolabel">{t("common.detail")}</span>- <Button- size="xs"- appearance="secondary"- onClick={page.closeTaskPanel}- >- <X className="h-4 w-4" />- {t("common.close")}- </Button>- </div>- }+ <PhaseSection+ anchorId={planPhaseAnchorId("deploy")}+ badge={phaseConfigs.deploy.badge}+ expanded={page.activePhases.has("deploy")}+ icon={<Rocket className="size-3 md:size-4" />}+ isLast+ label={t("plan.navigator.deploy")}+ status={phaseConfigs.deploy.status}+ onSelect={() => page.expandPhase("deploy")}+ onToggle={() => page.togglePhase("deploy")}+ summary={buildDeploySummary(page.rollout, t)}+ future={<PlanDetailDeployFuture />}>- <DeployTaskDetailPanel task={selectedTask} />- </DesktopColumn>- )}- </div>+ <DeployBranch />+ </PhaseSection>+ </div>+ </main></div>{!page.ready && (@@ -392,29 +319,6 @@ function ProjectPlanDetailPageInner({</div>)}- <Sheet- onOpenChange={(open) => {- if (!open) {- page.closeTaskPanel();- }- }}- open={showTaskDrawer}- >- <SheetContent- className="w-[40rem] max-w-[calc(100vw-2rem)]"- width="wide"- >- <SheetHeader>- <SheetTitle>{t("common.detail")}</SheetTitle>- </SheetHeader>- <SheetBody className="px-0 py-0">- {selectedTask ? (- <DeployTaskDetailPanel task={selectedTask} />- ) : null}- </SheetBody>- </SheetContent>- </Sheet>-<AlertDialogopen={page.pendingLeaveConfirm}onOpenChange={(open) => {@@ -560,20 +464,3 @@ function PhaseSection({</div>);}--function DesktopColumn({- children,- header,-}: {- children: ReactNode;- header?: ReactNode;-}) {- return (- <div className="min-w-0 border-l bg-white">- <div className="sticky top-0 flex max-h-[calc(100vh-4rem)] min-h-[calc(100vh-4rem)] flex-col overflow-hidden">- {header ? <div className="shrink-0">{header}</div> : null}- <div className="min-h-0 flex-1 overflow-y-auto">{children}</div>- </div>- </div>- );-}diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsxindex df2a414682..d9f2673207 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx@@ -36,6 +36,8 @@ const mocks = vi.hoisted(() => ({string,{ content: Uint8Array; contentSize: bigint; name: string }>(),+ localSheetsVersion: 0,+ localSheetListeners: new Set<() => void>(),patchState: vi.fn(),routerPush: vi.fn(),databaseStore: {@@ -345,30 +347,51 @@ vi.mock("@/utils/v1/databaseGroup", () => ({name.split("/databaseGroups/")[1] ?? name,}));-vi.mock("../utils/localSheet", () => ({- getLocalSheetByName: (name: string) => {- const existing = mocks.localSheets.get(name);- if (existing) return existing;- const sheet = { name, content: new Uint8Array(), contentSize: 0n };- mocks.localSheets.set(name, sheet);- return sheet;- },- getNextLocalSheetUID: () => "-1",- getSpecStatementContent: (spec: {- config?: { case?: string; value?: { sheet?: string } };- }) => {- if (spec.config?.case !== "changeDatabaseConfig") return undefined;- const sheetName = spec.config.value?.sheet;- const sheet = sheetName ? mocks.localSheets.get(sheetName) : undefined;- return sheet?.content;- },- isSameStatementContent: (a?: Uint8Array, b?: Uint8Array) => {- if (a === b) return true;- if (!a || !b || a.length !== b.length) return false;- return a.every((byte, index) => byte === b[index]);- },- removeLocalSheet: vi.fn(),-}));+vi.mock("../utils/localSheet", async () => {+ const { useSyncExternalStore } = await import("react");+ return {+ getLocalSheetByName: (name: string) => {+ const existing = mocks.localSheets.get(name);+ if (existing) return existing;+ const sheet = { name, content: new Uint8Array(), contentSize: 0n };+ mocks.localSheets.set(name, sheet);+ return sheet;+ },+ getNextLocalSheetUID: () => "-1",+ getSpecStatementContent: (spec: {+ config?: { case?: string; value?: { sheet?: string } };+ }) => {+ if (spec.config?.case !== "changeDatabaseConfig") return undefined;+ const sheetName = spec.config.value?.sheet;+ const sheet = sheetName ? mocks.localSheets.get(sheetName) : undefined;+ return sheet?.content;+ },+ isSameStatementContent: (a?: Uint8Array, b?: Uint8Array) => {+ if (a === b) return true;+ if (!a || !b || a.length !== b.length) return false;+ return a.every((byte, index) => byte === b[index]);+ },+ removeLocalSheet: vi.fn(),+ setLocalSheetStatement: (+ sheet: { content: Uint8Array; contentSize: bigint },+ statement: string+ ) => {+ const content = new TextEncoder().encode(statement);+ sheet.content = content;+ sheet.contentSize = BigInt(content.byteLength);+ mocks.localSheetsVersion += 1;+ for (const listener of mocks.localSheetListeners) listener();+ },+ useLocalSheetsVersion: () =>+ useSyncExternalStore(+ (listener) => {+ mocks.localSheetListeners.add(listener);+ return () => mocks.localSheetListeners.delete(listener);+ },+ () => mocks.localSheetsVersion+ ),+ };+});vi.mock("../utils/options", () => ({allowGhostForDatabase: () => false,@@ -543,8 +566,6 @@ function buildPageState(): PlanDetailPageState {return {activePhases: new Set(["changes"]),bypassLeaveGuardOnce: vi.fn(),- closeTaskPanel: vi.fn(),- containerWidth: 1200,currentUser: {name: "users/[email protected]",} as PlanDetailPageState["currentUser"],@@ -552,7 +573,6 @@ function buildPageState(): PlanDetailPageState {isCreating: true,isEditing: false,isInitializing: false,- isRefreshing: false,isRunningChecks: false,pageKey: "foo/create/spec-1",patchState: mocks.patchState,@@ -594,8 +614,8 @@ function buildPageState(): PlanDetailPageState {selectedTaskName: undefined,setEditing: vi.fn(),setIsRunningChecks: vi.fn(),- layoutMode: "DESKTOP",taskRuns: [],+ taskRunsByTaskName: new Map(),togglePhase: vi.fn(),};}@@ -1016,6 +1036,9 @@ describe("PlanDetailChangesBranch", () => {content: new TextEncoder().encode("create table t(id int);"),contentSize: 0n,});+ // A real statement edit goes through setLocalSheetStatement, which bumps the+ // local-sheet version so subscribed consumers re-read the content.+ mocks.localSheetsVersion += 1;act(render);await flush();diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsxindex 0363c756fc..d7695de114 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx@@ -105,11 +105,7 @@ import {import { getStatementSize } from "@/utils/sheet";import { extractDatabaseGroupName } from "@/utils/v1/databaseGroup";import { sheetNameOfSpec } from "@/utils/v1/issue/plan";-import {- extractSheetUID,- getSheetStatement,- setSheetStatement as setLocalSheetStatement,-} from "@/utils/v1/sheet";+import { extractSheetUID, getSheetStatement } from "@/utils/v1/sheet";import { usePlanDetailContext } from "../shell/PlanDetailContext";import {getDefaultGhostConfig,@@ -124,6 +120,8 @@ import {getNextLocalSheetUID,getSpecStatementContent,isSameStatementContent,+ setLocalSheetStatement,+ useLocalSheetsVersion,} from "../utils/localSheet";import {allowGhostForDatabase,@@ -496,10 +494,18 @@ export function PlanDetailChangesBranch({[specId]: (prev[specId] ?? 0) + 1,}));}, []);- const draftContent =- selectedSpec && page.isCreating- ? getSpecStatementContent(selectedSpec)- : undefined;+ // Re-read on every local sheet edit so the staleness gate below hides check+ // results computed for SQL that has since changed (this component doesn't+ // otherwise re-render on a local edit).+ const localSheetsVersion = useLocalSheetsVersion();+ const draftContent = useMemo(+ // localSheetsVersion is a dep so the read re-runs on a local sheet edit.+ () =>+ selectedSpec && page.isCreating+ ? getSpecStatementContent(selectedSpec)+ : undefined,+ [selectedSpec, page.isCreating, localSheetsVersion]+ );const draftCheckState = selectedSpec? draftCheckResultsBySpecId[selectedSpec.id]: undefined;diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsxindex 27b2d69275..ceb07a8f09 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx@@ -14,7 +14,10 @@ import {} from "@/types/proto-es/v1/release_service_pb";import { extractProjectResourceName } from "@/utils";import { usePlanDetailContext } from "../shell/PlanDetailContext";-import { getSpecStatementContent } from "../utils/localSheet";+import {+ getSpecStatementContent,+ useLocalSheetsVersion,+} from "../utils/localSheet";import { transformReleaseCheckResultsToPlanCheckRuns } from "../utils/planCheck";import { PlanTargetDisplay } from "./PlanTargetDisplay";@@ -34,11 +37,16 @@ export function PlanDetailDraftChecks({const page = usePlanDetailContext();const [isRunningChecks, setIsRunningChecks] = useState(false);+ // Re-read the statement bytes whenever a local sheet edit bumps the version,+ // so "Run checks" sends the current SQL rather than the bytes captured on the+ // first render.+ const localSheetsVersion = useLocalSheetsVersion();// content is already the UTF-8 statement bytes, so we send it as-is and use// its reference as the staleness signature — no decode/re-encode roundtrip.const content = useMemo(+ // localSheetsVersion is a dep so the read re-runs on a local sheet edit.() => getSpecStatementContent(selectedSpec),- [selectedSpec]+ [selectedSpec, localSheetsVersion]);const formattedCheckRuns = useMemo(diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsxindex c9e5c698f6..77c795cb59 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx@@ -48,6 +48,7 @@ import {createEmptyLocalSheet,getLocalSheetByName,removeLocalSheet,+ setLocalSheetStatement,} from "../utils/localSheet";import { getSQLAdviceMarkers } from "../utils/sqlAdvice";import { SchemaEditorSheet } from "./SchemaEditorSheet";@@ -65,7 +66,7 @@ export function PlanDetailStatementSection({}) {const { t } = useTranslation();const page = usePlanDetailContext();- const { patchState, setEditing } = page;+ const { setEditing } = page;const databasesByName = useAppStore((s) => s.databasesByName);const currentUser = page.currentUser;const project = page.project;@@ -275,13 +276,14 @@ export function PlanDetailStatementSection({const updateLocalStatement = (nextStatement: string) => {if (!sheetName) return;const sheet = getLocalSheetByName(sheetName);- setSheetStatement(sheet, nextStatement);+ // Notifying write: the empty-statement validation subscribes to local+ // sheets. (Previously this cloned the plan into patchState purely to+ // force a re-render — the identity-preserving snapshot rightly ignores a+ // content-identical clone, so the signal must be explicit.)+ setLocalSheetStatement(sheet, nextStatement);setStatement(nextStatement);setDraftStatement(nextStatement);setIsSheetOversize(false);- if (page.isCreating) {- patchState({ plan: clone(PlanSchema, page.plan) });- }};const handleUploadClick = () => inputRef.current?.click();diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTabStrip.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTabStrip.tsxindex 2ff9809dac..ba09ec2f32 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTabStrip.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTabStrip.tsx@@ -51,7 +51,9 @@ export function PlanDetailTabItem({return (<divclassName={cn(- "relative flex shrink-0 items-center rounded-t-lg border transition-all",+ // No transition here: the tab body swaps in the same commit, so a+ // color fade makes the highlight lag the content and read as flicker.+ "relative flex shrink-0 items-center rounded-t-lg border",selected? "border-gray-200 border-b-transparent bg-white": "border-b-gray-200 border-transparent hover:opacity-80"diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunDetail.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunDetail.tsxdeleted file mode 100644index 5ac11be325..0000000000--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunDetail.tsx+++ /dev/null@@ -1,67 +0,0 @@-import { RefreshCcw } from "lucide-react";-import { useState } from "react";-import { useTranslation } from "react-i18next";-import { TaskRunLogViewer } from "@/react/components/task-run-log";-import { Button } from "@/react/components/ui/button";-import {- Tabs,- TabsList,- TabsPanel,- TabsTrigger,-} from "@/react/components/ui/tabs";-import { Engine } from "@/types/proto-es/v1/common_pb";-import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";-import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";-import { PlanDetailTaskRunSession } from "./PlanDetailTaskRunSession";--export function PlanDetailTaskRunDetail({- databaseEngine,- taskRun,-}: {- databaseEngine?: Engine;- taskRun: TaskRun;-}) {- const { t } = useTranslation();- const [detailKey, setDetailKey] = useState(0);- const showSessionTab = databaseEngine === Engine.POSTGRES;- const showRefreshButton = taskRun.status === TaskRun_Status.RUNNING;-- return (- <Tabs defaultValue="logs">- <TabsList className="gap-x-6">- <TabsTrigger value="logs">{t("issue.task-run.logs")}</TabsTrigger>- {showSessionTab && (- <TabsTrigger value="session">- {t("issue.task-run.session")}- </TabsTrigger>- )}- </TabsList>- {showRefreshButton && (- <div className="mt-2 flex justify-end">- <Button- size="xs"- appearance="secondary"- onClick={() => setDetailKey((value) => value + 1)}- >- <RefreshCcw className="h-3.5 w-3.5" />- {t("common.refresh")}- </Button>- </div>- )}- <TabsPanel value="logs">- <TaskRunLogViewer- key={`logs-${taskRun.name}-${taskRun.status}-${detailKey}`}- taskRunName={taskRun.name}- />- </TabsPanel>- {showSessionTab && (- <TabsPanel value="session">- <PlanDetailTaskRunSession- key={`session-${taskRun.name}-${taskRun.status}-${detailKey}`}- taskRun={taskRun}- />- </TabsPanel>- )}- </Tabs>- );-}diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunSession.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunSession.test.tsxnew file mode 100644index 0000000000..d6bc2c37bc--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunSession.test.tsx@@ -0,0 +1,209 @@+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import {+ type TaskRun,+ TaskRun_Status,+} from "@/types/proto-es/v1/rollout_service_pb";+import { PlanDetailTaskRunSession } from "./PlanDetailTaskRunSession";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ getTaskRunSession: vi.fn(),+}));++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/connect", () => ({+ rolloutServiceClientConnect: { getTaskRunSession: mocks.getTaskRunSession },+}));++// The component's live-session poll interval (module-private constant).+const SESSION_POLL_INTERVAL_MS = 5000;++// A minimal getTaskRunSession response carrying one Postgres session with the+// given pid, enough for the table to render and to tell responses apart.+const responseWithPid = (pid: string) => ({+ session: {+ case: "postgres" as const,+ value: {+ session: {+ pid,+ query: `select ${pid}`,+ state: "active",+ blockedByPids: [],+ },+ blockingSessions: [],+ blockedSessions: [],+ },+ },+});++const runningTaskRun = {+ name: "projects/p/rollouts/1/stages/s/tasks/t/taskRuns/1",+ status: TaskRun_Status.RUNNING,+} as unknown as TaskRun;++describe("PlanDetailTaskRunSession", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ test("an out-of-order session response cannot overwrite fresher data", async () => {+ let resolveFirst: () => void = () => {};+ let resolveSecond: () => void = () => {};+ mocks.getTaskRunSession+ .mockReturnValueOnce(+ new Promise((resolve) => {+ resolveFirst = () => resolve(responseWithPid("111"));+ })+ )+ .mockReturnValueOnce(+ new Promise((resolve) => {+ resolveSecond = () => resolve(responseWithPid("222"));+ })+ )+ .mockReturnValue(new Promise(() => {}));++ const container = document.createElement("div");+ const root = createRoot(container);++ // Mount RUNNING: the initial-load fetch (#1) is in flight.+ await act(async () => {+ root.render(<PlanDetailTaskRunSession taskRun={runningTaskRun} />);+ });++ // A live-poll tick fires the second fetch (#2) while #1 is still pending.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(SESSION_POLL_INTERVAL_MS);+ });++ // The newer fetch resolves first with the fresh session…+ await act(async () => {+ resolveSecond();+ await Promise.resolve();+ });+ // …then the older, superseded fetch resolves late (also clearing loading).+ await act(async () => {+ resolveFirst();+ await Promise.resolve();+ });++ // The stale response must be dropped: the panel shows the fresh session.+ expect(container.textContent).toContain("222");+ expect(container.textContent).not.toContain("111");++ act(() => root.unmount());+ });++ test("a live-poll response is not masked by a slow initial fetch", async () => {+ let resolveInitial: () => void = () => {};+ mocks.getTaskRunSession+ // #1 initial load — held in flight (slow / contended DB).+ .mockReturnValueOnce(+ new Promise((resolve) => {+ resolveInitial = () => resolve(responseWithPid("111"));+ })+ )+ // #2 poll tick — resolves promptly with fresh data.+ .mockResolvedValueOnce(responseWithPid("222"))+ .mockReturnValue(new Promise(() => {}));++ const container = document.createElement("div");+ const root = createRoot(container);++ await act(async () => {+ root.render(<PlanDetailTaskRunSession taskRun={runningTaskRun} />);+ });+ // While the initial fetch is still pending, the spinner is shown.+ expect(container.querySelector(".animate-spin")).not.toBeNull();++ // A poll tick resolves with data before the initial fetch settles.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(SESSION_POLL_INTERVAL_MS);+ await Promise.resolve();+ });++ // The fresh session must render now, not stay hidden behind the spinner+ // until the slow initial fetch settles.+ expect(container.textContent).toContain("222");+ expect(container.querySelector(".animate-spin")).toBeNull();++ // The initial fetch is superseded by the newer poll seq, so its late+ // resolution can't rewind the panel.+ await act(async () => {+ resolveInitial();+ await Promise.resolve();+ });+ expect(container.textContent).toContain("222");++ act(() => root.unmount());+ });++ test("does not fetch on mount while the stage is hidden (inactive)", async () => {+ mocks.getTaskRunSession.mockResolvedValue(responseWithPid("111"));+ const container = document.createElement("div");+ const root = createRoot(container);++ // Mount RUNNING but inactive (a hidden kept-alive stage): no request fires.+ await act(async () => {+ root.render(+ <PlanDetailTaskRunSession taskRun={runningTaskRun} active={false} />+ );+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(15000);+ });+ expect(mocks.getTaskRunSession).not.toHaveBeenCalled();++ // Becoming active loads it lazily.+ await act(async () => {+ root.render(<PlanDetailTaskRunSession taskRun={runningTaskRun} active />);+ });+ await act(async () => {+ await Promise.resolve();+ });+ expect(mocks.getTaskRunSession).toHaveBeenCalled();++ act(() => root.unmount());+ });++ test("pauses the session poll while the stage is hidden (inactive)", async () => {+ mocks.getTaskRunSession.mockResolvedValue(responseWithPid("111"));+ const container = document.createElement("div");+ const root = createRoot(container);++ // Active + running: the initial load plus at least one 5s poll tick fire.+ await act(async () => {+ root.render(<PlanDetailTaskRunSession taskRun={runningTaskRun} active />);+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ const callsWhileActive = mocks.getTaskRunSession.mock.calls.length;+ expect(callsWhileActive).toBeGreaterThanOrEqual(2);++ // Switch stages: the card stays mounted but goes inactive — the poll stops.+ await act(async () => {+ root.render(+ <PlanDetailTaskRunSession taskRun={runningTaskRun} active={false} />+ );+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(15000);+ });+ expect(mocks.getTaskRunSession.mock.calls.length).toBe(callsWhileActive);++ act(() => root.unmount());+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunSession.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunSession.tsxindex 0d83dc751c..23035a14f9 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunSession.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunSession.tsx@@ -1,7 +1,7 @@import { create } from "@bufbuild/protobuf";import { createContextValues } from "@connectrpc/connect";import { AlignHorizontalJustifyStart, Loader2 } from "lucide-react";-import { useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { rolloutServiceClientConnect } from "@/connect";import { silentContextKey } from "@/connect/context-key";@@ -13,6 +13,8 @@ import {TableHeader,TableRow,} from "@/react/components/ui/table";+import { usePolling } from "@/react/hooks/usePolling";+import { sameMessage } from "@/react/lib/protoIdentity";import { getDateForPbTimestampProtoEs } from "@/types";import {GetTaskRunSessionRequestSchema,@@ -20,64 +22,99 @@ import {TaskRun_Status,type TaskRunSession_Postgres,type TaskRunSession_Postgres_Session,+ TaskRunSession_PostgresSchema,} from "@/types/proto-es/v1/rollout_service_pb";-export function PlanDetailTaskRunSession({ taskRun }: { taskRun: TaskRun }) {+// A running task holds its session for the duration of the execution; refresh+// on this cadence so blocking/blocked sessions reflect the live database state+// rather than the moment the panel opened.+const SESSION_POLL_INTERVAL_MS = 5000;++export function PlanDetailTaskRunSession({+ taskRun,+ // When false, pause the live session poll — the card is mounted but its stage+ // is hidden. Defaults to live.+ active = true,+}: {+ taskRun: TaskRun;+ active?: boolean;+}) {const { t } = useTranslation();const [loading, setLoading] = useState(false);const [session, setSession] = useState<TaskRunSession_Postgres | undefined>();+ const isRunning = taskRun.status === TaskRun_Status.RUNNING;+ // Monotonic per-fetch sequence: two overlapping 5s poll ticks (or a tick still+ // in flight when the run settles) must not write a stale session over fresher+ // data. A response whose number is no longer the latest is dropped.+ const sessionFetchSeq = useRef(0);+ const fetchSession = useCallback(async () => {+ const seq = ++sessionFetchSeq.current;+ const response = await rolloutServiceClientConnect.getTaskRunSession(+ create(GetTaskRunSessionRequestSchema, { parent: taskRun.name }),+ { contextValues: createContextValues().set(silentContextKey, true) }+ );+ if (seq !== sessionFetchSeq.current) {+ return;+ }+ const next =+ response.session.case === "postgres" ? response.session.value : undefined;+ // Keep the previous reference when the content is unchanged so the tables+ // don't re-render for nothing.+ setSession((prev) =>+ prev && next && sameMessage(TaskRunSession_PostgresSchema, prev, next)+ ? prev+ : next+ );+ }, [taskRun.name]);++ // Initial load (with spinner). Resetting session + loading when not running+ // keeps the panel consistent if the run finishes before the load resolves.useEffect(() => {+ if (!isRunning) {+ // Invalidate any in-flight fetch so it can't re-populate after the clear.+ sessionFetchSeq.current++;+ setSession(undefined);+ setLoading(false);+ return;+ }+ if (!active) {+ // Hidden kept-alive stage: skip the initial fetch (the live poll is also+ // paused) so a stage the user can't see doesn't issue a request on mount.+ // The load runs lazily once the stage becomes active.+ return;+ }let canceled = false;-- const load = async () => {- if (taskRun.status !== TaskRun_Status.RUNNING) {- setSession(undefined);- return;- }-- try {- setLoading(true);- const response = await rolloutServiceClientConnect.getTaskRunSession(- create(GetTaskRunSessionRequestSchema, {- parent: taskRun.name,- }),- {- contextValues: createContextValues().set(silentContextKey, true),- }- );- if (canceled) {- return;- }- if (response.session.case === "postgres") {- setSession(response.session.value);- } else {- setSession(undefined);- }- } finally {- if (!canceled) {- setLoading(false);- }- }- };-- void load();+ setLoading(true);+ fetchSession()+ .catch(() => undefined)+ .finally(() => {+ if (!canceled) setLoading(false);+ });return () => {canceled = true;};- }, [taskRun.name, taskRun.status]);+ }, [active, isRunning, fetchSession]);- if (loading) {+ // Live refresh while running — swaps data in place (no spinner); a failing+ // tick is swallowed by usePolling.+ usePolling(active && isRunning, SESSION_POLL_INTERVAL_MS, fetchSession);++ // Spinner only before any data lands. A live-poll response that resolves+ // before a slow initial fetch (plausible on a contended DB — exactly what+ // this panel surfaces) must not stay hidden behind the spinner, and a hung+ // initial fetch must not mask session data the poll already fetched.+ if (loading && !session) {return (<div className="flex items-center justify-center py-8 text-control-light">- <Loader2 className="h-5 w-5 animate-spin" />+ <Loader2 className="size-5 animate-spin" /></div>);}if (!session?.session) {return (- <div className="rounded-md border bg-gray-50 p-3 text-sm text-control-light">+ <div className="rounded-md border bg-control-bg p-3 text-sm text-control-light">{t("task-run.no-session-found")}</div>);@@ -86,22 +123,34 @@ export function PlanDetailTaskRunSession({ taskRun }: { taskRun: TaskRun }) {return (<div className="flex w-full flex-col gap-y-2"><SessionTable rows={[session.session]} />- <div>- <div className="flex items-center justify-start gap-x-1 pt-2">- <span className="textlabel">{t("task-run.blocking-sessions")}</span>- <span className="textinfolabel">- ({t("task-run.blocking-sessions-description")})- </span>+ {/* When nothing blocks (the common case), a one-line note replaces the+ header + description + empty table box. */}+ {session.blockingSessions.length > 0 ? (+ <div>+ <div className="flex items-center justify-start gap-x-1 pt-2">+ <span className="text-sm font-medium text-control">+ {t("task-run.blocking-sessions")}+ </span>+ <span className="textinfolabel">+ ({t("task-run.blocking-sessions-description")})+ </span>+ </div>+ <div className="mt-2">+ <SessionTable rows={session.blockingSessions} />+ </div></div>- <div className="mt-2">- <SessionTable rows={session.blockingSessions} />+ ) : (+ <div className="text-sm text-control-light">+ {t("task-run.no-blocking-sessions")}</div>- </div>+ )}{session.blockedSessions.length > 0 && (<div><div className="flex items-center justify-start gap-x-2 pt-2">- <AlignHorizontalJustifyStart className="h-4 w-4 opacity-80" />- <span className="textlabel">{t("task-run.blocked-sessions")}</span>+ <AlignHorizontalJustifyStart className="size-4 opacity-80" />+ <span className="text-sm font-medium text-control">+ {t("task-run.blocked-sessions")}+ </span><span className="textinfolabel">{t("task-run.blocked-sessions-description")}</span>@@ -120,7 +169,7 @@ function SessionTable({ rows }: { rows: TaskRunSession_Postgres_Session[] }) {if (normalizedRows.length === 0) {return (- <div className="rounded-md border bg-gray-50 p-3 text-sm text-control-light">+ <div className="rounded-md border bg-control-bg p-3 text-sm text-control-light">-</div>);diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunTable.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunTable.tsxdeleted file mode 100644index bc9f0070fb..0000000000--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunTable.tsx+++ /dev/null@@ -1,249 +0,0 @@-import { create } from "@bufbuild/protobuf";-import { DurationSchema } from "@bufbuild/protobuf/wkt";-import { useMemo, useState } from "react";-import { useTranslation } from "react-i18next";-import { HumanizeTs } from "@/react/components/HumanizeTs";-import { TaskRunStatusIcon } from "@/react/components/TaskRunStatusIcon";-import { Button } from "@/react/components/ui/button";-import { EllipsisText } from "@/react/components/ui/ellipsis-text";-import {- Sheet,- SheetBody,- SheetContent,- SheetHeader,- SheetTitle,-} from "@/react/components/ui/sheet";-import {- Table,- TableBody,- TableCell,- TableHead,- TableHeader,- TableRow,-} from "@/react/components/ui/table";-import { useAppStore } from "@/react/stores/app";-import {- getDateForPbTimestampProtoEs,- getTimeForPbTimestampProtoEs,-} from "@/types";-import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";-import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";-import { formatAbsoluteDateTime, humanizeDurationV1 } from "@/utils";-import { PlanDetailTaskRunDetail } from "./PlanDetailTaskRunDetail";--export function PlanDetailTaskRunTable({- databaseName,- taskRuns,- selectedTaskRunName,- onSelectTaskRun,-}: {- databaseName?: string;- taskRuns: TaskRun[];- selectedTaskRunName?: string;- onSelectTaskRun?: (taskRunName: string) => void;-}) {- const { t } = useTranslation();- const databasesByName = useAppStore((s) => s.databasesByName);- const [detailTaskRun, setDetailTaskRun] = useState<TaskRun | undefined>();- const sortedTaskRuns = useMemo(() => {- return [...taskRuns].sort((left, right) => {- const leftTime = left.createTime ? Number(left.createTime.seconds) : 0;- const rightTime = right.createTime ? Number(right.createTime.seconds) : 0;- return rightTime - leftTime;- });- }, [taskRuns]);- const database = databaseName ? databasesByName[databaseName] : undefined;-- return (- <>- <div className="overflow-auto rounded-sm border">- <Table className="table-fixed">- <TableHeader>- <TableRow className="hover:bg-transparent">- <TableHead className="sticky top-0 z-10 w-9 bg-gray-50 px-2" />- <TableHead className="sticky top-0 z-10 bg-gray-50">- {t("common.detail")}- </TableHead>- <TableHead className="sticky top-0 z-10 w-36 bg-gray-50">- {t("task.created")}- </TableHead>- <TableHead className="sticky top-0 z-10 w-36 bg-gray-50">- {t("task.started")}- </TableHead>- <TableHead className="sticky top-0 z-10 w-28 bg-gray-50 pr-6 whitespace-nowrap text-sm">- {t("task.execution-time")}- </TableHead>- {!onSelectTaskRun && (- <TableHead className="sticky top-0 z-10 w-24 bg-gray-50 pr-4" />- )}- </TableRow>- </TableHeader>- <TableBody>- {sortedTaskRuns.map((taskRun) => (- <TableRow- key={taskRun.name}- className={[- onSelectTaskRun ? "cursor-pointer" : "",- selectedTaskRunName === taskRun.name- ? "bg-accent/5 hover:bg-accent/5"- : undefined,- ]- .filter(Boolean)- .join(" ")}- onClick={() => onSelectTaskRun?.(taskRun.name)}- >- <TableCell className="px-2">- <TaskRunStatusIcon status={taskRun.status} />- </TableCell>- <TableCell className="min-w-0 pr-2">- <TaskRunComment taskRun={taskRun} />- </TableCell>- <TableCell>- <TaskRunDateCell date={taskRun.createTime} />- </TableCell>- <TableCell>- <TaskRunDateCell date={taskRun.startTime} />- </TableCell>- <TableCell className="pr-6 whitespace-nowrap">- <span className="whitespace-nowrap text-sm text-control">- {executionDurationOfTaskRun(taskRun)- ? humanizeDurationV1(executionDurationOfTaskRun(taskRun))- : "-"}- </span>- </TableCell>- {!onSelectTaskRun && (- <TableCell className="pr-4">- {shouldShowDetailButton(taskRun) ? (- <Button- size="xs"- appearance="outline"- onClick={() => setDetailTaskRun(taskRun)}- >- {t("common.detail")}- </Button>- ) : null}- </TableCell>- )}- </TableRow>- ))}- </TableBody>- </Table>- </div>-- <Sheet- onOpenChange={(open) => {- if (!open) {- setDetailTaskRun(undefined);- }- }}- open={Boolean(detailTaskRun)}- >- <SheetContent width="wide">- <SheetHeader>- <SheetTitle>{t("common.detail")}</SheetTitle>- </SheetHeader>- <SheetBody className="gap-y-4">- {detailTaskRun && (- <PlanDetailTaskRunDetail- databaseEngine={database?.instanceResource?.engine}- taskRun={detailTaskRun}- />- )}- </SheetBody>- </SheetContent>- </Sheet>- </>- );-}--function TaskRunComment({ taskRun }: { taskRun: TaskRun }) {- const { t } = useTranslation();- const earliestAllowedTime = taskRun.runTime- ? getTimeForPbTimestampProtoEs(taskRun.runTime)- : null;-- const comment = (() => {- if (taskRun.status === TaskRun_Status.PENDING) {- if (earliestAllowedTime) {- return t("task-run.status.enqueued-with-rollout-time", {- time: formatAbsoluteDateTime(earliestAllowedTime),- });- }- return t("task-run.status.enqueued");- }- if (taskRun.status === TaskRun_Status.RUNNING && taskRun.schedulerInfo) {- const cause = taskRun.schedulerInfo.waitingCause;- if (cause?.cause?.case === "parallelTasksLimit") {- return t("task-run.status.waiting-max-tasks-per-rollout", {- time: formatAbsoluteDateTime(- getTimeForPbTimestampProtoEs(taskRun.schedulerInfo.reportTime)- ),- });- }- }- return taskRun.detail || "-";- })();-- return (- <div className="flex flex-col gap-y-0.5 xl:flex-row xl:items-center xl:gap-x-1">- <div className="min-w-0 flex-1">- <EllipsisText className="line-clamp-1" text={comment} />- </div>- </div>- );-}--function TaskRunDateCell({- date,-}: {- date?: Parameters<typeof getDateForPbTimestampProtoEs>[0];-}) {- if (!date) {- return <span className="text-control-light">-</span>;- }-- const parsedDate = getDateForPbTimestampProtoEs(date);- if (!parsedDate) {- return <span className="text-control-light">-</span>;- }-- return (- <HumanizeTs- ts={parsedDate.getTime() / 1000}- className="text-sm text-control"- />- );-}--function executionDurationOfTaskRun(taskRun: TaskRun) {- const { startTime, updateTime } = taskRun;- if (!startTime || !updateTime) {- return undefined;- }- if (Number(startTime.seconds) === 0) {- return undefined;- }- if (taskRun.status === TaskRun_Status.RUNNING) {- const elapsedMS = Date.now() - getTimeForPbTimestampProtoEs(startTime);- return create(DurationSchema, {- nanos: (elapsedMS % 1000) * 1e6,- seconds: BigInt(Math.floor(elapsedMS / 1000)),- });- }- const elapsedMS =- getTimeForPbTimestampProtoEs(updateTime) -- getTimeForPbTimestampProtoEs(startTime);- return create(DurationSchema, {- nanos: (elapsedMS % 1000) * 1e6,- seconds: BigInt(Math.floor(elapsedMS / 1000)),- });-}--function shouldShowDetailButton(taskRun: TaskRun) {- return [- TaskRun_Status.RUNNING,- TaskRun_Status.DONE,- TaskRun_Status.FAILED,- TaskRun_Status.CANCELED,- ].includes(taskRun.status);-}diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.test.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.test.tsxnew file mode 100644index 0000000000..88aecefedc--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.test.tsx@@ -0,0 +1,96 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, test, vi } from "vitest";+import type { Rollout, Stage } from "@/types/proto-es/v1/rollout_service_pb";+import type { PlanDetailPageState } from "../../shell/hooks/types";+import { PlanDetailProvider } from "../../shell/PlanDetailContext";+import { DeployBranch } from "./DeployBranch";++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => undefined },+ useTranslation: () => ({ t: (key: string) => key }),+}));++const routerMocks = vi.hoisted(() => ({ push: vi.fn() }));+vi.mock("@/react/router", () => ({ router: { push: routerMocks.push } }));++// Render a button per stage that calls the CURRENT onSelectStage prop, so a+// click uses the latest render's handler (with up-to-date optimistic state).+vi.mock("./DeployStageCard", () => ({+ DeployStageList: ({+ onSelectStage,+ rollout,+ }: {+ onSelectStage: (stage: Stage) => void;+ rollout: Rollout;+ }) => (+ <div>+ {rollout.stages.map((stage) => (+ <button+ key={stage.name}+ type="button"+ data-testid={`select-${stage.name.split("/").pop()}`}+ onClick={() => onSelectStage(stage)}+ >+ {stage.name}+ </button>+ ))}+ </div>+ ),+}));+vi.mock("./DeployStageContentView", () => ({+ DeployStageContentView: () => null,+}));+vi.mock("./DeployPendingTasksSection", () => ({+ DeployPendingTasksSection: () => null,+}));+vi.mock("../../utils/rolloutPreview", () => ({+ generateRolloutPreview: () => Promise.resolve({ stages: [] }),+}));++const ROLLOUT = "projects/p/rollouts/r";+const stage = (id: string): Stage =>+ ({+ name: `${ROLLOUT}/stages/${id}`,+ environment: `environments/${id}`,+ tasks: [{ name: `${ROLLOUT}/stages/${id}/tasks/t1` }],+ }) as unknown as Stage;++const makePage = (routeStageId: string): PlanDetailPageState =>+ ({+ projectId: "p",+ routeStageId,+ selectedTaskName: undefined,+ readonly: false,+ projectCanCreateRollout: true,+ isEditing: false,+ bypassLeaveGuardOnce: vi.fn(),+ refreshState: () => Promise.resolve(),+ plan: { name: "projects/p/plans/1", specs: [] },+ rollout: { name: ROLLOUT, stages: [stage("a"), stage("b")] },+ }) as unknown as PlanDetailPageState;++describe("DeployBranch stage selection", () => {+ test("a quick click back to the route stage supersedes a pending optimistic switch", () => {+ routerMocks.push.mockClear();+ render(+ <PlanDetailProvider value={makePage("a")}>+ <DeployBranch />+ </PlanDetailProvider>+ );++ // Switch to b optimistically. routeStageId still reads "a" (its URL+ // re-render is pending), but the view now shows b.+ fireEvent.click(screen.getByTestId("select-b"));+ expect(routerMocks.push).toHaveBeenLastCalledWith({+ query: { phase: "deploy", stageId: "b" },+ });++ // Immediately click back to a. This must NOT be dropped as a no-op just+ // because routeStageId still reads "a" — the on-screen stage is b, so the+ // click has to push a and win over the pending b navigation.+ fireEvent.click(screen.getByTestId("select-a"));+ expect(routerMocks.push).toHaveBeenLastCalledWith({+ query: { phase: "deploy", stageId: "a" },+ });+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsxindex c122355bbd..c624303260 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsx@@ -2,18 +2,16 @@ import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { Button } from "@/react/components/ui/button";import { router } from "@/react/router";-import { useAppStore } from "@/react/stores/app";-import { projectNamePrefix } from "@/store/modules/v1/common";import type { Plan } from "@/types/proto-es/v1/plan_service_pb";import type { Rollout, Task } from "@/types/proto-es/v1/rollout_service_pb";-import { hasProjectPermissionV2 } from "@/utils";+import { extractStageUID } from "@/utils/v1/issue/rollout";import { usePlanDetailContext } from "../../shell/PlanDetailContext";import { generateRolloutPreview } from "../../utils/rolloutPreview";import { getFrontierStage } from "../lifecycle/frontierStage";import { DeployPendingTasksSection } from "./DeployPendingTasksSection";import { DeployStageList } from "./DeployStageCard";import { DeployStageContentView } from "./DeployStageContentView";-import type { DeployBranchProps, PendingTaskGroup } from "./types";+import type { PendingTaskGroup } from "./types";async function loadPendingGroups(plan: Plan,@@ -43,37 +41,69 @@ async function loadPendingGroups(}));}-export function DeployBranch({- selectedTask,- onCloseTaskPanel: _onCloseTaskPanel,-}: DeployBranchProps) {+export function DeployBranch() {const { t } = useTranslation();const page = usePlanDetailContext();- const projectsByName = useAppStore((s) => s.projectsByName);- const project = useMemo(- () =>- useAppStore- .getState()- .getProjectByName(`${projectNamePrefix}${page.projectId}`),- [page.projectId, projectsByName]- );+ // Full task resource name resolved from the ?taskId= deep link.+ const selectedTaskName = page.selectedTaskName;const projectName = `projects/${page.projectId}`;const [pendingOpen, setPendingOpen] = useState(false);const [pendingGroups, setPendingGroups] = useState<PendingTaskGroup[]>([]);- const rolloutKey =- page.rollout?.stages- .map(- (stage) =>- `${stage.name}:${stage.tasks.map((task) => `${task.target}:${task.specId}`).join(",")}`- )- .join("|") ?? "";- const planKey = `${page.plan.name}:${page.plan.specs.map((spec) => spec.id).join(",")}`;+ // Content fingerprints for the pending-groups effect. rollout/plan+ // identities are poll-stable (snapshot gate), so the O(tasks) string builds+ // run only when content actually changed.+ const rolloutKey = useMemo(+ () =>+ page.rollout?.stages+ .map(+ (stage) =>+ `${stage.name}:${stage.tasks.map((task) => `${task.target}:${task.specId}`).join(",")}`+ )+ .join("|") ?? "",+ [page.rollout]+ );+ const planKey = useMemo(+ () =>+ `${page.plan.name}:${page.plan.specs.map((spec) => spec.id).join(",")}`,+ [page.plan]+ );++ // Stage selection is optimistic: a tab click paints in the same commit,+ // while router.push merely reflects it into the URL. Waiting for the route+ // round trip (which re-renders the whole plan page) reads as a dead click+ // followed by an all-at-once swap. The override is dropped only once the URL+ // actually reflects it — clearing on any routeStageId change instead (the+ // previous approach) let an earlier click's late-settling push reset a newer+ // click, causing a visible snap-back on rapid tab switches.+ const [optimisticStageName, setOptimisticStageName] = useState<+ string | undefined+ >(undefined);+ if (+ optimisticStageName &&+ page.routeStageId &&+ extractStageUID(optimisticStageName) === page.routeStageId+ ) {+ setOptimisticStageName(undefined);+ }+const selectedStage = useMemo(() => {if (!page.rollout?.stages.length) return undefined;- if (selectedTask) {- return page.rollout.stages.find((stage) =>- stage.tasks.some((task) => task.name === selectedTask.name)+ // The optimistic pick wins over the (still-stale) URL selections.+ if (optimisticStageName) {+ const optimisticStage = page.rollout.stages.find(+ (stage) => stage.name === optimisticStageName);+ if (optimisticStage) {+ return optimisticStage;+ }+ }+ if (selectedTaskName) {+ const stageOfTask = page.rollout.stages.find((stage) =>+ stage.tasks.some((task) => task.name === selectedTaskName)+ );+ if (stageOfTask) {+ return stageOfTask;+ }}if (page.routeStageId) {return page.rollout.stages.find((stage) =>@@ -83,7 +113,7 @@ export function DeployBranch({// Default to the frontier (first non-complete) stage, falling back to the// first stage once every stage is complete.return getFrontierStage(page.rollout) ?? page.rollout.stages[0];- }, [page.rollout, page.routeStageId, selectedTask]);+ }, [page.rollout, page.routeStageId, selectedTaskName, optimisticStageName]);useEffect(() => {let canceled = false;@@ -106,8 +136,7 @@ export function DeployBranch({}, [planKey, projectName, rolloutKey]);const hasPendingTasks = pendingGroups.length > 0;- const canCreateRollout =- !page.readonly && hasProjectPermissionV2(project, "bb.rollouts.create");+ const canCreateRollout = !page.readonly && page.projectCanCreateRollout;if (!page.rollout) {return null;@@ -141,7 +170,7 @@ export function DeployBranch({if (!selectedStage) {return (<div className="flex items-center justify-center py-12">- <p className="text-gray-500">{t("rollout.no-stages")}</p>+ <p className="text-control-light">{t("rollout.no-stages")}</p></div>);}@@ -152,21 +181,60 @@ export function DeployBranch({hasPendingTasks={hasPendingTasks}onOpenPreview={() => setPendingOpen(true)}onSelectStage={(stage) => {- void router.push({- query: {- phase: "deploy",- stageId: stage.name.split("/").pop(),- },- });+ // Compare against the stage on screen, not page.routeStageId: an+ // earlier optimistic switch may have already pushed a different stage+ // to the URL while routeStageId still reads the old value (its+ // re-render is pending). Keying off selectedStage lets a quick click+ // back to the route stage supersede that pending switch instead of+ // being dropped as a no-op — and re-clicking the visible stage is+ // still a true no-op (so no unused one-shot guard bypass).+ if (stage.name === selectedStage.name) {+ return;+ }+ const stageId = extractStageUID(stage.name);+ setOptimisticStageName(stage.name);+ // The URL carries only the stage; each stage's card expansion is its+ // own local state (kept alive across switches), so there's nothing+ // per-task to restore through the URL.+ const target = { query: { phase: "deploy", stageId } };+ // A stage switch is an internal same-path query change and a pure+ // visibility flip — keep-alive preserves every stage's editor state,+ // so no edit is lost. Bypass the unsaved-edits guard so it doesn't+ // cancel this push or pop a spurious discard dialog. Arm it ONLY when+ // the push will actually change the URL: the one-shot is consumed by+ // the router guard that fires on a real navigation, so arming it for a+ // no-op push (e.g. a rapid switch-back whose intermediate push hasn't+ // committed) would leave it set for the next genuine leave, silently+ // skipping the discard prompt.+ if (+ page.isEditing &&+ router.resolve(target).fullPath !==+ router.currentRoute.value.fullPath+ ) {+ page.bypassLeaveGuardOnce();+ }+ void router.push(target);}}rollout={page.rollout}selectedStageId={selectedStage.name}/>- <DeployStageContentView- selectedTaskName={selectedTask?.name}- stage={selectedStage}- />+ {/* Every stage's content stays mounted; only the selected one is+ visible. A stage switch just flips visibility, so card state —+ expansion, Monaco editors, fetched logs — survives instead of+ remounting (the flicker). Heavy per-stage work is deferred to first+ activation inside DeployTaskList. */}+ {page.rollout.stages.map((stage) => (+ <div+ className={stage.name === selectedStage.name ? undefined : "hidden"}+ key={stage.name}+ >+ <DeployStageContentView+ active={stage.name === selectedStage.name}+ stage={stage}+ />+ </div>+ ))}<DeployPendingTasksSectiononCreated={async () => {diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployLatestTaskRunInfo.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployLatestTaskRunInfo.tsxindex d151f6dcd8..dc995ddbbe 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployLatestTaskRunInfo.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployLatestTaskRunInfo.tsx@@ -1,105 +1,81 @@-import type { Timestamp } from "@bufbuild/protobuf/wkt";-import {- CheckCircle2,- Circle,- Clock3,- LoaderCircle,- User,- XCircle,-} from "lucide-react";+import { Clock3, History, User } from "lucide-react";import { useTranslation } from "react-i18next";import { HumanizeTs } from "@/react/components/HumanizeTs";+import { TaskRunStatusIcon } from "@/react/components/TaskRunStatusIcon";import { TaskRunLogViewer } from "@/react/components/task-run-log";+import { Button } from "@/react/components/ui/button";import { Tooltip } from "@/react/components/ui/tooltip";+import { executorEmailOfTaskRun } from "@/react/lib/taskRun";+import { cn } from "@/react/lib/utils";import { getDateForPbTimestampProtoEs } from "@/types";+import type { Engine } from "@/types/proto-es/v1/common_pb";+import { Engine as EngineEnum } from "@/types/proto-es/v1/common_pb";+import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";+import { stringifyTaskRunStatus } from "@/utils/v1/issue/rollout";+import { PlanDetailTaskRunSession } from "../PlanDetailTaskRunSession";++const STATUS_LABEL_CLASS: Partial<Record<TaskRun_Status, string>> = {+ [TaskRun_Status.RUNNING]: "text-info",+ [TaskRun_Status.DONE]: "text-success",+ [TaskRun_Status.FAILED]: "text-error",+};export function DeployLatestTaskRunInfo({+ active = true,+ databaseEngine,duration,- executorEmail,- status,- taskRunName,- updateTime,+ historyCount,+ onShowHistory,+ taskRun,}: {+ // When false, the card's stage is hidden (kept mounted); pause the live log+ // and session polls below.+ active?: boolean;+ databaseEngine?: Engine;duration?: string;- executorEmail?: string;- status: TaskRun_Status;- taskRunName?: string;- updateTime?: Timestamp;+ historyCount: number;+ onShowHistory: () => void;+ taskRun: TaskRun;}) {const { t } = useTranslation();- const updateDate = getDateForPbTimestampProtoEs(updateTime);- const statusConfig = (() => {- switch (status) {- case TaskRun_Status.RUNNING:- return {- className: "text-blue-600",- icon: LoaderCircle,- label: t("task.status.running"),- spinning: true,- };- case TaskRun_Status.DONE:- return {- className: "text-green-600",- icon: CheckCircle2,- label: t("task.status.done"),- spinning: false,- };- case TaskRun_Status.FAILED:- return {- className: "text-red-600",- icon: XCircle,- label: t("task.status.failed"),- spinning: false,- };- case TaskRun_Status.CANCELED:- return {- className: "text-gray-500",- icon: Circle,- label: t("task.status.canceled"),- spinning: false,- };- default:- return {- className: "text-gray-500",- icon: Circle,- label: t("task.status.pending"),- spinning: false,- };- }- })();- const StatusIcon = statusConfig.icon;+ const updateDate = getDateForPbTimestampProtoEs(taskRun.updateTime);+ const executorEmail = executorEmailOfTaskRun(taskRun);+ const showSession =+ taskRun.status === TaskRun_Status.RUNNING &&+ databaseEngine === EngineEnum.POSTGRES;return (- <div className="space-y-2">+ <div className="flex flex-col gap-2"><div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">- <span className="shrink-0 font-medium text-gray-700">+ <span className="shrink-0 font-medium text-control">{t("task-run.latest")}</span>- <span className="text-gray-300">·</span>+ <span className="text-control-placeholder">·</span><span- className={`flex shrink-0 items-center gap-x-1 ${statusConfig.className}`}+ className={cn(+ "flex shrink-0 items-center gap-x-1",+ STATUS_LABEL_CLASS[taskRun.status] ?? "text-control-light"+ )}>- <StatusIcon- className={`h-4 w-4 ${statusConfig.spinning ? "animate-spin" : ""}`}- />- <span>{statusConfig.label}</span>+ <TaskRunStatusIcon size="tiny" status={taskRun.status} />+ <span>{stringifyTaskRunStatus(taskRun.status, t)}</span></span>{updateDate && (<>- <span className="text-gray-300">·</span>+ <span className="text-control-placeholder">·</span><HumanizeTsts={updateDate.getTime() / 1000}- className="shrink-0 text-gray-500"+ className="shrink-0 text-control-light"/></>)}{executorEmail && (<>- <span className="text-gray-300">·</span>+ <span className="text-control-placeholder">·</span><Tooltip content={t("task.executed-by")}>- <span className="flex shrink-0 items-center gap-x-1 text-gray-500">- <User className="h-3.5 w-3.5" />+ <span className="flex shrink-0 items-center gap-x-1 text-control-light">+ <User className="size-3.5" /><span className="truncate">{executorEmail}</span></span></Tooltip>@@ -107,22 +83,48 @@ export function DeployLatestTaskRunInfo({)}{duration && (<>- <span className="text-gray-300">·</span>+ <span className="text-control-placeholder">·</span><Tooltip content={t("common.duration")}>- <span className="flex shrink-0 items-center gap-x-1 text-gray-500">- <Clock3 className="h-3.5 w-3.5" />+ <span className="flex shrink-0 items-center gap-x-1 tabular-nums text-control-light">+ <Clock3 className="size-3.5" />{duration}</span></Tooltip></>)}+ {historyCount > 1 && (+ <span className="ml-auto flex shrink-0 items-center">+ <Button onClick={onShowHistory} size="xs" appearance="secondary">+ <History className="size-3.5" />+ {t("task-run.history-with-count", { count: historyCount })}+ </Button>+ </span>+ )}</div>- {taskRunName && (- <TaskRunLogViewer- key={`${taskRunName}-${status}`}- taskRunName={taskRunName}- />+ {/* Status is part of the key on purpose: a status flip (RUNNING→DONE)+ remounts the viewer for a fresh disclosure state on the new phase.+ The remount paints fully formed — useTaskRunLogData seeds from its+ caches during render — and the status prop still drives terminal+ cache freshness and the live poll while running. */}+ <TaskRunLogViewer+ active={active}+ key={`logs-${taskRun.name}-${taskRun.status}`}+ taskRunName={taskRun.name}+ taskRunStatus={taskRun.status}+ />++ {showSession && (+ <div className="flex flex-col gap-1">+ <div className="text-sm font-medium text-control">+ {t("issue.task-run.session")}+ </div>+ <PlanDetailTaskRunSession+ active={active}+ key={taskRun.name}+ taskRun={taskRun}+ />+ </div>)}</div>);diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.test.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.test.tsxindex 93f4669d70..99e838ab74 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.test.tsx@@ -68,17 +68,11 @@ const page = {refreshState: () => Promise.resolve(),} as unknown as PlanDetailPageState;-const renderStage = (stage: Stage) => (- <PlanDetailProvider value={page}>- <DeployStageContentView stage={stage} />- </PlanDetailProvider>-);-const visibleTaskNames = () =>screen.queryAllByTestId("visible-task").map((node) => node.textContent);describe("DeployStageContentView filter scoping", () => {- test("does not carry the task filter across stages (BYT-9762)", () => {+ test("each stage instance keeps its own filter (BYT-9762)", () => {const testStage = makeStage("projects/p1/rollouts/r1/stages/test", [{name: "projects/p1/rollouts/r1/stages/test/tasks/t1",@@ -100,21 +94,23 @@ describe("DeployStageContentView filter scoping", () => {},]);- const { rerender } = render(renderStage(testStage));+ // All stages stay mounted side by side (the active one is visible, the+ // rest are hidden by the parent); each instance owns its stage's filter.+ render(+ <PlanDetailProvider value={page}>+ <DeployStageContentView stage={testStage} />+ <DeployStageContentView active={false} stage={prodStage} />+ </PlanDetailProvider>+ );- // Both Test tasks visible before filtering.- expect(visibleTaskNames()).toHaveLength(2);+ // All four tasks rendered before filtering.+ expect(visibleTaskNames()).toHaveLength(4);- // Filter the Test stage down to RUNNING tasks.- fireEvent.click(screen.getByTestId("select-running"));+ // Filter the Test stage down to RUNNING tasks. Prod has no RUNNING task —+ // a filter leaking across stages (BYT-9762) would hide its tasks too.+ fireEvent.click(screen.getAllByTestId("select-running")[0]);expect(visibleTaskNames()).toEqual(["projects/p1/rollouts/r1/stages/test/tasks/t1",- ]);-- // Switch to the Prod stage (same instance, no `key`). Prod has no RUNNING- // task, so a leaked filter would hide everything; the filter must reset.- rerender(renderStage(prodStage));- expect(visibleTaskNames()).toEqual(["projects/p1/rollouts/r1/stages/prod/tasks/p1","projects/p1/rollouts/r1/stages/prod/tasks/p2",]);diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsxindex 3b17174ec1..d636f7c187 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx@@ -1,6 +1,6 @@import { create } from "@bufbuild/protobuf";import { Plus } from "lucide-react";-import { useState } from "react";+import { memo, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { rolloutServiceClientConnect } from "@/connect";import { Button } from "@/react/components/ui/button";@@ -15,33 +15,44 @@ import { DeployStageRollbackSection } from "./DeployStageRollbackSection";import { DeployTaskFilter } from "./DeployTaskFilter";import { DeployTaskList } from "./DeployTaskList";-export function DeployStageContentView({- selectedTaskName,+// One instance per stage, all kept mounted; the parent hides the inactive+// ones. Because an instance is permanently bound to its stage, per-stage view+// state (the status filter here, selection/expansion in the list) is scoped by+// construction — a filter can never leak onto another stage's tasks+// (BYT-9762), and it survives switching away and back.+//+// memo: with stage identity stable across renders (identity-preserving+// snapshot), parent-local re-renders in DeployBranch (e.g. the optimistic tab+// highlight) skip this whole subtree. Context changes still propagate to the+// consumers below regardless of memo.+export const DeployStageContentView = memo(function DeployStageContentView({stage,+ active = true,}: {- selectedTaskName?: string;stage: Stage;+ active?: boolean;}) {const { t } = useTranslation();const page = usePlanDetailContext();const [filterStatuses, setFilterStatuses] = useState<Task_Status[]>([]);- // Scope the task filter to the stage: when switching to a different stage,- // drop the previous stage's filter so it can't silently hide the new stage's- // tasks (BYT-9762). Resetting during render — rather than in a post-paint- // effect — keeps the new stage's first paint correct instead of briefly- // showing the wrong filtered set.- const [filteredStageName, setFilteredStageName] = useState(stage.name);- if (stage.name !== filteredStageName) {- setFilteredStageName(stage.name);- setFilterStatuses([]);- }const isStageCreated = stage.tasks.length > 0;- const filteredTasks =- filterStatuses.length > 0- ? stage.tasks.filter((task) => filterStatuses.includes(task.status))- : stage.tasks;+ // Pass `stage` through untouched when no filter is active (the common case)+ // and memoize the filtered variant — a fresh stage object every render would+ // re-render the whole task list for nothing.+ const filteredStage = useMemo(+ () =>+ filterStatuses.length > 0+ ? {+ ...stage,+ tasks: stage.tasks.filter((task) =>+ filterStatuses.includes(task.status)+ ),+ }+ : stage,+ [filterStatuses, stage]+ );return (<div className="w-full">@@ -94,7 +105,7 @@ export function DeployStageContentView({}}size="sm">- <Plus className="h-4 w-4" />+ <Plus className="size-4" />{t("common.create")}</Button></div>@@ -104,16 +115,13 @@ export function DeployStageContentView({<div className="flex flex-col"><DeployTaskList+ active={active}readonly={!isStageCreated}- selectedTaskName={selectedTaskName}- stage={{- ...stage,- tasks: filteredTasks,- }}+ stage={filteredStage}/>{isStageCreated && <DeployStageRollbackSection stage={stage} />}</div></div>);-}+});diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.test.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskBody.test.tsxsimilarity index 86%rename from frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.test.tsxrename to frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskBody.test.tsxindex 0479ac39b8..3035b33dd9 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskBody.test.tsx@@ -1,6 +1,6 @@import { describe, expect, test } from "vitest";-import source from "./DeployTaskItem.tsx?raw";+import source from "./DeployTaskBody.tsx?raw";const statementReadonlyMonacoProps = (src: string): string => {const match = src.match(@@ -10,7 +10,7 @@ const statementReadonlyMonacoProps = (src: string): string => {return match?.[0] ?? "";};-describe("DeployTaskItem statement editor", () => {+describe("DeployTaskBody statement editor", () => {test("lets Monaco own the compact statement viewport", () => {const props = statementReadonlyMonacoProps(source);diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskBody.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskBody.tsxnew file mode 100644index 0000000000..f3483965a0--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskBody.tsx@@ -0,0 +1,118 @@+import { useTranslation } from "react-i18next";+import { ReadonlyMonaco } from "@/react/components/monaco";+import { getTaskRunWaitingMessage } from "@/react/lib/taskRun";+import { cn } from "@/react/lib/utils";+import type { Engine } from "@/types/proto-es/v1/common_pb";+import type { Task, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";+import {+ isReleaseBasedTask,+ releaseNameOfTaskV1,+} from "@/utils/v1/issue/rollout";+import { DeployLatestTaskRunInfo } from "./DeployLatestTaskRunInfo";+import { DeployReleaseInfoCard } from "./DeployReleaseInfoCard";+import { DeployTaskSkippedReason } from "./DeployTaskSkippedReason";++// The expanded card body: a skipped reason, a waiting note, the SQL statement+// (or release info), and the latest task run. Only mounts when the card is+// expanded, so everything derived here is off the collapsed poll path. Stateful+// inputs (the statement, store lookups) stay in the orchestrating+// DeployTaskItem; pure derivations of `task`/`latestTaskRun` live here.+export function DeployTaskBody({+ active,+ databaseEngine,+ historyCount,+ isStatementLoading,+ isTruncated,+ latestTaskRun,+ onShowHistory,+ statement,+ task,+ timingDisplay,+}: {+ // Whether this card's stage is the visible one; forwarded to pause live polls.+ active?: boolean;+ databaseEngine?: Engine;+ historyCount: number;+ isStatementLoading: boolean;+ isTruncated: boolean;+ latestTaskRun?: TaskRun;+ onShowHistory: () => void;+ statement: string;+ task: Task;+ // The latest run's duration, formatted by DeployTaskItem (single source).+ timingDisplay: string;+}) {+ const { t } = useTranslation();+ const isReleaseTask = isReleaseBasedTask(task);+ const releaseName = releaseNameOfTaskV1(task);+ // The one state line that matters for a waiting task.+ const waitingComment = latestTaskRun+ ? getTaskRunWaitingMessage(latestTaskRun, t)+ : undefined;+ // A pending task shows no elapsed time; otherwise reuse the item's string.+ const duration =+ task.status === Task_Status.PENDING+ ? undefined+ : timingDisplay || undefined;++ return (+ <div className="flex flex-col gap-3">+ <DeployTaskSkippedReason task={task} />+ {waitingComment && (+ <div className="text-xs italic text-control-light">+ {waitingComment}+ </div>+ )}+ {!isReleaseTask ? (+ <div>+ <div className="mb-1 text-sm font-medium text-control">+ {t("common.statement")}+ </div>+ {isStatementLoading ? (+ // min-h-32 matches the editor's min height (min={128}) so the+ // statement fills this box in place instead of reflowing the card.+ <div className="flex min-h-32 items-center justify-center rounded-sm border p-3 text-sm text-control-light">+ {t("common.loading")}+ </div>+ ) : statement ? (+ <>+ <ReadonlyMonaco+ className={cn(+ "relative rounded border text-sm",+ isTruncated && "rounded-b-none"+ )}+ content={statement}+ language="sql"+ min={128}+ max={256}+ />+ {isTruncated && (+ <div className="rounded-b border border-t-0 bg-control-bg px-3 py-1.5 text-xs text-control-light">+ {t("rollout.task.statement-truncated-hint")}+ </div>+ )}+ </>+ ) : (+ <div className="rounded-sm border p-3 text-sm text-control-light">+ {t("common.no-data")}+ </div>+ )}+ </div>+ ) : releaseName ? (+ <DeployReleaseInfoCard releaseName={releaseName} />+ ) : null}++ {latestTaskRun && (+ <DeployLatestTaskRunInfo+ active={active}+ databaseEngine={databaseEngine}+ duration={duration}+ historyCount={historyCount}+ onShowHistory={onShowHistory}+ taskRun={latestTaskRun}+ />+ )}+ </div>+ );+}diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskDetailPanel.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskDetailPanel.tsxdeleted file mode 100644index cb5e9a5b7d..0000000000--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskDetailPanel.tsx+++ /dev/null@@ -1,288 +0,0 @@-import { CalendarClock, EllipsisVertical, Undo2 } from "lucide-react";-import { useMemo, useState } from "react";-import { useTranslation } from "react-i18next";-import { ReadonlyMonaco } from "@/react/components/monaco";-import { TaskStatusIcon } from "@/react/components/TaskStatusIcon";-import { Button } from "@/react/components/ui/button";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@/react/components/ui/dropdown-menu";-import { Tooltip } from "@/react/components/ui/tooltip";-import { useAppStore } from "@/react/stores/app";-import { getTimeForPbTimestampProtoEs } from "@/types";-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";-import {- Task_Status,- TaskRun_Status,-} from "@/types/proto-es/v1/rollout_service_pb";-import { databaseForTask, formatAbsoluteDateTime, humanizeTs } from "@/utils";-import {- isReleaseBasedTask,- releaseNameOfTaskV1,-} from "@/utils/v1/issue/rollout";-import { usePlanDetailContext } from "../../shell/PlanDetailContext";-import { PlanDetailRollbackSheet } from "../PlanDetailRollbackSheet";-import {- type PlanDetailTaskRolloutAction,- PlanDetailTaskRolloutActionPanel,-} from "../PlanDetailTaskRolloutActionPanel";-import { PlanDetailTaskRunDetail } from "../PlanDetailTaskRunDetail";-import { PlanDetailTaskRunTable } from "../PlanDetailTaskRunTable";-import { PlanTargetDisplay } from "../PlanTargetDisplay";-import { DeployReleaseInfoCard } from "./DeployReleaseInfoCard";-import { DeployTaskSkippedReason } from "./DeployTaskSkippedReason";-import { useDeployTaskActions } from "./taskActions";-import { useDeployTaskStatement } from "./useDeployTaskStatement";--export function DeployTaskDetailPanel({ task }: { task: Task }) {- const { t } = useTranslation();- const page = usePlanDetailContext();- const environmentList = useAppStore((s) => s.environmentList);- const project = page.project;- const taskRuns = useMemo(- () =>- page.taskRuns- .filter((taskRun) => taskRun.name.startsWith(`${task.name}/taskRuns/`))- .sort((left, right) => {- const leftTime = left.createTime- ? Number(left.createTime.seconds)- : 0;- const rightTime = right.createTime- ? Number(right.createTime.seconds)- : 0;- return rightTime - leftTime;- }),- [page.taskRuns, task.name]- );- const latestTaskRun = taskRuns[0];- const [taskActionOpen, setTaskActionOpen] = useState(false);- const [taskAction, setTaskAction] = useState<- PlanDetailTaskRolloutAction | undefined- >(undefined);- const [rollbackOpen, setRollbackOpen] = useState(false);- const database = useMemo(- () => databaseForTask(project, task, page.plan),- [page.plan, project, task]- );- const stage = useMemo(- () =>- page.rollout?.stages.find((candidate) =>- candidate.tasks.some((item) => item.name === task.name)- ),- [page.rollout?.stages, task.name]- );- const stageTitle = useMemo(- () =>- stage?.environment- ? useAppStore.getState().getEnvironmentByName(stage.environment).title- : "",- [environmentList, stage?.environment]- );- const scheduledTime = useMemo(() => {- const ts = getTimeForPbTimestampProtoEs(task.runTime, 0);- if (!ts) return undefined;- return {- relative: humanizeTs(ts / 1000),- absolute: formatAbsoluteDateTime(ts),- };- }, [task.runTime]);- const isReleaseTask = useMemo(() => isReleaseBasedTask(task), [task]);- const {- isLoading: isStatementLoading,- isTruncated,- statement,- } = useDeployTaskStatement({- enabled: !isReleaseTask,- task,- });- const releaseName = useMemo(() => releaseNameOfTaskV1(task), [task]);- const rollbackableTaskRun =- latestTaskRun &&- latestTaskRun.status === TaskRun_Status.DONE &&- latestTaskRun.hasPriorBackup- ? latestTaskRun- : undefined;- const { canCancel, canRun, canSkip } = useDeployTaskActions({ stage, task });- const primaryActionLabel =- task.status === Task_Status.FAILED ? t("common.retry") : t("common.run");-- return (- <div className="space-y-4 p-4">- <div className="flex flex-col gap-y-3">- <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">- <div className="flex flex-row flex-wrap items-center gap-x-3 gap-y-2">- <TaskStatusIcon size="large" status={task.status} />- {stageTitle && (- <span className="rounded-full bg-control-bg px-2 py-0.5 text-xs text-control">- {stageTitle}- </span>- )}- <PlanTargetDisplay- showEnvironment- size="md"- target={database.name}- />- {scheduledTime && task.status === Task_Status.PENDING && (- <Tooltip- content={- <div className="flex flex-col gap-y-1">- <div className="text-sm opacity-80">- {t("task.scheduled-time")}- </div>- <div className="whitespace-nowrap text-sm">- {scheduledTime.absolute}- </div>- </div>- }- >- <span className="inline-flex items-center gap-1 rounded-full bg-control-bg px-2 py-0.5 text-xs text-control">- <CalendarClock className="h-3.5 w-3.5 opacity-80" />- <span>{scheduledTime.relative}</span>- </span>- </Tooltip>- )}- </div>-- <div className="flex justify-start sm:justify-end">- <div className="flex flex-wrap items-center gap-x-2 gap-y-2">- {canRun && (- <Button- onClick={() => {- setTaskAction("RUN");- setTaskActionOpen(true);- }}- size="sm"- >- {primaryActionLabel}- </Button>- )}- {(canSkip || canCancel) && (- <DropdownMenu>- <DropdownMenuTrigger className="inline-flex h-8 items-center justify-center rounded-xs px-1 text-sm text-control outline-hidden hover:bg-control-bg focus-visible:ring-2 focus-visible:ring-accent">- <EllipsisVertical className="h-4 w-4" />- </DropdownMenuTrigger>- <DropdownMenuContent>- {canSkip && (- <DropdownMenuItem- onClick={() => {- setTaskAction("SKIP");- setTaskActionOpen(true);- }}- >- {t("common.skip")}- </DropdownMenuItem>- )}- {canCancel && (- <DropdownMenuItem- onClick={() => {- setTaskAction("CANCEL");- setTaskActionOpen(true);- }}- >- {t("common.cancel")}- </DropdownMenuItem>- )}- </DropdownMenuContent>- </DropdownMenu>- )}- {rollbackableTaskRun && (- <Button onClick={() => setRollbackOpen(true)} size="sm">- <Undo2 className="h-4 w-4" />- {t("common.rollback")}- </Button>- )}- </div>- </div>- </div>- </div>-- <DeployTaskSkippedReason task={task} />-- {latestTaskRun && (- <div className="flex w-full flex-col gap-2">- <span className="textlabel uppercase">- {t("task-run.latest-logs")}- </span>- <PlanDetailTaskRunDetail- databaseEngine={database.instanceResource?.engine}- taskRun={latestTaskRun}- />- </div>- )}-- {taskRuns.length > 0 && (- <div className="space-y-2">- <span className="textlabel uppercase">{t("task-run.history")}</span>- <PlanDetailTaskRunTable- databaseName={database.name}- taskRuns={taskRuns}- />- </div>- )}-- {!isReleaseTask && (- <div className="flex min-h-0 flex-1 flex-col gap-2">- <span className="textlabel uppercase">{t("common.statement")}</span>- <div className="rounded-sm border bg-white p-3">- {isStatementLoading ? (- <div className="text-sm text-control-light">- {t("common.loading")}- </div>- ) : statement ? (- <>- <ReadonlyMonaco- className="relative h-auto max-h-[420px] min-h-[160px]"- content={statement}- language="sql"- />- {isTruncated && (- <div className="mt-2 text-xs text-gray-500">- {t("rollout.task.statement-truncated-hint")}- </div>- )}- </>- ) : (- <div className="text-sm text-control-light">- {t("common.no-data")}- </div>- )}- </div>- </div>- )}-- {isReleaseTask && releaseName && (- <DeployReleaseInfoCard className="w-full" releaseName={releaseName} />- )}-- {stage && taskAction && (- <PlanDetailTaskRolloutActionPanel- action={taskAction}- onConfirm={async () => {- await page.refreshState();- }}- onOpenChange={(open) => {- setTaskActionOpen(open);- if (!open) {- setTaskAction(undefined);- }- }}- open={taskActionOpen}- target={{ type: "tasks", stage, tasks: [task] }}- />- )}-- {rollbackableTaskRun && (- <PlanDetailRollbackSheet- items={[{ task, taskRun: rollbackableTaskRun }]}- onOpenChange={setRollbackOpen}- open={rollbackOpen}- projectName={project.name}- rolloutName={page.rollout?.name ?? ""}- />- )}- </div>- );-}diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskHeader.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskHeader.tsxnew file mode 100644index 0000000000..8491c29f34--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskHeader.tsx@@ -0,0 +1,182 @@+import {+ ChevronDown,+ ChevronRight,+ LoaderCircle,+ Play,+ SkipForward,+ X,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import { HumanizeTs } from "@/react/components/HumanizeTs";+import { TaskStatusIcon } from "@/react/components/TaskStatusIcon";+import { Button } from "@/react/components/ui/button";+import { Checkbox } from "@/react/components/ui/checkbox";+import { cn } from "@/react/lib/utils";+import { getTimeForPbTimestampProtoEs } from "@/types";+import type { Task, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";+import type { PlanDetailTaskRolloutAction } from "../PlanDetailTaskRolloutActionPanel";+import { PlanTargetDisplay } from "../PlanTargetDisplay";++type ActionItem = { key: PlanDetailTaskRolloutAction; label: string };++// The card header: a bulk-select checkbox, the task identity (which toggles the+// card open/closed), the per-card actions when expanded, and a caret. Purely+// presentational — DeployTaskItem owns the derived data and handlers.+export function DeployTaskHeader({+ actionItems,+ collapsedContextInfo,+ collapsedStatusText,+ isExpanded,+ isSelectable,+ isSelected,+ latestTaskRun,+ onAction,+ onRollback,+ onToggleExpand,+ onToggleSelect,+ scheduledTimeTs,+ showRollback,+ task,+ timingDisplay,+}: {+ actionItems: ActionItem[];+ collapsedContextInfo: string;+ collapsedStatusText: string;+ isExpanded: boolean;+ isSelectable: boolean;+ isSelected: boolean;+ latestTaskRun?: TaskRun;+ onAction: (action: PlanDetailTaskRolloutAction) => void;+ onRollback: () => void;+ onToggleExpand: () => void;+ onToggleSelect: () => void;+ scheduledTimeTs: number;+ showRollback: boolean;+ task: Task;+ timingDisplay: string;+}) {+ const { t } = useTranslation();+ const showActions = actionItems.length > 0 || showRollback;++ return (+ <>+ <div className="flex items-center gap-x-2">+ <Checkbox+ aria-label={t("task.select-task")}+ checked={isSelected}+ className="shrink-0"+ disabled={!isSelectable}+ onCheckedChange={() => onToggleSelect()}+ onClick={(event) => event.stopPropagation()}+ />+ {/* The identity is the toggle. It hugs its content, not the full row,+ so the hover and hit target track the target — not the empty space+ out to the caret. */}+ <button+ aria-expanded={isExpanded}+ className="flex min-w-0 cursor-pointer items-center gap-x-2 rounded-md border-0 bg-transparent p-0 text-left outline-none hover:bg-control-bg/50 focus-visible:ring-2 focus-visible:ring-accent"+ onClick={onToggleExpand}+ type="button"+ >+ <TaskStatusIcon size="small" status={task.status} />+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">+ <PlanTargetDisplay size="md" target={task.target} />+ {isExpanded && scheduledTimeTs > 0 && (+ <span className="flex shrink-0 items-center gap-x-1 rounded-full bg-info/10 px-2 py-0.5 text-xs text-info">+ <LoaderCircle className="size-3 animate-spin motion-reduce:animate-none" />+ <HumanizeTs ts={scheduledTimeTs} />+ </span>+ )}+ </div>+ </button>++ {/* Right cluster, pushed to the row's edge: the collapsed duration or+ the expanded actions, then the caret. Actions live in the header —+ consistent with the app, reachable without scrolling the body. */}+ <div className="ml-auto flex shrink-0 items-center gap-x-2">+ {!isExpanded && (+ <span className="text-xs tabular-nums text-control-light">+ {scheduledTimeTs > 0 ||+ (task.status === Task_Status.RUNNING && timingDisplay) ? (+ <span className="flex items-center gap-x-1 text-info">+ <LoaderCircle className="size-3 animate-spin motion-reduce:animate-none" />+ {scheduledTimeTs > 0 ? (+ <HumanizeTs ts={scheduledTimeTs} />+ ) : (+ timingDisplay+ )}+ </span>+ ) : collapsedContextInfo ? (+ <span>{collapsedContextInfo}</span>+ ) : null}+ </span>+ )}+ {isExpanded && showActions && (+ <div className="flex flex-wrap items-center justify-end gap-2">+ {actionItems.map((item) => (+ <Button+ key={item.key}+ onClick={() => onAction(item.key)}+ size="xs"+ appearance={item.key === "RUN" ? "solid" : "outline"}+ >+ {item.key === "RUN" && <Play className="size-3" />}+ {item.key === "SKIP" && <SkipForward className="size-3" />}+ {item.key === "CANCEL" && <X className="size-3" />}+ {item.label}+ </Button>+ ))}+ {showRollback && (+ <Button onClick={onRollback} size="xs" appearance="outline">+ {t("common.rollback")}+ </Button>+ )}+ </div>+ )}+ {/* Redundant mouse affordance for the toggle; the identity button is+ the keyboard-accessible control, so keep this out of the tab+ order. */}+ <button+ aria-hidden="true"+ className="shrink-0 rounded-md p-1 text-control-light outline-none hover:bg-control-bg/50"+ onClick={onToggleExpand}+ tabIndex={-1}+ type="button"+ >+ {isExpanded ? (+ <ChevronDown className="size-4" />+ ) : (+ <ChevronRight className="size-4" />+ )}+ </button>+ </div>+ </div>++ {!isExpanded && collapsedStatusText && (+ <div className="mt-1 flex items-center gap-x-2 text-xs">+ {latestTaskRun?.createTime && (+ <span className="rounded-full border bg-control-bg px-2 py-0.5 text-control-light">+ <HumanizeTs+ ts={+ getTimeForPbTimestampProtoEs(latestTaskRun.createTime, 0) /+ 1000+ }+ />+ </span>+ )}+ <span+ className={cn(+ "min-w-0 truncate",+ task.status === Task_Status.FAILED+ ? "text-error"+ : "italic text-control-light"+ )}+ >+ {collapsedStatusText}+ </span>+ </div>+ )}+ </>+ );+}diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsxindex bf329665f2..e6a879e18f 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx@@ -1,84 +1,116 @@-import {- ArrowUpRight,- ChevronDown,- ChevronRight,- LoaderCircle,- Play,- SkipForward,- X,-} from "lucide-react";-import { useMemo, useState } from "react";+import { memo, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { HumanizeTs } from "@/react/components/HumanizeTs";-import { ReadonlyMonaco } from "@/react/components/monaco";-import { RouterLink } from "@/react/components/RouterLink";-import { TaskStatusIcon } from "@/react/components/TaskStatusIcon";-import { Button } from "@/react/components/ui/button";-import { Checkbox } from "@/react/components/ui/checkbox";+import { formatTaskRunDuration } from "@/react/lib/taskRun";import { cn } from "@/react/lib/utils";import { getTimeForPbTimestampProtoEs } from "@/types";+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";import {type Stage,type Task,Task_Status,+ type TaskRun,TaskRun_Status,} from "@/types/proto-es/v1/rollout_service_pb";-import {- isReleaseBasedTask,- releaseNameOfTaskV1,-} from "@/utils/v1/issue/rollout";-import { usePlanDetailContext } from "../../shell/PlanDetailContext";+import type { User } from "@/types/proto-es/v1/user_service_pb";+import { databaseForTask } from "@/utils";+import { isReleaseBasedTask } from "@/utils/v1/issue/rollout";+import { isRerunnableTaskStatus } from "../lifecycle/frontierStage";import { PlanDetailRollbackSheet } from "../PlanDetailRollbackSheet";import {type PlanDetailTaskRolloutAction,PlanDetailTaskRolloutActionPanel,} from "../PlanDetailTaskRolloutActionPanel";-import { PlanTargetDisplay } from "../PlanTargetDisplay";-import { DeployLatestTaskRunInfo } from "./DeployLatestTaskRunInfo";-import { DeployReleaseInfoCard } from "./DeployReleaseInfoCard";-import { DeployTaskSkippedReason } from "./DeployTaskSkippedReason";+import { DeployTaskBody } from "./DeployTaskBody";+import { DeployTaskHeader } from "./DeployTaskHeader";+import { DeployTaskRunHistorySheet } from "./DeployTaskRunHistorySheet";import { useDeployTaskActions } from "./taskActions";-import { getTaskRunDuration } from "./taskRunUtils";import { useDeployTaskStatement } from "./useDeployTaskStatement";-export function DeployTaskItem({+// Orchestrates a single deploy task card: derives the display state, owns the+// action/rollback/history overlays, and composes the presentational+// DeployTaskHeader + DeployTaskBody. The card is one disclosure toggle.+//+// memo + props only (no page context): every input is identity-stable across+// poll ticks thanks to the snapshot gate's structural sharing, so a tick that+// changes one task re-renders that one card — the other mounted cards (across+// every kept-alive stage, and the siblings in this one) skip entirely. The+// stage object itself is NOT stable (the gate rebuilds it whenever any task in+// it changes), so the card takes the stage's stable identity (name ++// environment) as primitives and reads the live stage lazily through getStage+// only where the rarely-open action panel needs it.+export const DeployTaskItem = memo(function DeployTaskItem({active,+ currentUser,+ deepLinked,+ getStage,isExpanded,isSelected,isSelectable,+ issue,+ onRefresh,onToggleExpand,onToggleSelect,- readonly,- stageId,- stage,+ plan,+ project,+ rolloutName,+ stageEnvironment,task,+ taskRuns,}: {- active: boolean;+ // Whether this card's stage is the visible one; forwarded to pause the live+ // log/session polls in the expanded body while a kept-alive stage is hidden.+ active?: boolean;+ currentUser: User;+ deepLinked: boolean;isExpanded: boolean;isSelected: boolean;isSelectable: boolean;- onToggleExpand: () => void;- onToggleSelect: () => void;- readonly: boolean;- stageId: string;- stage: Stage;+ issue?: Issue;+ onRefresh: () => Promise<void>;+ onToggleExpand: (task: Task) => void;+ onToggleSelect: (task: Task) => void;+ plan: Plan;+ project: Project;+ rolloutName: string;+ // Stable identity of this task's stage (the stage object churns every poll+ // tick; the environment doesn't). Drives the always-on permission check.+ stageEnvironment: string;+ // Reads the live stage on demand — only the action panel (open on user+ // interaction) needs the full object, so it stays out of the memo inputs.+ getStage: () => Stage;task: Task;+ // This task's runs, newest first (grouped upstream with stable identities).+ taskRuns: TaskRun[];}) {const { t } = useTranslation();- const page = usePlanDetailContext();- const taskRunsForTask = useMemo(- () =>- page.taskRuns.filter((run) =>- run.name.startsWith(`${task.name}/taskRuns/`)- ),- [page.taskRuns, task.name]- );- const latestTaskRun = taskRunsForTask[taskRunsForTask.length - 1];+ const latestTaskRun = taskRuns[0];const [action, setAction] = useState<PlanDetailTaskRolloutAction | undefined>();const [actionOpen, setActionOpen] = useState(false);const [rollbackOpen, setRollbackOpen] = useState(false);+ const [historyOpen, setHistoryOpen] = useState(false);+ // A deep link (?taskId=) brings its card into view once. `deepLinked` only+ // changes with the route, so polling re-renders don't re-trigger the scroll.+ // Skip when the card top is already on screen — opening a card writes its own+ // ?taskId=, and the card the user just clicked must not yank the viewport.+ const hostRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ if (!deepLinked) {+ return;+ }+ const host = hostRef.current;+ if (!host) {+ return;+ }+ const { top } = host.getBoundingClientRect();+ const alreadyVisible = top >= 0 && top <= window.innerHeight * 0.8;+ if (!alreadyVisible) {+ host.scrollIntoView({ block: "center" });+ }+ }, [deepLinked]);const isReleaseTask = isReleaseBasedTask(task);const {isLoading: isStatementLoading,@@ -88,9 +120,11 @@ export function DeployTaskItem({enabled: isExpanded && !isReleaseTask,task,});- const releaseName = releaseNameOfTaskV1(task);const { canCancel, canRun, canSkip } = useDeployTaskActions({- stage,+ currentUser,+ issue,+ project,+ environment: stageEnvironment,task,});const rollbackableTaskRun =@@ -103,9 +137,11 @@ export function DeployTaskItem({task.runTime && task.status === Task_Status.PENDING? getTimeForPbTimestampProtoEs(task.runTime, 0) / 1000: 0;- const timingDisplay = latestTaskRun ? getTaskRunDuration(latestTaskRun) : "";- const executorEmail =- latestTaskRun?.creator.match(/users\/([^/]+)/)?.[1] ?? "";+ // Same duration source as the history sheet and the expanded body, so all+ // three render identical strings for the same run.+ const timingDisplay = latestTaskRun+ ? formatTaskRunDuration(latestTaskRun)+ : "";const collapsedContextInfo =task.status === Task_Status.DONE ? timingDisplay : "";const collapsedStatusText =@@ -119,10 +155,11 @@ export function DeployTaskItem({const actionItems = [{key: "RUN" as const,- label:- task.status === Task_Status.FAILED- ? t("common.retry")- : t("common.run"),+ // Match the stage/plan-header verb: re-executing a failed or canceled+ // task is "Rerun"; a fresh execution is "Run".+ label: isRerunnableTaskStatus(task.status)+ ? t("plan.lifecycle.rerun")+ : t("plan.lifecycle.run"),visible: canRun,},{@@ -136,223 +173,58 @@ export function DeployTaskItem({visible: canCancel,},].filter((item) => item.visible);- const showHeaderActions =- isExpanded && (actionItems.length > 0 || Boolean(rollbackableTaskRun));- const isClickableCollapsed = !readonly && !isExpanded;+ // Read only in the expanded branch; databaseForTask does store lookups, so+ // don't pay for it on collapsed cards.+ const databaseEngine =+ isExpanded && latestTaskRun+ ? databaseForTask(project, task, plan).instanceResource?.engine+ : undefined;return (<>- <div- className={cn(- "group relative rounded-lg border bg-white transition-all",- active && "border-accent bg-accent/5",- isClickableCollapsed && "cursor-pointer hover:bg-control-bg"- )}- onClick={isClickableCollapsed ? onToggleExpand : undefined}- >+ <div className="group rounded-lg border bg-white" ref={hostRef}>+ {/* Same padding in both modes: the header row is button-height (h-6)+ either way, so expanding only reveals content below — nothing+ above the fold moves. */}<div- className={- isExpanded ? "space-y-3 py-4 pl-3 pr-4" : "py-2.5 pl-3 pr-4"- }- >- <div- className={cn(- "flex justify-between gap-x-3",- isExpanded- ? "flex-col gap-y-2 sm:flex-row sm:items-center"- : "items-center"- )}- >- <div className="flex min-w-0 flex-1 items-center gap-x-2">- <Checkbox- checked={isSelected}- className="shrink-0"- disabled={!isSelectable}- onCheckedChange={() => onToggleSelect()}- onClick={(event) => event.stopPropagation()}- />- <TaskStatusIcon- size={isExpanded ? "large" : "small"}- status={task.status}- />- <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">- <PlanTargetDisplay size="md" target={task.target} />- {isExpanded && !readonly && (- <RouterLink- to={{- query: {- phase: "deploy",- stageId,- taskId: task.name.split("/").pop(),- },- }}- className="flex shrink-0 items-center gap-x-1 text-xs text-accent transition-opacity hover:opacity-80"- >- <ArrowUpRight className="h-4 w-4" />- <span>{t("common.view-details")}</span>- </RouterLink>- )}- {isExpanded && scheduledTimeTs > 0 && (- <span className="flex shrink-0 items-center gap-x-1 rounded-full bg-blue-50 px-2 py-0.5 text-xs text-blue-600">- <LoaderCircle className="h-3 w-3 animate-spin" />- <HumanizeTs ts={scheduledTimeTs} />- </span>- )}- </div>- {!isExpanded && (- <div className="ml-auto shrink-0 text-xs text-gray-500">- {scheduledTimeTs > 0 ? (- <span className="flex items-center gap-x-1 text-blue-600">- <LoaderCircle className="h-3 w-3 animate-spin" />- <HumanizeTs ts={scheduledTimeTs} />- </span>- ) : task.status === Task_Status.RUNNING && timingDisplay ? (- <span className="flex items-center gap-x-1 text-blue-600">- <LoaderCircle className="h-3 w-3 animate-spin" />- {timingDisplay}- </span>- ) : collapsedContextInfo ? (- <span>{collapsedContextInfo}</span>- ) : null}- </div>- )}- </div>-- {(showHeaderActions || !readonly) && (- <div className="flex shrink-0 items-center gap-x-2 max-sm:justify-end">- {showHeaderActions && (- <div className="flex flex-wrap items-center justify-end gap-2">- {actionItems.map((item) => (- <Button- key={item.key}- onClick={() => {- setAction(item.key);- setActionOpen(true);- }}- size="xs"- appearance={item.key === "RUN" ? "solid" : "outline"}- >- {item.key === "RUN" && <Play className="h-3 w-3" />}- {item.key === "SKIP" && (- <SkipForward className="h-3 w-3" />- )}- {item.key === "CANCEL" && <X className="h-3 w-3" />}- {item.label}- </Button>- ))}- {rollbackableTaskRun && (- <Button- onClick={() => setRollbackOpen(true)}- size="xs"- appearance="outline"- >- {t("common.rollback")}- </Button>- )}- </div>- )}-- {!readonly && (- <Button- onClick={(event) => {- event.stopPropagation();- onToggleExpand();- }}- size="xs"- appearance="secondary"- >- {isExpanded ? (- <ChevronDown className="h-4 w-4 text-gray-500" />- ) : (- <ChevronRight className="h-4 w-4 text-gray-500" />- )}- </Button>- )}- </div>- )}- </div>-- {!isExpanded && collapsedStatusText && (- <div className="mt-1 flex items-center gap-x-2 text-xs">- {latestTaskRun?.createTime && (- <span className="rounded-full border bg-gray-50 px-2 py-0.5 text-gray-500">- <HumanizeTs- ts={- getTimeForPbTimestampProtoEs(- latestTaskRun.createTime,- 0- ) / 1000- }- />- </span>- )}- <span- className={cn(- "truncate",- task.status === Task_Status.FAILED- ? "text-error"- : "italic text-gray-500"- )}- >- {collapsedStatusText}- </span>- </div>+ className={cn(+ "py-2.5 pl-3 pr-4",+ isExpanded && "flex flex-col gap-3")}-+ >+ <DeployTaskHeader+ actionItems={actionItems}+ collapsedContextInfo={collapsedContextInfo}+ collapsedStatusText={collapsedStatusText}+ isExpanded={isExpanded}+ isSelectable={isSelectable}+ isSelected={isSelected}+ latestTaskRun={latestTaskRun}+ onAction={(nextAction) => {+ setAction(nextAction);+ setActionOpen(true);+ }}+ onRollback={() => setRollbackOpen(true)}+ onToggleExpand={() => onToggleExpand(task)}+ onToggleSelect={() => onToggleSelect(task)}+ scheduledTimeTs={scheduledTimeTs}+ showRollback={Boolean(rollbackableTaskRun)}+ task={task}+ timingDisplay={timingDisplay}+ />{isExpanded && (- <div className="space-y-3">- <DeployTaskSkippedReason task={task} />- {!isReleaseTask ? (- <div>- <div className="mb-1 text-sm font-medium text-gray-700">- {t("common.statement")}- </div>- {isStatementLoading ? (- <div className="rounded-sm border p-3 text-sm text-control-light">- {t("common.loading")}- </div>- ) : statement ? (- <>- <ReadonlyMonaco- className={cn(- "relative rounded border text-sm",- isTruncated && "rounded-b-none"- )}- content={statement}- language="sql"- min={128}- max={256}- />- {isTruncated && (- <div className="rounded-b border border-t-0 bg-gray-50 px-3 py-1.5 text-xs text-gray-500">- {t("rollout.task.statement-truncated-hint")}- </div>- )}- </>- ) : (- <div className="rounded-sm border p-3 text-sm text-control-light">- {t("common.no-data")}- </div>- )}- </div>- ) : releaseName ? (- <DeployReleaseInfoCard releaseName={releaseName} />- ) : null}-- {latestTaskRun && (- <DeployLatestTaskRunInfo- duration={- task.status !== Task_Status.PENDING- ? timingDisplay- : undefined- }- executorEmail={executorEmail}- status={latestTaskRun.status}- taskRunName={latestTaskRun.name}- updateTime={latestTaskRun.updateTime}- />- )}- </div>+ <DeployTaskBody+ active={active}+ databaseEngine={databaseEngine}+ historyCount={taskRuns.length}+ isStatementLoading={isStatementLoading}+ isTruncated={isTruncated}+ latestTaskRun={latestTaskRun}+ onShowHistory={() => setHistoryOpen(true)}+ statement={statement}+ task={task}+ timingDisplay={timingDisplay}+ />)}</div></div>@@ -361,7 +233,7 @@ export function DeployTaskItem({<PlanDetailTaskRolloutActionPanelaction={action}onConfirm={async () => {- await page.refreshState();+ await onRefresh();}}onOpenChange={(open) => {setActionOpen(open);@@ -370,7 +242,7 @@ export function DeployTaskItem({}}}open={actionOpen}- target={{ type: "tasks", tasks: [task], stage }}+ target={{ type: "tasks", tasks: [task], stage: getStage() }}/>)}@@ -379,10 +251,20 @@ export function DeployTaskItem({items={[{ task, taskRun: rollbackableTaskRun }]}onOpenChange={setRollbackOpen}open={rollbackOpen}- projectName={`projects/${page.projectId}`}- rolloutName={page.rollout?.name ?? ""}+ projectName={project.name}+ rolloutName={rolloutName}+ />+ )}++ {/* Only openable when the History (n) control renders (>1 run); run+ lists only grow, so this never unmounts while open. */}+ {taskRuns.length > 1 && (+ <DeployTaskRunHistorySheet+ onOpenChange={setHistoryOpen}+ open={historyOpen}+ taskRuns={taskRuns}/>)}</>);-}+});diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.test.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.test.tsxindex 336bebbf6b..de34c2e915 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.test.tsx@@ -1,4 +1,4 @@-import { render, screen } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";import { describe, expect, test, vi } from "vitest";import {type Stage,@@ -10,18 +10,37 @@ import { PlanDetailProvider } from "../../shell/PlanDetailContext";import { DeployTaskList } from "./DeployTaskList";vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => undefined },useTranslation: () => ({ t: (key: string) => key }),}));+const routerMocks = vi.hoisted(() => ({+ replace: vi.fn(),+}));++vi.mock("@/react/router", () => ({+ router: { replace: routerMocks.replace },+}));+vi.mock("./DeployTaskItem", () => ({DeployTaskItem: ({task,+ deepLinked,isExpanded,+ onToggleExpand,}: {task: Task;+ deepLinked: boolean;isExpanded: boolean;+ onToggleExpand: (task: Task) => void;}) => (- <div data-expanded={isExpanded ? "true" : "false"} data-testid="task">+ // One control per card: clicking the card toggles it open or closed.+ <div+ data-deeplinked={deepLinked ? "true" : "false"}+ data-expanded={isExpanded ? "true" : "false"}+ data-testid="task"+ onClick={() => onToggleExpand(task)}+ >{task.name}</div>),@@ -29,25 +48,35 @@ vi.mock("./DeployTaskItem", () => ({vi.mock("./DeployTaskToolbar", () => ({ DeployTaskToolbar: () => null }));-const page = {- refreshState: () => Promise.resolve(),-} as unknown as PlanDetailPageState;+const makePage = (selectedTaskName?: string) =>+ ({+ refreshState: () => Promise.resolve(),+ selectedTaskName,+ taskRunsByTaskName: new Map(),+ }) as unknown as PlanDetailPageState;-const makeStage = (name: string, taskNames: string[]): Stage =>+const makeStage = (+ name: string,+ tasks: Array<string | { name: string; status: Task_Status }>+): Stage =>({name,environment: "environments/test",- tasks: taskNames.map((taskName) => ({- name: taskName,- status: Task_Status.NOT_STARTED,- })) as unknown as Task[],+ tasks: tasks.map((task) =>+ typeof task === "string"+ ? { name: task, status: Task_Status.NOT_STARTED }+ : task+ ) as unknown as Task[],}) as unknown as Stage;const expandedOf = (taskName: string) =>screen.getByText(taskName).getAttribute("data-expanded");-const renderList = (stage: Stage) => (- <PlanDetailProvider value={page}>+const deepLinkedOf = (taskName: string) =>+ screen.getByText(taskName).getAttribute("data-deeplinked");++const renderList = (stage: Stage, selectedTaskName?: string) => (+ <PlanDetailProvider value={makePage(selectedTaskName)}><DeployTaskList readonly stage={stage} /></PlanDetailProvider>);@@ -76,3 +105,321 @@ describe("DeployTaskList stage switching (BYT-9763)", () => {expect(expandedOf("rollouts/r/stages/b/tasks/b2")).toBe("false");});});++describe("DeployTaskList first-actionable auto-expand", () => {+ const stageName = "rollouts/r/stages/s";+ const taskName = (id: string) => `${stageName}/tasks/${id}`;++ test("expands the first running task over earlier finished ones", () => {+ const stage = makeStage(stageName, [+ { name: taskName("t1"), status: Task_Status.DONE },+ { name: taskName("t2"), status: Task_Status.RUNNING },+ { name: taskName("t3"), status: Task_Status.FAILED },+ ]);+ render(renderList(stage));+ expect(expandedOf(taskName("t1"))).toBe("false");+ expect(expandedOf(taskName("t2"))).toBe("true");+ expect(expandedOf(taskName("t3"))).toBe("false");+ });++ test("expands the first failed task when nothing is running", () => {+ const stage = makeStage(stageName, [+ { name: taskName("t1"), status: Task_Status.DONE },+ { name: taskName("t2"), status: Task_Status.FAILED },+ ]);+ render(renderList(stage));+ expect(expandedOf(taskName("t1"))).toBe("false");+ expect(expandedOf(taskName("t2"))).toBe("true");+ });++ test("falls back to the first task when nothing is actionable", () => {+ const stage = makeStage(stageName, [+ { name: taskName("t1"), status: Task_Status.DONE },+ { name: taskName("t2"), status: Task_Status.DONE },+ ]);+ render(renderList(stage));+ expect(expandedOf(taskName("t1"))).toBe("true");+ expect(expandedOf(taskName("t2"))).toBe("false");+ });+});++describe("DeployTaskList deep-linked task", () => {+ const stageName = "rollouts/r/stages/s";+ const taskName = (id: number) => `${stageName}/tasks/t${id}`;+ const manyTasks = Array.from({ length: 30 }, (_, i) => taskName(i + 1));++ test("expands only the deep-linked task, not the auto pick", () => {+ const stage = makeStage(stageName, [taskName(1), taskName(2), taskName(3)]);+ render(renderList(stage, taskName(3)));+ // An explicit ?taskId= selection is the focus — the auto pick (the first+ // task) must NOT also open, or a reloaded deep link shows two cards.+ expect(expandedOf(taskName(1))).toBe("false");+ expect(expandedOf(taskName(2))).toBe("false");+ expect(expandedOf(taskName(3))).toBe("true");+ });++ test("reveals a deep-linked task beyond the first page", () => {+ const stage = makeStage(stageName, manyTasks);+ render(renderList(stage, taskName(26)));+ expect(expandedOf(taskName(26))).toBe("true");+ });++ test("expands and reveals when the deep link changes after mount", () => {+ const stage = makeStage(stageName, manyTasks);+ const { rerender } = render(renderList(stage));+ expect(screen.queryByText(taskName(26))).toBeNull();++ rerender(renderList(stage, taskName(26)));+ expect(expandedOf(taskName(26))).toBe("true");+ // The earlier auto pick stays expanded — deep links add, never collapse.+ expect(expandedOf(taskName(1))).toBe("true");+ });+});++describe("DeployTaskList mirrors the focused task into the URL", () => {+ const stageName = "rollouts/r/stages/s";+ const taskName = (id: number) => `${stageName}/tasks/t${id}`;++ test("mounting an active stage writes its default task to the URL", () => {+ routerMocks.replace.mockClear();+ const stage = makeStage(stageName, [+ { name: taskName(1), status: Task_Status.DONE },+ { name: taskName(2), status: Task_Status.RUNNING },+ ]);+ render(+ <PlanDetailProvider value={makePage()}>+ <DeployTaskList stage={stage} />+ </PlanDetailProvider>+ );++ // The default focus (first running task) is expanded and mirrored so the+ // URL is a shareable link to the stage + task from the start.+ expect(expandedOf(taskName(2))).toBe("true");+ expect(routerMocks.replace).toHaveBeenCalledWith({+ query: { phase: "deploy", stageId: "s", taskId: "t2" },+ });+ });++ test("opening a card writes that task to the URL", () => {+ routerMocks.replace.mockClear();+ const stage = makeStage(stageName, [taskName(1), taskName(2)]);+ render(+ <PlanDetailProvider value={makePage()}>+ <DeployTaskList stage={stage} />+ </PlanDetailProvider>+ );++ // t1 is the default; opening t2 focuses it and mirrors it into the URL.+ fireEvent.click(screen.getByText(taskName(2)));+ expect(expandedOf(taskName(2))).toBe("true");+ expect(routerMocks.replace).toHaveBeenLastCalledWith({+ query: { phase: "deploy", stageId: "s", taskId: "t2" },+ });+ });++ test("preview (readonly) never writes the URL", () => {+ routerMocks.replace.mockClear();+ const stage = makeStage(stageName, [taskName(1), taskName(2)]);+ render(renderList(stage));++ fireEvent.click(screen.getByText(taskName(2)));+ expect(expandedOf(taskName(2))).toBe("true");+ expect(routerMocks.replace).not.toHaveBeenCalled();+ });++ test("landing with a ?taskId= honors it without re-writing", () => {+ routerMocks.replace.mockClear();+ const stage = makeStage(stageName, [taskName(1), taskName(2)]);+ render(+ <PlanDetailProvider value={makePage(taskName(2))}>+ <DeployTaskList stage={stage} />+ </PlanDetailProvider>+ );++ // The incoming ?taskId= already matches the focus — no redundant write.+ expect(expandedOf(taskName(2))).toBe("true");+ expect(routerMocks.replace).not.toHaveBeenCalled();+ });+});++describe("DeployTaskList keep-alive activation", () => {+ const stageName = "rollouts/r/stages/s";+ const taskName = (id: number) => `${stageName}/tasks/t${id}`;++ const renderActive = (stage: Stage, active: boolean) => (+ <PlanDetailProvider value={makePage()}>+ <DeployTaskList active={active} stage={stage} />+ </PlanDetailProvider>+ );++ test("a hidden list mounts collapsed and never writes the URL", () => {+ routerMocks.replace.mockClear();+ const stage = makeStage(stageName, [taskName(1), taskName(2)]);+ render(renderActive(stage, false));++ // No default expansion (that would mount Monaco + fetch logs offscreen)+ // and no ?taskId= mirror from a stage the user isn't looking at.+ expect(expandedOf(taskName(1))).toBe("false");+ expect(expandedOf(taskName(2))).toBe("false");+ expect(routerMocks.replace).not.toHaveBeenCalled();+ });++ test("first activation expands the default task and mirrors it", () => {+ routerMocks.replace.mockClear();+ const stage = makeStage(stageName, [taskName(1), taskName(2)]);+ const { rerender } = render(renderActive(stage, false));++ rerender(renderActive(stage, true));+ expect(expandedOf(taskName(1))).toBe("true");+ expect(routerMocks.replace).toHaveBeenCalledWith({+ query: { phase: "deploy", stageId: "s", taskId: "t1" },+ });+ });++ test("first activation reseeds focus to a task that went active while hidden", () => {+ routerMocks.replace.mockClear();+ // Mount hidden with everything not-started — the captured default focus is+ // the first task.+ const hidden = makeStage(stageName, [+ { name: taskName(1), status: Task_Status.NOT_STARTED },+ { name: taskName(2), status: Task_Status.NOT_STARTED },+ ]);+ const { rerender } = render(renderActive(hidden, false));++ // Still hidden, t2 starts running. Same task names, so the name-keyed reseed+ // doesn't fire — the captured focus (t1) is now stale.+ const running = makeStage(stageName, [+ { name: taskName(1), status: Task_Status.DONE },+ { name: taskName(2), status: Task_Status.RUNNING },+ ]);+ rerender(renderActive(running, false));++ // On first activation the default-open card AND the URL mirror must reflect+ // the current statuses (t2), not the stale mount-time default (t1).+ rerender(renderActive(running, true));+ expect(expandedOf(taskName(2))).toBe("true");+ expect(routerMocks.replace).toHaveBeenLastCalledWith({+ query: { phase: "deploy", stageId: "s", taskId: "t2" },+ });+ });++ test("bypasses the leave guard for the internal URL sync while editing", () => {+ routerMocks.replace.mockClear();+ const bypass = vi.fn();+ const stage = makeStage(stageName, [+ { name: taskName(1), status: Task_Status.DONE },+ { name: taskName(2), status: Task_Status.RUNNING },+ ]);+ const page = {+ ...makePage(),+ isEditing: true,+ bypassLeaveGuardOnce: bypass,+ } as unknown as PlanDetailPageState;+ render(+ <PlanDetailProvider value={page}>+ <DeployTaskList stage={stage} />+ </PlanDetailProvider>+ );+ // The internal same-path mirror still writes the URL, and bypasses the+ // unsaved-edits guard so no discard dialog interrupts it mid-edit.+ expect(routerMocks.replace).toHaveBeenCalledWith({+ query: { phase: "deploy", stageId: "s", taskId: "t2" },+ });+ expect(bypass).toHaveBeenCalled();+ });++ test("does not touch the leave guard when not editing", () => {+ routerMocks.replace.mockClear();+ const bypass = vi.fn();+ const stage = makeStage(stageName, [+ { name: taskName(1), status: Task_Status.RUNNING },+ ]);+ const page = {+ ...makePage(),+ isEditing: false,+ bypassLeaveGuardOnce: bypass,+ } as unknown as PlanDetailPageState;+ render(+ <PlanDetailProvider value={page}>+ <DeployTaskList stage={stage} />+ </PlanDetailProvider>+ );+ expect(routerMocks.replace).toHaveBeenCalled();+ expect(bypass).not.toHaveBeenCalled();+ });++ test("switching away and back preserves state without re-seeding", () => {+ const stage = makeStage(stageName, [taskName(1), taskName(2)]);+ const { rerender } = render(renderActive(stage, true));+ expect(expandedOf(taskName(1))).toBe("true");++ // User closes the default card, then switches to another stage and back;+ // the list keeps what the user left — no default re-expansion.+ fireEvent.click(screen.getByText(taskName(1)));+ expect(expandedOf(taskName(1))).toBe("false");+ rerender(renderActive(stage, false));+ rerender(renderActive(stage, true));+ expect(expandedOf(taskName(1))).toBe("false");+ });+});++describe("DeployTaskList arrival scroll (BYT-9765 offset jump)", () => {+ const stageName = "rollouts/r/stages/s";+ const taskName = (id: number) => `${stageName}/tasks/t${id}`;++ test("a genuine ?taskId= arrival deep-links its card", () => {+ const stage = makeStage(stageName, [taskName(1), taskName(2)]);+ // Arrived via a shared link to t2 (nothing self-written yet).+ render(+ <PlanDetailProvider value={makePage(taskName(2))}>+ <DeployTaskList stage={stage} />+ </PlanDetailProvider>+ );+ expect(deepLinkedOf(taskName(2))).toBe("true");+ });++ test("a task we wrote ourselves is not a deep-link once the route catches up", () => {+ const stage = makeStage(stageName, [taskName(1), taskName(2)]);+ const { rerender } = render(+ <PlanDetailProvider value={makePage()}>+ <DeployTaskList stage={stage} />+ </PlanDetailProvider>+ );++ // Open t2 — it is mirrored into the URL and marked self-written.+ fireEvent.click(screen.getByText(taskName(2)));++ // The route settles to t2 (as router.replace would deliver it). Because we+ // wrote it, it must NOT deep-link/scroll — nor may any other card, which is+ // the intermittent offset-jump the old per-render derivation caused.+ rerender(+ <PlanDetailProvider value={makePage(taskName(2))}>+ <DeployTaskList stage={stage} />+ </PlanDetailProvider>+ );+ expect(deepLinkedOf(taskName(1))).toBe("false");+ expect(deepLinkedOf(taskName(2))).toBe("false");+ });++ test("forward-navigation to a self-opened task still deep-links (scrolls)", () => {+ const stage = makeStage(stageName, [taskName(1), taskName(2)]);+ const at = (selected?: string) => (+ <PlanDetailProvider value={makePage(selected)}>+ <DeployTaskList stage={stage} />+ </PlanDetailProvider>+ );+ const { rerender } = render(at());++ // Open t2 ourselves, then let the route settle to it — not an arrival.+ fireEvent.click(screen.getByText(taskName(2)));+ rerender(at(taskName(2)));+ expect(deepLinkedOf(taskName(2))).toBe("false");++ // Back to t1, then FORWARD to t2. The forward navigation is a real arrival+ // and must deep-link, even though we opened t2 earlier — the self-write+ // marker is one-shot, not a persistent suppressor.+ rerender(at(taskName(1)));+ rerender(at(taskName(2)));+ expect(deepLinkedOf(taskName(2))).toBe("true");+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsxindex 02a001b7ca..43c76845d9 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx@@ -1,49 +1,173 @@-import { useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { Button } from "@/react/components/ui/button";-import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";+import { useLatestRef } from "@/react/hooks/useLatestRef";+import { useOnKeyChange } from "@/react/hooks/useOnKeyChange";+import { router } from "@/react/router";+import {+ type Stage,+ type Task,+ Task_Status,+ type TaskRun,+} from "@/types/proto-es/v1/rollout_service_pb";+import { extractStageUID, extractTaskUID } from "@/utils/v1/issue/rollout";import { usePlanDetailContext } from "../../shell/PlanDetailContext";import { DeployTaskItem } from "./DeployTaskItem";import { DeployTaskToolbar } from "./DeployTaskToolbar";import { isDeployTaskSelectable } from "./taskActionState";const DEFAULT_PAGE_SIZE = 20;+const EMPTY_TASK_RUNS: TaskRun[] = [];++// The task worth opening by default: the first one that needs attention+// (running or failed), falling back to the first task.+const autoExpandTaskName = (tasks: Task[]): string | undefined =>+ (+ tasks.find(+ (task) =>+ task.status === Task_Status.RUNNING ||+ task.status === Task_Status.FAILED+ ) ?? tasks[0]+ )?.name;++// The shareable ?stageId&taskId= shape for a task.+const deployTaskQuery = (stageName: string, taskName: string) => ({+ phase: "deploy",+ stageId: extractStageUID(stageName),+ taskId: extractTaskUID(taskName),+});++const initialExpandedNames = (+ tasks: Task[],+ selectedTaskName?: string+): Set<string> => {+ // An explicit ?taskId= selection is the user's focus — open only that task.+ // (Matches focusedTaskName's selection-wins logic; opening the auto pick too+ // would leave two unrelated cards expanded on reload of a deep link.)+ if (+ selectedTaskName &&+ tasks.some((task) => task.name === selectedTaskName)+ ) {+ return new Set([selectedTaskName]);+ }+ // No selection: open a sensible default so the list isn't all-collapsed.+ const autoName = autoExpandTaskName(tasks);+ return autoName ? new Set([autoName]) : new Set();+};++// Grow the page so a deep-linked task beyond the first page is visible.+const initialDisplayedCount = (+ tasks: Task[],+ selectedTaskName?: string+): number => {+ const index = selectedTaskName+ ? tasks.findIndex((task) => task.name === selectedTaskName)+ : -1;+ return Math.max(DEFAULT_PAGE_SIZE, index + 1);+};export function DeployTaskList({- selectedTaskName,stage,readonly = false,+ active = true,}: {- selectedTaskName?: string;stage: Stage;readonly?: boolean;+ // Every stage's list stays mounted (visibility is the parent's concern);+ // `active` marks the one the user is looking at. The default card expansion+ // (Monaco + log fetch) is deferred to the first activation so loading the+ // page doesn't mount every stage's editors at once.+ active?: boolean;}) {const { t } = useTranslation();const page = usePlanDetailContext();- const [displayedTaskCount, setDisplayedTaskCount] =- useState(DEFAULT_PAGE_SIZE);+ // Full task resource name resolved from the ?taskId= deep link.+ const selectedTaskName = page.selectedTaskName;const filteredTasks = stage.tasks;+ // The stage object is rebuilt every poll tick, so passing it to the memoized+ // cards would re-render all of them each tick. The cards take the stage's+ // stable identity as primitives and reach the live object through this stable+ // accessor only when the action panel opens.+ const stageRef = useLatestRef(stage);+ const getStage = useCallback(() => stageRef.current, [stageRef]);+ const isTaskInStage = (name: string | undefined): name is string =>+ !!name && filteredTasks.some((task) => task.name === name);++ const [activated, setActivated] = useState(active);+ const [displayedTaskCount, setDisplayedTaskCount] = useState(() =>+ initialDisplayedCount(filteredTasks, selectedTaskName)+ );const [expandedTaskNames, setExpandedTaskNames] = useState<Set<string>>(() =>- filteredTasks.length > 0 ? new Set([filteredTasks[0].name]) : new Set()+ active ? initialExpandedNames(filteredTasks, selectedTaskName) : new Set());const [selectedTaskNames, setSelectedTaskNames] = useState<Set<string>>(new Set());- const taskNamesKey = filteredTasks.map((task) => task.name).join(",");-- // When the visible task set changes — most importantly when switching to a- // different stage — re-derive the per-stage list state (pagination, the- // auto-expanded first task, and the still-valid selection) during render- // rather than in a post-paint effect. Doing it here means the new stage's- // first paint already shows the first task expanded, instead of painting a- // collapsed list and expanding it a frame later, which read as a flash- // (BYT-9763).- const [trackedTaskNamesKey, setTrackedTaskNamesKey] = useState(taskNamesKey);- if (taskNamesKey !== trackedTaskNamesKey) {- setTrackedTaskNamesKey(taskNamesKey);- setDisplayedTaskCount(DEFAULT_PAGE_SIZE);+ // The focused task of this stage — the last card the user opened, defaulting+ // to the auto-expand pick or an incoming deep link. It is mirrored into+ // ?stageId&taskId= while this stage is active (the effect below), so the+ // address bar is a shareable link to this stage + task, and switching back to+ // a visited stage restores it.+ const [focusedTaskName, setFocusedTaskName] = useState<string | undefined>(+ () =>+ (isTaskInStage(selectedTaskName) ? selectedTaskName : undefined) ??+ autoExpandTaskName(filteredTasks)+ );+ // A card scrolls into view only for an EXTERNAL arrival (a shared link or+ // back/forward), never for a ?taskId= this list wrote itself. The mirror+ // effect records the value it writes here, and the route-settle handler below+ // CONSUMES it (one-shot). A persistent marker would misread a later external+ // navigation back to a previously self-opened task as a self-write and fail+ // to scroll (BYT-9765).+ const pendingSelfWriteRef = useRef<string | undefined>(undefined);+ const [arrivalTaskName, setArrivalTaskName] = useState<string | undefined>(+ () => (isTaskInStage(selectedTaskName) ? selectedTaskName : undefined)+ );+ // Latest expansion, read by the stable toggle callback without being a dep.+ const expandedTaskNamesRef = useRef(expandedTaskNames);+ expandedTaskNamesRef.current = expandedTaskNames;++ // filteredTasks identity is poll-stable (snapshot gate), so the join runs+ // only when the stage's task set actually changed.+ const taskNamesKey = useMemo(+ () => filteredTasks.map((task) => task.name).join(","),+ [filteredTasks]+ );++ // First activation of a lazily-mounted list: seed the default expansion+ // during render (same BYT-9763 idiom as below) so the stage's first visible+ // paint already shows the right card open.+ if (active && !activated) {+ setActivated(true);+ setDisplayedTaskCount(+ initialDisplayedCount(filteredTasks, selectedTaskName)+ );+ setExpandedTaskNames(initialExpandedNames(filteredTasks, selectedTaskName));+ // Reseed the focused task too: a task may have become RUNNING/FAILED while+ // this stage was mounted-but-hidden, so the default-open card — and the URL+ // mirror that follows it — must reflect the current statuses, not the ones+ // captured at the hidden mount (which would write a stale ?taskId=).+ setFocusedTaskName(+ (isTaskInStage(selectedTaskName) ? selectedTaskName : undefined) ??+ autoExpandTaskName(filteredTasks)+ );+ }++ // When the visible task set changes (a plan edit, a filter change), re-derive+ // the list state during render (useOnKeyChange / BYT-9763), so the first paint+ // after the change already shows the right task expanded. Keyed on task+ // names, not statuses, so polling-driven status changes never reset the+ // user's expansion mid-view.+ useOnKeyChange(taskNamesKey, () => {+ setDisplayedTaskCount(+ initialDisplayedCount(filteredTasks, selectedTaskName)+ );+ // A never-activated (still hidden) list keeps everything collapsed — its+ // default expansion is seeded on first activation above.setExpandedTaskNames(- filteredTasks.length > 0 ? new Set([filteredTasks[0].name]) : new Set()+ activated+ ? initialExpandedNames(filteredTasks, selectedTaskName)+ : new Set());setSelectedTaskNames((prev) => {const remaining = [...prev].filter((taskName) =>@@ -51,7 +175,71 @@ export function DeployTaskList({);return remaining.length === prev.size ? prev : new Set(remaining);});- }+ // Keep focus valid: fall back to the default if the focused task is gone.+ setFocusedTaskName((prev) =>+ isTaskInStage(prev) ? prev : autoExpandTaskName(filteredTasks)+ );+ });++ // When ?taskId= settles to a task in this stage, focus + reveal it. Scroll+ // only when it is an external arrival (not a ?taskId= we just wrote) — decided+ // here, once the route has settled, so the transient render during our own+ // write can't be mistaken for an arrival.+ useOnKeyChange(selectedTaskName ?? "", () => {+ // Consume the one-shot self-write marker: this settled route value counts+ // as a self-write only if it matches what we just wrote.+ const wasSelfWrite = selectedTaskName === pendingSelfWriteRef.current;+ pendingSelfWriteRef.current = undefined;+ if (isTaskInStage(selectedTaskName)) {+ const index = filteredTasks.findIndex(+ (task) => task.name === selectedTaskName+ );+ setExpandedTaskNames((prev) =>+ prev.has(selectedTaskName) ? prev : new Set(prev).add(selectedTaskName)+ );+ setDisplayedTaskCount((count) => Math.max(count, index + 1));+ setFocusedTaskName(selectedTaskName);+ setArrivalTaskName(wasSelfWrite ? undefined : selectedTaskName);+ } else {+ setArrivalTaskName(undefined);+ }+ });++ // Mirror the focused task into ?stageId&taskId= while this stage is active,+ // so the URL is a shareable link. Only the active stage writes (a hidden+ // keep-alive list must not hijack the address bar); recording the write in+ // pendingSelfWriteRef keeps its own route echo from scrolling the card.+ const { isEditing, bypassLeaveGuardOnce } = page;+ useEffect(() => {+ if (+ readonly ||+ !active ||+ !focusedTaskName ||+ selectedTaskName === focusedTaskName+ ) {+ return;+ }+ pendingSelfWriteRef.current = focusedTaskName;+ // This is an internal, same-path query sync (a shareable ?taskId=), not a+ // page leave — bypass the unsaved-edits guard so it doesn't cancel the write+ // (which would strand pendingSelfWriteRef and desync focus from the URL) or+ // pop a spurious discard dialog mid-edit. Only while editing, so the one-shot+ // bypass is consumed by this navigation instead of lingering to a real leave.+ if (isEditing) {+ bypassLeaveGuardOnce();+ }+ void router.replace({+ query: deployTaskQuery(stage.name, focusedTaskName),+ });+ }, [+ active,+ readonly,+ focusedTaskName,+ selectedTaskName,+ stage.name,+ isEditing,+ bypassLeaveGuardOnce,+ ]);const visibleTasks = filteredTasks.slice(0, displayedTaskCount);const hasMoreTasks = filteredTasks.length > displayedTaskCount;@@ -61,22 +249,30 @@ export function DeployTaskList({[filteredTasks, selectedTaskNames]);- const toggleExpand = (task: Task) => {+ // One control per card: toggle it open or closed (local state; keep-alive+ // preserves it across stage switches). Opening focuses the task, which the+ // effect above mirrors into the URL. Stable identities so the memoized cards+ // don't re-render when the list does.+ const toggleTask = useCallback((task: Task) => {+ const willExpand = !expandedTaskNamesRef.current.has(task.name);setExpandedTaskNames((prev) => {const next = new Set(prev);if (next.has(task.name)) next.delete(task.name);else next.add(task.name);return next;});- };- const toggleSelect = (task: Task) => {+ if (willExpand) {+ setFocusedTaskName(task.name);+ }+ }, []);+ const toggleSelect = useCallback((task: Task) => {setSelectedTaskNames((prev) => {const next = new Set(prev);if (next.has(task.name)) next.delete(task.name);else next.add(task.name);return next;});- };+ }, []);return (<div className="w-full">@@ -101,25 +297,32 @@ export function DeployTaskList({/>)}- <div className="task-list space-y-3 px-4 py-3">+ <div className="task-list flex flex-col gap-3 px-4 py-3">{visibleTasks.map((task) => (<DeployTaskItem- active={selectedTaskName === task.name}+ active={active}+ currentUser={page.currentUser}+ deepLinked={arrivalTaskName === task.name}key={task.name}isExpanded={expandedTaskNames.has(task.name)}isSelected={selectedTaskNames.has(task.name)}isSelectable={!readonly && isDeployTaskSelectable(task)}- onToggleExpand={() => toggleExpand(task)}- onToggleSelect={() => toggleSelect(task)}- readonly={readonly}- stageId={stage.name.split("/").pop() ?? ""}- stage={stage}+ issue={page.issue}+ onRefresh={page.refreshState}+ onToggleExpand={toggleTask}+ onToggleSelect={toggleSelect}+ plan={page.plan}+ project={page.project}+ rolloutName={page.rollout?.name ?? ""}+ getStage={getStage}+ stageEnvironment={stage.environment}task={task}+ taskRuns={page.taskRunsByTaskName.get(task.name) ?? EMPTY_TASK_RUNS}/>))}{filteredTasks.length === 0 && (- <div className="py-8 text-center text-gray-500">+ <div className="py-8 text-center text-control-light">{t("rollout.task.no-tasks")}</div>)}diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRow.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRow.tsxdeleted file mode 100644index 10536f330a..0000000000--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRow.tsx+++ /dev/null@@ -1,67 +0,0 @@-import { X } from "lucide-react";-import { useTranslation } from "react-i18next";-import { TaskStatusIcon } from "@/react/components/TaskStatusIcon";-import { Button } from "@/react/components/ui/button";-import { cn } from "@/react/lib/utils";-import { router } from "@/react/router";-import { type Task } from "@/types/proto-es/v1/rollout_service_pb";-import { stringifyTaskStatus } from "@/utils";--export function DeployTaskRow({- active,- onCloseTaskPanel,- stageId,- task,-}: {- active: boolean;- onCloseTaskPanel: () => void;- stageId: string;- task: Task;-}) {- const { t } = useTranslation();- const taskId = task.name.split("/").pop();-- return (- <button- className={cn(- "flex w-full items-center justify-between rounded border px-3 py-2 text-left text-sm",- active- ? "border-accent bg-accent/5"- : "border-control-border hover:bg-gray-50"- )}- onClick={() => {- void router.push({- query: {- phase: "deploy",- stageId,- taskId,- },- });- }}- type="button"- >- <div className="flex min-w-0 items-center gap-2">- <TaskStatusIcon size="small" status={task.status} />- <div className="min-w-0">- <div className="truncate text-main">{task.name}</div>- <div className="text-xs text-control-light">- {stringifyTaskStatus(task.status, t)}- </div>- </div>- </div>- {active && (- <Button- aria-label={t("common.close")}- size="sm"- appearance="secondary"- onClick={(event) => {- event.stopPropagation();- onCloseTaskPanel();- }}- >- <X className="h-4 w-4" />- </Button>- )}- </button>- );-}diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRunHistorySheet.test.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRunHistorySheet.test.tsxnew file mode 100644index 0000000000..591c3fc560--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRunHistorySheet.test.tsx@@ -0,0 +1,180 @@+import { create } from "@bufbuild/protobuf";+import { TimestampSchema } from "@bufbuild/protobuf/wkt";+import type { ReactElement, ReactNode } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { describe, expect, test, vi } from "vitest";+import {+ TaskRun_Status,+ TaskRunSchema,+} from "@/types/proto-es/v1/rollout_service_pb";+import { DeployTaskRunHistorySheet } from "./DeployTaskRunHistorySheet";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) =>+ options ? `${key}:${JSON.stringify(options)}` : key,+ }),+}));++vi.mock("@/react/components/ui/sheet", () => ({+ Sheet: ({ children, open }: { children: ReactNode; open: boolean }) =>+ open ? <div>{children}</div> : null,+ SheetBody: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SheetContent: ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ ),+ SheetHeader: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SheetTitle: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}));++const viewerMounts = vi.hoisted(() => ({ count: 0 }));+vi.mock("@/react/components/task-run-log", async () => {+ const { useEffect } = await import("react");+ return {+ TaskRunLogViewer: ({ taskRunName }: { taskRunName: string }) => {+ // Counts fresh mounts so a test can assert the viewer remounts (rather+ // than re-renders in place) when its key changes.+ useEffect(() => {+ viewerMounts.count += 1;+ }, []);+ return <div data-task-run-name={taskRunName} data-testid="log-viewer" />;+ },+ };+});++vi.mock("@/react/components/HumanizeTs", () => ({+ HumanizeTs: ({ ts }: { ts: number }) => <span>{ts}</span>,+}));++const taskName = "projects/p1/rollouts/r1/stages/s1/tasks/t1";++const makeTaskRuns = (count: number) =>+ // Newest first, matching the component contract.+ Array.from({ length: count }, (_, index) =>+ create(TaskRunSchema, {+ createTime: create(TimestampSchema, {+ seconds: BigInt(1000 * (count - index)),+ }),+ creator: "users/[email protected]",+ name: `${taskName}/taskRuns/${count - index}`,+ status: TaskRun_Status.FAILED,+ })+ );++const renderSheet = (taskRuns: ReturnType<typeof makeTaskRuns>) => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ const element: ReactElement = (+ <DeployTaskRunHistorySheet+ onOpenChange={() => {}}+ open={true}+ taskRuns={taskRuns}+ />+ );+ act(() => {+ root.render(element);+ });+ return {+ container,+ cleanup: () => {+ act(() => root.unmount());+ container.remove();+ },+ };+};++const mountedLogNames = (container: HTMLElement) =>+ Array.from(+ container.querySelectorAll<HTMLElement>("[data-testid=log-viewer]")+ ).map((node) => node.dataset.taskRunName);++describe("DeployTaskRunHistorySheet", () => {+ test("renders runs newest-first with descending run numbers", () => {+ const { container, cleanup } = renderSheet(makeTaskRuns(3));+ const labels = Array.from(container.querySelectorAll("button")).map(+ (button) => button.textContent+ );+ expect(labels[0]).toContain('task-run.run-number:{"number":3}');+ expect(labels[2]).toContain('task-run.run-number:{"number":1}');+ cleanup();+ });++ test("expands every run when there are three or fewer", () => {+ const { container, cleanup } = renderSheet(makeTaskRuns(3));+ expect(mountedLogNames(container)).toEqual([+ `${taskName}/taskRuns/3`,+ `${taskName}/taskRuns/2`,+ `${taskName}/taskRuns/1`,+ ]);+ cleanup();+ });++ test("remounts the log viewer when a run flips RUNNING -> DONE", () => {+ viewerMounts.count = 0;+ const run = (status: TaskRun_Status) =>+ create(TaskRunSchema, {+ createTime: create(TimestampSchema, { seconds: 1000n }),+ creator: "users/[email protected]",+ name: `${taskName}/taskRuns/1`,+ status,+ });+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <DeployTaskRunHistorySheet+ onOpenChange={() => {}}+ open={true}+ taskRuns={[run(TaskRun_Status.RUNNING)]}+ />+ );+ });+ expect(viewerMounts.count).toBe(1);++ // Same run, now DONE. Status is part of the viewer key, so it must remount+ // (not re-render in place) — that's what triggers useTaskRunLogData's+ // unmount cleanup to invalidate any in-flight RUNNING log request.+ act(() => {+ root.render(+ <DeployTaskRunHistorySheet+ onOpenChange={() => {}}+ open={true}+ taskRuns={[run(TaskRun_Status.DONE)]}+ />+ );+ });+ expect(viewerMounts.count).toBe(2);++ act(() => root.unmount());+ container.remove();+ });++ test("collapses older runs at four or more, expanding on click", () => {+ const { container, cleanup } = renderSheet(makeTaskRuns(4));+ expect(mountedLogNames(container)).toEqual([`${taskName}/taskRuns/4`]);++ const buttons = container.querySelectorAll("button");+ expect(buttons[0].getAttribute("aria-expanded")).toBe("true");+ expect(buttons[1].getAttribute("aria-expanded")).toBe("false");++ act(() => {+ buttons[1].dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });++ expect(mountedLogNames(container)).toEqual([+ `${taskName}/taskRuns/4`,+ `${taskName}/taskRuns/3`,+ ]);+ expect(buttons[1].getAttribute("aria-expanded")).toBe("true");+ cleanup();+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRunHistorySheet.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRunHistorySheet.tsxnew file mode 100644index 0000000000..40b65c1b05--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRunHistorySheet.tsx@@ -0,0 +1,171 @@+import { ChevronDown, ChevronRight, Clock3, User } from "lucide-react";+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { HumanizeTs } from "@/react/components/HumanizeTs";+import { TaskRunStatusIcon } from "@/react/components/TaskRunStatusIcon";+import { TaskRunLogViewer } from "@/react/components/task-run-log";+import { EllipsisText } from "@/react/components/ui/ellipsis-text";+import {+ Sheet,+ SheetBody,+ SheetContent,+ SheetHeader,+ SheetTitle,+} from "@/react/components/ui/sheet";+import { useOnKeyChange } from "@/react/hooks/useOnKeyChange";+import {+ executorEmailOfTaskRun,+ formatTaskRunDuration,+ getTaskRunComment,+} from "@/react/lib/taskRun";+import { getTimeForPbTimestampProtoEs } from "@/types";+import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";++// With this many runs or more, only the newest run starts expanded; older+// runs collapse to header rows. Keeps the sheet scannable and avoids fetching+// every run's log up front.+const COLLAPSE_OLDER_RUNS_THRESHOLD = 4;++export function DeployTaskRunHistorySheet({+ onOpenChange,+ open,+ taskRuns,+}: {+ onOpenChange: (open: boolean) => void;+ open: boolean;+ // Sorted newest-first by the caller (the page's per-task run grouping).+ taskRuns: TaskRun[];+}) {+ const { t } = useTranslation();++ return (+ <Sheet onOpenChange={onOpenChange} open={open}>+ <SheetContent width="standard">+ <SheetHeader>+ <SheetTitle>{t("task-run.history")}</SheetTitle>+ </SheetHeader>+ {/* SheetContent unmounts its children after the close animation, so+ the run list's expansion state resets on every open. */}+ <SheetBody className="gap-y-2 overscroll-contain">+ <TaskRunHistoryList taskRuns={taskRuns} />+ </SheetBody>+ </SheetContent>+ </Sheet>+ );+}++function TaskRunHistoryList({ taskRuns }: { taskRuns: TaskRun[] }) {+ const [expandedRunNames, setExpandedRunNames] = useState<Set<string>>(() =>+ taskRuns.length >= COLLAPSE_OLDER_RUNS_THRESHOLD+ ? new Set([taskRuns[0].name])+ : new Set(taskRuns.map((taskRun) => taskRun.name))+ );+ // A rerun created while the sheet is open prepends a new newest run; expand+ // it so the latest is visible without reopening the sheet.+ useOnKeyChange(taskRuns[0]?.name ?? "", () => {+ const newest = taskRuns[0]?.name;+ if (newest) {+ setExpandedRunNames((prev) =>+ prev.has(newest) ? prev : new Set(prev).add(newest)+ );+ }+ });+ const toggle = (taskRun: TaskRun) => {+ setExpandedRunNames((prev) => {+ const next = new Set(prev);+ if (next.has(taskRun.name)) next.delete(taskRun.name);+ else next.add(taskRun.name);+ return next;+ });+ };++ return (+ <>+ {taskRuns.map((taskRun, index) => (+ <TaskRunHistoryItem+ isExpanded={expandedRunNames.has(taskRun.name)}+ key={taskRun.name}+ onToggle={() => toggle(taskRun)}+ runNumber={taskRuns.length - index}+ taskRun={taskRun}+ />+ ))}+ </>+ );+}++function TaskRunHistoryItem({+ isExpanded,+ onToggle,+ runNumber,+ taskRun,+}: {+ isExpanded: boolean;+ onToggle: () => void;+ runNumber: number;+ taskRun: TaskRun;+}) {+ const { t } = useTranslation();+ const startTs =+ getTimeForPbTimestampProtoEs(taskRun.startTime, 0) ||+ getTimeForPbTimestampProtoEs(taskRun.createTime, 0);+ const duration = formatTaskRunDuration(taskRun);+ const executorEmail = executorEmailOfTaskRun(taskRun);+ const comment = getTaskRunComment(taskRun, t);++ return (+ <div className="rounded-lg border">+ <button+ aria-expanded={isExpanded}+ className="flex w-full items-center gap-x-2 rounded-lg px-3 py-2 text-left hover:bg-control-bg focus-visible:ring-2 focus-visible:ring-accent"+ onClick={onToggle}+ type="button"+ >+ {isExpanded ? (+ <ChevronDown className="size-4 shrink-0 text-control-light" />+ ) : (+ <ChevronRight className="size-4 shrink-0 text-control-light" />+ )}+ <TaskRunStatusIcon status={taskRun.status} />+ <span className="shrink-0 text-sm font-medium text-control">+ {t("task-run.run-number", { number: runNumber })}+ </span>+ {/* Only when collapsed: the expanded body shows the full error, so a+ header teaser there would just duplicate it. */}+ <span className="min-w-0 flex-1 text-xs text-control-light">+ {!isExpanded && (+ <EllipsisText className="line-clamp-1" text={comment} />+ )}+ </span>+ <span className="flex shrink-0 items-center gap-x-3 text-xs text-control-light">+ {startTs > 0 && <HumanizeTs ts={startTs / 1000} />}+ {duration && (+ <span className="flex items-center gap-x-1">+ <Clock3 className="size-3" />+ {duration}+ </span>+ )}+ {executorEmail && (+ <span className="hidden items-center gap-x-1 lg:flex">+ <User className="size-3" />+ {executorEmail}+ </span>+ )}+ </span>+ </button>+ {isExpanded && (+ <div className="border-t p-3">+ {/* Status is part of the key (as in the latest-run panel): a+ RUNNING -> DONE flip remounts the viewer so useTaskRunLogData's+ unmount cleanup invalidates the in-flight RUNNING log request,+ which would otherwise cache an incomplete RUNNING log. */}+ <TaskRunLogViewer+ key={`logs-${taskRun.name}-${taskRun.status}`}+ taskRunName={taskRun.name}+ taskRunStatus={taskRun.status}+ />+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.tsxindex 7be63016a5..547aa4055d 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.tsx@@ -1,35 +1,51 @@import { useEffect, useMemo, useState } from "react";-import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";+import { useLatestRef } from "@/react/hooks/useLatestRef";+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";+import type { Task } from "@/types/proto-es/v1/rollout_service_pb";+import type { User } from "@/types/proto-es/v1/user_service_pb";import {canRolloutTasks,preloadRolloutPermissionContext,} from "../../../issue-detail/utils/rollout";-import { usePlanDetailContext } from "../../shell/PlanDetailContext";import {type DeployTaskActionState,getDeployTaskActionState,} from "./taskActionState";+// Page slices arrive as params (not via context) so the memoized card that+// calls this hook re-renders only when one of them actually changes.export const useDeployTaskActions = ({- stage,+ currentUser,+ issue,+ project,+ environment,task,}: {- stage?: Stage;+ currentUser: User;+ issue?: Issue;+ project: Project;+ environment?: string;task: Task;}): DeployTaskActionState & { permissionReady: boolean } => {- const page = usePlanDetailContext();- const currentUser = page.currentUser;- const project = page.project;const [permissionReady, setPermissionReady] = useState(false);+ // The permission context is per project + environment — the helpers below+ // never read task fields — so the effect and memo key on those stable+ // strings and read the latest task through this ref instead of re-running+ // when the task identity changes. Taking `environment` (not the whole stage+ // object, which the snapshot gate rebuilds every poll tick) keeps the memo+ // from recomputing on ticks that only touched a sibling task.+ const taskRef = useLatestRef(task);+useEffect(() => {let canceled = false;const load = async () => {setPermissionReady(false);await preloadRolloutPermissionContext({- environment: stage?.environment,+ environment,projectName: project.name,- tasks: [task],+ tasks: [taskRef.current],});if (!canceled) {setPermissionReady(true);@@ -39,20 +55,20 @@ export const useDeployTaskActions = ({return () => {canceled = true;};- }, [project.name, stage?.environment, task]);+ }, [project.name, environment]);const canPerformActions = useMemo(() => {- if (!permissionReady || !stage) {+ if (!permissionReady || environment === undefined) {return false;}return canRolloutTasks({currentUser,- environment: stage.environment,- issue: page.issue,+ environment,+ issue,project,- tasks: [task],+ tasks: [taskRef.current],});- }, [currentUser, page.issue, permissionReady, project, stage, task]);+ }, [currentUser, issue, permissionReady, project, environment]);return {...getDeployTaskActionState({diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/taskRunUtils.ts b/frontend/src/react/pages/project/plan-detail/components/deploy/taskRunUtils.tsdeleted file mode 100644index b02015f40b..0000000000--- a/frontend/src/react/pages/project/plan-detail/components/deploy/taskRunUtils.ts+++ /dev/null@@ -1,56 +0,0 @@-import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";-import {- Task_Status,- TaskRun_Status,-} from "@/types/proto-es/v1/rollout_service_pb";--const TASK_RUN_STATUS_TO_TASK_STATUS: Partial<- Record<TaskRun_Status, Task_Status>-> = {- [TaskRun_Status.DONE]: Task_Status.DONE,- [TaskRun_Status.FAILED]: Task_Status.FAILED,- [TaskRun_Status.RUNNING]: Task_Status.RUNNING,- [TaskRun_Status.PENDING]: Task_Status.PENDING,- [TaskRun_Status.AVAILABLE]: Task_Status.PENDING,-};--export const taskRunStatusToTaskStatus = (- status: TaskRun_Status-): Task_Status =>- TASK_RUN_STATUS_TO_TASK_STATUS[status] ?? Task_Status.CANCELED;--const formatDuration = (durationMs: number): string => {- const seconds = Math.floor(durationMs / 1000);- const minutes = Math.floor(seconds / 60);- const hours = Math.floor(minutes / 60);-- if (hours > 0) {- return `${hours}h ${minutes % 60}m`;- }- if (minutes > 0) {- return `${minutes}m ${seconds % 60}s`;- }- if (seconds > 0) {- return `${seconds}s`;- }- if (durationMs > 0) {- return `${Math.round(durationMs)}ms`;- }- return "< 1s";-};--export const getTaskRunDuration = (taskRun: TaskRun): string => {- if (taskRun.status === TaskRun_Status.PENDING || !taskRun.startTime) {- return "";- }- const endMs =- taskRun.status === TaskRun_Status.RUNNING- ? Date.now()- : taskRun.updateTime- ? Number(taskRun.updateTime.seconds) * 1000- : 0;- if (endMs === 0) {- return "";- }- return formatDuration(endMs - Number(taskRun.startTime.seconds) * 1000);-};diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/types.ts b/frontend/src/react/pages/project/plan-detail/components/deploy/types.tsindex 793b37da13..8f478cc004 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/types.ts+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/types.ts@@ -9,12 +9,3 @@ export type RollbackItem = {task: Task;taskRun: TaskRun;};--export type DeployBranchProps = {- selectedTask?: Task;- onCloseTaskPanel: () => void;-};--export type DeployTaskDetailPanelProps = {- task: Task;-};diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/frontierStage.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/frontierStage.tsindex 012c63999b..6cf81d7248 100644--- a/frontend/src/react/pages/project/plan-detail/components/lifecycle/frontierStage.ts+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/frontierStage.ts@@ -26,15 +26,16 @@ export function stageHasRunnableTasks(stage: Stage): boolean {);}-// A task that already executed once (failed or canceled) — running the stage-// again is a re-run rather than a first run. Mirrors the per-task "Retry" label,-// which keys off a prior execution. Named in full so it isn't mistaken for-// stageHasRunningTasks.+// A task that already executed once (failed or canceled) — running it again is+// a re-run ("Rerun") rather than a first run ("Run"). The single source for the+// verb choice at both the task and stage level.+export function isRerunnableTaskStatus(status: Task_Status): boolean {+ return status === Task_Status.FAILED || status === Task_Status.CANCELED;+}++// Named in full so it isn't mistaken for stageHasRunningTasks.export function stageHasFailedOrCanceledTasks(stage: Stage): boolean {- return stage.tasks.some(- (task) =>- task.status === Task_Status.FAILED || task.status === Task_Status.CANCELED- );+ return stage.tasks.some((task) => isRerunnableTaskStatus(task.status));}export function stageHasRunningTasks(stage: Stage): boolean {diff --git a/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsx b/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsxindex c0450d511e..b1fab6eda3 100644--- a/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsx@@ -380,7 +380,6 @@ const makePageState = (isCreating: false,isInitializing: false,isEditing: false,- isRefreshing: false,isRunningChecks: false,setIsRunningChecks: vi.fn(),ready: true,@@ -392,8 +391,6 @@ const makePageState = (routeStageId: undefined,routeTaskId: undefined,selectedTaskName: undefined,- layoutMode: "NONE",- containerWidth: 0,pendingLeaveConfirm: false,planCheckRuns: [],taskRuns: [],@@ -404,7 +401,6 @@ const makePageState = (setEditing: vi.fn(),togglePhase: vi.fn(),expandPhase: vi.fn(),- closeTaskPanel: vi.fn(),resolveLeaveConfirm: vi.fn(),...overrides,}) as unknown as PlanDetailPageState;diff --git a/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailSpecValidation.ts b/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailSpecValidation.tsindex d78e98a0a0..28efaf62c4 100644--- a/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailSpecValidation.ts+++ b/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailSpecValidation.ts@@ -3,7 +3,18 @@ import { useAppStore } from "@/react/stores/app";import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";import { sheetNameOfSpec } from "@/utils/v1/issue/plan";import { extractSheetUID, getSheetStatement } from "@/utils/v1/sheet";-import { getLocalSheetByName } from "../utils/localSheet";+import {+ getLocalSheetByName,+ useLocalSheetsVersion,+} from "../utils/localSheet";++const sameStringSet = (a: Set<string>, b: Set<string>): boolean => {+ if (a.size !== b.size) return false;+ for (const value of b) {+ if (!a.has(value)) return false;+ }+ return true;+};const checkSpecStatement = async (spec: Plan_Spec): Promise<boolean> => {if (@@ -43,6 +54,10 @@ export function usePlanDetailSpecValidation(specs: Plan_Spec[]) {const [emptySpecIdSet, setEmptySpecIdSet] = useState<Set<string>>(() => new Set());+ // Draft statements live in mutable local sheets outside React state; this+ // version bumps on every local-sheet write so edits re-run the validation+ // (the `specs` identity alone doesn't change while typing on a draft plan).+ const localSheetsVersion = useLocalSheetsVersion();useEffect(() => {let canceled = false;@@ -57,7 +72,10 @@ export function usePlanDetailSpecValidation(specs: Plan_Spec[]) {}));if (!canceled) {- setEmptySpecIdSet(next);+ // Reuse the prior Set when membership is unchanged: this runs on every+ // keystroke (localSheetsVersion bumps per edit), and a fresh Set ref+ // each time would re-render the header for nothing.+ setEmptySpecIdSet((prev) => (sameStringSet(prev, next) ? prev : next));}};@@ -66,7 +84,7 @@ export function usePlanDetailSpecValidation(specs: Plan_Spec[]) {return () => {canceled = true;};- }, [specs]);+ }, [specs, localSheetsVersion]);return {emptySpecIdSet,diff --git a/frontend/src/react/pages/project/plan-detail/shell/constants.ts b/frontend/src/react/pages/project/plan-detail/shell/constants.tsindex 26ff31b1db..3be17acede 100644--- a/frontend/src/react/pages/project/plan-detail/shell/constants.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/constants.ts@@ -1,14 +1 @@-export const POLLER_INTERVAL = {- min: 1000,- max: 30000,- growth: 2,- jitter: 250,-} as const;-export const PROJECT_NAME_PREFIX = "projects/";--// Width below which the layout switches to mobile mode.-export const MOBILE_BREAKPOINT_PX = 780;-// Width at or above which the task detail panel renders inline as a-// side-by-side column instead of as a drawer.-export const INLINE_TASK_PANEL_BREAKPOINT_PX = 1024;diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.tsindex eceae8c999..fd9f1d36d4 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.ts@@ -1,4 +1,5 @@import { create } from "@bufbuild/protobuf";+import { createContextValues } from "@connectrpc/connect";import {issueServiceClientConnect,planServiceClientConnect,@@ -6,6 +7,7 @@ import {rolloutServiceClientConnect,userServiceClientConnect,} from "@/connect";+import { silentContextKey } from "@/connect/context-key";import {GetIssueRequestSchema,type Issue,@@ -45,6 +47,28 @@ export interface PlanDetailFetchPatch {taskRuns: TaskRun[];}+// The rollout and its task-run listing are fetched by both the full page+// snapshot and the slim status lane; only their error handling differs. Keep the+// request shape — schema, silent context, task-run parent glob — in one place.+// Fetched WITHOUT touching the store here; the caller (patchState) seeds the+// store cache after its staleness guard, so a stale in-flight poll can't+// overwrite the shared cache the log viewer reads.+const requestRollout = (rolloutName: string) =>+ rolloutServiceClientConnect.getRollout(+ create(GetRolloutRequestSchema, { name: rolloutName }),+ { contextValues: createContextValues().set(silentContextKey, true) }+ );++const requestRolloutTaskRuns = (rolloutName: string) =>+ rolloutServiceClientConnect+ .listTaskRuns(+ create(ListTaskRunsRequestSchema, {+ parent: `${rolloutName}/stages/-/tasks/-`,+ }),+ { contextValues: createContextValues().set(silentContextKey, true) }+ )+ .then((response) => response.taskRuns);+const convertRouteQuery = (query: Record<string, unknown>) => {const kv: Record<string, string> = {};for (const [key, value] of Object.entries(query)) {@@ -58,18 +82,43 @@ const convertRouteQuery = (query: Record<string, unknown>) => {export const fetchPlanSnapshot = async (projectId: string,planId: string,- routeQuery: Record<string, unknown> = {}+ routeQuery: Record<string, unknown> = {},+ // When true (background poll ticks), suppress the global CRITICAL error toast+ // on transient failures — the poll runs every few seconds, so a flaky backend+ // would otherwise spam toasts. The initial load stays loud (default) so a+ // first-load failure is visible; 404/403 are handled explicitly by the caller.+ silent = false): Promise<PlanDetailFetchPatch> => {+ const silentCtx = silent+ ? { contextValues: createContextValues().set(silentContextKey, true) }+ : undefined;+ // The plan fetch depends only on route ids, so it runs alongside the+ // project/user wave instead of being serialized behind it. The detached+ // no-op catch keeps a plan failure from surfacing as an unhandled rejection+ // when the first wave throws before the plan is awaited; the await below+ // still propagates the error.+ const planPromise =+ planId.toLowerCase() === "create"+ ? undefined+ : planServiceClientConnect.getPlan(+ create(GetPlanRequestSchema, {+ name: `${PROJECT_NAME_PREFIX}${projectId}/plans/${planId}`,+ }),+ silentCtx+ );+ planPromise?.catch(() => undefined);+const [project, currentUser] = await Promise.all([projectServiceClientConnect.getProject(create(GetProjectRequestSchema, {name: `${PROJECT_NAME_PREFIX}${projectId}`,- })+ }),+ silentCtx),- userServiceClientConnect.getCurrentUser({}),+ userServiceClientConnect.getCurrentUser({}, silentCtx),]);- if (planId.toLowerCase() === "create") {+ if (!planPromise) {const plan = await createPlanSkeleton(project,convertRouteQuery(routeQuery)@@ -92,49 +141,37 @@ export const fetchPlanSnapshot = async (};}- const plan = await planServiceClientConnect.getPlan(- create(GetPlanRequestSchema, {- name: `${PROJECT_NAME_PREFIX}${projectId}/plans/${planId}`,- })- );+ const plan = await planPromise;- const [issue, planCheckRuns, rollout] = await Promise.all([+ // The rollout name is derived from the plan name, so task runs can load in+ // parallel with the rollout instead of being serialized behind it.+ const rolloutName = plan.hasRollout ? getRolloutFromPlan(plan.name) : "";+ const [issue, planCheckRuns, rollout, taskRuns] = await Promise.all([plan.issue? issueServiceClientConnect- .getIssue(create(GetIssueRequestSchema, { name: plan.issue }))+ .getIssue(+ create(GetIssueRequestSchema, { name: plan.issue }),+ silentCtx+ ).catch(() => undefined): Promise.resolve(undefined),planServiceClientConnect.getPlanCheckRun(create(GetPlanCheckRunRequestSchema, {name: `${plan.name}/planCheckRun`,- })+ }),+ silentCtx).then((run) => [run] as PlanCheckRun[]).catch(() => []),- plan.hasRollout- ? rolloutServiceClientConnect- .getRollout(- create(GetRolloutRequestSchema, {- name: getRolloutFromPlan(plan.name),- })- )- .catch(() => undefined)+ rolloutName+ ? requestRollout(rolloutName).catch(() => undefined): Promise.resolve(undefined),+ rolloutName+ ? requestRolloutTaskRuns(rolloutName).catch(() => [])+ : Promise.resolve([] as TaskRun[]),]);- const taskRuns =- rollout !== undefined- ? await rolloutServiceClientConnect- .listTaskRuns(- create(ListTaskRunsRequestSchema, {- parent: `${rollout.name}/stages/-/tasks/-`,- })- )- .then((response) => response.taskRuns)- .catch(() => [])- : [];-return {currentUser,plan,diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/types.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/types.tsindex 26155ac33e..4d8f6ea6a8 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/types.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/types.ts@@ -7,7 +7,6 @@ import {} from "@/types/proto-es/v1/rollout_service_pb";import type { User } from "@/types/proto-es/v1/user_service_pb";import type { PlanDetailPhase } from "../../shared/stores/types";-import type { PlanDetailLayoutMode } from "./useLayoutMode";export type { PlanDetailPhase } from "../../shared/stores/types";@@ -35,24 +34,22 @@ export interface PlanDetailPageSnapshot {export interface PlanDetailPageState extends PlanDetailPageSnapshot {isEditing: boolean;- isRefreshing: boolean;isRunningChecks: boolean;setIsRunningChecks: (running: boolean) => void;activePhases: Set<PlanDetailPhase>;routeName?: string;routePhase?: string;routeStageId?: string;- routeTaskId?: string;selectedTaskName?: string;+ // The plan's task runs grouped by task name, newest first, with group+ // identities preserved across poll ticks that didn't touch the task.+ taskRunsByTaskName: Map<string, TaskRun[]>;pendingLeaveConfirm: boolean;- layoutMode: PlanDetailLayoutMode;- containerWidth: number;patchState: (patch: Partial<PlanDetailPageSnapshot>) => void;refreshState: () => Promise<void>;bypassLeaveGuardOnce: () => void;setEditing: (scope: string, editing: boolean) => void;togglePhase: (phase: PlanDetailPhase) => void;expandPhase: (phase: PlanDetailPhase) => void;- closeTaskPanel: () => void;resolveLeaveConfirm: (confirmed: boolean) => void;}diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useDerivedPlanState.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useDerivedPlanState.tsindex c86a320343..ec584075d9 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/useDerivedPlanState.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useDerivedPlanState.ts@@ -1,51 +1,46 @@-import { useMemo } from "react";+import { useMemo, useRef } from "react";+import { sortTaskRunsNewestFirst } from "@/react/lib/taskRun";+import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";+import { extractTaskNameFromTaskRunName } from "@/utils";import type {PlanDetailPageSnapshot,PlanDetailPageState,PlanDetailPhase,} from "./types";import type { useEditingScopes } from "./useEditingScopes";-import type { useLayoutMode } from "./useLayoutMode";import type { usePhaseState } from "./usePhaseState";type EditingScopes = ReturnType<typeof useEditingScopes>;-type Layout = ReturnType<typeof useLayoutMode>;type PhaseState = ReturnType<typeof usePhaseState>;export function useDerivedPlanState(params: {snapshot: PlanDetailPageSnapshot;isEditing: boolean;- isRefreshing: boolean;isRunningChecks: boolean;setIsRunningChecks: (running: boolean) => void;phase: PhaseState;editing: EditingScopes;- layout: Layout;routeName?: string;routePhase?: PlanDetailPhase;routeStageId?: string;routeTaskId?: string;patchState: (patch: Partial<PlanDetailPageSnapshot>) => void;refreshState: () => Promise<void>;- closeTaskPanel: () => void;resolveLeaveConfirm: (confirmed: boolean) => void;}): PlanDetailPageState {const {snapshot,isEditing,- isRefreshing,isRunningChecks,setIsRunningChecks,phase,editing,- layout,routeName,routePhase,routeStageId,routeTaskId,patchState,refreshState,- closeTaskPanel,resolveLeaveConfirm,} = params;@@ -64,36 +59,65 @@ export function useDerivedPlanState(params: {return undefined;}, [routeTaskId, snapshot.rollout]);+ // Group the plan's task runs by task once for all consumers (every+ // kept-alive stage list reads from this map), reusing a task's previous+ // group array when all its runs kept their references — the snapshot gate's+ // per-run sharing makes that the common case — so memoized cards see stable+ // taskRuns/latestTaskRun props across poll ticks that only touched other+ // tasks.+ const taskRunsByTaskNameRef = useRef<Map<string, TaskRun[]>>(new Map());+ const taskRunsByTaskName = useMemo(() => {+ const prevGroups = taskRunsByTaskNameRef.current;+ const grouped = new Map<string, TaskRun[]>();+ for (const run of snapshot.taskRuns) {+ const taskName = extractTaskNameFromTaskRunName(run.name);+ const group = grouped.get(taskName);+ if (group) {+ group.push(run);+ } else {+ grouped.set(taskName, [run]);+ }+ }+ for (const [taskName, runs] of grouped) {+ const sorted = sortTaskRunsNewestFirst(runs);+ const prevRuns = prevGroups.get(taskName);+ grouped.set(+ taskName,+ prevRuns &&+ prevRuns.length === sorted.length &&+ sorted.every((run, index) => run === prevRuns[index])+ ? prevRuns+ : sorted+ );+ }+ taskRunsByTaskNameRef.current = grouped;+ return grouped;+ }, [snapshot.taskRuns]);+return useMemo(() => ({...snapshot,isEditing,- isRefreshing,isRunningChecks,setIsRunningChecks,activePhases: phase.activePhases,routeName,routePhase,routeStageId,- routeTaskId,selectedTaskName,+ taskRunsByTaskName,pendingLeaveConfirm: editing.pendingLeaveConfirm,- layoutMode: layout.layoutMode,- containerWidth: layout.containerWidth,bypassLeaveGuardOnce: editing.bypassLeaveGuardOnce,patchState,refreshState,setEditing: editing.setEditing,togglePhase: phase.togglePhase,expandPhase: phase.expandPhase,- closeTaskPanel,resolveLeaveConfirm,}),[- closeTaskPanel,editing,isEditing,- isRefreshing,isRunningChecks,patchState,phase,@@ -102,10 +126,9 @@ export function useDerivedPlanState(params: {routeName,routePhase,routeStageId,- routeTaskId,- layout,selectedTaskName,snapshot,+ taskRunsByTaskName,]);}diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useEditingScopes.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useEditingScopes.tsindex 8edd99533e..d59e7ed248 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/useEditingScopes.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useEditingScopes.ts@@ -22,12 +22,26 @@ export function useEditingScopes() {[setEditing]);- return {- editingScopes,- isEditing,- setEditing: setScopeEditing,- bypassLeaveGuardOnce,- pendingLeaveConfirm,- setPendingLeaveConfirm,- };+ // Stable facade: every field is already reference-stable, so memoize the+ // wrapper too. This keeps the derived `page` context value stable across+ // renders (it depends on this object), so context consumers re-render only on+ // real changes instead of on every page-hook render.+ return useMemo(+ () => ({+ editingScopes,+ isEditing,+ setEditing: setScopeEditing,+ bypassLeaveGuardOnce,+ pendingLeaveConfirm,+ setPendingLeaveConfirm,+ }),+ [+ editingScopes,+ isEditing,+ setScopeEditing,+ bypassLeaveGuardOnce,+ pendingLeaveConfirm,+ setPendingLeaveConfirm,+ ]+ );}diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useLayoutMode.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useLayoutMode.tsdeleted file mode 100644index 87d0f23291..0000000000--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/useLayoutMode.ts+++ /dev/null@@ -1,40 +0,0 @@-import { useEffect, useState } from "react";-import { MOBILE_BREAKPOINT_PX } from "../constants";--export type PlanDetailLayoutMode = "NONE" | "DESKTOP" | "MOBILE";--export function useLayoutMode(pageHost: HTMLElement | null) {- const [layoutMode, setLayoutMode] = useState<PlanDetailLayoutMode>("NONE");- const [containerWidth, setContainerWidth] = useState(0);-- useEffect(() => {- if (!pageHost) {- setLayoutMode("NONE");- setContainerWidth(0);- return;- }-- const updateLayout = () => {- const width = pageHost.getBoundingClientRect().width;- const mode: PlanDetailLayoutMode =- width === 0- ? "NONE"- : width < MOBILE_BREAKPOINT_PX- ? "MOBILE"- : "DESKTOP";- setContainerWidth(width);- setLayoutMode(mode);- };-- updateLayout();- const observer = new ResizeObserver(() => updateLayout());- observer.observe(pageHost);-- return () => observer.disconnect();- }, [pageHost]);-- return {- layoutMode,- containerWidth,- };-}diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePhaseState.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePhaseState.tsindex b1de549ec3..a365353e2a 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePhaseState.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePhaseState.ts@@ -1,4 +1,4 @@-import { useCallback } from "react";+import { useCallback, useMemo } from "react";import type { PlanDetailPhase } from "../../shared/stores/types";import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";@@ -13,11 +13,16 @@ export function usePhaseState() {[activePhases]);- return {- activePhases,- isActive,- setActivePhases,- togglePhase,- expandPhase,- };+ // Stable facade (see useEditingScopes): memoize so the derived `page` context+ // value stays reference-stable and consumers don't re-render every render.+ return useMemo(+ () => ({+ activePhases,+ isActive,+ setActivePhases,+ togglePhase,+ expandPhase,+ }),+ [activePhases, isActive, setActivePhases, togglePhase, expandPhase]+ );}diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsxindex 89895c25fb..b66ad10a81 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx@@ -1,7 +1,16 @@+import { create } from "@bufbuild/protobuf";import { renderHook, waitFor } from "@testing-library/react";import { act, type ReactNode } from "react";import { beforeEach, describe, expect, test, vi } from "vitest";import { State } from "@/types/proto-es/v1/common_pb";+import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";+import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";+import {+ RolloutSchema,+ Task_Status,+ TaskRunSchema,+} from "@/types/proto-es/v1/rollout_service_pb";+import { UserSchema } from "@/types/proto-es/v1/user_service_pb";import type { PlanDetailPageSnapshot } from "./types";const mocks = vi.hoisted(() => ({@@ -26,6 +35,8 @@ vi.mock("@/react/router", async (importOriginal) => ({}));vi.mock("@/utils", () => ({+ extractTaskNameFromTaskRunName: (taskRunName: string) =>+ taskRunName.split("/taskRuns/")[0],getIssueRoute: mocks.getIssueRoute,isDev: () => true,minmax: (value: number, min: number, max: number) =>@@ -95,7 +106,6 @@ describe("usePlanDetailPage", () => {projectId: "foo",planId: "create",routeName: "workspace.project.plan.detail.specs",- pageHost: null,}),{ wrapper });@@ -118,7 +128,6 @@ describe("usePlanDetailPage", () => {projectId: "foo",planId: "plan-1",routeQuery: { phase: "deploy" },- pageHost: null,}),{ wrapper });@@ -141,7 +150,6 @@ describe("usePlanDetailPage", () => {projectId: "foo",planId,routeQuery: { phase: "deploy" },- pageHost: null,}),{initialProps: { planId: "plan-1" },@@ -179,7 +187,6 @@ describe("usePlanDetailPage", () => {usePlanDetailPage({projectId: "foo",planId: "plan-1",- pageHost: null,}),{ wrapper });@@ -206,7 +213,6 @@ describe("usePlanDetailPage", () => {projectId: "foo",planId: "plan-1",routeName: "workspace.project.plan.detail.specs",- pageHost: null,}),{ wrapper });@@ -234,7 +240,6 @@ describe("usePlanDetailPage", () => {projectId: "foo",planId: "plan-1",routeName: "workspace.project.plan.detail.specs",- pageHost: null,}),{ wrapper });@@ -266,7 +271,6 @@ describe("usePlanDetailPage", () => {planId: "plan-1",routeName: "workspace.project.plan.detail.spec.detail",specId: "spec-1",- pageHost: null,}),{ wrapper });@@ -293,7 +297,6 @@ describe("usePlanDetailPage", () => {const page = usePlanDetailPage({projectId: "foo",planId: "plan-1",- pageHost: null,});if (page.ready) {readyRenders.push(new Set(page.activePhases));@@ -326,7 +329,6 @@ describe("usePlanDetailPage", () => {const page = usePlanDetailPage({projectId: "foo",planId: "plan-1",- pageHost: null,});if (page.ready) {readyRenders.push(new Set(page.activePhases));@@ -350,7 +352,6 @@ describe("usePlanDetailPage", () => {planId: "plan-1",routeName: "workspace.project.plan.detail.spec.detail",specId,- pageHost: null,}),{initialProps: { specId: "spec-1" },@@ -380,7 +381,6 @@ describe("usePlanDetailPage", () => {planId,routeName: "workspace.project.plan.detail.spec.detail",specId: "spec-1",- pageHost: null,}),{initialProps: { planId: "plan-1" },@@ -414,7 +414,6 @@ describe("usePlanDetailPage", () => {usePlanDetailPage({projectId: "foo",planId: "plan-1",- pageHost: null,}),{ wrapper });@@ -437,4 +436,352 @@ describe("usePlanDetailPage", () => {expect(result.current.activePhases.has("review")).toBe(false);expect(result.current.activePhases.has("changes")).toBe(true);});++ test("a poll returning identical content keeps the page state identity", async () => {+ // Real proto messages (not cast plain objects): the identity gate only+ // structurally compares actual messages.+ const buildProtoPatch = (): Partial<PlanDetailPageSnapshot> => ({+ projectId: "foo",+ planId: "plan-1",+ pageKey: "foo/plan-1",+ projectTitle: "Foo",+ projectRequireIssueApproval: false,+ projectRequirePlanCheckNoError: false,+ projectCanCreateRollout: true,+ currentUser: create(UserSchema, { name: "users/[email protected]" }),+ project: create(ProjectSchema, { name: "projects/foo", title: "Foo" }),+ isCreating: false,+ readonly: false,+ plan: create(PlanSchema, {+ name: "projects/foo/plans/plan-1",+ state: State.ACTIVE,+ specs: [{ id: "spec-1" }],+ }),+ issue: undefined,+ rollout: undefined,+ planCheckRuns: [],+ taskRuns: [],+ });+ mocks.fetchPlanSnapshot.mockImplementation(async () => buildProtoPatch());++ const { result } = renderHook(+ () =>+ usePlanDetailPage({+ projectId: "foo",+ planId: "plan-1",+ }),+ { wrapper }+ );+ await waitFor(() => expect(result.current.ready).toBe(true));++ // A quiet poll: fresh objects from the wire, identical content. The+ // snapshot (and thus the whole page object) must keep its identity so+ // nothing under the provider re-renders.+ const before = result.current;+ await act(async () => {+ await result.current.refreshState();+ });+ expect(mocks.fetchPlanSnapshot.mock.calls.length).toBeGreaterThanOrEqual(2);+ expect(result.current).toBe(before);++ // A real change (plan title) produces a new snapshot, but slices that+ // didn't change keep their references.+ mocks.fetchPlanSnapshot.mockImplementation(async () => ({+ ...buildProtoPatch(),+ plan: create(PlanSchema, {+ name: "projects/foo/plans/plan-1",+ title: "renamed",+ state: State.ACTIVE,+ specs: [{ id: "spec-1" }],+ }),+ }));+ await act(async () => {+ await result.current.refreshState();+ });+ expect(result.current).not.toBe(before);+ expect(result.current.plan.title).toBe("renamed");+ expect(result.current.currentUser).toBe(before.currentUser);+ expect(result.current.project).toBe(before.project);+ });++ test("a poll changing one task preserves sibling stage/task/run identities", async () => {+ const stage1 = "projects/foo/rollouts/1/stages/s1";+ const stage2 = "projects/foo/rollouts/1/stages/s2";+ const buildPatch = (+ t2Status: Task_Status,+ runDetail: string+ ): Partial<PlanDetailPageSnapshot> => ({+ ...buildSnapshotPatch({ planId: "plan-1" }),+ rollout: create(RolloutSchema, {+ name: "projects/foo/rollouts/1",+ stages: [+ {+ name: stage1,+ tasks: [+ { name: `${stage1}/tasks/t1`, status: Task_Status.DONE },+ { name: `${stage1}/tasks/t2`, status: t2Status },+ ],+ },+ {+ name: stage2,+ tasks: [+ { name: `${stage2}/tasks/t3`, status: Task_Status.NOT_STARTED },+ ],+ },+ ],+ }),+ taskRuns: [+ create(TaskRunSchema, {+ name: `${stage1}/tasks/t2/taskRuns/r2`,+ detail: runDetail,+ }),+ create(TaskRunSchema, {+ name: `${stage1}/tasks/t1/taskRuns/r1`,+ detail: "finished",+ }),+ ],+ });+ mocks.fetchPlanSnapshot.mockImplementation(async () =>+ buildPatch(Task_Status.RUNNING, "executing step 1")+ );++ const { result } = renderHook(+ () =>+ usePlanDetailPage({+ projectId: "foo",+ planId: "plan-1",+ }),+ { wrapper }+ );+ await waitFor(() => expect(result.current.ready).toBe(true));+ const before = result.current;++ // A poll tick where only task t2 (and its run) changed.+ mocks.fetchPlanSnapshot.mockImplementation(async () =>+ buildPatch(Task_Status.DONE, "executing step 2")+ );+ await act(async () => {+ await result.current.refreshState();+ });+ const after = result.current;++ // The rollout shell and the changed stage/task get new references…+ expect(after.rollout).not.toBe(before.rollout);+ expect(after.rollout?.stages[0]).not.toBe(before.rollout?.stages[0]);+ expect(after.rollout?.stages[0].tasks[1]).not.toBe(+ before.rollout?.stages[0].tasks[1]+ );+ // …while every untouched sibling keeps its previous reference, so+ // memoized cards skip re-rendering.+ expect(after.rollout?.stages[1]).toBe(before.rollout?.stages[1]);+ expect(after.rollout?.stages[0].tasks[0]).toBe(+ before.rollout?.stages[0].tasks[0]+ );+ expect(after.taskRuns).not.toBe(before.taskRuns);+ expect(after.taskRuns[0]).not.toBe(before.taskRuns[0]);+ expect(after.taskRuns[1]).toBe(before.taskRuns[1]);+ });++ const rolloutWithTask = (status: Task_Status) =>+ create(RolloutSchema, {+ name: "projects/foo/rollouts/1",+ stages: [+ {+ name: "projects/foo/rollouts/1/stages/s1",+ tasks: [+ {+ name: "projects/foo/rollouts/1/stages/s1/tasks/t1",+ status,+ },+ ],+ },+ ],+ });++ test("polls the full snapshot on the active cadence while a task transitions", async () => {+ vi.useFakeTimers();+ try {+ mocks.fetchPlanSnapshot.mockResolvedValue({+ ...buildSnapshotPatch({ planId: "plan-1" }),+ rollout: rolloutWithTask(Task_Status.RUNNING),+ });++ const { result } = renderHook(+ () => usePlanDetailPage({ projectId: "foo", planId: "plan-1" }),+ { wrapper }+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(result.current.ready).toBe(true);+ mocks.fetchPlanSnapshot.mockClear();++ // A RUNNING task → the poll re-fetches the full snapshot every ~1s.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });++ test("uses the idle cadence when no task is transitioning", async () => {+ vi.useFakeTimers();+ try {+ mocks.fetchPlanSnapshot.mockResolvedValue({+ ...buildSnapshotPatch({ planId: "plan-1" }),+ rollout: rolloutWithTask(Task_Status.NOT_STARTED),+ });++ const { result } = renderHook(+ () => usePlanDetailPage({ projectId: "foo", planId: "plan-1" }),+ { wrapper }+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(result.current.ready).toBe(true);+ mocks.fetchPlanSnapshot.mockClear();++ // No active task → the fast (1s) cadence must not fire; the idle (15s) one+ // eventually does.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000);+ });+ expect(mocks.fetchPlanSnapshot).not.toHaveBeenCalled();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(14000);+ });+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ test("a stale poll from the previous plan cannot overwrite the new plan", async () => {+ vi.useFakeTimers();+ try {+ const patchFor = (+ planId: string,+ title: string,+ status: Task_Status+ ) => ({+ ...buildSnapshotPatch({ planId }),+ projectTitle: title,+ rollout: rolloutWithTask(status),+ });+ mocks.fetchPlanSnapshot.mockImplementation(+ async (_projectId: string, planId: string) =>+ planId === "plan-a"+ ? patchFor("plan-a", "A", Task_Status.RUNNING)+ : patchFor("plan-b", "B", Task_Status.NOT_STARTED)+ );++ const { result, rerender } = renderHook(+ ({ planId }: { planId: string }) =>+ usePlanDetailPage({ projectId: "foo", planId }),+ { initialProps: { planId: "plan-a" }, wrapper }+ );+ // Initial plan-A load: its RUNNING task arms the 1s active cadence.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(result.current.projectTitle).toBe("A");++ // Hold the next fetch — the first plan-A poll tick — in flight.+ let releaseStalePoll: () => void = () => {};+ mocks.fetchPlanSnapshot.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ releaseStalePoll = () =>+ resolve(patchFor("plan-a", "A-late", Task_Status.RUNNING));+ })+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });++ // Navigate to plan B; the page is not remounted, so the plan-A poll stays+ // in flight. B's initial load resolves and wins.+ rerender({ planId: "plan-b" });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(result.current.projectTitle).toBe("B");++ // The held plan-A poll resolves late — the page-identity guard must drop+ // it so it can't merge plan A's data onto plan B's snapshot.+ await act(async () => {+ releaseStalePoll();+ await Promise.resolve();+ });+ expect(result.current.projectTitle).toBe("B");+ expect(result.current.planId).toBe("plan-b");+ } finally {+ vi.useRealTimers();+ }+ });++ test("a stale in-flight fetch cannot overwrite a newer refresh", async () => {+ const { result } = renderHook(+ () =>+ usePlanDetailPage({+ projectId: "foo",+ planId: "plan-1",+ }),+ { wrapper }+ );+ await waitFor(() => expect(result.current.ready).toBe(true));++ // A poll tick's fetch is in flight when a user action (e.g. task rerun)+ // triggers an immediate refresh. The older fetch carries pre-action data+ // and resolves late — it must be dropped, not applied over the newer one.+ let resolveStale: (patch: Partial<PlanDetailPageSnapshot>) => void = () =>+ undefined;+ let resolveFresh: (patch: Partial<PlanDetailPageSnapshot>) => void = () =>+ undefined;+ mocks.fetchPlanSnapshot+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveStale = resolve;+ })+ )+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFresh = resolve;+ })+ );++ let stalePending: Promise<void> = Promise.resolve();+ let freshPending: Promise<void> = Promise.resolve();+ act(() => {+ stalePending = result.current.refreshState();+ freshPending = result.current.refreshState();+ });++ await act(async () => {+ resolveFresh({+ ...buildSnapshotPatch({ planId: "plan-1" }),+ projectTitle: "fresh",+ });+ await freshPending;+ });+ expect(result.current.projectTitle).toBe("fresh");++ await act(async () => {+ resolveStale({+ ...buildSnapshotPatch({ planId: "plan-1" }),+ projectTitle: "stale",+ });+ await stalePending;+ });+ expect(result.current.projectTitle).toBe("fresh");+ });});diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.tsindex a35c275416..feed96dc27 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts@@ -7,19 +7,35 @@ import {useState,} from "react";import { useTranslation } from "react-i18next";-import { router } from "@/react/router";+import { usePolling } from "@/react/hooks/usePolling";+import {+ preserveTaskRunIdentities,+ sameMessage,+ sameMessageList,+} from "@/react/lib/protoIdentity";import {PLAN_DETAIL_PHASE_CHANGES,PLAN_DETAIL_PHASE_DEPLOY,PLAN_DETAIL_PHASE_REVIEW,} from "@/react/router/handles";+import { useAppStore } from "@/react/stores/app";import { State } from "@/types/proto-es/v1/common_pb";-import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";+import { IssueSchema, IssueStatus } from "@/types/proto-es/v1/issue_service_pb";+import {+ PlanCheckRunSchema,+ PlanSchema,+} from "@/types/proto-es/v1/plan_service_pb";+import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";+import {+ RolloutSchema,+ Task_Status,+} from "@/types/proto-es/v1/rollout_service_pb";+import { UserSchema } from "@/types/proto-es/v1/user_service_pb";import { unknownPlan } from "@/types/v1/issue/plan";import { unknownProject } from "@/types/v1/project";import { unknownUser } from "@/types/v1/user";import { setDocumentTitle } from "@/utils";+import { isTaskActivelyTransitioning } from "@/utils/v1/issue/rollout";import type { PlanDetailPhase } from "../../shared/stores/types";import { usePlanDetailStoreApi } from "../../shared/stores/usePlanDetailStore";import { fetchPlanSnapshot } from "./fetchPlanSnapshot";@@ -27,13 +43,17 @@ import type { PlanDetailPageSnapshot, PlanDetailPageState } from "./types";import { useDerivedPlanState } from "./useDerivedPlanState";import { useEditingScopes } from "./useEditingScopes";import { useInitialFetch } from "./useInitialFetch";-import { useLayoutMode } from "./useLayoutMode";import { useLeaveGuard } from "./useLeaveGuard";import { usePhaseState } from "./usePhaseState";-import { usePolling } from "./usePolling";import { useRedirects } from "./useRedirects";import { useRouteSelection } from "./useRouteSelection";+// Poll cadence: fast while a task is transitioning (PENDING/RUNNING) so a status+// change surfaces within ~1s; idle otherwise, just to catch externally-created+// rollouts/tasks and a scheduled task starting, without hammering the server.+const ACTIVE_POLL_INTERVAL_MS = 1000;+const IDLE_POLL_INTERVAL_MS = 15000;+const buildDefaultSnapshot = (projectId: string,planId: string@@ -71,6 +91,47 @@ const applyDerivedState = (};};+// Structural sharing across snapshot updates: every poll tick rebuilds all+// objects from the wire, but a slice whose content is unchanged keeps its+// previous reference here, and a fully-unchanged snapshot returns `prev`+// itself so the caller can skip the state update entirely. This is what makes+// a quiet poll tick render nothing — object identity is the contract every+// downstream memo, effect dep, and prop comparison keys off.+const preserveSnapshotIdentities = (+ prev: PlanDetailPageSnapshot,+ next: PlanDetailPageSnapshot+): PlanDetailPageSnapshot => {+ const out = { ...next };+ if (sameMessage(UserSchema, prev.currentUser, next.currentUser)) {+ out.currentUser = prev.currentUser;+ }+ if (sameMessage(ProjectSchema, prev.project, next.project)) {+ out.project = prev.project;+ }+ if (sameMessage(PlanSchema, prev.plan, next.plan)) {+ out.plan = prev.plan;+ }+ if (sameMessage(IssueSchema, prev.issue, next.issue)) {+ out.issue = prev.issue;+ }+ // The rollout store already deep-preserves per-stage/per-task identity and+ // hands patchState the merged instance, so here a plain reference/structural+ // guard is enough — keeping the snapshot's rollout identical to the store's.+ if (sameMessage(RolloutSchema, prev.rollout, next.rollout)) {+ out.rollout = prev.rollout;+ }+ if (+ sameMessageList(PlanCheckRunSchema, prev.planCheckRuns, next.planCheckRuns)+ ) {+ out.planCheckRuns = prev.planCheckRuns;+ }+ out.taskRuns = preserveTaskRunIdentities(prev.taskRuns, next.taskRuns);+ const changed = (Object.keys(out) as (keyof PlanDetailPageSnapshot)[]).some(+ (key) => out[key] !== prev[key]+ );+ return changed ? out : prev;+};+const getDefaultActivePhases = (phase: PlanDetailPhase): PlanDetailPhase[] => {if (phase === PLAN_DETAIL_PHASE_REVIEW) {return [PLAN_DETAIL_PHASE_CHANGES, PLAN_DETAIL_PHASE_REVIEW];@@ -116,14 +177,12 @@ export const usePlanDetailPage = ({routeName,routeQuery = {},specId,- pageHost,}: {projectId: string;planId: string;routeName?: string;routeQuery?: Record<string, unknown>;specId?: string;- pageHost: HTMLDivElement | null;}): PlanDetailPageState => {const { t } = useTranslation();const [snapshot, setSnapshot] = useState<PlanDetailPageSnapshot>(() =>@@ -132,8 +191,6 @@ export const usePlanDetailPage = ({const phase = usePhaseState();const editing = useEditingScopes();const storeApi = usePlanDetailStoreApi();- const layout = useLayoutMode(pageHost);- const [isRefreshing, setIsRefreshing] = useState(false);const [isRunningChecks, setIsRunningChecks] = useState(false);const latestSnapshotRef = useRef(snapshot);const { resolveLeaveConfirm } = useLeaveGuard();@@ -188,41 +245,65 @@ export const usePlanDetailPage = ({const patchState = useCallback((patch: Partial<PlanDetailPageSnapshot>) => {- const nextSnapshot = applyDerivedState({- ...latestSnapshotRef.current,- ...patch,- });+ const prevSnapshot = latestSnapshotRef.current;+ // Seed the shared rollout store from this (already staleness-guarded)+ // patch, and adopt the store's identity-preserved instance so the deploy+ // view and the log viewer read the exact same rollout object.+ if (patch.rollout) {+ patch = {+ ...patch,+ rollout: useAppStore.getState().upsertRollout(patch.rollout),+ };+ }+ const nextSnapshot = preserveSnapshotIdentities(+ prevSnapshot,+ applyDerivedState({+ ...prevSnapshot,+ ...patch,+ })+ );syncDefaultActivePhases(nextSnapshot);+ if (nextSnapshot === prevSnapshot) {+ // Content-identical (the common quiet poll tick) — no state update,+ // so nothing under the provider re-renders.+ return;+ }latestSnapshotRef.current = nextSnapshot;setSnapshot(nextSnapshot);},[syncDefaultActivePhases]);+ // Monotonic fetch sequence: a fetch already in flight when a newer one started+ // (a poll tick overlapping a user-action refresh) carries older data and must+ // not overwrite the fresher snapshot when it resolves late.+ const fetchSeqRef = useRef(0);const fetchState = useCallback(async () => {- try {- setIsRefreshing(true);- const current = latestSnapshotRef.current;- const patch = await fetchPlanSnapshot(- current.projectId,- current.planId,- routeQueryRef.current- );- patchState(patch);- } finally {- setIsRefreshing(false);+ const current = latestSnapshotRef.current;+ fetchSeqRef.current += 1;+ const seq = fetchSeqRef.current;+ const patch = await fetchPlanSnapshot(+ current.projectId,+ current.planId,+ routeQueryRef.current,+ // Background poll / post-action refresh: stay silent so a transient+ // failure doesn't spam the global toast (the initial load is loud).+ true+ );+ // The page isn't remounted on plan->plan navigation, so a poll started for+ // the previous plan can still be in flight after the switch. The seq guard+ // doesn't bump on navigation, so also drop the patch when the page identity+ // has changed — otherwise the old plan's data would merge onto the new+ // plan's snapshot (wrong data under a correct URL, until the next poll).+ if (+ seq !== fetchSeqRef.current ||+ latestSnapshotRef.current.pageKey !== current.pageKey+ ) {+ return;}+ patchState(patch);}, [patchState]);- const closeTaskPanel = useCallback(() => {- void router.replace({- query: {- ...(routePhase ? { phase: routePhase } : {}),- ...(routeStageId ? { stageId: routeStageId } : {}),- },- });- }, [routePhase, routeStageId]);-useInitialFetch({projectId,planId,@@ -263,51 +344,66 @@ export const usePlanDetailPage = ({syncDefaultActivePhases,]);- const isPlanDone = useMemo(() => {+ const { isPlanDone, hasActiveTasks } = useMemo(() => {if (!snapshot.rollout) {- return false;+ return { isPlanDone: false, hasActiveTasks: false };}- const allTasks = snapshot.rollout.stages.flatMap((stage) => stage.tasks);- return (- allTasks.length > 0 &&- allTasks.every(- (task) =>- task.status === Task_Status.DONE ||- task.status === Task_Status.SKIPPED- )- );+ const nowMs = Date.now();+ let taskCount = 0;+ let allSettled = true;+ let hasActiveTasks = false;+ for (const stage of snapshot.rollout.stages) {+ for (const task of stage.tasks) {+ taskCount++;+ if (+ task.status !== Task_Status.DONE &&+ task.status !== Task_Status.SKIPPED+ ) {+ allSettled = false;+ }+ // Poll fast for a task actually transitioning (RUNNING, or a PENDING+ // task due to run now); a task scheduled for a future maintenance window+ // stays on the idle cadence rather than polling every second while it+ // waits — the idle poll still catches it once the backend starts it.+ if (isTaskActivelyTransitioning(task, nowMs)) {+ hasActiveTasks = true;+ }+ }+ }+ return { isPlanDone: taskCount > 0 && allSettled, hasActiveTasks };}, [snapshot.rollout]);- const { restart: restartPolling } = usePolling({- enabled: snapshot.ready && !snapshot.isCreating && !isPlanDone,- refreshState: fetchState,- });+ // Poll the whole snapshot on a fixed cadence: fast while a task is+ // transitioning so PENDING -> RUNNING -> DONE surfaces promptly, idle+ // otherwise (a failed task awaiting rerun, a scheduled task, an unstarted+ // rollout) to catch changes without hammering the server. Stops once every+ // task is terminal. usePolling pauses on a hidden tab and never overlaps a+ // slow fetch. A user action's immediate fetch (refreshState) surfaces the+ // result at once, and the cadence tightens as soon as that status is active.+ usePolling(+ snapshot.ready && !snapshot.isCreating && !isPlanDone,+ hasActiveTasks ? ACTIVE_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS,+ fetchState+ );// Public refresh used by user actions (run/skip/cancel a task, edits, etc.).- // It fetches immediately and then resets the poll backoff so the follow-up- // status transition (e.g. a task moving PENDING -> RUNNING) is observed on- // the next ~1s tick instead of waiting out the current backoff interval.const refreshState = useCallback(async () => {await fetchState();- restartPolling();- }, [fetchState, restartPolling]);+ }, [fetchState]);return useDerivedPlanState({snapshot,isEditing,- isRefreshing,isRunningChecks,setIsRunningChecks,phase,editing,- layout,routeName,routePhase,routeStageId,routeTaskId,patchState,refreshState,- closeTaskPanel,resolveLeaveConfirm,});};diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePolling.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePolling.tsdeleted file mode 100644index 4ca430951f..0000000000--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePolling.ts+++ /dev/null@@ -1,88 +0,0 @@-import { useCallback, useEffect, useRef } from "react";-import { minmax } from "@/utils";-import { POLLER_INTERVAL } from "../constants";--export interface UsePollingParams {- enabled: boolean;- refreshState: () => Promise<void>;-}--export interface UsePollingResult {- // Reset the backoff and poll again from the minimum interval. Call this- // after a user-triggered mutation (run/skip/cancel a task, etc.) so the UI- // watches closely for the resulting status transition instead of waiting out- // the current (possibly maxed-out) backoff interval.- restart: () => void;-}--export function usePolling({- enabled,- refreshState,-}: UsePollingParams): UsePollingResult {- const pollTimerRef = useRef<number | undefined>(undefined);- // `active` mirrors the effect's mounted+enabled lifetime so a late-resolving- // refreshState (or a `restart` racing an unmount) cannot schedule a new poll.- const activeRef = useRef(false);- const refreshStateRef = useRef(refreshState);- refreshStateRef.current = refreshState;-- const stopPolling = useCallback(() => {- if (!pollTimerRef.current) {- return;- }- window.clearTimeout(pollTimerRef.current);- pollTimerRef.current = undefined;- }, []);-- const scheduleNext = useCallback(- (interval: number) => {- stopPolling();- const nextInterval = minmax(- interval +- Math.floor(Math.random() * (POLLER_INTERVAL.jitter * 2 + 1)) -- POLLER_INTERVAL.jitter,- POLLER_INTERVAL.min,- POLLER_INTERVAL.max- );-- pollTimerRef.current = window.setTimeout(async () => {- if (!activeRef.current) {- return;- }- await refreshStateRef.current().catch(() => undefined);- if (!activeRef.current) {- return;- }- scheduleNext(- Math.min(nextInterval * POLLER_INTERVAL.growth, POLLER_INTERVAL.max)- );- }, nextInterval);- },- [stopPolling]- );-- const restart = useCallback(() => {- if (!activeRef.current) {- return;- }- scheduleNext(POLLER_INTERVAL.min);- }, [scheduleNext]);-- useEffect(() => {- if (!enabled) {- activeRef.current = false;- stopPolling();- return;- }-- activeRef.current = true;- scheduleNext(POLLER_INTERVAL.min);-- return () => {- activeRef.current = false;- stopPolling();- };- }, [enabled, scheduleNext, stopPolling]);-- return { restart };-}diff --git a/frontend/src/react/pages/project/plan-detail/utils/createPlan.ts b/frontend/src/react/pages/project/plan-detail/utils/createPlan.tsindex 37bce14f67..cff7eefd19 100644--- a/frontend/src/react/pages/project/plan-detail/utils/createPlan.ts+++ b/frontend/src/react/pages/project/plan-detail/utils/createPlan.ts@@ -9,8 +9,12 @@ import {PlanSchema,} from "@/types/proto-es/v1/plan_service_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";-import { extractSheetUID, setSheetStatement } from "@/utils";-import { getLocalSheetByName, getNextLocalSheetUID } from "./localSheet";+import { extractSheetUID } from "@/utils";+import {+ getLocalSheetByName,+ getNextLocalSheetUID,+ setLocalSheetStatement,+} from "./localSheet";type PlanTemplate = "bb.plan.change-database";@@ -62,7 +66,7 @@ const maybeSetInitialSQLForSpec = (spec: Plan_Spec, initialSQL: InitialSQL) => {if (!sql) {return;}- setSheetStatement(getLocalSheetByName(sheet), sql);+ setLocalSheetStatement(getLocalSheetByName(sheet), sql);};const extractInitialSQLFromQuery = async (@@ -109,7 +113,10 @@ export const createPlanSkeleton = async ();}- const databaseNameList = (query.databaseList ?? "").split(",");+ const databaseList = query.databaseList ?? "";+ // Guard the empty case: "".split(",") yields [""], which would create a spec+ // with a single empty-string target.+ const databaseNameList = databaseList ? databaseList.split(",") : [];const targets = query.databaseGroupName? [query.databaseGroupName]: databaseNameList;diff --git a/frontend/src/react/pages/project/plan-detail/utils/localSheet.test.ts b/frontend/src/react/pages/project/plan-detail/utils/localSheet.test.tsnew file mode 100644index 0000000000..15eb99d06c--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/utils/localSheet.test.ts@@ -0,0 +1,34 @@+import { act, renderHook } from "@testing-library/react";+import { describe, expect, test, vi } from "vitest";+import {+ getLocalSheetByName,+ getLocalSheetsVersion,+ setLocalSheetStatement,+ subscribeLocalSheets,+ useLocalSheetsVersion,+} from "./localSheet";++describe("localSheet subscription", () => {+ test("setLocalSheetStatement bumps the version and notifies subscribers", () => {+ const before = getLocalSheetsVersion();+ const listener = vi.fn();+ const unsubscribe = subscribeLocalSheets(listener);++ setLocalSheetStatement(getLocalSheetByName("local/1"), "select 1");+ expect(getLocalSheetsVersion()).toBe(before + 1);+ expect(listener).toHaveBeenCalledTimes(1);++ unsubscribe();+ setLocalSheetStatement(getLocalSheetByName("local/1"), "select 2");+ // No longer notified after unsubscribe.+ expect(listener).toHaveBeenCalledTimes(1);+ });++ test("useLocalSheetsVersion re-renders a consumer on a local sheet edit", () => {+ const { result } = renderHook(() => useLocalSheetsVersion());+ const before = result.current;++ act(() => setLocalSheetStatement(getLocalSheetByName("local/2"), "x"));+ expect(result.current).toBe(before + 1);+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts b/frontend/src/react/pages/project/plan-detail/utils/localSheet.tsindex cea6b28ba8..539d560d43 100644--- a/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts+++ b/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts@@ -1,7 +1,9 @@import { create } from "@bufbuild/protobuf";+import { useSyncExternalStore } from "react";import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";import { SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";+import { extractSheetUID, setSheetStatement } from "@/utils/v1/sheet";const state = {uid: -101,@@ -9,6 +11,44 @@ const state = {const localSheetsByName = new Map<string, Sheet>();+// Local sheets live outside React state, so edits need an explicit external-+// store signal (consumed via useSyncExternalStore). Nothing re-runs "for free"+// anymore: snapshot updates preserve identity when content is unchanged, so a+// hidden dependency on this map must subscribe here instead of riding on+// unrelated re-renders.+let localSheetsVersion = 0;+const localSheetListeners = new Set<() => void>();++export const subscribeLocalSheets = (listener: () => void): (() => void) => {+ localSheetListeners.add(listener);+ return () => {+ localSheetListeners.delete(listener);+ };+};++export const getLocalSheetsVersion = (): number => localSheetsVersion;++// Subscribe a component to local-sheet edits. Any consumer that reads local+// sheet content during render (getSpecStatementContent) must call this, or it+// won't re-render when the statement is edited — the identity-preserving+// snapshot no longer re-renders the tree "for free" on a content-identical edit.+// Include the returned version in the deps of any memo that reads that content.+export const useLocalSheetsVersion = (): number =>+ useSyncExternalStore(subscribeLocalSheets, getLocalSheetsVersion);++// Write a local sheet's statement and notify subscribers (e.g. the+// empty-statement validation behind the create button).+export const setLocalSheetStatement = (+ sheet: Sheet,+ statement: string+): void => {+ setSheetStatement(sheet, statement);+ localSheetsVersion += 1;+ for (const listener of localSheetListeners) {+ listener();+ }+};+export const createEmptyLocalSheet = () => {return create(SheetSchema, {});};@@ -43,7 +83,14 @@ export const getSpecStatementContent = (spec: Plan_Spec): Uint8Array | undefined => {if (spec.config.case !== "changeDatabaseConfig") return undefined;- return getLocalSheetByName(spec.config.value.sheet).content;+ const sheetName = spec.config.value.sheet;+ // Only local (unsaved) sheets keep their content here; guard the UID so a+ // persisted sheet name doesn't mint a phantom empty local sheet and return+ // misleading empty bytes (same local/remote split as checkSpecStatement).+ if (!sheetName || !extractSheetUID(sheetName).startsWith("-")) {+ return undefined;+ }+ return getLocalSheetByName(sheetName).content;};// Byte-equality for statement content. The reference check is the O(1) fastdiff --git a/frontend/src/react/stores/app/rollout.ts b/frontend/src/react/stores/app/rollout.tsindex b580261635..bd88d4af85 100644--- a/frontend/src/react/stores/app/rollout.ts+++ b/frontend/src/react/stores/app/rollout.ts@@ -2,6 +2,7 @@ import { create as createProto } from "@bufbuild/protobuf";import { createContextValues } from "@connectrpc/connect";import { rolloutServiceClientConnect } from "@/connect";import { silentContextKey } from "@/connect/context-key";+import { preserveRolloutIdentities } from "@/react/lib/protoIdentity";import { GetRolloutRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";import { unknownRollout as createUnknownRollout } from "@/types/rollout";import type { AppSliceCreator, RolloutSlice } from "./types";@@ -17,10 +18,26 @@ export const createRolloutSlice: AppSliceCreator<RolloutSlice> = (set, get) => {createProto(GetRolloutRequestSchema, { name }),{ contextValues: createContextValues().set(silentContextKey, silent) });- set((state) => ({- rolloutsByName: { ...state.rolloutsByName, [rollout.name]: rollout },- }));- return rollout;+ return get().upsertRollout(rollout);+ },++ // Seed/refresh the cache with a rollout fetched elsewhere (e.g. the+ // plan-detail poller), so cache-first consumers like the task-run log+ // viewer resolve tasks without their own GetRollout round trip. The store+ // owns identity preservation — unchanged content keeps the cached+ // reference (poll ticks don't notify subscribers for nothing), and a+ // change hands out new references only for the changed stage/task — and+ // returns the stored instance so every consumer, page snapshot included,+ // shares the same identities.+ upsertRollout: (rollout) => {+ const cached = get().rolloutsByName[rollout.name];+ const merged = preserveRolloutIdentities(cached, rollout) ?? rollout;+ if (merged !== cached) {+ set((state) => ({+ rolloutsByName: { ...state.rolloutsByName, [rollout.name]: merged },+ }));+ }+ return merged;},getRolloutByName: (name) => get().rolloutsByName[name] ?? unknownRollout,diff --git a/frontend/src/react/stores/app/sheet.ts b/frontend/src/react/stores/app/sheet.tsindex 34a0b9742e..656a2ab17b 100644--- a/frontend/src/react/stores/app/sheet.ts+++ b/frontend/src/react/stores/app/sheet.ts@@ -5,7 +5,7 @@ import {GetSheetRequestSchema,type Sheet,} from "@/types/proto-es/v1/sheet_service_pb";-import { extractSheetUID } from "@/utils/v1/sheet";+import { extractSheetUID, isSheetContentComplete } from "@/utils/v1/sheet";import type { AppSliceCreator, SheetSlice } from "./types";import { toError } from "./utils";@@ -22,49 +22,67 @@ export const createSheetSlice: AppSliceCreator<SheetSlice> = (set, get) => ({fetchSheet: async (name, raw = false) => {if (!isValidSheetName(name)) return undefined;- if (!raw) {- const existing = get().sheetsByName[name];- if (existing) return existing;+ const existing = get().sheetsByName[name];+ // Sheets are immutable, so a complete cached copy satisfies raw consumers+ // too; a truncated preview only satisfies non-raw ones.+ if (existing && (!raw || isSheetContentComplete(existing))) {+ return existing;}const pending = get().sheetRequests[name];- if (pending) return pending;+ // A pending raw request satisfies everyone; a pending preview request may+ // resolve to truncated content, so a raw consumer can't join it.+ if (pending && (pending.raw || !raw)) return pending.request;++ // Clear the pending-request entry only if it is still THIS request — a+ // later raw request may have replaced a preview's entry, and that raw+ // request must keep coalescing until it resolves.+ const clearOwnRequest = (requests: SheetSlice["sheetRequests"]) => {+ if (requests[name]?.request !== request) return requests;+ const { [name]: _omit, ...rest } = requests;+ return rest;+ };const request = sheetServiceClientConnect.getSheet(createProto(GetSheetRequestSchema, { name, raw })).then((sheet: Sheet) => {set((state) => {- const { [name]: _, ...sheetRequests } = state.sheetRequests;+ const cached = state.sheetsByName[sheet.name];+ // Never replace a complete cached sheet with a truncated preview+ // (a slower non-raw request may resolve after a raw one).+ const next =+ cached &&+ isSheetContentComplete(cached) &&+ !isSheetContentComplete(sheet)+ ? cached+ : sheet;return {sheetsByName: {...state.sheetsByName,- [sheet.name]: sheet,+ [sheet.name]: next,},sheetErrorsByName: {...state.sheetErrorsByName,[name]: undefined,},- sheetRequests,+ sheetRequests: clearOwnRequest(state.sheetRequests),};});return sheet;}).catch((error) => {- set((state) => {- const { [name]: _, ...sheetRequests } = state.sheetRequests;- return {- sheetErrorsByName: {- ...state.sheetErrorsByName,- [name]: toError(error),- },- sheetRequests,- };- });+ set((state) => ({+ sheetErrorsByName: {+ ...state.sheetErrorsByName,+ [name]: toError(error),+ },+ sheetRequests: clearOwnRequest(state.sheetRequests),+ }));return undefined;});set((state) => ({sheetRequests: {...state.sheetRequests,- [name]: request,+ [name]: { raw, request },},}));return request;diff --git a/frontend/src/react/stores/app/types.ts b/frontend/src/react/stores/app/types.tsindex 1846928788..df1357cc2d 100644--- a/frontend/src/react/stores/app/types.ts+++ b/frontend/src/react/stores/app/types.ts@@ -586,7 +586,10 @@ export type DBGroupSlice = {export type SheetSlice = {sheetsByName: Record<string, Sheet>;- sheetRequests: Record<string, Promise<Sheet | undefined>>;+ sheetRequests: Record<+ string,+ { raw: boolean; request: Promise<Sheet | undefined> }+ >;sheetErrorsByName: Record<string, Error | undefined>;fetchSheet: (name: string, raw?: boolean) => Promise<Sheet | undefined>;createSheet: (parent: string, sheet: Sheet) => Promise<Sheet>;@@ -1060,6 +1063,10 @@ export type RolloutSlice = {fetchRolloutByName: (name: string, silent?: boolean) => Promise<Rollout>;// Synchronous cache read; returns a stable unknownRollout on miss.getRolloutByName: (name: string) => Rollout;+ // Seed/refresh the cache with a rollout fetched elsewhere. Returns the+ // stored, identity-preserved instance — use it instead of the wire object so+ // consumers share references.+ upsertRollout: (rollout: Rollout) => Rollout;};export type AppStoreState = AuthSlice &diff --git a/frontend/src/utils/v1/issue/rollout.test.ts b/frontend/src/utils/v1/issue/rollout.test.tsindex 263af1d699..c38f14808e 100644--- a/frontend/src/utils/v1/issue/rollout.test.ts+++ b/frontend/src/utils/v1/issue/rollout.test.ts@@ -11,6 +11,7 @@ import {getRolloutStatus,getStageStatus,getStageStatusFromCounts,+ isTaskActivelyTransitioning,} from "./rollout";const stage = (...statuses: Task_Status[]) =>@@ -118,3 +119,48 @@ describe("getStageStatusFromCounts", () => {expect(getStageStatusFromCounts([])).toBe(Task_Status.STATUS_UNSPECIFIED);});});++describe("isTaskActivelyTransitioning", () => {+ const NOW = 1_700_000_000_000; // fixed "now" in ms+ const at = (offsetSec: number) => ({+ seconds: BigInt(NOW / 1000 + offsetSec),+ });+ const task = (status: Task_Status, runTime?: { seconds: bigint }) =>+ create(TaskSchema, runTime ? { status, runTime } : { status });++ test("RUNNING is always active, regardless of run_time", () => {+ expect(isTaskActivelyTransitioning(task(Task_Status.RUNNING), NOW)).toBe(+ true+ );+ expect(+ isTaskActivelyTransitioning(task(Task_Status.RUNNING, at(3600)), NOW)+ ).toBe(true);+ });++ test("PENDING is active when unscheduled or already due", () => {+ expect(isTaskActivelyTransitioning(task(Task_Status.PENDING), NOW)).toBe(+ true+ );+ expect(+ isTaskActivelyTransitioning(task(Task_Status.PENDING, at(-3600)), NOW)+ ).toBe(true);+ });++ test("PENDING scheduled for a future run_time is not active", () => {+ expect(+ isTaskActivelyTransitioning(task(Task_Status.PENDING, at(3600)), NOW)+ ).toBe(false);+ });++ test("settled and not-started tasks are never active", () => {+ for (const status of [+ Task_Status.NOT_STARTED,+ Task_Status.DONE,+ Task_Status.FAILED,+ Task_Status.CANCELED,+ Task_Status.SKIPPED,+ ]) {+ expect(isTaskActivelyTransitioning(task(status), NOW)).toBe(false);+ }+ });+});diff --git a/frontend/src/utils/v1/issue/rollout.ts b/frontend/src/utils/v1/issue/rollout.tsindex 37e6b53eca..65ce5faff8 100644--- a/frontend/src/utils/v1/issue/rollout.ts+++ b/frontend/src/utils/v1/issue/rollout.ts@@ -1,6 +1,11 @@import i18n from "@/react/i18n";import { getDatabaseByName } from "@/react/stores/app/databaseAccess";-import { isValidDatabaseName, UNKNOWN_ID, unknownDatabase } from "@/types";+import {+ getTimeForPbTimestampProtoEs,+ isValidDatabaseName,+ UNKNOWN_ID,+ unknownDatabase,+} from "@/types";import type {Plan,Plan_TaskStatusCount,@@ -136,8 +141,30 @@ export const releaseNameOfTaskV1 = (task: Task): string => {return "";};+// A task is "actively transitioning" — worth fast-polling — when it is RUNNING,+// or PENDING and expected to start imminently. A PENDING task scheduled for a+// future run_time (a maintenance window, possibly hours out) is NOT imminent, so+// it's excluded: the deploy view backs off instead of hammering the rollout RPCs+// while it waits. `nowMs` is injected for testability.+export const isTaskActivelyTransitioning = (+ task: Task,+ nowMs: number = Date.now()+): boolean => {+ if (task.status === Task_Status.RUNNING) {+ return true;+ }+ if (task.status !== Task_Status.PENDING) {+ return false;+ }+ return !task.runTime || getTimeForPbTimestampProtoEs(task.runTime) <= nowMs;+};++// Task_Status ONLY. Task_Status and TaskRun_Status share names but their+// numeric values are offset by one (Task_Status.PENDING === 2 ===+// TaskRun_Status.RUNNING), so one switch cannot serve both enums — a task+// run's status must go through stringifyTaskRunStatus below.export const stringifyTaskStatus = (- status: Task_Status | TaskRun_Status,+ status: Task_Status,translate: (key: string,named?: Record<string, unknown>@@ -158,10 +185,33 @@ export const stringifyTaskStatus = (return translate("task.status.canceled");case Task_Status.SKIPPED:return translate("task.status.skipped");+ default:+ return Task_Status[status] || String(status);+ }+};++export const stringifyTaskRunStatus = (+ status: TaskRun_Status,+ translate: (+ key: string,+ named?: Record<string, unknown>+ ) => string = i18n.t.bind(i18n)+): string => {+ switch (status) {+ case TaskRun_Status.PENDING:+ return translate("task.status.pending");+ case TaskRun_Status.RUNNING:+ return translate("task.status.running");+ case TaskRun_Status.DONE:+ return translate("task.status.done");+ case TaskRun_Status.FAILED:+ return translate("task.status.failed");+ case TaskRun_Status.CANCELED:+ return translate("task.status.canceled");case TaskRun_Status.AVAILABLE:return translate("task.status.available");default:- return Task_Status[status] || String(status);+ return TaskRun_Status[status] || String(status);}};diff --git a/frontend/src/utils/v1/sheet.ts b/frontend/src/utils/v1/sheet.tsindex 8d5e7f0c33..bb3bdf4d40 100644--- a/frontend/src/utils/v1/sheet.ts+++ b/frontend/src/utils/v1/sheet.ts@@ -18,3 +18,9 @@ export const setSheetStatement = (export const getSheetStatement = (sheet: Sheet | Worksheet) => {return new TextDecoder().decode(sheet.content);};++// Whether the sheet carries its full content rather than a truncated preview+// (fetches without `raw` return at most a size-capped prefix). `content` is+// already the encoded bytes, so this is an O(1) size check.+export const isSheetContentComplete = (sheet: Sheet | Worksheet): boolean =>+ BigInt(sheet.content.byteLength) >= sheet.contentSize;