Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(plan): improve live updates on the plan detail page (#20917)

boojack7c03012ab9f0
diff --git a/backend/api/v1/rollout_service_converter.go b/backend/api/v1/rollout_service_converter.go
index 575e95db64..828b971255 100644
--- a/backend/api/v1/rollout_service_converter.go
+++ b/backend/api/v1/rollout_service_converter.go
@@ -106,6 +106,8 @@ func convertToTaskRunStatus(status storepb.TaskRun_Status) v1pb.TaskRun_Status {
return v1pb.TaskRun_STATUS_UNSPECIFIED
case storepb.TaskRun_PENDING:
return v1pb.TaskRun_PENDING
+ case storepb.TaskRun_AVAILABLE:
+ return v1pb.TaskRun_AVAILABLE
case storepb.TaskRun_RUNNING:
return v1pb.TaskRun_RUNNING
case storepb.TaskRun_DONE:
diff --git a/backend/api/v1/rollout_service_converter_test.go b/backend/api/v1/rollout_service_converter_test.go
index 54cbd27214..cbdd9cab19 100644
--- a/backend/api/v1/rollout_service_converter_test.go
+++ b/backend/api/v1/rollout_service_converter_test.go
@@ -12,6 +12,27 @@ import (
"github.com/bytebase/bytebase/backend/store"
)
+func TestConvertToTaskRunStatus(t *testing.T) {
+ tests := []struct {
+ storeStatus storepb.TaskRun_Status
+ want v1pb.TaskRun_Status
+ }{
+ {storeStatus: storepb.TaskRun_STATUS_UNSPECIFIED, want: v1pb.TaskRun_STATUS_UNSPECIFIED},
+ {storeStatus: storepb.TaskRun_PENDING, want: v1pb.TaskRun_PENDING},
+ {storeStatus: storepb.TaskRun_AVAILABLE, want: v1pb.TaskRun_AVAILABLE},
+ {storeStatus: storepb.TaskRun_RUNNING, want: v1pb.TaskRun_RUNNING},
+ {storeStatus: storepb.TaskRun_DONE, want: v1pb.TaskRun_DONE},
+ {storeStatus: storepb.TaskRun_FAILED, want: v1pb.TaskRun_FAILED},
+ {storeStatus: storepb.TaskRun_CANCELED, want: v1pb.TaskRun_CANCELED},
+ }
+
+ for _, test := range tests {
+ t.Run(test.storeStatus.String(), func(t *testing.T) {
+ require.Equal(t, test.want, convertToTaskRunStatus(test.storeStatus))
+ })
+ }
+}
+
func TestConvertToTaskRunLogEntries_GhostMigration(t *testing.T) {
start := time.Date(2026, 5, 8, 10, 0, 0, 0, time.UTC)
end := start.Add(3 * time.Second)
diff --git a/frontend/src/react/components/plan-check/PlanCheckSection.tsx b/frontend/src/react/components/plan-check/PlanCheckSection.tsx
index 326500802a..3828a40826 100644
--- a/frontend/src/react/components/plan-check/PlanCheckSection.tsx
+++ b/frontend/src/react/components/plan-check/PlanCheckSection.tsx
@@ -53,9 +53,9 @@ interface PlanCheckSectionProps {
isRunning: boolean;
runDisabled?: boolean;
onRun: () => void | Promise<void>;
- // Called when the drawer opens; should refresh runs and return the latest.
- // Return value replaces what the drawer renders.
- onRefreshOnOpen?: () => Promise<PlanCheckRun[]>;
+ // Called when the drawer opens. The parent owns the refreshed runs and feeds
+ // them back through planCheckRuns; the callback result itself is ignored.
+ onRefreshOnOpen?: () => Promise<unknown>;
// Optional trailing element rendered after status counts (e.g. affected rows).
trailingSummary?: ReactNode;
renderTarget?: (target: string) => ReactNode;
@@ -241,7 +241,7 @@ interface PlanCheckResultsDrawerProps {
open: boolean;
onOpenChange: (next: boolean) => void;
planCheckRuns: PlanCheckRun[];
- onRefreshOnOpen?: () => Promise<PlanCheckRun[]>;
+ onRefreshOnOpen?: () => Promise<unknown>;
includeRunFailure?: boolean;
renderTarget?: (target: string) => ReactNode;
}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskFilter.test.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskFilter.test.tsx
new file mode 100644
index 0000000000..556f7c3c58
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskFilter.test.tsx
@@ -0,0 +1,56 @@
+import { create } from "@bufbuild/protobuf";
+import { render, screen } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+import {
+ StageSchema,
+ TaskSchema,
+ Task_Status,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import { DeployTaskFilter } from "./DeployTaskFilter";
+
+vi.mock("react-i18next", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("react-i18next")>()),
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/react/components/TaskStatusIcon", () => ({
+ TaskStatusIcon: () => null,
+}));
+
+describe("DeployTaskFilter", () => {
+ test("orders statuses by the canonical task status priority", () => {
+ const stage = create(StageSchema, {
+ tasks: [
+ Task_Status.NOT_STARTED,
+ Task_Status.DONE,
+ Task_Status.FAILED,
+ Task_Status.CANCELED,
+ Task_Status.SKIPPED,
+ Task_Status.PENDING,
+ Task_Status.RUNNING,
+ ].map((status, index) =>
+ create(TaskSchema, { name: `tasks/${index}`, status })
+ ),
+ });
+
+ render(
+ <DeployTaskFilter
+ onChange={vi.fn()}
+ selectedStatuses={[]}
+ stage={stage}
+ />
+ );
+
+ expect(
+ screen.getAllByRole("button").map((button) => button.textContent)
+ ).toEqual([
+ "task.status.failed1",
+ "task.status.running1",
+ "task.status.pending1",
+ "task.status.canceled1",
+ "task.status.not-started1",
+ "task.status.done1",
+ "task.status.skipped1",
+ ]);
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskFilter.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskFilter.tsx
index 56f77ff33a..8a9d4f8405 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskFilter.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskFilter.tsx
@@ -2,17 +2,7 @@ import { useTranslation } from "react-i18next";
import { TaskStatusIcon } from "@/react/components/TaskStatusIcon";
import type { Stage } from "@/types/proto-es/v1/rollout_service_pb";
import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
-import { stringifyTaskStatus } from "@/utils";
-
-const TASK_STATUS_FILTERS = [
- Task_Status.NOT_STARTED,
- Task_Status.PENDING,
- Task_Status.RUNNING,
- Task_Status.DONE,
- Task_Status.FAILED,
- Task_Status.CANCELED,
- Task_Status.SKIPPED,
-];
+import { stringifyTaskStatus, TASK_STATUS_PRIORITY } from "@/utils";
export function DeployTaskFilter({
selectedStatuses,
@@ -29,7 +19,7 @@ export function DeployTaskFilter({
return (
<div className="flex flex-row items-center gap-1">
- {TASK_STATUS_FILTERS.map((status) => {
+ {TASK_STATUS_PRIORITY.map((status) => {
const count = getTaskCount(status);
if (count <= 0) return null;
const checked = selectedStatuses.includes(status);
diff --git a/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.test.tsx b/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.test.tsx
new file mode 100644
index 0000000000..91e62709b5
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.test.tsx
@@ -0,0 +1,158 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ getPlan: vi.fn(),
+ getPlanCheckRun: vi.fn(),
+ page: {} as Record<string, unknown>,
+ patchState: vi.fn(),
+ pushNotification: vi.fn(),
+ refreshState: vi.fn(),
+ runPlanChecks: vi.fn(),
+ setIsRunningChecks: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/connect", () => ({
+ planServiceClientConnect: {
+ getPlan: mocks.getPlan,
+ getPlanCheckRun: mocks.getPlanCheckRun,
+ runPlanChecks: mocks.runPlanChecks,
+ },
+}));
+
+vi.mock("@/react/hooks/useAppState", () => ({
+ useCurrentUser: () => ({ email: "[email protected]" }),
+}));
+
+vi.mock("@/react/hooks/useProjectByName", () => ({
+ useProjectByName: () => ({ name: "projects/foo" }),
+}));
+
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: (selector: (state: { projectsByName: object }) => unknown) =>
+ selector({ projectsByName: {} }),
+}));
+
+vi.mock("@/store", () => ({
+ projectNamePrefix: "projects/",
+ pushNotification: mocks.pushNotification,
+}));
+
+vi.mock("@/store/modules/v1/common", () => ({
+ extractUserEmail: (name: string) => name.replace(/^users\//, ""),
+}));
+
+vi.mock("@/utils", () => ({
+ hasProjectPermissionV2: () => true,
+}));
+
+vi.mock("../shell/PlanDetailContext", () => ({
+ usePlanDetailContext: () => mocks.page,
+}));
+
+import { usePlanCheckActions } from "./usePlanCheckActions";
+
+describe("usePlanCheckActions", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ Object.assign(mocks.page, {
+ isRunningChecks: false,
+ patchState: mocks.patchState,
+ plan: {
+ creator: "users/[email protected]",
+ hasRollout: false,
+ name: "projects/foo/plans/1",
+ },
+ projectId: "foo",
+ readonly: false,
+ refreshState: mocks.refreshState,
+ setIsRunningChecks: mocks.setIsRunningChecks,
+ });
+ mocks.getPlan.mockResolvedValue({ name: "projects/foo/plans/1" });
+ mocks.getPlanCheckRun.mockResolvedValue({
+ name: "projects/foo/plans/1/planCheckRun",
+ });
+ mocks.refreshState.mockResolvedValue(undefined);
+ mocks.runPlanChecks.mockResolvedValue({});
+ });
+
+ test("refreshes the full page snapshot after starting checks", async () => {
+ const { result } = renderHook(() => usePlanCheckActions());
+
+ await act(async () => {
+ await result.current.runChecks();
+ });
+
+ expect(mocks.runPlanChecks).toHaveBeenCalledTimes(1);
+ expect(mocks.refreshState).toHaveBeenCalledTimes(1);
+ expect(mocks.getPlan).not.toHaveBeenCalled();
+ expect(mocks.getPlanCheckRun).not.toHaveBeenCalled();
+ expect(mocks.patchState).not.toHaveBeenCalled();
+ expect(mocks.setIsRunningChecks.mock.calls.map(([value]) => value)).toEqual([
+ true,
+ false,
+ ]);
+ });
+
+ test("does not report a successful run as failed when refresh fails", async () => {
+ mocks.refreshState.mockRejectedValue(new Error("refresh failed"));
+ const { result } = renderHook(() => usePlanCheckActions());
+
+ await act(async () => {
+ await result.current.runChecks();
+ });
+
+ expect(mocks.runPlanChecks).toHaveBeenCalledTimes(1);
+ expect(mocks.refreshState).toHaveBeenCalledTimes(1);
+ expect(mocks.pushNotification).toHaveBeenCalledTimes(1);
+ expect(mocks.pushNotification).toHaveBeenCalledWith(
+ expect.objectContaining({
+ style: "SUCCESS",
+ title: "plan.checks.started",
+ })
+ );
+ expect(mocks.setIsRunningChecks.mock.calls.map(([value]) => value)).toEqual([
+ true,
+ false,
+ ]);
+ });
+
+ test("reports a run failure without refreshing", async () => {
+ mocks.runPlanChecks.mockRejectedValue(new Error("run failed"));
+ const { result } = renderHook(() => usePlanCheckActions());
+
+ await act(async () => {
+ await result.current.runChecks();
+ });
+
+ expect(mocks.refreshState).not.toHaveBeenCalled();
+ expect(mocks.pushNotification).toHaveBeenCalledTimes(1);
+ expect(mocks.pushNotification).toHaveBeenCalledWith(
+ expect.objectContaining({
+ style: "CRITICAL",
+ title: "plan.checks.failed-to-run",
+ })
+ );
+ expect(mocks.setIsRunningChecks.mock.calls.map(([value]) => value)).toEqual([
+ true,
+ false,
+ ]);
+ });
+
+ test("refreshes the full page snapshot when opening check results", async () => {
+ const { result } = renderHook(() => usePlanCheckActions());
+
+ await act(async () => {
+ await result.current.refreshChecks();
+ });
+
+ expect(mocks.refreshState).toHaveBeenCalledTimes(1);
+ expect(mocks.getPlan).not.toHaveBeenCalled();
+ expect(mocks.getPlanCheckRun).not.toHaveBeenCalled();
+ expect(mocks.patchState).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx b/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx
index 640cdb0a14..c4e5d8a75c 100644
--- a/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx
+++ b/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx
@@ -7,12 +7,7 @@ import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix, pushNotification } from "@/store";
import { extractUserEmail } from "@/store/modules/v1/common";
-import {
- GetPlanCheckRunRequestSchema,
- GetPlanRequestSchema,
- type PlanCheckRun,
- RunPlanChecksRequestSchema,
-} from "@/types/proto-es/v1/plan_service_pb";
+import { RunPlanChecksRequestSchema } from "@/types/proto-es/v1/plan_service_pb";
import { hasProjectPermissionV2 } from "@/utils";
import { usePlanDetailContext } from "../shell/PlanDetailContext";
@@ -21,7 +16,7 @@ import { usePlanDetailContext } from "../shell/PlanDetailContext";
export function usePlanCheckActions() {
const { t } = useTranslation();
const page = usePlanDetailContext();
- const { patchState, isRunningChecks, setIsRunningChecks } = page;
+ const { isRunningChecks, refreshState, setIsRunningChecks } = page;
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
void projectsByName;
@@ -44,36 +39,18 @@ export function usePlanCheckActions() {
project,
]);
- const refreshChecks = useCallback(async (): Promise<PlanCheckRun[]> => {
- const [nextPlan, runOrNull] = await Promise.all([
- planServiceClientConnect.getPlan(
- create(GetPlanRequestSchema, { name: page.plan.name })
- ),
- planServiceClientConnect
- .getPlanCheckRun(
- create(GetPlanCheckRunRequestSchema, {
- name: `${page.plan.name}/planCheckRun`,
- })
- )
- .catch(() => null),
- ]);
- const nextPlanCheckRuns = runOrNull ? [runOrNull] : [];
- patchState({ plan: nextPlan, planCheckRuns: nextPlanCheckRuns });
- return nextPlanCheckRuns;
- }, [page.plan.name, patchState]);
-
const runChecks = useCallback(async () => {
try {
setIsRunningChecks(true);
await planServiceClientConnect.runPlanChecks(
create(RunPlanChecksRequestSchema, { name: page.plan.name })
);
- await refreshChecks();
pushNotification({
module: "bytebase",
style: "SUCCESS",
title: t("plan.checks.started"),
});
+ await refreshState().catch(() => undefined);
} catch (error) {
pushNotification({
module: "bytebase",
@@ -84,12 +61,12 @@ export function usePlanCheckActions() {
} finally {
setIsRunningChecks(false);
}
- }, [page.plan.name, refreshChecks, t]);
+ }, [page.plan.name, refreshState, setIsRunningChecks, t]);
return {
allowRunChecks,
isRunningChecks,
- refreshChecks,
+ refreshChecks: refreshState,
runChecks,
};
}
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.tsx
index 64e95c5952..26b9353f96 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,7 @@
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 { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { ApprovalStatus, State } from "@/types/proto-es/v1/common_pb";
import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";
@@ -9,6 +9,7 @@ import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";
import {
RolloutSchema,
Task_Status,
+ TaskRun_Status,
TaskRunSchema,
} from "@/types/proto-es/v1/rollout_service_pb";
import { UserSchema } from "@/types/proto-es/v1/user_service_pb";
@@ -94,12 +95,17 @@ const buildSnapshotPatch = ({
describe("usePlanDetailPage", () => {
beforeEach(() => {
vi.clearAllMocks();
+ vi.spyOn(Math, "random").mockReturnValue(0.5);
mocks.fetchPlanSnapshot.mockImplementation(
async (_projectId: string, planId: string) =>
buildSnapshotPatch({ planId })
);
});
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
test("defaults to only the changes phase on the specs route", async () => {
const { result } = renderHook(
() =>
@@ -642,13 +648,21 @@ describe("usePlanDetailPage", () => {
expect(result.current.ready).toBe(true);
mocks.fetchPlanSnapshot.mockClear();
- // A RUNNING task → the poll re-fetches the full snapshot every ~1s.
+ // Active work starts at 500ms, then backs off to 1s.
await act(async () => {
- await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(499);
+ });
+ expect(mocks.fetchPlanSnapshot).not.toHaveBeenCalled();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
});
expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
await act(async () => {
- await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(999);
+ });
+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
});
expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(2);
} finally {
@@ -656,6 +670,101 @@ describe("usePlanDetailPage", () => {
}
});
+ test("does not reset active backoff when protobuf map key order changes", async () => {
+ vi.useFakeTimers();
+ try {
+ const patch = buildSnapshotPatch({ planId: "plan-1" });
+ const planWithStatusCount = (
+ planCheckRunStatusCount: Record<string, number>
+ ) =>
+ create(PlanSchema, {
+ name: "projects/foo/plans/plan-1",
+ creator: "users/[email protected]",
+ state: State.ACTIVE,
+ specs: [{ id: "spec-1" }, { id: "spec-2" }],
+ planCheckRunStatusCount,
+ });
+ mocks.fetchPlanSnapshot
+ .mockResolvedValueOnce({
+ ...patch,
+ plan: planWithStatusCount({ RUNNING: 1, SUCCESS: 1 }),
+ })
+ .mockResolvedValue({
+ ...patch,
+ plan: planWithStatusCount({ SUCCESS: 1, RUNNING: 1 }),
+ });
+
+ 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();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ });
+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
+ mocks.fetchPlanSnapshot.mockClear();
+
+ // Map insertion order is not protobuf content. Structural sharing keeps
+ // the original plan identity, so the active cadence continues to 1s
+ // instead of spuriously restarting at 500ms.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(999);
+ });
+ expect(mocks.fetchPlanSnapshot).not.toHaveBeenCalled();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test.each([
+ { name: "pending", status: TaskRun_Status.PENDING },
+ { name: "available", status: TaskRun_Status.AVAILABLE },
+ { name: "running", status: TaskRun_Status.RUNNING },
+ ])("keeps polling while a terminal task has a $name task run", async ({
+ status,
+ }) => {
+ vi.useFakeTimers();
+ try {
+ mocks.fetchPlanSnapshot.mockResolvedValue({
+ ...buildSnapshotPatch({ planId: "plan-1" }),
+ rollout: rolloutWithTask(Task_Status.DONE),
+ taskRuns: [
+ create(TaskRunSchema, {
+ name: "projects/foo/rollouts/1/stages/s1/tasks/t1/taskRuns/r1",
+ status,
+ }),
+ ],
+ });
+
+ 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();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ });
+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
test("uses the idle cadence when no task is transitioning", async () => {
vi.useFakeTimers();
try {
@@ -674,16 +783,20 @@ describe("usePlanDetailPage", () => {
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.
+ // Idle starts at 1s, then backs off to 2s.
await act(async () => {
- await vi.advanceTimersByTimeAsync(2000);
+ await vi.advanceTimersByTimeAsync(1000);
+ });
+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
+ mocks.fetchPlanSnapshot.mockClear();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1999);
});
expect(mocks.fetchPlanSnapshot).not.toHaveBeenCalled();
await act(async () => {
- await vi.advanceTimersByTimeAsync(14000);
+ await vi.advanceTimersByTimeAsync(1);
});
- expect(mocks.fetchPlanSnapshot).toHaveBeenCalled();
+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
} finally {
vi.useRealTimers();
}
@@ -714,7 +827,7 @@ describe("usePlanDetailPage", () => {
mocks.fetchPlanSnapshot.mockClear();
await act(async () => {
- await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(500);
});
expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
} finally {
@@ -742,7 +855,7 @@ describe("usePlanDetailPage", () => {
mocks.fetchPlanSnapshot.mockClear();
await act(async () => {
- await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(500);
});
expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
} finally {
@@ -754,34 +867,60 @@ describe("usePlanDetailPage", () => {
{
approvalStatus: ApprovalStatus.APPROVED,
checkStatusCount: { SUCCESS: 2 },
- expectedCalls: 1,
+ expectedCalls: 2,
name: "approved with passing checks",
},
{
approvalStatus: ApprovalStatus.SKIPPED,
checkStatusCount: {},
- expectedCalls: 1,
+ expectedCalls: 2,
name: "skipped with no required checks",
},
{
approvalStatus: ApprovalStatus.PENDING,
checkStatusCount: { SUCCESS: 2 },
- expectedCalls: 0,
+ expectedCalls: 1,
name: "pending approval",
},
+ {
+ approvalStatus: ApprovalStatus.CHECKING,
+ checkStatusCount: { SUCCESS: 2 },
+ expectedCalls: 2,
+ name: "approval finding after checks finish",
+ },
+ {
+ approvalRoles: [],
+ approvalStatus: ApprovalStatus.PENDING,
+ checkStatusCount: { SUCCESS: 2 },
+ expectedCalls: 2,
+ name: "no approval steps",
+ },
{
approvalStatus: ApprovalStatus.APPROVED,
checkStatusCount: { RUNNING: 1 },
- expectedCalls: 0,
+ expectedCalls: 2,
name: "running checks",
},
+ {
+ approvalStatus: ApprovalStatus.PENDING,
+ checkStatusCount: { AVAILABLE: 1 },
+ expectedCalls: 2,
+ name: "queued checks",
+ },
{
approvalStatus: ApprovalStatus.APPROVED,
checkStatusCount: { ERROR: 1 },
- expectedCalls: 0,
+ expectedCalls: 1,
name: "failed checks",
},
+ {
+ approvalStatus: ApprovalStatus.APPROVED,
+ checkStatusCount: { CANCELED: 1 },
+ expectedCalls: 1,
+ name: "canceled checks",
+ },
])("uses the expected pre-rollout cadence for $name", async ({
+ approvalRoles,
approvalStatus,
checkStatusCount,
expectedCalls,
@@ -794,6 +933,9 @@ describe("usePlanDetailPage", () => {
name: "projects/foo/issues/1",
status: IssueStatus.OPEN,
approvalStatus,
+ approvalTemplate: approvalRoles
+ ? { flow: { roles: approvalRoles } }
+ : undefined,
} as PlanDetailPageSnapshot["issue"],
});
mocks.fetchPlanSnapshot.mockResolvedValue({
@@ -815,7 +957,7 @@ describe("usePlanDetailPage", () => {
mocks.fetchPlanSnapshot.mockClear();
await act(async () => {
- await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(2000);
});
expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(expectedCalls);
} finally {
@@ -823,6 +965,121 @@ describe("usePlanDetailPage", () => {
}
});
+ test("returns to the idle cadence after plan checks finish", async () => {
+ vi.useFakeTimers();
+ try {
+ const patch = buildSnapshotPatch({ planId: "plan-1" });
+ mocks.fetchPlanSnapshot
+ .mockResolvedValueOnce({
+ ...patch,
+ plan: {
+ ...patch.plan,
+ planCheckRunStatusCount: { RUNNING: 1 },
+ },
+ })
+ .mockResolvedValue({
+ ...patch,
+ plan: {
+ ...patch.plan,
+ planCheckRunStatusCount: { SUCCESS: 1 },
+ },
+ });
+
+ 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();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ });
+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
+ expect(result.current.plan.planCheckRunStatusCount).toEqual({
+ SUCCESS: 1,
+ });
+ mocks.fetchPlanSnapshot.mockClear();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(999);
+ });
+ expect(mocks.fetchPlanSnapshot).not.toHaveBeenCalled();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test("keeps the active cadence from completed checks through approval finding", async () => {
+ vi.useFakeTimers();
+ try {
+ const issue = {
+ name: "projects/foo/issues/1",
+ status: IssueStatus.OPEN,
+ approvalStatus: ApprovalStatus.CHECKING,
+ } as PlanDetailPageSnapshot["issue"];
+ const patch = buildSnapshotPatch({ issue, planId: "plan-1" });
+ mocks.fetchPlanSnapshot
+ .mockResolvedValueOnce({
+ ...patch,
+ plan: {
+ ...patch.plan,
+ planCheckRunStatusCount: { RUNNING: 1 },
+ },
+ })
+ .mockResolvedValueOnce({
+ ...patch,
+ plan: {
+ ...patch.plan,
+ planCheckRunStatusCount: { DONE: 1, SUCCESS: 1 },
+ },
+ })
+ .mockResolvedValue({
+ ...patch,
+ plan: {
+ ...patch.plan,
+ hasRollout: true,
+ planCheckRunStatusCount: { DONE: 1, SUCCESS: 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();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000);
+ });
+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
+ expect(result.current.issue?.approvalStatus).toBe(
+ ApprovalStatus.CHECKING
+ );
+ mocks.fetchPlanSnapshot.mockClear();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000);
+ });
+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);
+ expect(result.current.rollout).toBeDefined();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
test("a stale poll from the previous plan cannot overwrite the new plan", async () => {
vi.useFakeTimers();
try {
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.ts
index 98e0ff0f50..ce3d60b5ae 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,7 +7,6 @@ import {
useState,
} from "react";
import { useTranslation } from "react-i18next";
-import { usePolling } from "@/react/hooks/usePolling";
import {
preserveTaskRunIdentities,
sameMessage,
@@ -29,6 +28,7 @@ import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";
import {
RolloutSchema,
Task_Status,
+ TaskRun_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";
@@ -46,15 +46,10 @@ import { useEditingScopes } from "./useEditingScopes";
import { useInitialFetch } from "./useInitialFetch";
import { useLeaveGuard } from "./useLeaveGuard";
import { usePhaseState } from "./usePhaseState";
+import { type PlanPollingMode, usePlanPolling } from "./usePlanPolling";
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
@@ -345,25 +340,60 @@ export const usePlanDetailPage = ({
syncDefaultActivePhases,
]);
- const { isPlanDone, shouldPollActively } = useMemo(() => {
+ const { activePollingKey, isPlanDone, pollingMode } = useMemo((): {
+ activePollingKey: string;
+ isPlanDone: boolean;
+ pollingMode: PlanPollingMode;
+ } => {
if (!snapshot.rollout) {
const checks = getPlanCheckSummary(snapshot.plan);
+ // A newly queued check is AVAILABLE until the scheduler claims it. The
+ // public check-run enum maps that store status to UNSPECIFIED, but the
+ // plan status-count map preserves the key. Keep polling actively across
+ // that short queueing window as well as while the check is RUNNING.
+ const hasActivePlanChecks =
+ checks.running > 0 ||
+ (snapshot.plan.planCheckRunStatusCount?.AVAILABLE ?? 0) > 0;
+ const hasCanceledPlanChecks =
+ (snapshot.plan.planCheckRunStatusCount?.CANCELED ?? 0) > 0;
+ // The backend considers an approval template with zero roles approved,
+ // although its API approval status can still be PENDING. Treat the
+ // resolved empty flow as passed so we keep polling through rollout
+ // creation instead of falling back to the idle cadence in that window.
+ const hasNoApprovalSteps =
+ snapshot.issue?.approvalTemplate?.flow?.roles.length === 0;
const approvalPassed =
snapshot.issue?.approvalStatus === ApprovalStatus.APPROVED ||
- snapshot.issue?.approvalStatus === ApprovalStatus.SKIPPED;
+ snapshot.issue?.approvalStatus === ApprovalStatus.SKIPPED ||
+ hasNoApprovalSteps;
+ const approvalChecking =
+ snapshot.issue?.status === IssueStatus.OPEN &&
+ !snapshot.issue.draft &&
+ snapshot.issue.approvalStatus === ApprovalStatus.CHECKING;
const rolloutExpected =
snapshot.plan.hasRollout ||
snapshot.issue?.status === IssueStatus.DONE ||
(snapshot.issue?.status === IssueStatus.OPEN &&
+ !snapshot.issue.draft &&
approvalPassed &&
- checks.running === 0 &&
+ !hasActivePlanChecks &&
+ !hasCanceledPlanChecks &&
checks.error === 0);
// Once every gate passes, rollout creation is asynchronous. Keep polling
// at the active cadence through that gap, as well as when either the plan
// or issue already proves the rollout committed but its data is missing.
return {
+ activePollingKey: [
+ snapshot.plan.hasRollout,
+ snapshot.issue?.status,
+ snapshot.issue?.approvalStatus,
+ JSON.stringify(snapshot.plan.planCheckRunStatusCount),
+ ].join(":"),
isPlanDone: false,
- shouldPollActively: rolloutExpected,
+ pollingMode:
+ hasActivePlanChecks || approvalChecking || rolloutExpected
+ ? "active"
+ : "idle",
};
}
const nowMs = Date.now();
@@ -388,26 +418,44 @@ export const usePlanDetailPage = ({
}
}
}
- return { isPlanDone: taskCount > 0 && allSettled, shouldPollActively };
- }, [snapshot.issue, snapshot.plan, snapshot.rollout]);
+ const hasActiveTaskRuns = snapshot.taskRuns.some(
+ (taskRun) =>
+ taskRun.status === TaskRun_Status.PENDING ||
+ taskRun.status === TaskRun_Status.AVAILABLE ||
+ taskRun.status === TaskRun_Status.RUNNING
+ );
+ const activePollingKey = [
+ ...snapshot.rollout.stages.flatMap((stage) =>
+ stage.tasks.map((task) => `${task.name}:${task.status}`)
+ ),
+ ...snapshot.taskRuns.map(
+ (taskRun) => `${taskRun.name}:${taskRun.status}`
+ ),
+ ].join("|");
+ return {
+ activePollingKey,
+ isPlanDone: taskCount > 0 && allSettled && !hasActiveTaskRuns,
+ pollingMode: shouldPollActively || hasActiveTaskRuns ? "active" : "idle",
+ };
+ }, [snapshot.issue, snapshot.plan, snapshot.rollout, snapshot.taskRuns]);
- // 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,
- shouldPollActively ? ACTIVE_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS,
- fetchState
- );
+ // Poll the complete snapshot. Idle polling backs off from 1s to 16s. Active
+ // plan checks, approval finding, rollout creation, and task execution share a
+ // faster 500ms -> 1s -> 2s -> 4s cadence which resets when state changes.
+ // Independent jitter prevents synchronized clients; hidden tabs pause until
+ // they become visible again.
+ const { restart: restartPolling } = usePlanPolling({
+ enabled: snapshot.ready && !snapshot.isCreating && !isPlanDone,
+ mode: pollingMode,
+ refreshState: fetchState,
+ resetKey: pollingMode === "active" ? activePollingKey : undefined,
+ });
// Public refresh used by user actions (run/skip/cancel a task, edits, etc.).
const refreshState = useCallback(async () => {
await fetchState();
- }, [fetchState]);
+ restartPolling();
+ }, [fetchState, restartPolling]);
return useDerivedPlanState({
snapshot,
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanPolling.test.tsx b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanPolling.test.tsx
new file mode 100644
index 0000000000..fb78fd120a
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanPolling.test.tsx
@@ -0,0 +1,441 @@
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { usePlanPolling } from "./usePlanPolling";
+
+describe("usePlanPolling", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.spyOn(Math, "random").mockReturnValue(0.5);
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ test("backs off the idle base interval from 1s to 16s", async () => {
+ const refreshState = vi.fn().mockResolvedValue(undefined);
+ renderHook(() =>
+ usePlanPolling({ enabled: true, mode: "idle", refreshState })
+ );
+
+ for (const intervalMs of [1000, 2000, 4000, 8000, 16000]) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(intervalMs - 1);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(
+ [1000, 2000, 4000, 8000, 16000].indexOf(intervalMs)
+ );
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ }
+ expect(refreshState).toHaveBeenCalledTimes(5);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(16000);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(6);
+ });
+
+ test("backs off the active base interval from 500ms to 4s", async () => {
+ const refreshState = vi.fn().mockResolvedValue(undefined);
+ renderHook(() =>
+ usePlanPolling({ enabled: true, mode: "active", refreshState })
+ );
+
+ for (const intervalMs of [500, 1000, 2000, 4000]) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(intervalMs - 1);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(
+ [500, 1000, 2000, 4000].indexOf(intervalMs)
+ );
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ }
+ expect(refreshState).toHaveBeenCalledTimes(4);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(4000);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(5);
+ });
+
+ test("applies scaled jitter to the active 500ms floor", async () => {
+ vi.mocked(Math.random).mockReturnValue(0);
+ const refreshState = vi.fn().mockResolvedValue(undefined);
+ const { unmount } = renderHook(() =>
+ usePlanPolling({ enabled: true, mode: "active", refreshState })
+ );
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(374);
+ });
+ expect(refreshState).not.toHaveBeenCalled();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+ unmount();
+
+ vi.mocked(Math.random).mockReturnValue(0.999999);
+ renderHook(() =>
+ usePlanPolling({ enabled: true, mode: "active", refreshState })
+ );
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(624);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(2);
+ });
+
+ test("does not feed a jittered wait back into the next base interval", async () => {
+ vi.mocked(Math.random)
+ .mockReturnValueOnce(0.999999)
+ .mockReturnValueOnce(0)
+ .mockReturnValue(0.5);
+ const refreshState = vi.fn().mockResolvedValue(undefined);
+ renderHook(() =>
+ usePlanPolling({ enabled: true, mode: "active", refreshState })
+ );
+
+ // 500ms base + 125ms jitter.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(625);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+
+ // The next base is still 1s, independently jittered down by 250ms. If the
+ // first 625ms wait fed back into backoff, this tick would arrive at 1s.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(749);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(2);
+ });
+
+ test("restarts at the 500ms floor when active mode begins", async () => {
+ const refreshState = vi.fn().mockResolvedValue(undefined);
+ const { rerender } = renderHook(
+ ({ mode }: { mode: "active" | "idle" }) =>
+ usePlanPolling({ enabled: true, mode, refreshState }),
+ {
+ initialProps: { mode: "idle" } as { mode: "active" | "idle" },
+ }
+ );
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+
+ rerender({ mode: "active" });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(499);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(2);
+ });
+
+ test("restarts active polling when observed state changes", async () => {
+ const refreshState = vi.fn().mockResolvedValue(undefined);
+ const { rerender } = renderHook(
+ ({ resetKey }: { resetKey: string }) =>
+ usePlanPolling({
+ enabled: true,
+ mode: "active",
+ refreshState,
+ resetKey,
+ }),
+ { initialProps: { resetKey: "pending" } }
+ );
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+
+ rerender({ resetKey: "running" });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(499);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(2);
+ });
+
+ test("does not overlap slow refreshes", async () => {
+ let resolveRefresh: () => void = () => {};
+ const refreshState = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveRefresh = resolve;
+ })
+ )
+ .mockResolvedValue(undefined);
+ renderHook(() =>
+ usePlanPolling({ enabled: true, mode: "active", refreshState })
+ );
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10000);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ resolveRefresh();
+ await Promise.resolve();
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(2);
+ });
+
+ test("restart resets idle backoff to the 1s floor", async () => {
+ const refreshState = vi.fn().mockResolvedValue(undefined);
+ const { result } = renderHook(() =>
+ usePlanPolling({ enabled: true, mode: "idle", refreshState })
+ );
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+
+ act(() => result.current.restart());
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(2);
+ });
+
+ test("continues polling after a transient refresh failure", async () => {
+ const refreshState = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("refresh failed"))
+ .mockResolvedValue(undefined);
+ renderHook(() =>
+ usePlanPolling({ enabled: true, mode: "active", refreshState })
+ );
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(999);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(2);
+ });
+
+ test("pauses while hidden and restarts at the active floor when visible", async () => {
+ const hidden = vi
+ .spyOn(document, "hidden", "get")
+ .mockReturnValue(true);
+ const refreshState = vi.fn().mockResolvedValue(undefined);
+ renderHook(() =>
+ usePlanPolling({ enabled: true, mode: "active", refreshState })
+ );
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10000);
+ });
+ expect(refreshState).not.toHaveBeenCalled();
+
+ hidden.mockReturnValue(false);
+ act(() => document.dispatchEvent(new Event("visibilitychange")));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(499);
+ });
+ expect(refreshState).not.toHaveBeenCalled();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+ });
+
+ test("restarts idle backoff at the floor after reconnecting", async () => {
+ const refreshState = vi.fn().mockResolvedValue(undefined);
+ renderHook(() =>
+ usePlanPolling({ enabled: true, mode: "idle", refreshState })
+ );
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ });
+ act(() => window.dispatchEvent(new Event("online")));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(999);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(2);
+ });
+
+ test("defers a state-change restart until the in-flight refresh settles", async () => {
+ let resolveRefresh: () => void = () => {};
+ const refreshState = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveRefresh = resolve;
+ })
+ )
+ .mockResolvedValue(undefined);
+ const { rerender } = renderHook(
+ ({ resetKey }: { resetKey: string }) =>
+ usePlanPolling({
+ enabled: true,
+ mode: "active",
+ refreshState,
+ resetKey,
+ }),
+ { initialProps: { resetKey: "pending" } }
+ );
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+
+ rerender({ resetKey: "running" });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10000);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ resolveRefresh();
+ await Promise.resolve();
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(499);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(2);
+ });
+
+ test("returns to the 1s idle floor when active work finishes", async () => {
+ const refreshState = vi.fn().mockResolvedValue(undefined);
+ const { rerender } = renderHook(
+ ({ mode, resetKey }: { mode: "active" | "idle"; resetKey?: string }) =>
+ usePlanPolling({ enabled: true, mode, refreshState, resetKey }),
+ {
+ initialProps: {
+ mode: "active",
+ resetKey: "running",
+ } as { mode: "active" | "idle"; resetKey?: string },
+ }
+ );
+
+ for (const intervalMs of [500, 1000, 2000, 4000]) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(intervalMs);
+ });
+ }
+ expect(refreshState).toHaveBeenCalledTimes(4);
+
+ rerender({ mode: "idle", resetKey: undefined });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(999);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(4);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(5);
+ });
+
+ test("does not reschedule when disabled during an in-flight refresh", async () => {
+ let resolveRefresh: () => void = () => {};
+ const refreshState = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveRefresh = resolve;
+ })
+ );
+ const { rerender } = renderHook(
+ ({ enabled }: { enabled: boolean }) =>
+ usePlanPolling({ enabled, mode: "active", refreshState }),
+ { initialProps: { enabled: true } }
+ );
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+
+ rerender({ enabled: false });
+ await act(async () => {
+ resolveRefresh();
+ await Promise.resolve();
+ await vi.advanceTimersByTimeAsync(10000);
+ });
+ expect(refreshState).toHaveBeenCalledTimes(1);
+ });
+
+ test("uses the latest refresh callback without resetting backoff", async () => {
+ const firstRefresh = vi.fn().mockResolvedValue(undefined);
+ const latestRefresh = vi.fn().mockResolvedValue(undefined);
+ const { rerender } = renderHook(
+ ({ refreshState }: { refreshState: () => Promise<void> }) =>
+ usePlanPolling({ enabled: true, mode: "active", refreshState }),
+ { initialProps: { refreshState: firstRefresh } }
+ );
+
+ rerender({ refreshState: latestRefresh });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ });
+ expect(firstRefresh).not.toHaveBeenCalled();
+ expect(latestRefresh).toHaveBeenCalledTimes(1);
+
+ rerender({ refreshState: firstRefresh });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(999);
+ });
+ expect(firstRefresh).not.toHaveBeenCalled();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(firstRefresh).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanPolling.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanPolling.ts
new file mode 100644
index 0000000000..5a6d02b0b1
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanPolling.ts
@@ -0,0 +1,179 @@
+import { useCallback, useEffect, useRef } from "react";
+import { useLatestRef } from "@/react/hooks/useLatestRef";
+
+const IDLE_MIN_INTERVAL_MS = 1000;
+const IDLE_MAX_INTERVAL_MS = 16000;
+const ACTIVE_MIN_INTERVAL_MS = 500;
+const ACTIVE_MAX_INTERVAL_MS = 4000;
+const GROWTH_FACTOR = 2;
+const JITTER_MS = 250;
+
+export type PlanPollingMode = "active" | "idle";
+
+const minimumInterval = (mode: PlanPollingMode): number =>
+ mode === "active" ? ACTIVE_MIN_INTERVAL_MS : IDLE_MIN_INTERVAL_MS;
+
+const nextInterval = (intervalMs: number, mode: PlanPollingMode): number => {
+ if (mode === "active") {
+ return Math.min(intervalMs * GROWTH_FACTOR, ACTIVE_MAX_INTERVAL_MS);
+ }
+ return Math.min(
+ Math.max(intervalMs * GROWTH_FACTOR, IDLE_MIN_INTERVAL_MS),
+ IDLE_MAX_INTERVAL_MS
+ );
+};
+
+const addJitter = (intervalMs: number): number => {
+ // Keep the existing +/-250ms bound, but scale it down for the new 500ms
+ // active floor so jitter never consumes half of that latency budget.
+ const jitterMs = Math.min(JITTER_MS, intervalMs * 0.25);
+ return intervalMs + Math.floor(Math.random() * (jitterMs * 2 + 1)) - jitterMs;
+};
+
+type PollingControl = {
+ restart: () => void;
+ setMode: (mode: PlanPollingMode) => void;
+};
+
+const NOOP_CONTROL: PollingControl = {
+ restart: () => {},
+ setMode: () => {},
+};
+
+/**
+ * Polls the full plan snapshot without overlapping requests. The idle cadence
+ * backs off from 1s to 16s; active mode backs off from 500ms to 4s. Every
+ * scheduled wait gets independent jitter so clients do not synchronize, while
+ * the jittered delay never feeds back into the next base interval.
+ */
+export const usePlanPolling = ({
+ enabled,
+ mode,
+ refreshState,
+ resetKey,
+}: {
+ enabled: boolean;
+ mode: PlanPollingMode;
+ refreshState: () => void | Promise<void>;
+ resetKey?: string;
+}): { restart: () => void } => {
+ const refreshStateRef = useLatestRef(refreshState);
+ const controlRef = useRef<PollingControl>(NOOP_CONTROL);
+ const previousResetKeyRef = useRef(resetKey);
+
+ useEffect(() => {
+ if (!enabled) {
+ controlRef.current = NOOP_CONTROL;
+ return;
+ }
+
+ let canceled = false;
+ let timer: number | undefined;
+ let inFlight = false;
+ let restartAfterFlight = false;
+ let pollingMode = mode;
+ let lastCompletedBaseIntervalMs = 0;
+
+ const clearTimer = () => {
+ if (timer !== undefined) {
+ window.clearTimeout(timer);
+ timer = undefined;
+ }
+ };
+
+ const schedule = (baseIntervalMs: number) => {
+ clearTimer();
+ timer = window.setTimeout(async () => {
+ timer = undefined;
+ if (canceled || document.hidden) {
+ return;
+ }
+
+ inFlight = true;
+ try {
+ await refreshStateRef.current();
+ } catch {
+ // A transient refresh failure must not stop the polling loop.
+ } finally {
+ inFlight = false;
+ if (canceled) {
+ return;
+ }
+
+ lastCompletedBaseIntervalMs = baseIntervalMs;
+ if (restartAfterFlight) {
+ restartAfterFlight = false;
+ lastCompletedBaseIntervalMs = 0;
+ schedule(minimumInterval(pollingMode));
+ return;
+ }
+
+ schedule(nextInterval(baseIntervalMs, pollingMode));
+ }
+ }, addJitter(baseIntervalMs));
+ };
+
+ const restart = () => {
+ lastCompletedBaseIntervalMs = 0;
+ if (inFlight) {
+ restartAfterFlight = true;
+ return;
+ }
+ schedule(minimumInterval(pollingMode));
+ };
+
+ const setMode = (nextMode: PlanPollingMode) => {
+ if (pollingMode === nextMode) {
+ return;
+ }
+ pollingMode = nextMode;
+ if (nextMode === "active") {
+ restart();
+ return;
+ }
+ if (!inFlight) {
+ schedule(nextInterval(lastCompletedBaseIntervalMs, nextMode));
+ }
+ };
+
+ const control = { restart, setMode };
+ controlRef.current = control;
+
+ const handleVisibilityChange = () => {
+ if (!document.hidden) {
+ restart();
+ }
+ };
+ document.addEventListener("visibilitychange", handleVisibilityChange);
+ window.addEventListener("online", restart);
+ schedule(minimumInterval(pollingMode));
+
+ return () => {
+ canceled = true;
+ clearTimer();
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
+ window.removeEventListener("online", restart);
+ if (controlRef.current === control) {
+ controlRef.current = NOOP_CONTROL;
+ }
+ };
+ }, [enabled, refreshStateRef]);
+
+ useEffect(() => {
+ controlRef.current.setMode(mode);
+ }, [mode]);
+
+ useEffect(() => {
+ if (previousResetKeyRef.current === resetKey) {
+ return;
+ }
+ previousResetKeyRef.current = resetKey;
+ controlRef.current.restart();
+ }, [resetKey]);
+
+ const restart = useCallback(() => {
+ controlRef.current.restart();
+ }, []);
+
+ return { restart };
+};
diff --git a/frontend/src/utils/v1/issue/rollout.ts b/frontend/src/utils/v1/issue/rollout.ts
index 65ce5faff8..92a979c668 100644
--- a/frontend/src/utils/v1/issue/rollout.ts
+++ b/frontend/src/utils/v1/issue/rollout.ts
@@ -24,12 +24,11 @@ import {
mockDatabase,
} from "./issue";
-// Priority order for aggregating child task statuses into a parent (stage /
-// rollout) status: the highest-priority status present wins. Failure outranks
+// Canonical task status priority for aggregation and display. Failure outranks
// active work (a failed task needs attention even while siblings run — see
// BYT-9822); a cancel is deliberate rather than an error, so it stays below
// active statuses but above NOT_STARTED, surfacing once nothing is in motion.
-const TASK_STATUS_AGGREGATION_PRIORITY: Task_Status[] = [
+export const TASK_STATUS_PRIORITY: readonly Task_Status[] = [
Task_Status.FAILED,
Task_Status.RUNNING,
Task_Status.PENDING,
@@ -215,14 +214,14 @@ export const stringifyTaskRunStatus = (
}
};
-// Return the highest-priority Task_Status (per TASK_STATUS_AGGREGATION_PRIORITY)
+// Return the highest-priority Task_Status (per TASK_STATUS_PRIORITY)
// for which `has` reports a member, or `fallback` when none match. Shared by the
// stage and rollout status reducers below.
const foldByStatusPriority = (
has: (status: Task_Status) => boolean,
fallback: Task_Status
): Task_Status => {
- for (const status of TASK_STATUS_AGGREGATION_PRIORITY) {
+ for (const status of TASK_STATUS_PRIORITY) {
if (has(status)) return status;
}
return fallback;